From 1751cef8960e3553644c1389b21084b93fc7a2f1 Mon Sep 17 00:00:00 2001 From: Tsu-ba-me Date: Mon, 19 Jun 2023 00:20:06 -0400 Subject: [PATCH] fix(striker-ui): handle checks in List with useChecklist hook --- striker-ui/hooks/useChecklist.tsx | 59 +++++++++++++++++++++++++++++++ striker-ui/types/Checklist.d.ts | 13 +++++++ 2 files changed, 72 insertions(+) create mode 100644 striker-ui/hooks/useChecklist.tsx create mode 100644 striker-ui/types/Checklist.d.ts diff --git a/striker-ui/hooks/useChecklist.tsx b/striker-ui/hooks/useChecklist.tsx new file mode 100644 index 00000000..c12dd188 --- /dev/null +++ b/striker-ui/hooks/useChecklist.tsx @@ -0,0 +1,59 @@ +import { useCallback, useMemo, useState } from 'react'; + +import buildObjectStateSetterCallback from '../lib/buildObjectStateSetterCallback'; + +import FormSummary from '../components/FormSummary'; + +const useChecklist = (): { + buildDeleteDialogProps: BuildDeleteDialogPropsFunction; + checklist: Checklist; + checks: ArrayChecklist; + getCheck: GetCheckFunction; + hasChecks: boolean; + setCheck: SetCheckFunction; +} => { + const [checklist, setChecklist] = useState({}); + + const checks = useMemo(() => Object.entries(checklist), [checklist]); + + const hasChecks = useMemo(() => checks.length > 0, [checks.length]); + + const buildDeleteDialogProps = useCallback( + ({ + confirmDialogProps = {}, + formSummaryProps = {}, + getConfirmDialogTitle, + }) => ({ + actionProceedText: 'Delete', + content: ( + + ), + proceedColour: 'red', + titleText: getConfirmDialogTitle(checks.length), + ...confirmDialogProps, + }), + [checklist, checks.length], + ); + + const getCheck = useCallback( + (key) => checklist[key], + [checklist], + ); + + const setCheck = useCallback( + (key, checked) => + setChecklist(buildObjectStateSetterCallback(key, checked || undefined)), + [], + ); + + return { + buildDeleteDialogProps, + checklist, + checks, + getCheck, + hasChecks, + setCheck, + }; +}; + +export default useChecklist; diff --git a/striker-ui/types/Checklist.d.ts b/striker-ui/types/Checklist.d.ts new file mode 100644 index 00000000..749552db --- /dev/null +++ b/striker-ui/types/Checklist.d.ts @@ -0,0 +1,13 @@ +type Checklist = Record; + +type ArrayChecklist = [keyof Checklist, Checklist[string]][]; + +type BuildDeleteDialogPropsFunction = (args: { + confirmDialogProps?: Partial>; + formSummaryProps?: Omit, 'entries'>; + getConfirmDialogTitle: (length: number) => ReactNode; +}) => ConfirmDialogProps; + +type GetCheckFunction = (key: string) => boolean; + +type SetCheckFunction = (key: string, checked?: boolean) => void;