app-effort-command.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import React from "react";
  2. import {
  3. filterEffortOptions,
  4. reconcileEffortCommandSelection,
  5. selectedEffortOption,
  6. } from "./app-input.js";
  7. import type { EffortCommandSelectionState } from "./app-model.js";
  8. import type { TuiEffortOption } from "./types.js";
  9. export function useEffortCommandController(
  10. draft: string,
  11. effortOptions: readonly TuiEffortOption[],
  12. ): {
  13. filteredOptions: readonly TuiEffortOption[];
  14. reconcileDraft: (value: string) => EffortCommandSelectionState | undefined;
  15. selectedOption: (submittedValue: string) => TuiEffortOption | undefined;
  16. selection: EffortCommandSelectionState | undefined;
  17. setSelection: React.Dispatch<React.SetStateAction<EffortCommandSelectionState | undefined>>;
  18. } {
  19. const [selection, setSelection] = React.useState<EffortCommandSelectionState | undefined>();
  20. const filteredOptions = React.useMemo(
  21. () => filterEffortOptions(draft, effortOptions),
  22. [draft, effortOptions],
  23. );
  24. const reconcileDraft = React.useCallback(
  25. (value: string) => {
  26. const nextSelection = reconcileEffortCommandSelection(value, effortOptions);
  27. setSelection(nextSelection);
  28. return nextSelection;
  29. },
  30. [effortOptions],
  31. );
  32. const selectedOption = React.useCallback(
  33. (submittedValue: string) => selectedEffortOption(submittedValue, selection, filteredOptions),
  34. [filteredOptions, selection],
  35. );
  36. return {
  37. filteredOptions,
  38. reconcileDraft,
  39. selectedOption,
  40. selection,
  41. setSelection,
  42. };
  43. }