@fuf-stack/uniform 1.28.0 → 1.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -35
- package/dist/Checkboxes/index.d.mts +11 -13
- package/dist/Checkboxes/index.d.mts.map +1 -1
- package/dist/Checkboxes/index.mjs +2 -4
- package/dist/Checkboxes/index.mjs.map +1 -1
- package/dist/DatePicker/index.d.mts +21 -23
- package/dist/DatePicker/index.d.mts.map +1 -1
- package/dist/DatePicker/index.mjs +3 -6
- package/dist/DatePicker/index.mjs.map +1 -1
- package/dist/FieldArray/index.d.mts +2 -8
- package/dist/FieldArray/index.d.mts.map +1 -1
- package/dist/FieldArray/index.mjs +13 -23
- package/dist/FieldArray/index.mjs.map +1 -1
- package/dist/FieldCard/index.d.mts +0 -2
- package/dist/FieldCard/index.d.mts.map +1 -1
- package/dist/FieldCard/index.mjs +5 -8
- package/dist/FieldCard/index.mjs.map +1 -1
- package/dist/{FieldCopyTestIdButton-9xTF-DBW.mjs → FieldCopyTestIdButton-Y9SfvaM9.mjs} +3 -5
- package/dist/{FieldCopyTestIdButton-9xTF-DBW.mjs.map → FieldCopyTestIdButton-Y9SfvaM9.mjs.map} +1 -1
- package/dist/FieldReset/index.d.mts +415 -0
- package/dist/FieldReset/index.d.mts.map +1 -0
- package/dist/FieldReset/index.mjs +241 -0
- package/dist/FieldReset/index.mjs.map +1 -0
- package/dist/{FieldValidationError-ByRoIxaM.mjs → FieldValidationError-BcUV0r1I.mjs} +3 -5
- package/dist/{FieldValidationError-ByRoIxaM.mjs.map → FieldValidationError-BcUV0r1I.mjs.map} +1 -1
- package/dist/Form/index.d.mts +12 -14
- package/dist/Form/index.d.mts.map +1 -1
- package/dist/Form/index.mjs +7 -10
- package/dist/Form/index.mjs.map +1 -1
- package/dist/{FormContext-CB7Glm02.mjs → FormContext-B8G_Xxd6.mjs} +49 -14
- package/dist/FormContext-B8G_Xxd6.mjs.map +1 -0
- package/dist/FormContext-BnNJYZOo.d.mts +124 -0
- package/dist/FormContext-BnNJYZOo.d.mts.map +1 -0
- package/dist/Grid/index.d.mts +0 -2
- package/dist/Grid/index.d.mts.map +1 -1
- package/dist/Grid/index.mjs +1 -2
- package/dist/{Grid-CTs-Rb9G.mjs → Grid-Us2JFczS.mjs} +3 -5
- package/dist/{Grid-CTs-Rb9G.mjs.map → Grid-Us2JFczS.mjs.map} +1 -1
- package/dist/Input/index.d.mts +14 -16
- package/dist/Input/index.d.mts.map +1 -1
- package/dist/Input/index.mjs +4 -7
- package/dist/Input/index.mjs.map +1 -1
- package/dist/RadioBoxes/index.d.mts +13 -17
- package/dist/RadioBoxes/index.d.mts.map +1 -1
- package/dist/RadioBoxes/index.mjs +3 -6
- package/dist/RadioBoxes/index.mjs.map +1 -1
- package/dist/RadioTabs/index.d.mts +46 -48
- package/dist/RadioTabs/index.d.mts.map +1 -1
- package/dist/RadioTabs/index.mjs +2 -4
- package/dist/RadioTabs/index.mjs.map +1 -1
- package/dist/Radios/index.d.mts +5 -7
- package/dist/Radios/index.d.mts.map +1 -1
- package/dist/Radios/index.mjs +2 -4
- package/dist/Radios/index.mjs.map +1 -1
- package/dist/Select/index.d.mts +28 -30
- package/dist/Select/index.d.mts.map +1 -1
- package/dist/Select/index.mjs +4 -7
- package/dist/Select/index.mjs.map +1 -1
- package/dist/Slider/index.d.mts +44 -46
- package/dist/Slider/index.d.mts.map +1 -1
- package/dist/Slider/index.mjs +2 -4
- package/dist/Slider/index.mjs.map +1 -1
- package/dist/SubmitButton/index.d.mts +0 -2
- package/dist/SubmitButton/index.d.mts.map +1 -1
- package/dist/SubmitButton/index.mjs +2 -4
- package/dist/SubmitButton/index.mjs.map +1 -1
- package/dist/Switch/index.d.mts +23 -25
- package/dist/Switch/index.d.mts.map +1 -1
- package/dist/Switch/index.mjs +2 -4
- package/dist/Switch/index.mjs.map +1 -1
- package/dist/SwitchBox/index.d.mts +39 -41
- package/dist/SwitchBox/index.d.mts.map +1 -1
- package/dist/SwitchBox/index.mjs +2 -4
- package/dist/SwitchBox/index.mjs.map +1 -1
- package/dist/TextArea/index.d.mts +11 -13
- package/dist/TextArea/index.d.mts.map +1 -1
- package/dist/TextArea/index.mjs +3 -5
- package/dist/TextArea/index.mjs.map +1 -1
- package/dist/Time/index.d.mts +11 -13
- package/dist/Time/index.d.mts.map +1 -1
- package/dist/Time/index.mjs +3 -6
- package/dist/Time/index.mjs.map +1 -1
- package/dist/helpers/index.d.mts +0 -6
- package/dist/helpers/index.d.mts.map +1 -1
- package/dist/helpers/index.mjs +3 -6
- package/dist/helpers/index.mjs.map +1 -1
- package/dist/hooks/useClientValidation/index.d.mts +0 -2
- package/dist/hooks/useClientValidation/index.d.mts.map +1 -1
- package/dist/hooks/useClientValidation/index.mjs +3 -5
- package/dist/hooks/useController/index.d.mts +1 -2
- package/dist/hooks/useController/index.mjs +2 -4
- package/dist/hooks/useFormContext/index.d.mts +2 -3
- package/dist/hooks/useFormContext/index.mjs +2 -4
- package/dist/hooks/useInput/index.mjs +2 -4
- package/dist/hooks/useInputValueDebounce/index.d.mts +2 -4
- package/dist/hooks/useInputValueDebounce/index.d.mts.map +1 -1
- package/dist/hooks/useInputValueDebounce/index.mjs +3 -5
- package/dist/hooks/useInputValueDebounce/index.mjs.map +1 -1
- package/dist/hooks/useInputValueTransform/index.d.mts +1 -1
- package/dist/hooks/useInputValueTransform/index.mjs +2 -4
- package/dist/hooks/useUniformField/index.d.mts +2 -100
- package/dist/hooks/useUniformField/index.mjs +9 -11
- package/dist/hooks/useUniformField/index.mjs.map +1 -1
- package/dist/hooks/useUniformFieldArray/index.d.mts +23 -49
- package/dist/hooks/useUniformFieldArray/index.d.mts.map +1 -1
- package/dist/hooks/useUniformFieldArray/index.mjs +3 -5
- package/dist/hooks/useUniformFieldArray/index.mjs.map +1 -1
- package/dist/hooks/useWatchFormReset/index.d.mts +0 -2
- package/dist/hooks/useWatchFormReset/index.d.mts.map +1 -1
- package/dist/hooks/useWatchFormReset/index.mjs +3 -5
- package/dist/hooks/useWatchUserChange/index.d.mts +2 -4
- package/dist/hooks/useWatchUserChange/index.d.mts.map +1 -1
- package/dist/hooks/useWatchUserChange/index.mjs +3 -5
- package/dist/hooks/useWatchUserChange/index.mjs.map +1 -1
- package/dist/index-DaiTW5Bl.d.mts +99 -0
- package/dist/index-DaiTW5Bl.d.mts.map +1 -0
- package/dist/partials/FieldCopyTestIdButton/index.d.mts +0 -2
- package/dist/partials/FieldCopyTestIdButton/index.d.mts.map +1 -1
- package/dist/partials/FieldCopyTestIdButton/index.mjs +1 -2
- package/dist/partials/FieldValidationError/index.d.mts +0 -2
- package/dist/partials/FieldValidationError/index.d.mts.map +1 -1
- package/dist/partials/FieldValidationError/index.mjs +1 -2
- package/dist/{useController-BBSbeKbn.mjs → useController-CJjMqXU5.mjs} +3 -4
- package/dist/{useController-BBSbeKbn.mjs.map → useController-CJjMqXU5.mjs.map} +1 -1
- package/dist/{useController-DcK2YHbw.d.mts → useController-CdFEp-Wa.d.mts} +2 -4
- package/dist/useController-CdFEp-Wa.d.mts.map +1 -0
- package/dist/{useFormContext-DNb_B8LQ.mjs → useFormContext-BEjPBdzb.mjs} +3 -4
- package/dist/useFormContext-BEjPBdzb.mjs.map +1 -0
- package/dist/useFormContext-BhPzFXwF.d.mts +45 -0
- package/dist/useFormContext-BhPzFXwF.d.mts.map +1 -0
- package/dist/useInput-NPbS4w_n.mjs +1 -0
- package/dist/{useInputValueTransform-DJ5zkqSy.mjs → useInputValueTransform-D44BLp1Z.mjs} +2 -3
- package/dist/{useInputValueTransform-DJ5zkqSy.mjs.map → useInputValueTransform-D44BLp1Z.mjs.map} +1 -1
- package/dist/{useInputValueTransform-LOaEim7k.d.mts → useInputValueTransform-cevZBrIN.d.mts} +3 -5
- package/dist/useInputValueTransform-cevZBrIN.d.mts.map +1 -0
- package/package.json +11 -10
- package/dist/FormContext-CB7Glm02.mjs.map +0 -1
- package/dist/FormContext-CsFiNvuJ.d.mts +0 -19
- package/dist/FormContext-CsFiNvuJ.d.mts.map +0 -1
- package/dist/hooks/useUniformField/index.d.mts.map +0 -1
- package/dist/index-CAdGtKE_.d.mts +0 -1
- package/dist/index-CwJo1b4Z.d.mts +0 -1
- package/dist/useController-DcK2YHbw.d.mts.map +0 -1
- package/dist/useFormContext-BegmYvGA.d.mts +0 -66
- package/dist/useFormContext-BegmYvGA.d.mts.map +0 -1
- package/dist/useFormContext-DNb_B8LQ.mjs.map +0 -1
- package/dist/useInput-C0aJaAGe.mjs +0 -2
- package/dist/useInputValueTransform-LOaEim7k.d.mts.map +0 -1
package/dist/Form/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/Form/subcomponents/FormDebugViewer.tsx","../../src/Form/Form.tsx","../../src/Form/index.ts"],"sourcesContent":["import type { TVClassName, TVProps } from '@fuf-stack/pixel-utils';\nimport type { CardProps } from '@fuf-stack/pixels/Card';\n\nimport { useEffect, useState } from 'react';\nimport { FaTimes } from 'react-icons/fa';\nimport { FaBug, FaBullseye } from 'react-icons/fa6';\n\nimport { tv, variantsToClassNames } from '@fuf-stack/pixel-utils';\nimport { Button } from '@fuf-stack/pixels/Button';\nimport { Card } from '@fuf-stack/pixels/Card';\nimport { Json } from '@fuf-stack/pixels/Json';\n\nimport { useFormContext } from '../../hooks/useFormContext';\nimport { redactDebugData, useSensitiveDebug } from './SensitiveFields';\n\n// form debug viewer styling variants\nexport const formDebugViewerVariants = tv({\n slots: {\n /** class of the debug card */\n base: '',\n /** class of the button that toggles the field copy testid buttons */\n copyButtonToggle: 'mb-4 ml-auto mr-auto',\n /** class of the debug card header */\n header: 'justify-between',\n /** class of the json viewer */\n json: '',\n /** class of the button that enables debug mode */\n triggerButton: 'fixed bottom-2.5 right-2.5 w-5 text-default-400',\n },\n});\n\ntype VariantProps = TVProps<typeof formDebugViewerVariants>;\ntype ClassName = TVClassName<typeof formDebugViewerVariants>;\n\nexport interface FormDebugViewerProps extends VariantProps {\n /** CSS class name */\n className?: ClassName;\n}\n\n/** Renders a form debug panel with information about the current form state */\nconst FormDebugViewer = ({ className = undefined }: FormDebugViewerProps) => {\n const {\n debugMode,\n formState: { isValid, isSubmitting, submitCount, isSubmitSuccessful },\n getValues,\n setDebugMode,\n validation: { errors },\n subscribe,\n } = useFormContext();\n\n const { paths: sensitivePaths, ready: sensitiveFieldsReady } =\n useSensitiveDebug();\n\n const showDebugButton = debugMode === 'off';\n const showDebugCard = debugMode === 'debug' || debugMode === 'debug-testids';\n const showDebugTestIds = debugMode === 'debug-testids';\n\n // classNames from slots\n const variants = formDebugViewerVariants();\n const classNames = variantsToClassNames(variants, className, 'base');\n const cardClassNames: CardProps['className'] = {\n base: classNames.base,\n header: classNames.header,\n };\n\n // We intentionally keep the local state + subscription approach here.\n // A previous useSyncExternalStore refactor caused unstable runtime behavior\n // in consuming wizard apps (max update depth loops inside react-json-view).\n // Keeping this explicit state bridge is the currently stable baseline.\n // Use subscribe instead of watch() to avoid triggering re-renders on parent components.\n // This component manages its own state and only updates itself when form values change.\n const [values, setValues] = useState<Record<string, unknown>>(() => {\n return getValues() ?? {};\n });\n\n useEffect(() => {\n // Only subscribe when debug card is visible\n if (!showDebugCard) {\n return undefined;\n }\n\n const subscription = subscribe({\n formState: { values: true },\n callback: (state) => {\n setValues(state.values ?? {});\n },\n });\n\n return () => {\n subscription();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [showDebugCard]);\n\n // handle show debug mode\n const handleShowDebugMode = () => {\n // Seed current values on open from an event handler (not effect body)\n // to avoid cascading-render lint warnings for sync setState in effects.\n setValues(getValues() ?? {});\n // set debug mode to debug\n setDebugMode('debug');\n };\n\n if (showDebugButton) {\n return (\n <Button\n ariaLabel=\"Enable form debug mode\"\n className={classNames.triggerButton}\n icon={<FaBug />}\n onClick={handleShowDebugMode}\n variant=\"light\"\n />\n );\n }\n\n // do not show card\n if (!showDebugCard || !sensitiveFieldsReady) {\n return null;\n }\n\n return (\n <Card\n className={cardClassNames}\n header={\n <>\n <span className=\"text-lg\">Debug Mode</span>\n <Button\n color=\"danger\"\n icon={<FaTimes />}\n onClick={() => {\n setDebugMode('off');\n }}\n size=\"sm\"\n variant=\"light\"\n />\n </>\n }\n >\n <Button\n className={classNames.copyButtonToggle}\n icon={<FaBullseye />}\n onClick={() => {\n setDebugMode(debugMode === 'debug' ? 'debug-testids' : 'debug');\n }}\n variant={showDebugTestIds ? 'solid' : 'light'}\n >\n {showDebugTestIds ? 'Hide CopyButton' : 'Show CopyButton'}\n </Button>\n <Json\n className={classNames.json}\n value={{\n values: redactDebugData(values, sensitivePaths),\n errors: redactDebugData(errors ?? null, sensitivePaths),\n submit: {\n isValid,\n isSubmitting,\n isSubmitSuccessful,\n submitCount,\n },\n }}\n />\n </Card>\n );\n};\n\nexport default FormDebugViewer;\n","import type { TVClassName, TVProps } from '@fuf-stack/pixel-utils';\nimport type { VetoInstance } from '@fuf-stack/veto';\nimport type { ReactNode } from 'react';\nimport type { FieldValues, SubmitHandler } from 'react-hook-form';\nimport type { DebugModeSettings } from './subcomponents/FormContext';\nimport type { FormDebugViewerProps } from './subcomponents/FormDebugViewer';\n\nimport { slugify, tv, variantsToClassNames } from '@fuf-stack/pixel-utils';\n\nimport FormProvider from './subcomponents/FormContext';\nimport FormDebugViewer from './subcomponents/FormDebugViewer';\n\nconst IS_TEST = process.env.NODE_ENV === 'test';\n\n// form styling variants\nexport const formVariants = tv({\n slots: {\n /** class of the wrapper around form and debug viewer */\n base: 'flex w-full flex-row justify-between gap-6',\n /** class of the debug viewer card */\n debugViewer: 'w-96 shrink',\n /** class of the debug viewer button that toggles the field copy testid buttons */\n debugViewerCopyButtonToggle: '',\n /** class of the debug viewer card header */\n debugViewerHeader: '',\n /** class of the debug viewer json viewer */\n debugViewerJson: '',\n /** class of the debug viewer trigger button */\n debugViewerTriggerButton: '',\n /** class of the HTML form element */\n form: 'grow',\n },\n});\n\ntype VariantProps = TVProps<typeof formVariants>;\ntype ClassName = TVClassName<typeof formVariants>;\n\nexport interface FormProps extends VariantProps {\n /** form children */\n children: ReactNode | ReactNode[];\n /** CSS class name */\n className?: ClassName;\n /** settings for from debug mode */\n debug?: DebugModeSettings;\n /** initial form values */\n initialValues?: FieldValues;\n /** name of the form */\n name?: string;\n /** form submit handler */\n onSubmit: SubmitHandler<FieldValues>;\n /** id set as the form's HTML `id`, so a SubmitButton rendered OUTSIDE this\n * form (e.g. a modal footer) can be associated with it via its own\n * `remoteFormId` prop (native HTML `form` attribute) */\n remoteFormId?: string;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n /** veto validation schema */\n validation?: VetoInstance;\n /** when the validation should be triggered */\n validationTrigger?: 'onChange' | 'onBlur' | 'onSubmit' | 'onTouched' | 'all';\n}\n\n/**\n * Form component that has to wrap every uniform\n */\nconst Form = ({\n children,\n className = undefined,\n debug = undefined,\n initialValues = undefined,\n name = undefined,\n onSubmit,\n remoteFormId = undefined,\n testId = undefined,\n validation = undefined,\n validationTrigger = 'all',\n}: FormProps) => {\n // classNames from slots\n const variants = formVariants();\n const classNames = variantsToClassNames(variants, className, 'base');\n const debugViewerClassNames: FormDebugViewerProps['className'] = {\n base: classNames.debugViewer,\n copyButtonToggle: classNames.debugViewerCopyButtonToggle,\n header: classNames.debugViewerHeader,\n json: classNames.debugViewerJson,\n triggerButton: classNames.debugViewerTriggerButton,\n };\n\n return (\n <FormProvider\n debugModeSettings={debug}\n initialValues={initialValues}\n onSubmit={onSubmit}\n validation={validation}\n validationTrigger={validationTrigger}\n >\n {({ handleSubmit, isValid }) => {\n return (\n <div className={classNames.base}>\n <form\n className={classNames.form}\n data-form-is-valid={isValid}\n data-testid={slugify(testId ?? name ?? '')}\n id={remoteFormId}\n name={name}\n // disable native HTML constraint validation so an invalid submit\n // (e.g. pressing Enter with empty required fields) still fires the\n // submit event and lets react-hook-form/veto validate and show\n // field errors, instead of the browser blocking the submit.\n noValidate\n onSubmit={handleSubmit}\n >\n {children}\n </form>\n {/* render debug viewer when not in test environment and debug not disabled */}\n {!IS_TEST && !debug?.disable && (\n <FormDebugViewer className={debugViewerClassNames} />\n )}\n </div>\n );\n }}\n </FormProvider>\n );\n};\n\nexport default Form;\n","import Form from './Form';\n\nexport type { FormProps } from './Form';\n\nexport { formVariants } from './Form';\n\nexport default Form;\n"],"mappings":";;;;;;;;;;;AAgBA,MAAa,0BAA0B,GAAG,EACxC,OAAO;;CAEL,MAAM;;CAEN,kBAAkB;;CAElB,QAAQ;;CAER,MAAM;;CAEN,eAAe;AACjB,EACF,CAAC;;AAWD,MAAM,mBAAmB,EAAE,YAAY,KAAA,QAAsC;CAC3E,MAAM,EACJ,WACA,WAAW,EAAE,SAAS,cAAc,aAAa,sBACjD,WACA,cACA,YAAY,EAAE,UACd,cACE,eAAe;CAEnB,MAAM,EAAE,OAAO,gBAAgB,OAAO,yBACpC,kBAAkB;CAEpB,MAAM,kBAAkB,cAAc;CACtC,MAAM,gBAAgB,cAAc,WAAW,cAAc;CAC7D,MAAM,mBAAmB,cAAc;CAGvC,MAAM,WAAW,wBAAwB;CACzC,MAAM,aAAa,qBAAqB,UAAU,WAAW,MAAM;CACnE,MAAM,iBAAyC;EAC7C,MAAM,WAAW;EACjB,QAAQ,WAAW;CACrB;CAQA,MAAM,CAAC,QAAQ,aAAa,eAAwC;EAClE,OAAO,UAAU,KAAK,CAAC;CACzB,CAAC;CAED,gBAAgB;EAEd,IAAI,CAAC,eACH;EAGF,MAAM,eAAe,UAAU;GAC7B,WAAW,EAAE,QAAQ,KAAK;GAC1B,WAAW,UAAU;IACnB,UAAU,MAAM,UAAU,CAAC,CAAC;GAC9B;EACF,CAAC;EAED,aAAa;GACX,aAAa;EACf;CAEF,GAAG,CAAC,aAAa,CAAC;CAGlB,MAAM,4BAA4B;EAGhC,UAAU,UAAU,KAAK,CAAC,CAAC;EAE3B,aAAa,OAAO;CACtB;CAEA,IAAI,iBACF,OACE,oBAAC,QAAD;EACE,WAAU;EACV,WAAW,W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WAAW,MAAM;CACnE,MAAM,wBAA2D;EAC/D,MAAM,WAAW;EACjB,kBAAkB,WAAW;EAC7B,QAAQ,WAAW;EACnB,MAAM,WAAW;EACjB,eAAe,WAAW;CAC5B;CAEA,OACE,oBAAC,cAAD;EACE,mBAAmB;EACJ;EACL;EACE;EACO;EAEjB,WAAA,EAAE,cAAc,cAAc;GAC9B,OACE,qBAAC,OAAD;IAAK,WAAW,WAAW;IAA3B,UAAA,CACE,oBAAC,QAAD;KACE,WAAW,WAAW;KACtB,sBAAoB;KACpB,eAAa,QAAQ,UAAU,QAAQ,EAAE;KACzC,IAAI;KACE;KAKN,YAAA;KACA,UAAU;KAET;IACG,CAAA,GAEL,CAAC,WAAW,CAAC,OAAO,WACnB,oBAAC,iBAAD,EAAiB,WAAW,sBAAwB,CAAA,CAEnD;;EAET;CACY,CAAA;AAElB;;;ACrHA,IAAA,eAAe"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/Form/subcomponents/FormDebugViewer.tsx","../../src/Form/Form.tsx","../../src/Form/index.ts"],"sourcesContent":["import type { TVClassName, TVProps } from '@fuf-stack/pixel-utils';\nimport type { CardProps } from '@fuf-stack/pixels/Card';\n\nimport { useLayoutEffect, useState } from 'react';\nimport { FaTimes } from 'react-icons/fa';\nimport { FaBug, FaBullseye } from 'react-icons/fa6';\n\nimport { tv, variantsToClassNames } from '@fuf-stack/pixel-utils';\nimport { Button } from '@fuf-stack/pixels/Button';\nimport { Card } from '@fuf-stack/pixels/Card';\nimport { Json } from '@fuf-stack/pixels/Json';\n\nimport { useFormContext } from '../../hooks/useFormContext';\nimport { redactDebugData, useSensitiveDebug } from './SensitiveFields';\n\n// form debug viewer styling variants\nexport const formDebugViewerVariants = tv({\n slots: {\n /** class of the debug card */\n base: '',\n /** class of the button that toggles the field copy testid buttons */\n copyButtonToggle: 'mb-4 ml-auto mr-auto',\n /** class of the debug card header */\n header: 'justify-between',\n /** class of the json viewer */\n json: '',\n /** class of the button that enables debug mode */\n triggerButton: 'fixed bottom-2.5 right-2.5 w-5 text-default-400',\n },\n});\n\ntype VariantProps = TVProps<typeof formDebugViewerVariants>;\ntype ClassName = TVClassName<typeof formDebugViewerVariants>;\n\nexport interface FormDebugViewerProps extends VariantProps {\n /** CSS class name */\n className?: ClassName;\n}\n\n/** Renders a form debug panel with information about the current form state */\nconst FormDebugViewer = ({ className = undefined }: FormDebugViewerProps) => {\n const {\n debugMode,\n formState: { isValid, isSubmitting, submitCount, isSubmitSuccessful },\n getValues,\n setDebugMode,\n validation: { errors },\n subscribe,\n } = useFormContext();\n\n const { paths: sensitivePaths, ready: sensitiveFieldsReady } =\n useSensitiveDebug();\n\n const showDebugButton = debugMode === 'off';\n const showDebugCard = debugMode === 'debug' || debugMode === 'debug-testids';\n const showDebugTestIds = debugMode === 'debug-testids';\n\n // classNames from slots\n const variants = formDebugViewerVariants();\n const classNames = variantsToClassNames(variants, className, 'base');\n const cardClassNames: CardProps['className'] = {\n base: classNames.base,\n header: classNames.header,\n };\n\n // We intentionally keep the local state + subscription approach here.\n // A previous useSyncExternalStore refactor caused unstable runtime behavior\n // in consuming wizard apps (max update depth loops inside react-json-view).\n // Keeping this explicit state bridge is the currently stable baseline.\n // Use subscribe instead of watch() to avoid triggering re-renders on parent components.\n // This component manages its own state and only updates itself when form values change.\n const [values, setValues] = useState<Record<string, unknown>>(() => {\n return getValues() ?? {};\n });\n\n // Subscribe before sibling fields initialize values in passive effects.\n useLayoutEffect(() => {\n // Only subscribe when debug card is visible\n if (!showDebugCard) {\n return undefined;\n }\n\n const subscription = subscribe({\n formState: { values: true },\n callback: (state) => {\n setValues(state.values ?? {});\n },\n });\n\n return () => {\n subscription();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [showDebugCard]);\n\n // handle show debug mode\n const handleShowDebugMode = () => {\n // Seed current values on open from an event handler (not effect body)\n // to avoid cascading-render lint warnings for sync setState in effects.\n setValues(getValues() ?? {});\n // set debug mode to debug\n setDebugMode('debug');\n };\n\n if (showDebugButton) {\n return (\n <Button\n ariaLabel=\"Enable form debug mode\"\n className={classNames.triggerButton}\n icon={<FaBug />}\n onClick={handleShowDebugMode}\n variant=\"light\"\n />\n );\n }\n\n // do not show card\n if (!showDebugCard || !sensitiveFieldsReady) {\n return null;\n }\n\n return (\n <Card\n className={cardClassNames}\n header={\n <>\n <span className=\"text-lg\">Debug Mode</span>\n <Button\n color=\"danger\"\n icon={<FaTimes />}\n onClick={() => {\n setDebugMode('off');\n }}\n size=\"sm\"\n variant=\"light\"\n />\n </>\n }\n >\n <Button\n className={classNames.copyButtonToggle}\n icon={<FaBullseye />}\n onClick={() => {\n setDebugMode(debugMode === 'debug' ? 'debug-testids' : 'debug');\n }}\n variant={showDebugTestIds ? 'solid' : 'light'}\n >\n {showDebugTestIds ? 'Hide CopyButton' : 'Show CopyButton'}\n </Button>\n <Json\n className={classNames.json}\n value={{\n values: redactDebugData(values, sensitivePaths),\n errors: redactDebugData(errors ?? null, sensitivePaths),\n submit: {\n isValid,\n isSubmitting,\n isSubmitSuccessful,\n submitCount,\n },\n }}\n />\n </Card>\n );\n};\n\nexport default FormDebugViewer;\n","import type { TVClassName, TVProps } from '@fuf-stack/pixel-utils';\nimport type { VetoInstance } from '@fuf-stack/veto';\nimport type { ReactNode } from 'react';\nimport type { FieldValues, SubmitHandler } from 'react-hook-form';\nimport type { DebugModeSettings } from './subcomponents/FormContext';\nimport type { FormDebugViewerProps } from './subcomponents/FormDebugViewer';\n\nimport { slugify, tv, variantsToClassNames } from '@fuf-stack/pixel-utils';\n\nimport FormProvider from './subcomponents/FormContext';\nimport FormDebugViewer from './subcomponents/FormDebugViewer';\n\nconst IS_TEST = process.env.NODE_ENV === 'test';\n\n// form styling variants\nexport const formVariants = tv({\n slots: {\n /** class of the wrapper around form and debug viewer */\n base: 'flex w-full flex-row justify-between gap-6',\n /** class of the debug viewer card */\n debugViewer: 'w-96 shrink',\n /** class of the debug viewer button that toggles the field copy testid buttons */\n debugViewerCopyButtonToggle: '',\n /** class of the debug viewer card header */\n debugViewerHeader: '',\n /** class of the debug viewer json viewer */\n debugViewerJson: '',\n /** class of the debug viewer trigger button */\n debugViewerTriggerButton: '',\n /** class of the HTML form element */\n form: 'grow',\n },\n});\n\ntype VariantProps = TVProps<typeof formVariants>;\ntype ClassName = TVClassName<typeof formVariants>;\n\nexport interface FormProps extends VariantProps {\n /** form children */\n children: ReactNode | ReactNode[];\n /** CSS class name */\n className?: ClassName;\n /** settings for from debug mode */\n debug?: DebugModeSettings;\n /** initial form values */\n initialValues?: FieldValues;\n /** name of the form */\n name?: string;\n /** form submit handler */\n onSubmit: SubmitHandler<FieldValues>;\n /** id set as the form's HTML `id`, so a SubmitButton rendered OUTSIDE this\n * form (e.g. a modal footer) can be associated with it via its own\n * `remoteFormId` prop (native HTML `form` attribute) */\n remoteFormId?: string;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n /** veto validation schema */\n validation?: VetoInstance;\n /** when the validation should be triggered */\n validationTrigger?: 'onChange' | 'onBlur' | 'onSubmit' | 'onTouched' | 'all';\n}\n\n/**\n * Form component that has to wrap every uniform\n */\nconst Form = ({\n children,\n className = undefined,\n debug = undefined,\n initialValues = undefined,\n name = undefined,\n onSubmit,\n remoteFormId = undefined,\n testId = undefined,\n validation = undefined,\n validationTrigger = 'all',\n}: FormProps) => {\n // classNames from slots\n const variants = formVariants();\n const classNames = variantsToClassNames(variants, className, 'base');\n const debugViewerClassNames: FormDebugViewerProps['className'] = {\n base: classNames.debugViewer,\n copyButtonToggle: classNames.debugViewerCopyButtonToggle,\n header: classNames.debugViewerHeader,\n json: classNames.debugViewerJson,\n triggerButton: classNames.debugViewerTriggerButton,\n };\n\n return (\n <FormProvider\n debugModeSettings={debug}\n initialValues={initialValues}\n onSubmit={onSubmit}\n validation={validation}\n validationTrigger={validationTrigger}\n >\n {({ handleSubmit, isValid }) => {\n return (\n <div className={classNames.base}>\n <form\n className={classNames.form}\n data-form-is-valid={isValid}\n data-testid={slugify(testId ?? name ?? '')}\n id={remoteFormId}\n name={name}\n // disable native HTML constraint validation so an invalid submit\n // (e.g. pressing Enter with empty required fields) still fires the\n // submit event and lets react-hook-form/veto validate and show\n // field errors, instead of the browser blocking the submit.\n noValidate\n onSubmit={handleSubmit}\n >\n {children}\n </form>\n {/* render debug viewer when not in test environment and debug not disabled */}\n {!IS_TEST && !debug?.disable && (\n <FormDebugViewer className={debugViewerClassNames} />\n )}\n </div>\n );\n }}\n </FormProvider>\n );\n};\n\nexport default Form;\n","import Form from './Form';\n\nexport type { FormProps } from './Form';\n\nexport { formVariants } from './Form';\n\nexport default Form;\n"],"mappings":";;;;;;;;;;;AAgBA,MAAa,0BAA0B,GAAG,EACxC,OAAO;;CAEL,MAAM;;CAEN,kBAAkB;;CAElB,QAAQ;;CAER,MAAM;;CAEN,eAAe;AACjB,EACF,CAAC;;AAWD,MAAM,mBAAmB,EAAE,YAAY,KAAA,QAAsC;CAC3E,MAAM,EACJ,WACA,WAAW,EAAE,SAAS,cAAc,aAAa,sBACjD,WACA,cACA,YAAY,EAAE,UACd,cACE,eAAe;CAEnB,MAAM,EAAE,OAAO,gBAAgB,OAAO,yBACpC,kBAAkB;CAEpB,MAAM,kBAAkB,cAAc;CACtC,MAAM,gBAAgB,cAAc,WAAW,cAAc;CAC7D,MAAM,mBAAmB,cAAc;CAGvC,MAAM,WAAW,wBAAwB;CACzC,MAAM,aAAa,qBAAqB,UAAU,WAAW,MAAM;CACnE,MAAM,iBAAyC;EAC7C,MAAM,WAAW;EACjB,QAAQ,WAAW;CACrB;CAQA,MAAM,CAAC,QAAQ,aAAa,eAAwC;EAClE,OAAO,UAAU,KAAK,CAAC;CACzB,CAAC;CAGD,sBAAsB;EAEpB,IAAI,CAAC,eACH;EAGF,MAAM,eAAe,UAAU;GAC7B,WAAW,EAAE,QAAQ,KAAK;GAC1B,WAAW,UAAU;IACnB,UAAU,MAAM,UAAU,CAAC,CAAC;GAC9B;EACF,CAAC;EAED,aAAa;GAC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Z,QAAQ,KAAA,GACR,gBAAgB,KAAA,GAChB,OAAO,KAAA,GACP,UACA,eAAe,KAAA,GACf,SAAS,KAAA,GACT,aAAa,KAAA,GACb,oBAAoB,YACL;CAEf,MAAM,WAAW,aAAa;CAC9B,MAAM,aAAa,qBAAqB,UAAU,WAAW,MAAM;CACnE,MAAM,wBAA2D;EAC/D,MAAM,WAAW;EACjB,kBAAkB,WAAW;EAC7B,QAAQ,WAAW;EACnB,MAAM,WAAW;EACjB,eAAe,WAAW;CAC5B;CAEA,OACE,oBAAC,cAAD;EACE,mBAAmB;EACJ;EACL;EACE;EACO;EAEjB,WAAA,EAAE,cAAc,cAAc;GAC9B,OACE,qBAAC,OAAD;IAAK,WAAW,WAAW;IAA3B,UAAA,CACE,oBAAC,QAAD;KACE,WAAW,WAAW;KACtB,sBAAoB;KACpB,eAAa,QAAQ,UAAU,QAAQ,EAAE;KACzC,IAAI;KACE;KAKN,YAAA;KACA,UAAU;KAET;IACG,CAAA,GAEL,CAAC,WAAW,CAAC,OAAO,WACnB,oBAAC,iBAAD,EAAiB,WAAW,sBAAwB,CAAA,CAEnD;;EAET;CACY,CAAA;AAElB;;ACrHA,IAAA,eAAe"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { toFormFormat, toSubmitFormat, toValidationFormat } from "./helpers/index.mjs";
|
|
1
|
+
import { flatArrayKey, toFormFormat, toSubmitFormat, toValidationFormat } from "./helpers/index.mjs";
|
|
2
2
|
import React, { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
3
3
|
import { useLocalStorage } from "@fuf-stack/pixels";
|
|
4
4
|
import { jsx } from "react/jsx-runtime";
|
|
5
5
|
import { FormProvider, useForm } from "react-hook-form";
|
|
6
6
|
import createDebug from "debug";
|
|
7
7
|
import { and, veto } from "@fuf-stack/veto";
|
|
8
|
-
|
|
8
|
+
// src/Form/subcomponents/SensitiveFields.tsx
|
|
9
9
|
/**
|
|
10
10
|
* Diagnostic redaction for explicitly registered form paths.
|
|
11
11
|
*
|
|
@@ -197,8 +197,25 @@ const useSensitiveDebug = () => {
|
|
|
197
197
|
const registry = useContext(SensitiveFieldsContext) ?? defaultSensitiveFields;
|
|
198
198
|
return useSyncExternalStore(registry.subscribe, registry.getSnapshot, registry.getSnapshot);
|
|
199
199
|
};
|
|
200
|
-
|
|
201
|
-
|
|
200
|
+
// src/helpers/disabledFields/disabledFields.ts
|
|
201
|
+
/** Removes one path by copying only its ancestors, leaving stored values and array indices intact. */
|
|
202
|
+
const omitPath = (value, [key, ...rest]) => {
|
|
203
|
+
if (!value || typeof value !== "object" || key === void 0 || !Object.getOwnPropertyDescriptor(value, key)) return value;
|
|
204
|
+
const copy = Array.isArray(value) ? value.slice() : { ...value };
|
|
205
|
+
if (rest.length) copy[key] = omitPath(copy[key], rest);
|
|
206
|
+
else delete copy[key];
|
|
207
|
+
return copy;
|
|
208
|
+
};
|
|
209
|
+
/** Omits disabled fields from normalized validation/submission data without changing form state. */
|
|
210
|
+
const omitDisabledValues = (values, names) => {
|
|
211
|
+
return names.reduce((data, name) => {
|
|
212
|
+
const path = name.replace(/\[(\d+)\]/g, ".$1").split(".").filter((part) => {
|
|
213
|
+
return part !== flatArrayKey;
|
|
214
|
+
});
|
|
215
|
+
return omitPath(data, path);
|
|
216
|
+
}, values);
|
|
217
|
+
};
|
|
218
|
+
// src/Form/subcomponents/FormResolver.ts
|
|
202
219
|
/**
|
|
203
220
|
* Hook that manages client validation schemas state.
|
|
204
221
|
*
|
|
@@ -266,14 +283,26 @@ const useExtendedValidation = (baseValidation) => {
|
|
|
266
283
|
* Creates a React Hook Form resolver from an extended validation instance and
|
|
267
284
|
* stores its latest formatted Veto errors as React state.
|
|
268
285
|
*
|
|
286
|
+
* Bind the owning RHF control before validation runs. Each resolver call omits
|
|
287
|
+
* disabled values from normalized input and validated output while preserving
|
|
288
|
+
* stored form values. The schema stays unchanged, so required fields can still
|
|
289
|
+
* report missing-value errors and defaults cannot restore disabled output.
|
|
290
|
+
*
|
|
269
291
|
* Keeping the resolver errors in state lets Uniform context consumers re-render
|
|
270
292
|
* when validation output changes, while the hash prevents repeated validations
|
|
271
293
|
* with equivalent errors from causing unnecessary updates.
|
|
272
294
|
*
|
|
273
295
|
* @param extendedValidation - Extended validation instance from useExtendedValidation
|
|
274
|
-
* @returns Resolver
|
|
296
|
+
* @returns Resolver, validation error state, and a binder for the owning RHF control
|
|
275
297
|
*/
|
|
276
298
|
const useFormResolver = (extendedValidation) => {
|
|
299
|
+
const control = useRef(null);
|
|
300
|
+
const bindControl = useCallback((instance) => {
|
|
301
|
+
control.current = instance;
|
|
302
|
+
return () => {
|
|
303
|
+
if (control.current === instance) control.current = null;
|
|
304
|
+
};
|
|
305
|
+
}, []);
|
|
277
306
|
const [validationErrorsState, setValidationErrorsState] = useState({
|
|
278
307
|
errors: void 0,
|
|
279
308
|
hash: void 0
|
|
@@ -295,15 +324,19 @@ const useFormResolver = (extendedValidation) => {
|
|
|
295
324
|
});
|
|
296
325
|
}, []);
|
|
297
326
|
return {
|
|
327
|
+
bindControl,
|
|
298
328
|
resolver: useMemo(() => {
|
|
299
329
|
if (!extendedValidation) return;
|
|
300
330
|
return async (values) => {
|
|
301
331
|
const validationValues = toValidationFormat(values) ?? {};
|
|
302
|
-
const
|
|
332
|
+
const disabledFields = [...control.current?._names.disabled ?? []];
|
|
333
|
+
const validationInput = omitDisabledValues(validationValues, disabledFields);
|
|
334
|
+
const result = await extendedValidation.validateAsync(validationInput);
|
|
303
335
|
updateValidationErrors(result.errors ?? void 0);
|
|
336
|
+
const submissionValues = omitDisabledValues(result.data ?? {}, disabledFields);
|
|
304
337
|
return {
|
|
305
|
-
|
|
306
|
-
|
|
338
|
+
errors: result.errors ?? {},
|
|
339
|
+
values: submissionValues
|
|
307
340
|
};
|
|
308
341
|
};
|
|
309
342
|
}, [extendedValidation, updateValidationErrors]),
|
|
@@ -311,8 +344,7 @@ const useFormResolver = (extendedValidation) => {
|
|
|
311
344
|
validationErrorsHash: validationErrorsState.hash
|
|
312
345
|
};
|
|
313
346
|
};
|
|
314
|
-
|
|
315
|
-
//#region src/Form/subcomponents/FormContext.tsx
|
|
347
|
+
// src/Form/subcomponents/FormContext.tsx
|
|
316
348
|
const debug = createDebug("uniform:FormContext");
|
|
317
349
|
const DEBUG_MODE_LOCAL_STORAGE_KEY_DEFAULT = "uniform:debug-mode";
|
|
318
350
|
if (!window.__UNIFORM_CONTEXT__) {
|
|
@@ -347,6 +379,7 @@ debug("UniformContext exported", {
|
|
|
347
379
|
* FormProvider component provides:
|
|
348
380
|
* - Veto validation schema context
|
|
349
381
|
* - Resolver-backed validation error state
|
|
382
|
+
* - RHF control binding for disabled-value omission without changing schema rules
|
|
350
383
|
* - Client validation schema management
|
|
351
384
|
* - Submit handler with automatic data conversion and submission control with preventSubmit
|
|
352
385
|
* - Form Debug Mode state
|
|
@@ -360,12 +393,15 @@ const FormProvider$1 = ({ children, debugModeSettings = void 0, initialValues =
|
|
|
360
393
|
}, []);
|
|
361
394
|
const [debugMode, setDebugMode] = useLocalStorage(debugModeSettings?.localStorageKey ?? DEBUG_MODE_LOCAL_STORAGE_KEY_DEFAULT, "off");
|
|
362
395
|
const { extendedValidation, setClientValidationSchema } = useExtendedValidation(baseValidation);
|
|
363
|
-
const { resolver, validationErrors, validationErrorsHash } = useFormResolver(extendedValidation);
|
|
396
|
+
const { bindControl, resolver, validationErrors, validationErrorsHash } = useFormResolver(extendedValidation);
|
|
364
397
|
const methods = useForm({
|
|
365
398
|
defaultValues: initialValues ? toFormFormat(initialValues) : initialValues,
|
|
366
399
|
mode: validationTrigger,
|
|
367
400
|
resolver
|
|
368
401
|
});
|
|
402
|
+
useLayoutEffect(() => {
|
|
403
|
+
return bindControl(methods.control);
|
|
404
|
+
}, [bindControl, methods.control]);
|
|
369
405
|
const isValid = methods.formState?.isValid;
|
|
370
406
|
const [preventSubmit, setPreventSubmit] = useState(false);
|
|
371
407
|
const formResetListenersRef = useRef(/* @__PURE__ */ new Set());
|
|
@@ -416,7 +452,7 @@ const FormProvider$1 = ({ children, debugModeSettings = void 0, initialValues =
|
|
|
416
452
|
});
|
|
417
453
|
const wrappedOnSubmit = (data, event) => {
|
|
418
454
|
const submitData = toSubmitFormat(data) ?? {};
|
|
419
|
-
debug("onSubmit callback called", { submitData: sensitiveFields.redact(
|
|
455
|
+
debug("onSubmit callback called", { submitData: toSubmitFormat(sensitiveFields.redact(data)) ?? {} });
|
|
420
456
|
return onSubmit(submitData, event);
|
|
421
457
|
};
|
|
422
458
|
await methods.handleSubmit(wrappedOnSubmit)(e);
|
|
@@ -471,7 +507,6 @@ const FormProvider$1 = ({ children, debugModeSettings = void 0, initialValues =
|
|
|
471
507
|
})
|
|
472
508
|
});
|
|
473
509
|
};
|
|
474
|
-
//#endregion
|
|
475
510
|
export { useSensitiveField as a, useSensitiveDebug as i, UniformContext as n, redactDebugData as r, FormProvider$1 as t };
|
|
476
511
|
|
|
477
|
-
//# sourceMappingURL=FormContext-
|
|
512
|
+
//# sourceMappingURL=FormContext-B8G_Xxd6.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"FormContext-B8G_Xxd6.mjs","names":["FormProvider","HookFormProvider"],"sources":["../src/Form/subcomponents/SensitiveFields.tsx","../src/helpers/disabledFields/disabledFields.ts","../src/Form/subcomponents/FormResolver.ts","../src/Form/subcomponents/FormContext.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport {\n createContext,\n useContext,\n useLayoutEffect,\n useSyncExternalStore,\n} from 'react';\n\n/**\n * Diagnostic redaction for explicitly registered form paths.\n *\n * Flow:\n * 1. FormProvider creates one registry for its form and supplies it through context.\n * 2. useUniformField calls useSensitiveField for declared password inputs and\n * fields marked sensitive. This module does not infer secrets from names,\n * inspect the DOM, or search strings for password-like content.\n * 3. Field layout effects register their paths before the provider marks the\n * initial registry ready. The debug viewer waits for that ready signal.\n * 4. The viewer and Uniform's debug logger redact diagnostic copies using the\n * same registry. JSON copy actions receive the viewer's redacted data too.\n *\n * This is protection against accidental disclosure in Uniform diagnostics,\n * not encryption or a boundary against browser inspection. Real values remain\n * available to inputs, validation, submission, and application callbacks.\n * Application logging and secrets embedded in unrelated paths/custom messages\n * are outside this path-based redaction mechanism.\n */\n\n// A fixed placeholder avoids exposing the secret's content, type, or length.\nconst REDACTED = '[REDACTED]';\n\n/**\n * Build a diagnostic copy with each registered field replaced by [REDACTED].\n *\n * Matching a field masks its entire subtree. For validation errors, that also\n * removes error metadata/messages beneath that field, which may contain input.\n * The source object is never changed: redacting form state itself would corrupt\n * validation and the values ultimately delivered to onSubmit.\n *\n * Paths use React Hook Form dot notation, with numeric bracket indices accepted\n * as well. Normalization removes Uniform's __FLAT__ transport wrapper so the\n * same registration covers raw form data and normalized/submitted array values.\n *\n * Traversal covers arrays and plain objects. Non-data instances such as dates\n * and DOM refs are preserved unless their path or an ancestor is sensitive.\n * This is deliberately not a general-purpose serializer or secret detector.\n *\n * @param data - Form values or errors destined for Uniform diagnostics\n * @param paths - Sensitive field paths registered for this form\n * @returns A diagnostic copy with registered fields replaced, or the unchanged\n * primitive/non-data instance when no traversal is necessary\n */\nexport const redactDebugData = (\n data: unknown,\n paths: readonly string[],\n): unknown => {\n const sensitivePaths = new Set(\n paths.map((path) => {\n return path\n .replace(/\\[(\\d+)\\]/g, '.$1')\n .split('.')\n .filter((part) => {\n return part !== '__FLAT__';\n })\n .join('.');\n }),\n );\n // Track only the current recursion's ancestors. This breaks traversal cycles\n // without reusing a differently redacted copy at another field path.\n const copies = new WeakMap<object, unknown>();\n const visit = (value: unknown, path: string): unknown => {\n // Check before descending or returning an object reference: a sensitive\n // field must be replaced wholesale, even when its value is an object.\n if (sensitivePaths.has(path)) {\n return REDACTED;\n }\n if (!value || typeof value !== 'object') {\n return value;\n }\n const existing = copies.get(value);\n if (existing) {\n return existing;\n }\n if (Array.isArray(value)) {\n const copy: unknown[] = [];\n copies.set(value, copy);\n value.forEach((item, index) => {\n copy[index] = visit(item, path ? `${path}.${index}` : String(index));\n });\n copies.delete(value);\n return copy;\n }\n // Preserve non-data objects, such as dates and refs in non-sensitive errors.\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n return value;\n }\n const copy: Record<string, unknown> = {};\n copies.set(value, copy);\n Object.entries(value as Record<string, unknown>).forEach(([key, entry]) => {\n // Define an own property rather than assigning through __proto__ or any\n // inherited setter when copying arbitrary form-data keys.\n Object.defineProperty(copy, key, {\n value: visit(entry, path ? `${path}.${key}` : key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n });\n // Cache only ancestors for cycle handling: shared objects at other paths\n // need their own redaction pass because sensitivity belongs to the path.\n copies.delete(value);\n return copy;\n };\n return visit(data, '');\n};\n\n/**\n * Create an isolated, append-only sensitivity registry for one form instance.\n *\n * Only field paths and readiness are stored here; the registry does not retain\n * password values. Paths intentionally survive input unmounts, resets, and a\n * later sensitive=false declaration because RHF can retain the original value.\n * A new form instance gets a fresh registry; there is no cross-form path sharing.\n *\n * Snapshot objects stay referentially stable until metadata actually changes.\n * useSyncExternalStore depends on that stability to avoid repeated renders.\n */\nexport const createSensitiveFields = () => {\n let snapshot: { paths: readonly string[]; ready: boolean } = {\n paths: [],\n ready: false,\n };\n const listeners = new Set<() => void>();\n const notify = () => {\n listeners.forEach((listener) => {\n listener();\n });\n };\n return {\n /** Return the current stable metadata snapshot, without reading form values. */\n getSnapshot: () => {\n return snapshot;\n },\n /** Subscribe to metadata changes; cleanup removes the listener, not paths. */\n subscribe: (listener: () => void) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n /** Mark a path once; duplicate registrations and Strict Mode repeats are safe. */\n register: (name: string) => {\n if (snapshot.paths.includes(name)) {\n return;\n }\n // RHF retains values for unmounted fields. Retain their sensitivity for\n // the form's lifetime too, so hiding an input never reveals its secret.\n snapshot = { ...snapshot, paths: [...snapshot.paths, name] };\n notify();\n },\n /** Allow the debug viewer to render after initial field registration finishes. */\n ready: () => {\n if (snapshot.ready) {\n return;\n }\n snapshot = { ...snapshot, ready: true };\n notify();\n },\n /** Use the latest paths for logs, even while the debug viewer is closed. */\n redact: (data: unknown) => {\n return redactDebugData(data, snapshot.paths);\n },\n };\n};\n\ntype SensitiveFields = ReturnType<typeof createSensitiveFields>;\n// An immutable-in-practice empty fallback supports isolated viewer tests and\n// consumers without this provider. useSensitiveField never writes to it, so it\n// cannot leak registrations between unrelated forms or component tests.\nconst defaultSensitiveFields = createSensitiveFields();\ndefaultSensitiveFields.ready();\nconst SensitiveFieldsContext = createContext<SensitiveFields | undefined>(\n undefined,\n);\n\n/**\n * Supply the form-owned registry and release the initial debug-render gate.\n *\n * React runs descendant layout effects before this provider's layout effect,\n * so initially mounted fields register before ready becomes true. The viewer\n * must not render raw values while ready is false, even if debug mode was\n * restored from localStorage before the form's first render.\n */\nexport const SensitiveFieldsProvider = ({\n children,\n registry,\n}: {\n children: ReactNode;\n registry: SensitiveFields;\n}) => {\n // Child layout effects register initial fields before debug data is shown.\n useLayoutEffect(() => {\n registry.ready();\n }, [registry]);\n return (\n <SensitiveFieldsContext.Provider value={registry}>\n {children}\n </SensitiveFieldsContext.Provider>\n );\n};\n\n/**\n * Register a field's sensitivity as declared by its renderer/shared field hook.\n *\n * Registration happens during commit, not render, so abandoned React renders\n * cannot mutate the registry. Layout timing makes new registrations available\n * before paint. Password detection uses the declared input type in\n * useUniformField, so toggling the rendered type to text does not reveal debug\n * values. Once registered, a path is never downgraded within this form instance.\n *\n * @param name - The field path used for form registration\n * @param sensitive - Whether the renderer declares this field sensitive\n */\nexport const useSensitiveField = (name: string, sensitive: boolean) => {\n const registry = useContext(SensitiveFieldsContext);\n useLayoutEffect(() => {\n if (sensitive) {\n registry?.register(name);\n }\n }, [registry, name, sensitive]);\n};\n\n/**\n * Observe sensitivity metadata for rendering diagnostic copies.\n *\n * This subscription contains neither passwords nor RHF's mutable value objects.\n * The debug viewer keeps its existing value subscription and applies these paths\n * when handing values/errors to Json; getValues and onSubmit stay untouched.\n * Callers must honor ready before exposing an initial diagnostic payload.\n */\nexport const useSensitiveDebug = () => {\n const registry = useContext(SensitiveFieldsContext) ?? defaultSensitiveFields;\n // Subscribe only to stable metadata snapshots, not RHF's mutable value objects.\n return useSyncExternalStore(\n registry.subscribe,\n registry.getSnapshot,\n registry.getSnapshot,\n );\n};\n","import type { FieldValues } from 'react-hook-form';\n\nimport { flatArrayKey } from '../nullishFields/nullishFields';\n\n/** Removes one path by copying only its ancestors, leaving stored values and array indices intact. */\nconst omitPath = (\n value: unknown,\n [key, ...rest]: readonly string[],\n): unknown => {\n if (\n !value ||\n typeof value !== 'object' ||\n key === undefined ||\n !Object.getOwnPropertyDescriptor(value, key)\n ) {\n return value;\n }\n\n // Preserve holes left by previously omitted array entries.\n const copy = (Array.isArray(value) ? value.slice() : { ...value }) as Record<\n string,\n unknown\n >;\n\n if (rest.length) {\n copy[key] = omitPath(copy[key], rest);\n } else {\n // Delete rather than splice so later array fields keep their indices.\n delete copy[key];\n }\n\n return copy;\n};\n\n/** Omits disabled fields from normalized validation/submission data without changing form state. */\nconst omitDisabledValues = (\n values: FieldValues,\n names: readonly string[],\n): FieldValues => {\n return names.reduce((data, name) => {\n // Match RHF names to normalized data, where flat-array wrappers are gone.\n const path = name\n .replace(/\\[(\\d+)\\]/g, '.$1')\n .split('.')\n .filter((part) => {\n return part !== flatArrayKey;\n });\n\n return omitPath(data, path) as FieldValues;\n }, values);\n};\n\nexport default omitDisabledValues;\n","import type {\n VetoFormattedError,\n VetoInstance,\n VetoTypeAny,\n} from '@fuf-stack/veto';\nimport type { Control, FieldValues } from 'react-hook-form';\n\nimport { useCallback, useMemo, useRef, useState } from 'react';\n\nimport { and, veto } from '@fuf-stack/veto';\n\nimport { toValidationFormat } from '../../helpers';\nimport omitDisabledValues from '../../helpers/disabledFields/disabledFields';\n\n/**\n * Hook that manages client validation schemas state.\n *\n * Provides a centralized way to add/remove dynamic validation schemas\n * that can be combined with base form validation.\n *\n * @returns Object with client validation state and memoized setter function\n */\nexport const useClientValidationManager = () => {\n // Client validation schemas state\n const [clientValidationSchemas, setClientValidationSchemas] = useState<\n Record<string, VetoTypeAny>\n >({});\n\n // Memoized function to set/clear client validation schema\n const setClientValidationSchema = useMemo(() => {\n return (key: string, schema: VetoTypeAny | null) => {\n // update client validation schemas\n setClientValidationSchemas((prev) => {\n // if no schema and no existing client validation schema for this key, do nothing\n if (!prev[key] && !schema) {\n return prev;\n }\n // if no schema, remove the client validation schema for this key\n if (!schema) {\n const { [key]: _removed, ...rest } = prev;\n return rest;\n }\n // if schema, add or update the client validation schema for this key\n return { ...prev, [key]: schema };\n });\n };\n }, []);\n\n return {\n clientValidationSchemas,\n setClientValidationSchema,\n };\n};\n\n/**\n * Hook that creates an extended validation instance combining base Veto validation with dynamic client validation.\n *\n * @param baseValidation - Optional base Veto validation schema\n * @returns Combined validation instance and client schema setter\n */\nexport const useExtendedValidation = (baseValidation?: VetoInstance) => {\n // Setup client validation schemas\n const { clientValidationSchemas, setClientValidationSchema } =\n useClientValidationManager();\n\n // Create a stable dependency array from the client validation schemas\n const clientSchemaValues = useMemo<VetoTypeAny[]>(\n () => {\n const keys = Object.keys(clientValidationSchemas).sort();\n return keys\n .map((key) => {\n return clientValidationSchemas[key];\n })\n .filter((schema): schema is VetoTypeAny => {\n return Boolean(schema);\n });\n },\n // Include the object identity to react to schema instance updates with same shape\n [clientValidationSchemas],\n );\n\n // Memoized extended validation instance\n const extendedValidation = useMemo(\n () => {\n const hasBaseValidation = !!baseValidation;\n const hasClientSchemas = clientSchemaValues.length > 0;\n\n // If no base validation and no client schemas, return undefined\n if (!hasBaseValidation && !hasClientSchemas) {\n return undefined;\n }\n\n // If no client schemas, return base validation\n if (!hasClientSchemas) {\n return baseValidation;\n }\n\n // Combine client validation schemas\n const clientSchemasCombined =\n clientSchemaValues.reduce<VetoTypeAny | null>(\n (combined, clientSchema) => {\n return combined ? and(combined, clientSchema) : clientSchema;\n },\n null,\n );\n\n // return combined validation\n if (baseValidation && clientSchemasCombined) {\n // Put client validation first so dynamic/domain-specific messages\n // are returned before generic base validation errors.\n const baseSchema = baseValidation.schema as VetoTypeAny;\n return veto(and(clientSchemasCombined, baseSchema));\n }\n\n // If we only have client schemas, return them as a veto instance\n if (clientSchemasCombined) {\n return veto(clientSchemasCombined);\n }\n\n // This should not happen due to the conditions above, but just in case\n return baseValidation;\n },\n // Recompute when validation schema instances change\n [baseValidation, clientSchemaValues],\n );\n\n return {\n extendedValidation,\n setClientValidationSchema,\n };\n};\n\n/**\n * Render state for formatted validation errors produced by the resolver.\n *\n * `errors` is the value exposed through Uniform context. `hash` is the stable\n * comparison key used to avoid re-rendering context consumers when validation\n * returns an equivalent error object with a new identity.\n */\ninterface ValidationErrorsState {\n /** Formatted validation errors exposed to Uniform consumers. */\n errors: VetoFormattedError | undefined;\n /** JSON hash of `errors`, used as a cheap equality signal. */\n hash: string | undefined;\n}\n\n/**\n * Creates a React Hook Form resolver from an extended validation instance and\n * stores its latest formatted Veto errors as React state.\n *\n * Bind the owning RHF control before validation runs. Each resolver call omits\n * disabled values from normalized input and validated output while preserving\n * stored form values. The schema stays unchanged, so required fields can still\n * report missing-value errors and defaults cannot restore disabled output.\n *\n * Keeping the resolver errors in state lets Uniform context consumers re-render\n * when validation output changes, while the hash prevents repeated validations\n * with equivalent errors from causing unnecessary updates.\n *\n * @param extendedValidation - Extended validation instance from useExtendedValidation\n * @returns Resolver, validation error state, and a binder for the owning RHF control\n */\nexport const useFormResolver = (extendedValidation?: VetoInstance) => {\n const control = useRef<Control | null>(null);\n\n // Resolver options only contain the triggered fields. Bind the complete RHF\n // control so disabled siblings and registry changes after reset are visible.\n const bindControl = useCallback((instance: Control) => {\n control.current = instance;\n return () => {\n if (control.current === instance) {\n control.current = null;\n }\n };\n }, []);\n\n // Keep the latest resolver errors in React state so Uniform context consumers\n // re-render when validation output changes. The paired hash lets us skip the\n // state update when a resolver run returns equivalent errors.\n const [validationErrorsState, setValidationErrorsState] =\n useState<ValidationErrorsState>({\n errors: undefined,\n hash: undefined,\n });\n\n /**\n * Updates resolver error state only when the formatted validation result\n * actually changes. Veto/RHF may create new error objects for equivalent\n * validation output, so the hash is the guard against avoidable context\n * refreshes.\n */\n const updateValidationErrors = useCallback(\n (errors: VetoFormattedError | undefined): void => {\n const nextHash = JSON.stringify(errors);\n\n setValidationErrorsState((current) => {\n if (current.hash === nextHash) {\n return current;\n }\n\n return {\n errors,\n hash: nextHash,\n };\n });\n },\n [],\n );\n\n // Memoized resolver function for React Hook Form\n const resolver = useMemo(() => {\n if (!extendedValidation) {\n return undefined;\n }\n\n return async (values: FieldValues) => {\n const validationValues = toValidationFormat(values) ?? {};\n\n // RHF exposes no public complete disabled registry; this relies on its\n // internal control structure and needs checking when upgrading RHF.\n // Use one snapshot even if a field changes state during async validation.\n const disabledFields = [...(control.current?._names.disabled ?? [])];\n\n // Omit values, not schema rules: required disabled fields must still fail.\n const validationInput = omitDisabledValues(\n validationValues,\n disabledFields,\n );\n const result = await extendedValidation.validateAsync(validationInput);\n updateValidationErrors(result.errors ?? undefined);\n\n // Omit disabled values again because schema defaults or transforms may\n // have added them back to the output.\n const submissionValues = omitDisabledValues(\n result.data ?? {},\n disabledFields,\n );\n\n return {\n errors: result.errors ?? {},\n values: submissionValues,\n };\n };\n }, [extendedValidation, updateValidationErrors]);\n\n return {\n bindControl,\n resolver,\n validationErrors: validationErrorsState.errors,\n validationErrorsHash: validationErrorsState.hash,\n };\n};\n","import type {\n VetoFormattedError,\n VetoInstance,\n VetoTypeAny,\n} from '@fuf-stack/veto';\nimport type { BaseSyntheticEvent, ReactNode } from 'react';\nimport type { FieldValues, Path, SubmitHandler } from 'react-hook-form';\n\nimport React, {\n useCallback,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { FormProvider as HookFormProvider, useForm } from 'react-hook-form';\n\nimport createDebug from 'debug';\n\nimport { useLocalStorage } from '@fuf-stack/pixels';\n\nimport { toFormFormat, toSubmitFormat } from '../../helpers';\nimport { useExtendedValidation, useFormResolver } from './FormResolver';\nimport {\n createSensitiveFields,\n SensitiveFieldsProvider,\n} from './SensitiveFields';\n\nconst debug = createDebug('uniform:FormContext');\n\ntype DebugMode = 'debug' | 'debug-testids' | 'off' | 'disabled';\n\nexport interface DebugModeSettings {\n /** disable form debug completely */\n disable?: boolean;\n /** custom localStorage key to save debug mode state */\n localStorageKey?: string;\n}\n\n/** Listener function that gets called when a form reset is triggered */\nexport type FormResetListener = () => void;\n\n/**\n * Listener function that gets called when a field changes due to user input\n */\nexport type UserChangeListener<TFieldValues extends object = object> = (\n fieldName: Path<TFieldValues>,\n value: unknown,\n) => void;\n\nconst DEBUG_MODE_LOCAL_STORAGE_KEY_DEFAULT = 'uniform:debug-mode';\n\n/**\n * The `UniformContext` provides control over the form's submission behavior and may optionally include\n * a Veto validation schema for form validation.\n *\n * Specifically, this context offers:\n * 1. **Form Submission Control**: The `preventSubmit` function allows components to enable or disable\n * form submissions.\n * 2. **Optional Validation Schema**: The `validation` property may hold a Veto validation schema instance\n * that can be used to validate form fields and handle validation logic.\n * 3. **Client Validation**: The `setClientValidationSchema` function allows setting dynamic client-side\n * validation schemas that complement the base Veto validation.\n * 4. **User Change Tracking**: The `userChange` property provides a pub/sub system for tracking\n * user-initiated field changes (typing, clicking, selecting) - NOT programmatic changes like\n * form.reset() or form.setValue(). Used by the `useWatchUserChange` hook to enable reactive\n * field dependencies.\n * 5. **Form Reset Tracking**: The `formReset` property provides a pub/sub system for tracking\n * programmatic form resets triggered via the wrapped `reset()` from `useFormContext`.\n * Used by hooks like `useWatchFormReset` to run reset-specific normalization logic.\n *\n * This context is useful for components that need to interact with or control the form submission state,\n * or access the validation schema for managing form validation logic.\n *\n * IMPORTANT: Context Singleton Pattern for HMR (Hot Module Replacement)\n * =====================================================================\n *\n * We use a global window variable to ensure only ONE context instance exists across\n * hot module reloads during development. This is critical because:\n *\n * **The Problem:**\n * When using Vite/Storybook with Fast Refresh (HMR), editing this file causes it to\n * be re-evaluated. Each re-evaluation runs `React.createContext()` again, creating a\n * NEW context instance. This leads to \"context instance mismatch\":\n *\n * 1. FormProvider (provider) loads and uses context instance A\n * 2. File is edited, HMR triggers\n * 3. SubmitButton (consumer) hot-reloads and imports context instance B\n * 4. Provider writes to instance A, Consumer reads from instance B\n * 5. Result: Consumer sees default values (triggerSubmit = () => undefined)\n * 6. Clicking submit does nothing because it calls the empty default function\n *\n * **The Solution:**\n * By storing the context in `window.__UNIFORM_CONTEXT__`, we ensure:\n * - First load: Create context and store in window\n * - Subsequent HMRs: Reuse the same context from window\n * - All components always reference the SAME context instance\n * - Provider and consumers can properly communicate\n *\n * **Why This Is Safe:**\n * - Only affects development (production has no HMR)\n * - Context type never changes (same interface)\n * - React handles cleanup on unmount normally\n * - No memory leaks (context is lightweight)\n *\n * Without this pattern, you'd need to restart the dev server after every edit\n * to FormContext.tsx to ensure all components use the same context instance.\n */\n\n// Define the context type\ninterface UniformContextType {\n /** Form debug mode enabled or not */\n debugMode: DebugMode;\n /** settings for form debug mode */\n debugModeSettings?: DebugModeSettings;\n /** Form reset tracking (programmatic reset calls) */\n formReset: {\n /**\n * Subscribe to programmatic form resets.\n * Returns an unsubscribe function.\n */\n subscribe: (listener: FormResetListener) => () => void;\n /**\n * Notify all subscribers about a programmatic form reset.\n * Called from useFormContext when reset() is invoked.\n */\n notify: () => void;\n };\n /** Function to update if the form can currently be submitted */\n preventSubmit: (prevent: boolean) => void;\n /** Setter to enable or disable form debug mode */\n setDebugMode: (debugMode: DebugMode) => void;\n /** Function to trigger form submit programmatically */\n triggerSubmit: (e?: BaseSyntheticEvent) => Promise<void> | void;\n /** User change tracking (user input only, not programmatic changes) */\n userChange: {\n /**\n * Subscribe to user field changes.\n * Returns an unsubscribe function.\n */\n subscribe: (listener: UserChangeListener) => () => void;\n /**\n * Notify all subscribers about a user field change.\n * Called from useController when user interacts with a field.\n */\n notify: (fieldName: string, value: unknown) => void;\n };\n /** Form validation configuration */\n validation: {\n /** Base validation schema instance (without client validation) */\n baseInstance?: VetoInstance;\n /** Veto validation schema instance for form validation */\n instance?: VetoInstance;\n /** Current validation errors in form */\n errors?: VetoFormattedError;\n /** Function to set client validation schema for a specific key */\n setClientValidationSchema: (\n key: string,\n schema: VetoTypeAny | null,\n ) => void;\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nif (!(window as any).__UNIFORM_CONTEXT__) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (window as any).__UNIFORM_CONTEXT__ = React.createContext<UniformContextType>(\n {\n debugMode: 'off',\n formReset: {\n subscribe: () => {\n return () => {\n return undefined;\n };\n },\n notify: () => {\n return undefined;\n },\n },\n preventSubmit: () => {\n return undefined;\n },\n setDebugMode: () => {\n return undefined;\n },\n triggerSubmit: () => {\n return undefined;\n },\n userChange: {\n subscribe: () => {\n return () => {\n return undefined;\n };\n },\n notify: () => {\n return undefined;\n },\n },\n validation: {\n setClientValidationSchema: () => {\n return undefined;\n },\n },\n },\n );\n debug('Creating new UniformContext instance');\n} else {\n debug(\n 'Reusing existing UniformContext instance from window.__UNIFORM_CONTEXT__',\n );\n}\n\n// Export the singleton context instance from window\n// This ensures all imports get the same context, even after HMR\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const UniformContext = (window as any)\n .__UNIFORM_CONTEXT__ as React.Context<UniformContextType>;\n\ndebug('UniformContext exported', {\n contextExists: !!UniformContext,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n windowContextExists: !!(window as any).__UNIFORM_CONTEXT__,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n contextsMatch: UniformContext === (window as any).__UNIFORM_CONTEXT__,\n});\n\n// Define props for the internal FormProvider component\ninterface FormProviderProps {\n /** children form render function */\n children: (childProps: {\n handleSubmit: (e?: BaseSyntheticEvent) => Promise<void>;\n isValid: boolean;\n }) => ReactNode;\n /** settings for form debug mode */\n debugModeSettings?: DebugModeSettings;\n /** initial form values */\n initialValues?: FieldValues;\n /** form submit handler */\n onSubmit: SubmitHandler<FieldValues>;\n /** Veto validation schema instance */\n validation?: VetoInstance;\n /** when the validation should be triggered */\n validationTrigger: 'onChange' | 'onBlur' | 'onSubmit' | 'onTouched' | 'all';\n}\n\n/**\n * FormProvider component provides:\n * - Veto validation schema context\n * - Resolver-backed validation error state\n * - RHF control binding for disabled-value omission without changing schema rules\n * - Client validation schema management\n * - Submit handler with automatic data conversion and submission control with preventSubmit\n * - Form Debug Mode state\n * - Form reset pub/sub notifications (`formReset`)\n * - User change pub/sub notifications (`userChange`)\n * - React Hook Form context\n */\nconst FormProvider: React.FC<FormProviderProps> = ({\n children,\n debugModeSettings = undefined,\n initialValues = undefined,\n onSubmit,\n validation: baseValidation = undefined,\n validationTrigger,\n}) => {\n const sensitiveFields = useMemo(() => {\n return createSensitiveFields();\n }, []);\n\n // Form Debug mode state is handled in the form context\n const [debugMode, setDebugMode] = useLocalStorage<DebugMode>(\n debugModeSettings?.localStorageKey ?? DEBUG_MODE_LOCAL_STORAGE_KEY_DEFAULT,\n 'off',\n );\n\n // Create extended validation combining base + client validations\n const { extendedValidation, setClientValidationSchema } =\n useExtendedValidation(baseValidation);\n\n // Create resolver from extended validation + reactive validation error state\n const { bindControl, resolver, validationErrors, validationErrorsHash } =\n useFormResolver(extendedValidation);\n\n // Initialize react hook form with the resolver\n const methods = useForm({\n defaultValues: initialValues ? toFormFormat(initialValues) : initialValues,\n // set rhf mode\n // see: https://react-hook-form.com/docs/useform#mode\n mode: validationTrigger,\n resolver,\n });\n\n // The resolver is created before useForm, so bind its control afterwards,\n // before RHF's passive effects can trigger validation.\n useLayoutEffect(() => {\n return bindControl(methods.control);\n }, [bindControl, methods.control]);\n\n // Get isValid from React Hook Form's formState\n const isValid = methods.formState?.isValid;\n\n // Control if the form can currently be submitted\n const [preventSubmit, setPreventSubmit] = useState(false);\n\n // Form reset listener registry (stored in ref to avoid re-renders)\n const formResetListenersRef = useRef<Set<FormResetListener>>(new Set());\n\n // Subscribe to form reset notifications\n const subscribeFormReset = useCallback(\n (listener: FormResetListener): (() => void) => {\n formResetListenersRef.current.add(listener);\n return () => {\n formResetListenersRef.current.delete(listener);\n };\n },\n [],\n );\n\n // Notify all subscribers about a programmatic form reset\n const notifyFormReset = useCallback((): void => {\n formResetListenersRef.current.forEach((listener) => {\n listener();\n });\n }, []);\n\n // User change listener registry (stored in ref to avoid re-renders)\n const userChangeListenersRef = useRef<Set<UserChangeListener>>(new Set());\n\n // Subscribe to user changes\n const subscribeUserChange = useCallback(\n (listener: UserChangeListener): (() => void) => {\n userChangeListenersRef.current.add(listener);\n // Return cleanup function to unsubscribe\n return () => {\n userChangeListenersRef.current.delete(listener);\n };\n },\n [],\n );\n\n // Notify all subscribers about user change\n const notifyUserChange = useCallback(\n (fieldName: string, value: unknown): void => {\n // Notify all registered listeners\n userChangeListenersRef.current.forEach((listener) => {\n listener(fieldName as Path<object>, value);\n });\n },\n [],\n );\n\n // Create submit handler with automatic data conversion\n // eslint-disable-next-line consistent-return\n const handleSubmit = async (e?: React.BaseSyntheticEvent) => {\n debug('handleSubmit called', {\n preventSubmit,\n formStateIsValid: methods.formState.isValid,\n validationErrors: sensitiveFields.redact(methods.formState.errors),\n validationTrigger,\n formValues: sensitiveFields.redact(methods.getValues()),\n });\n\n // only prevent submit when form state is valid, because otherwise\n // submit will only trigger validation and add errors / focus invalid fields\n if (methods.formState.isValid && preventSubmit) {\n debug('⛔ Form submit PREVENTED', {\n formStateIsValid: methods.formState.isValid,\n preventSubmit,\n });\n console.warn(\n '[FormProvider] form submit was prevented because preventSubmit is true...',\n );\n e?.preventDefault();\n return Promise.resolve();\n }\n\n debug('✓ Form submit ALLOWED', {\n formStateIsValid: methods.formState.isValid,\n preventSubmit,\n reason: !methods.formState.isValid\n ? 'Form is invalid (will trigger validation and show errors)'\n : 'Form is valid and preventSubmit is false',\n });\n\n // Convert form data to submission format:\n // - Unwrap flat array wrappers and convert markers\n // - Remove empty strings, nulls, empty arrays, and empty objects\n const wrappedOnSubmit = (data: FieldValues, event?: BaseSyntheticEvent) => {\n const submitData = toSubmitFormat(data) ?? {};\n debug('onSubmit callback called', {\n // Match sensitive paths before removing empty rows shifts array indices.\n submitData:\n toSubmitFormat(sensitiveFields.redact(data) as FieldValues) ?? {},\n });\n return onSubmit(submitData, event);\n };\n\n await methods.handleSubmit(wrappedOnSubmit)(e);\n\n debug('handleSubmit completed');\n };\n\n // Memoize the context value so consumers only re-render when context-relevant\n // state changes, including resolver-backed validation errors.\n const contextValue = useMemo(\n () => {\n return {\n // set debugMode to disabled when debugModeSettings.disable is true\n // otherwise use current debug mode from localStorage\n debugMode: debugModeSettings?.disable ? 'disabled' : debugMode,\n preventSubmit: (prevent: boolean) => {\n debug('preventSubmit called', {\n previousValue: preventSubmit,\n newValue: prevent,\n formStateIsValid: methods.formState.isValid,\n validationErrors: sensitiveFields.redact(methods.formState.errors),\n });\n setPreventSubmit(prevent);\n },\n setClientValidationSchema,\n setDebugMode,\n triggerSubmit: handleSubmit,\n formReset: {\n subscribe: subscribeFormReset,\n notify: notifyFormReset,\n },\n userChange: {\n subscribe: subscribeUserChange,\n notify: notifyUserChange,\n },\n validation: {\n baseInstance: baseValidation,\n instance: extendedValidation,\n errors: validationErrors,\n setClientValidationSchema,\n },\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [debugMode, debugModeSettings?.disable, validationErrorsHash],\n );\n\n return (\n <SensitiveFieldsProvider registry={sensitiveFields}>\n <UniformContext.Provider value={contextValue}>\n {/* Spread all hook form props into HookFormProvider */}\n <HookFormProvider {...methods}>\n {children({ handleSubmit, isValid })}\n </HookFormProvider>\n </UniformContext.Provider>\n </SensitiveFieldsProvider>\n );\n};\n\nexport default FormProvider;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;AAuBjB,MAAa,mBACX,MACA,UACY;CACZ,MAAM,iBAAiB,IAAI,IAC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,UAAU;GACpC;GACA,QAAQ,CAAC,QAAQ,UAAU,UACvB,8DACA;EACN,CAAC;EAKD,MAAM,mBAAmB,MAAmB,UAA+B;GACzE,MAAM,aAAa,eAAe,IAAI,KAAK,CAAC;GAC5C,MAAM,4BAA4B,EAEhC,YACE,eAAe,gBAAgB,OAAO,IAAI,CAAgB,KAAK,CAAC,EACpE,CAAC;GACD,OAAO,SAAS,YAAY,KAAK;EACnC;EAEA,MAAM,QAAQ,aAAa,eAAe,CAAC,CAAC,CAAC;EAE7C,MAAM,wBAAwB;CAChC;CAIA,MAAM,eAAe,cACb;EACJ,OAAO;GAGL,WAAW,mBAAmB,UAAU,aAAa;GACrD,gBAAgB,YAAqB;IACnC,MAAM,wBAAwB;KAC5B,eAAe;KACf,UAAU;KACV,kBAAkB,QAAQ,UAAU;KACpC,kBAAkB,gBAAgB,OAAO,QAAQ,UAAU,MAAM;IACnE,CAAC;IACD,iBAAiB,OAAO;GAC1B;GACA;GACA;GACA,eAAe;GACf,WAAW;IACT,WAAW;IACX,QAAQ;GACV;GACA,YAAY;IACV,WAAW;IACX,QAAQ;GACV;GACA,YAAY;IACV,cAAc;IACd,UAAU;IACV,QAAQ;IACR;GACF;EACF;CACF,GAEA;EAAC;EAAW,mBAAmB;EAAS;CAAoB,CAC9D;CAEA,OACE,oBAAC,yBAAD;EAAyB,UAAU;EACjC,UAAA,oBAAC,eAAe,UAAhB;GAAyB,OAAO;GAE9B,UAAA,oBAACC,cAAD;IAAkB,GAAI;IACnB,UAAA,SAAS;KAAE;KAAc;IAAQ,CAAC;GACnB,CAAA;EACK,CAAA;CACF,CAAA;AAE7B"}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import React, { BaseSyntheticEvent, ReactNode } from "react";
|
|
2
|
+
import { FieldValues, Path, SubmitHandler } from "react-hook-form";
|
|
3
|
+
import { VetoFormattedError, VetoInstance, VetoTypeAny } from "@fuf-stack/veto";
|
|
4
|
+
type DebugMode = 'debug' | 'debug-testids' | 'off' | 'disabled';
|
|
5
|
+
interface DebugModeSettings {
|
|
6
|
+
/** disable form debug completely */
|
|
7
|
+
disable?: boolean;
|
|
8
|
+
/** custom localStorage key to save debug mode state */
|
|
9
|
+
localStorageKey?: string;
|
|
10
|
+
}
|
|
11
|
+
/** Listener function that gets called when a form reset is triggered */
|
|
12
|
+
type FormResetListener = () => void;
|
|
13
|
+
/**
|
|
14
|
+
* Listener function that gets called when a field changes due to user input
|
|
15
|
+
*/
|
|
16
|
+
type UserChangeListener<TFieldValues extends object = object> = (fieldName: Path<TFieldValues>, value: unknown) => void;
|
|
17
|
+
/**
|
|
18
|
+
* The `UniformContext` provides control over the form's submission behavior and may optionally include
|
|
19
|
+
* a Veto validation schema for form validation.
|
|
20
|
+
*
|
|
21
|
+
* Specifically, this context offers:
|
|
22
|
+
* 1. **Form Submission Control**: The `preventSubmit` function allows components to enable or disable
|
|
23
|
+
* form submissions.
|
|
24
|
+
* 2. **Optional Validation Schema**: The `validation` property may hold a Veto validation schema instance
|
|
25
|
+
* that can be used to validate form fields and handle validation logic.
|
|
26
|
+
* 3. **Client Validation**: The `setClientValidationSchema` function allows setting dynamic client-side
|
|
27
|
+
* validation schemas that complement the base Veto validation.
|
|
28
|
+
* 4. **User Change Tracking**: The `userChange` property provides a pub/sub system for tracking
|
|
29
|
+
* user-initiated field changes (typing, clicking, selecting) - NOT programmatic changes like
|
|
30
|
+
* form.reset() or form.setValue(). Used by the `useWatchUserChange` hook to enable reactive
|
|
31
|
+
* field dependencies.
|
|
32
|
+
* 5. **Form Reset Tracking**: The `formReset` property provides a pub/sub system for tracking
|
|
33
|
+
* programmatic form resets triggered via the wrapped `reset()` from `useFormContext`.
|
|
34
|
+
* Used by hooks like `useWatchFormReset` to run reset-specific normalization logic.
|
|
35
|
+
*
|
|
36
|
+
* This context is useful for components that need to interact with or control the form submission state,
|
|
37
|
+
* or access the validation schema for managing form validation logic.
|
|
38
|
+
*
|
|
39
|
+
* IMPORTANT: Context Singleton Pattern for HMR (Hot Module Replacement)
|
|
40
|
+
* =====================================================================
|
|
41
|
+
*
|
|
42
|
+
* We use a global window variable to ensure only ONE context instance exists across
|
|
43
|
+
* hot module reloads during development. This is critical because:
|
|
44
|
+
*
|
|
45
|
+
* **The Problem:**
|
|
46
|
+
* When using Vite/Storybook with Fast Refresh (HMR), editing this file causes it to
|
|
47
|
+
* be re-evaluated. Each re-evaluation runs `React.createContext()` again, creating a
|
|
48
|
+
* NEW context instance. This leads to "context instance mismatch":
|
|
49
|
+
*
|
|
50
|
+
* 1. FormProvider (provider) loads and uses context instance A
|
|
51
|
+
* 2. File is edited, HMR triggers
|
|
52
|
+
* 3. SubmitButton (consumer) hot-reloads and imports context instance B
|
|
53
|
+
* 4. Provider writes to instance A, Consumer reads from instance B
|
|
54
|
+
* 5. Result: Consumer sees default values (triggerSubmit = () => undefined)
|
|
55
|
+
* 6. Clicking submit does nothing because it calls the empty default function
|
|
56
|
+
*
|
|
57
|
+
* **The Solution:**
|
|
58
|
+
* By storing the context in `window.__UNIFORM_CONTEXT__`, we ensure:
|
|
59
|
+
* - First load: Create context and store in window
|
|
60
|
+
* - Subsequent HMRs: Reuse the same context from window
|
|
61
|
+
* - All components always reference the SAME context instance
|
|
62
|
+
* - Provider and consumers can properly communicate
|
|
63
|
+
*
|
|
64
|
+
* **Why This Is Safe:**
|
|
65
|
+
* - Only affects development (production has no HMR)
|
|
66
|
+
* - Context type never changes (same interface)
|
|
67
|
+
* - React handles cleanup on unmount normally
|
|
68
|
+
* - No memory leaks (context is lightweight)
|
|
69
|
+
*
|
|
70
|
+
* Without this pattern, you'd need to restart the dev server after every edit
|
|
71
|
+
* to FormContext.tsx to ensure all components use the same context instance.
|
|
72
|
+
*/
|
|
73
|
+
interface UniformContextType {
|
|
74
|
+
/** Form debug mode enabled or not */
|
|
75
|
+
debugMode: DebugMode;
|
|
76
|
+
/** settings for form debug mode */
|
|
77
|
+
debugModeSettings?: DebugModeSettings;
|
|
78
|
+
/** Form reset tracking (programmatic reset calls) */
|
|
79
|
+
formReset: {
|
|
80
|
+
/**
|
|
81
|
+
* Subscribe to programmatic form resets.
|
|
82
|
+
* Returns an unsubscribe function.
|
|
83
|
+
*/
|
|
84
|
+
subscribe: (listener: FormResetListener) => () => void;
|
|
85
|
+
/**
|
|
86
|
+
* Notify all subscribers about a programmatic form reset.
|
|
87
|
+
* Called from useFormContext when reset() is invoked.
|
|
88
|
+
*/
|
|
89
|
+
notify: () => void;
|
|
90
|
+
};
|
|
91
|
+
/** Function to update if the form can currently be submitted */
|
|
92
|
+
preventSubmit: (prevent: boolean) => void;
|
|
93
|
+
/** Setter to enable or disable form debug mode */
|
|
94
|
+
setDebugMode: (debugMode: DebugMode) => void;
|
|
95
|
+
/** Function to trigger form submit programmatically */
|
|
96
|
+
triggerSubmit: (e?: BaseSyntheticEvent) => Promise<void> | void;
|
|
97
|
+
/** User change tracking (user input only, not programmatic changes) */
|
|
98
|
+
userChange: {
|
|
99
|
+
/**
|
|
100
|
+
* Subscribe to user field changes.
|
|
101
|
+
* Returns an unsubscribe function.
|
|
102
|
+
*/
|
|
103
|
+
subscribe: (listener: UserChangeListener) => () => void;
|
|
104
|
+
/**
|
|
105
|
+
* Notify all subscribers about a user field change.
|
|
106
|
+
* Called from useController when user interacts with a field.
|
|
107
|
+
*/
|
|
108
|
+
notify: (fieldName: string, value: unknown) => void;
|
|
109
|
+
};
|
|
110
|
+
/** Form validation configuration */
|
|
111
|
+
validation: {
|
|
112
|
+
/** Base validation schema instance (without client validation) */
|
|
113
|
+
baseInstance?: VetoInstance;
|
|
114
|
+
/** Veto validation schema instance for form validation */
|
|
115
|
+
instance?: VetoInstance;
|
|
116
|
+
/** Current validation errors in form */
|
|
117
|
+
errors?: VetoFormattedError;
|
|
118
|
+
/** Function to set client validation schema for a specific key */
|
|
119
|
+
setClientValidationSchema: (key: string, schema: VetoTypeAny | null) => void;
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
declare const UniformContext: React.Context<UniformContextType>;
|
|
123
|
+
export { UniformContext as n, DebugModeSettings as t };
|
|
124
|
+
//# sourceMappingURL=FormContext-BnNJYZOo.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"FormContext-BnNJYZOo.d.mts","names":[],"sources":["../src/Form/subcomponents/FormContext.tsx"],"mappings":";;;KA8BK;UAEY;;EAEf;;EAEA;;;KAIU;;;;KAKA,mBAAmB,yCAC7B,WAAW,KAAK,eAChB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA+DQ;;EAER,WAAW;;EAEX,oBAAoB;;EAEpB;;;;;IAKE,YAAY,UAAU;;;;;IAKtB;;;EAGF,gBAAgB;;EAEhB,eAAe,WAAW;;EAE1B,gBAAgB,IAAI,uBAAuB;;EAE3C;;;;;IAKE,YAAY,UAAU;;;;;IAKtB,SAAS,mBAAmB;;;EAG9B;;IAEE,eAAe;;IAEf,WAAW;;IAEX,SAAS;;IAET,4BACE,aACA,QAAQ;;;cAyDD,gBACa,MAAM,QAAQ"}
|
package/dist/Grid/index.d.mts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { ReactNode } from "react";
|
|
2
|
-
//#region src/Grid/Grid.d.ts
|
|
3
2
|
interface GridProps {
|
|
4
3
|
/** child components */
|
|
5
4
|
children?: ReactNode;
|
|
@@ -12,6 +11,5 @@ interface GridProps {
|
|
|
12
11
|
* Defines the default grid for form components
|
|
13
12
|
*/
|
|
14
13
|
declare const Grid: ({ children, className, testId }: GridProps) => import("react").JSX.Element;
|
|
15
|
-
//#endregion
|
|
16
14
|
export { type GridProps, Grid as default };
|
|
17
15
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/Grid/Grid.tsx"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/Grid/Grid.tsx"],"mappings":";UAIiB;;EAEf,WAAW;;EAEX;;EAEA;;;;;cAMI,SAAQ,UAAA,WAAA,UAIX,8BAAS,IAAA"}
|
package/dist/Grid/index.mjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { Grid_default as default };
|
|
1
|
+
export { t as default } from "../Grid-Us2JFczS.mjs";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { cn } from "@fuf-stack/pixel-utils";
|
|
2
2
|
import { jsx } from "react/jsx-runtime";
|
|
3
|
-
|
|
3
|
+
// src/Grid/Grid.tsx
|
|
4
4
|
/**
|
|
5
5
|
* Defines the default grid for form components
|
|
6
6
|
*/
|
|
@@ -11,10 +11,8 @@ const Grid = ({ children = null, className = void 0, testId = void 0 }) => {
|
|
|
11
11
|
children
|
|
12
12
|
});
|
|
13
13
|
};
|
|
14
|
-
|
|
15
|
-
//#region src/Grid/index.ts
|
|
14
|
+
// src/Grid/index.ts
|
|
16
15
|
var Grid_default = Grid;
|
|
17
|
-
//#endregion
|
|
18
16
|
export { Grid_default as t };
|
|
19
17
|
|
|
20
|
-
//# sourceMappingURL=Grid-
|
|
18
|
+
//# sourceMappingURL=Grid-Us2JFczS.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Grid-
|
|
1
|
+
{"version":3,"file":"Grid-Us2JFczS.mjs","names":[],"sources":["../src/Grid/Grid.tsx","../src/Grid/index.ts"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport { cn } from '@fuf-stack/pixel-utils';\n\nexport interface GridProps {\n /** child components */\n children?: ReactNode;\n /** CSS class name */\n className?: string;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n}\n\n/**\n * Defines the default grid for form components\n */\nconst Grid = ({\n children = null,\n className = undefined,\n testId = undefined,\n}: GridProps) => {\n return (\n <div className={cn('grid gap-6', className)} data-testid={testId}>\n {children}\n </div>\n );\n};\n\nexport default Grid;\n","import Grid from './Grid';\n\nexport type { GridProps } from './Grid';\n\nexport default Grid;\n"],"mappings":";;;;;;AAgBA,MAAM,QAAQ,EACZ,WAAW,MACX,YAAY,KAAA,GACZ,SAAS,KAAA,QACM;CACf,OACE,oBAAC,OAAD;EAAK,WAAW,GAAG,cAAc,SAAS;EAAG,eAAa;EACvD;CACE,CAAA;AAET;;ACtBA,IAAA,eAAe"}
|