69 lines
2.3 KiB
TypeScript
69 lines
2.3 KiB
TypeScript
import { useEffect, useMemo } from "react";
|
|
import { useDebouncedValue } from "./use-debounced-value";
|
|
import { useTemplateSearchStore } from "../store/template-search.store";
|
|
import type { TemplateContractResponse } from "../types/presentation.types";
|
|
|
|
export function makeTemplateSearchScope(moduleCode: string, templateCode: string) {
|
|
return `${moduleCode.trim()}:${templateCode.trim()}`;
|
|
}
|
|
|
|
export function useTemplateSearchController({
|
|
moduleCode,
|
|
templateCode,
|
|
contract,
|
|
debounceMs = 350,
|
|
}: {
|
|
moduleCode: string;
|
|
templateCode: string;
|
|
contract: TemplateContractResponse;
|
|
debounceMs?: number;
|
|
}) {
|
|
const scope = useMemo(
|
|
() => makeTemplateSearchScope(moduleCode, templateCode),
|
|
[moduleCode, templateCode],
|
|
);
|
|
|
|
const initialize = useTemplateSearchStore((state) => state.initialize);
|
|
const query = useTemplateSearchStore(
|
|
(state) => state.scopes[scope]?.query ?? "",
|
|
);
|
|
const logic = useTemplateSearchStore(
|
|
(state) => state.scopes[scope]?.logic ?? contract.search.default_logic,
|
|
);
|
|
const filters = useTemplateSearchStore(
|
|
(state) => state.scopes[scope]?.filters ?? [],
|
|
);
|
|
const sort = useTemplateSearchStore(
|
|
(state) => state.scopes[scope]?.sort ?? contract.search.default_sort,
|
|
);
|
|
|
|
const setQueryAction = useTemplateSearchStore((state) => state.setQuery);
|
|
const setLogicAction = useTemplateSearchStore((state) => state.setLogic);
|
|
const setFiltersAction = useTemplateSearchStore((state) => state.setFilters);
|
|
const setSortAction = useTemplateSearchStore((state) => state.setSort);
|
|
const resetAction = useTemplateSearchStore((state) => state.reset);
|
|
|
|
useEffect(() => {
|
|
initialize(scope, {
|
|
logic: contract.search.default_logic,
|
|
sort: contract.search.default_sort,
|
|
});
|
|
}, [contract.search.default_logic, contract.search.default_sort, initialize, scope]);
|
|
|
|
const debouncedQuery = useDebouncedValue(query.trim(), debounceMs);
|
|
|
|
return {
|
|
scope,
|
|
query,
|
|
debouncedQuery,
|
|
logic,
|
|
filters,
|
|
sort,
|
|
setQuery: (value: string) => setQueryAction(scope, value),
|
|
setLogic: (value: typeof logic) => setLogicAction(scope, value),
|
|
setFilters: (value: typeof filters) => setFiltersAction(scope, value),
|
|
setSort: (value: typeof sort) => setSortAction(scope, value),
|
|
reset: () => resetAction(scope),
|
|
};
|
|
}
|