@fuf-stack/uniform 1.27.0 → 2.0.0-next.1

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.
Files changed (149) hide show
  1. package/README.md +9 -0
  2. package/dist/Checkboxes/index.d.mts +192 -263
  3. package/dist/Checkboxes/index.d.mts.map +1 -1
  4. package/dist/Checkboxes/index.mjs +294 -90
  5. package/dist/Checkboxes/index.mjs.map +1 -1
  6. package/dist/DatePicker/index.d.mts +1282 -500
  7. package/dist/DatePicker/index.d.mts.map +1 -1
  8. package/dist/DatePicker/index.mjs +403 -83
  9. package/dist/DatePicker/index.mjs.map +1 -1
  10. package/dist/FieldArray/index.d.mts +105 -98
  11. package/dist/FieldArray/index.d.mts.map +1 -1
  12. package/dist/FieldArray/index.mjs +344 -195
  13. package/dist/FieldArray/index.mjs.map +1 -1
  14. package/dist/FieldCard/index.d.mts +37 -35
  15. package/dist/FieldCard/index.d.mts.map +1 -1
  16. package/dist/FieldCard/index.mjs +187 -128
  17. package/dist/FieldCard/index.mjs.map +1 -1
  18. package/dist/{FieldCopyTestIdButton-CRJBix9D.mjs → FieldCopyTestIdButton-DV0tkdh2.mjs} +5 -3
  19. package/dist/FieldCopyTestIdButton-DV0tkdh2.mjs.map +1 -0
  20. package/dist/FieldDescription-C4l0HKGL.mjs +36 -0
  21. package/dist/FieldDescription-C4l0HKGL.mjs.map +1 -0
  22. package/dist/FieldLabel-DKzqkuY1.mjs +125 -0
  23. package/dist/FieldLabel-DKzqkuY1.mjs.map +1 -0
  24. package/dist/FieldLayout-BLW5S-Jm.mjs +46 -0
  25. package/dist/FieldLayout-BLW5S-Jm.mjs.map +1 -0
  26. package/dist/FieldValidationError-DgkCL3cC.mjs +77 -0
  27. package/dist/FieldValidationError-DgkCL3cC.mjs.map +1 -0
  28. package/dist/Form/index.d.mts +11 -11
  29. package/dist/Form/index.d.mts.map +1 -1
  30. package/dist/Form/index.mjs +14 -11
  31. package/dist/Form/index.mjs.map +1 -1
  32. package/dist/FormContext-CHctWFAP.mjs +520 -0
  33. package/dist/FormContext-CHctWFAP.mjs.map +1 -0
  34. package/dist/FormContext-CsFiNvuJ.d.mts.map +1 -1
  35. package/dist/Grid/index.mjs +1 -2
  36. package/dist/{Grid-CTs-Rb9G.mjs → Grid-DfcZeuib.mjs} +4 -2
  37. package/dist/Grid-DfcZeuib.mjs.map +1 -0
  38. package/dist/Input/index.d.mts +640 -392
  39. package/dist/Input/index.d.mts.map +1 -1
  40. package/dist/Input/index.mjs +421 -76
  41. package/dist/Input/index.mjs.map +1 -1
  42. package/dist/RadioBoxes/index.d.mts +1583 -120
  43. package/dist/RadioBoxes/index.d.mts.map +1 -1
  44. package/dist/RadioBoxes/index.mjs +159 -114
  45. package/dist/RadioBoxes/index.mjs.map +1 -1
  46. package/dist/RadioTabs/index.d.mts +300 -81
  47. package/dist/RadioTabs/index.d.mts.map +1 -1
  48. package/dist/RadioTabs/index.mjs +277 -86
  49. package/dist/RadioTabs/index.mjs.map +1 -1
  50. package/dist/Radios/index.d.mts +1353 -108
  51. package/dist/Radios/index.d.mts.map +1 -1
  52. package/dist/Radios/index.mjs +105 -54
  53. package/dist/Radios/index.mjs.map +1 -1
  54. package/dist/Select/index.d.mts +558 -3013
  55. package/dist/Select/index.d.mts.map +1 -1
  56. package/dist/Select/index.mjs +319 -177
  57. package/dist/Select/index.mjs.map +1 -1
  58. package/dist/Slider/index.d.mts +414 -1326
  59. package/dist/Slider/index.d.mts.map +1 -1
  60. package/dist/Slider/index.mjs +276 -94
  61. package/dist/Slider/index.mjs.map +1 -1
  62. package/dist/SubmitButton/index.d.mts.map +1 -1
  63. package/dist/SubmitButton/index.mjs +4 -1
  64. package/dist/SubmitButton/index.mjs.map +1 -1
  65. package/dist/Switch/index.d.mts +2 -1248
  66. package/dist/Switch/index.mjs +167 -68
  67. package/dist/Switch/index.mjs.map +1 -1
  68. package/dist/Switch-CvPO8IF9.d.mts +601 -0
  69. package/dist/Switch-CvPO8IF9.d.mts.map +1 -0
  70. package/dist/SwitchBox/index.d.mts +139 -43
  71. package/dist/SwitchBox/index.d.mts.map +1 -1
  72. package/dist/SwitchBox/index.mjs +142 -87
  73. package/dist/SwitchBox/index.mjs.map +1 -1
  74. package/dist/TextArea/index.d.mts +295 -411
  75. package/dist/TextArea/index.d.mts.map +1 -1
  76. package/dist/TextArea/index.mjs +200 -48
  77. package/dist/TextArea/index.mjs.map +1 -1
  78. package/dist/Time/index.d.mts +1170 -601
  79. package/dist/Time/index.d.mts.map +1 -1
  80. package/dist/Time/index.mjs +162 -74
  81. package/dist/Time/index.mjs.map +1 -1
  82. package/dist/helpers/index.d.mts +1 -1
  83. package/dist/helpers/index.mjs +1 -1
  84. package/dist/helpers/index.mjs.map +1 -1
  85. package/dist/hooks/useClientValidation/index.mjs +1 -1
  86. package/dist/hooks/useController/index.d.mts +31 -3
  87. package/dist/hooks/useController/index.d.mts.map +1 -0
  88. package/dist/hooks/useController/index.mjs +1 -2
  89. package/dist/hooks/useFormContext/index.d.mts +65 -3
  90. package/dist/hooks/useFormContext/index.d.mts.map +1 -0
  91. package/dist/hooks/useFormContext/index.mjs +1 -2
  92. package/dist/hooks/useInputValueDebounce/index.d.mts +11 -5
  93. package/dist/hooks/useInputValueDebounce/index.d.mts.map +1 -1
  94. package/dist/hooks/useInputValueDebounce/index.mjs +27 -5
  95. package/dist/hooks/useInputValueDebounce/index.mjs.map +1 -1
  96. package/dist/hooks/useInputValueTransform/index.d.mts +1 -2
  97. package/dist/hooks/useInputValueTransform/index.mjs +1 -2
  98. package/dist/hooks/useWatchFormReset/index.mjs +1 -1
  99. package/dist/hooks/useWatchUserChange/index.d.mts +2 -2
  100. package/dist/hooks/useWatchUserChange/index.d.mts.map +1 -1
  101. package/dist/hooks/useWatchUserChange/index.mjs +1 -1
  102. package/dist/hooks/useWatchUserChange/index.mjs.map +1 -1
  103. package/dist/{useInputValueTransform-LOaEim7k.d.mts → index-BS8IoBOn.d.mts} +3 -3
  104. package/dist/index-BS8IoBOn.d.mts.map +1 -0
  105. package/dist/partials/FieldCopyTestIdButton/index.mjs +1 -2
  106. package/dist/partials/FieldValidationError/index.d.mts +637 -3
  107. package/dist/partials/FieldValidationError/index.d.mts.map +1 -1
  108. package/dist/partials/FieldValidationError/index.mjs +1 -2
  109. package/dist/radioControlVariants-Cm6WufWo.mjs +188 -0
  110. package/dist/radioControlVariants-Cm6WufWo.mjs.map +1 -0
  111. package/dist/switchVariants-BaQw2DA7.mjs +67 -0
  112. package/dist/switchVariants-BaQw2DA7.mjs.map +1 -0
  113. package/dist/timeVariants-B9HDfNYt.mjs +58 -0
  114. package/dist/timeVariants-B9HDfNYt.mjs.map +1 -0
  115. package/dist/{useController-CK39i6HI.mjs → useController-BCFeZbBZ.mjs} +2 -2
  116. package/dist/{useController-CK39i6HI.mjs.map → useController-BCFeZbBZ.mjs.map} +1 -1
  117. package/dist/{useFormContext-fYWtlnpE.mjs → useFormContext-BPjJjNnM.mjs} +2 -2
  118. package/dist/{useFormContext-fYWtlnpE.mjs.map → useFormContext-BPjJjNnM.mjs.map} +1 -1
  119. package/dist/{useInputValueTransform-DJ5zkqSy.mjs → useInputValueTransform-Mw8YEOXT.mjs} +2 -2
  120. package/dist/{useInputValueTransform-DJ5zkqSy.mjs.map → useInputValueTransform-Mw8YEOXT.mjs.map} +1 -1
  121. package/package.json +17 -29
  122. package/dist/FieldCopyTestIdButton-CRJBix9D.mjs.map +0 -1
  123. package/dist/FieldValidationError-ByRoIxaM.mjs +0 -50
  124. package/dist/FieldValidationError-ByRoIxaM.mjs.map +0 -1
  125. package/dist/FormContext-gHSwOlcy.mjs +0 -278
  126. package/dist/FormContext-gHSwOlcy.mjs.map +0 -1
  127. package/dist/Grid-CTs-Rb9G.mjs.map +0 -1
  128. package/dist/Switch/index.d.mts.map +0 -1
  129. package/dist/hooks/useInput/index.d.mts +0 -2
  130. package/dist/hooks/useInput/index.mjs +0 -7
  131. package/dist/hooks/useInput/index.mjs.map +0 -1
  132. package/dist/hooks/useUniformField/index.d.mts +0 -98
  133. package/dist/hooks/useUniformField/index.d.mts.map +0 -1
  134. package/dist/hooks/useUniformField/index.mjs +0 -137
  135. package/dist/hooks/useUniformField/index.mjs.map +0 -1
  136. package/dist/hooks/useUniformFieldArray/index.d.mts +0 -73
  137. package/dist/hooks/useUniformFieldArray/index.d.mts.map +0 -1
  138. package/dist/hooks/useUniformFieldArray/index.mjs +0 -101
  139. package/dist/hooks/useUniformFieldArray/index.mjs.map +0 -1
  140. package/dist/index-CAdGtKE_.d.mts +0 -1
  141. package/dist/index-CaxrMD1A.d.mts +0 -1
  142. package/dist/index-D5HVU2jP.d.mts +0 -1
  143. package/dist/useController-DcK2YHbw.d.mts +0 -32
  144. package/dist/useController-DcK2YHbw.d.mts.map +0 -1
  145. package/dist/useFormContext-B3QGVVaO.d.mts +0 -66
  146. package/dist/useFormContext-B3QGVVaO.d.mts.map +0 -1
  147. package/dist/useInput-C0aJaAGe.mjs +0 -2
  148. package/dist/useInput-ClpHDPdr.d.mts +0 -2
  149. package/dist/useInputValueTransform-LOaEim7k.d.mts.map +0 -1
@@ -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';\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 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) {\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,\n errors: errors ?? null,\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":"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"}
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 } 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';\nimport { useStyling } from '@fuf-stack/pixels/StylingProvider';\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 styling = useStyling();\n const classNames = styling.variantsToClassNames(\n styling.resolve(formDebugViewerVariants),\n className,\n 'base',\n );\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 } from '@fuf-stack/pixel-utils';\nimport { useStyling } from '@fuf-stack/pixels/StylingProvider';\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 styling = useStyling();\n const classNames = styling.variantsToClassNames(\n styling.resolve(formVariants),\n className,\n 'base',\n );\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} data-component=\"form\">\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":"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"}
@@ -0,0 +1,520 @@
1
+ import { flatArrayKey, toFormFormat, toSubmitFormat, toValidationFormat } from "./helpers/index.mjs";
2
+ import React, { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
3
+ import { useLocalStorage } from "@fuf-stack/pixels";
4
+ import { jsx } from "react/jsx-runtime";
5
+ import { FormProvider, useForm } from "react-hook-form";
6
+ import createDebug from "debug";
7
+ import { and, veto } from "@fuf-stack/veto";
8
+ //#region src/Form/subcomponents/SensitiveFields.tsx
9
+ /**
10
+ * Diagnostic redaction for explicitly registered form paths.
11
+ *
12
+ * Flow:
13
+ * 1. FormProvider creates one registry for its form and supplies it through context.
14
+ * 2. useUniformField calls useSensitiveField for declared password inputs and
15
+ * fields marked sensitive. This module does not infer secrets from names,
16
+ * inspect the DOM, or search strings for password-like content.
17
+ * 3. Field layout effects register their paths before the provider marks the
18
+ * initial registry ready. The debug viewer waits for that ready signal.
19
+ * 4. The viewer and Uniform's debug logger redact diagnostic copies using the
20
+ * same registry. JSON copy actions receive the viewer's redacted data too.
21
+ *
22
+ * This is protection against accidental disclosure in Uniform diagnostics,
23
+ * not encryption or a boundary against browser inspection. Real values remain
24
+ * available to inputs, validation, submission, and application callbacks.
25
+ * Application logging and secrets embedded in unrelated paths/custom messages
26
+ * are outside this path-based redaction mechanism.
27
+ */
28
+ const REDACTED = "[REDACTED]";
29
+ /**
30
+ * Build a diagnostic copy with each registered field replaced by [REDACTED].
31
+ *
32
+ * Matching a field masks its entire subtree. For validation errors, that also
33
+ * removes error metadata/messages beneath that field, which may contain input.
34
+ * The source object is never changed: redacting form state itself would corrupt
35
+ * validation and the values ultimately delivered to onSubmit.
36
+ *
37
+ * Paths use React Hook Form dot notation, with numeric bracket indices accepted
38
+ * as well. Normalization removes Uniform's __FLAT__ transport wrapper so the
39
+ * same registration covers raw form data and normalized/submitted array values.
40
+ *
41
+ * Traversal covers arrays and plain objects. Non-data instances such as dates
42
+ * and DOM refs are preserved unless their path or an ancestor is sensitive.
43
+ * This is deliberately not a general-purpose serializer or secret detector.
44
+ *
45
+ * @param data - Form values or errors destined for Uniform diagnostics
46
+ * @param paths - Sensitive field paths registered for this form
47
+ * @returns A diagnostic copy with registered fields replaced, or the unchanged
48
+ * primitive/non-data instance when no traversal is necessary
49
+ */
50
+ const redactDebugData = (data, paths) => {
51
+ const sensitivePaths = new Set(paths.map((path) => {
52
+ return path.replace(/\[(\d+)\]/g, ".$1").split(".").filter((part) => {
53
+ return part !== "__FLAT__";
54
+ }).join(".");
55
+ }));
56
+ const copies = /* @__PURE__ */ new WeakMap();
57
+ const visit = (value, path) => {
58
+ if (sensitivePaths.has(path)) return REDACTED;
59
+ if (!value || typeof value !== "object") return value;
60
+ const existing = copies.get(value);
61
+ if (existing) return existing;
62
+ if (Array.isArray(value)) {
63
+ const copy = [];
64
+ copies.set(value, copy);
65
+ value.forEach((item, index) => {
66
+ copy[index] = visit(item, path ? `${path}.${index}` : String(index));
67
+ });
68
+ copies.delete(value);
69
+ return copy;
70
+ }
71
+ const prototype = Object.getPrototypeOf(value);
72
+ if (prototype !== Object.prototype && prototype !== null) return value;
73
+ const copy = {};
74
+ copies.set(value, copy);
75
+ Object.entries(value).forEach(([key, entry]) => {
76
+ Object.defineProperty(copy, key, {
77
+ value: visit(entry, path ? `${path}.${key}` : key),
78
+ enumerable: true,
79
+ writable: true,
80
+ configurable: true
81
+ });
82
+ });
83
+ copies.delete(value);
84
+ return copy;
85
+ };
86
+ return visit(data, "");
87
+ };
88
+ /**
89
+ * Create an isolated, append-only sensitivity registry for one form instance.
90
+ *
91
+ * Only field paths and readiness are stored here; the registry does not retain
92
+ * password values. Paths intentionally survive input unmounts, resets, and a
93
+ * later sensitive=false declaration because RHF can retain the original value.
94
+ * A new form instance gets a fresh registry; there is no cross-form path sharing.
95
+ *
96
+ * Snapshot objects stay referentially stable until metadata actually changes.
97
+ * useSyncExternalStore depends on that stability to avoid repeated renders.
98
+ */
99
+ const createSensitiveFields = () => {
100
+ let snapshot = {
101
+ paths: [],
102
+ ready: false
103
+ };
104
+ const listeners = /* @__PURE__ */ new Set();
105
+ const notify = () => {
106
+ listeners.forEach((listener) => {
107
+ listener();
108
+ });
109
+ };
110
+ return {
111
+ /** Return the current stable metadata snapshot, without reading form values. */
112
+ getSnapshot: () => {
113
+ return snapshot;
114
+ },
115
+ /** Subscribe to metadata changes; cleanup removes the listener, not paths. */
116
+ subscribe: (listener) => {
117
+ listeners.add(listener);
118
+ return () => {
119
+ listeners.delete(listener);
120
+ };
121
+ },
122
+ /** Mark a path once; duplicate registrations and Strict Mode repeats are safe. */
123
+ register: (name) => {
124
+ if (snapshot.paths.includes(name)) return;
125
+ snapshot = {
126
+ ...snapshot,
127
+ paths: [...snapshot.paths, name]
128
+ };
129
+ notify();
130
+ },
131
+ /** Allow the debug viewer to render after initial field registration finishes. */
132
+ ready: () => {
133
+ if (snapshot.ready) return;
134
+ snapshot = {
135
+ ...snapshot,
136
+ ready: true
137
+ };
138
+ notify();
139
+ },
140
+ /** Use the latest paths for logs, even while the debug viewer is closed. */
141
+ redact: (data) => {
142
+ return redactDebugData(data, snapshot.paths);
143
+ }
144
+ };
145
+ };
146
+ const defaultSensitiveFields = createSensitiveFields();
147
+ defaultSensitiveFields.ready();
148
+ const SensitiveFieldsContext = createContext(void 0);
149
+ /**
150
+ * Supply the form-owned registry and release the initial debug-render gate.
151
+ *
152
+ * React runs descendant layout effects before this provider's layout effect,
153
+ * so initially mounted fields register before ready becomes true. The viewer
154
+ * must not render raw values while ready is false, even if debug mode was
155
+ * restored from localStorage before the form's first render.
156
+ */
157
+ const SensitiveFieldsProvider = ({ children, registry }) => {
158
+ useLayoutEffect(() => {
159
+ registry.ready();
160
+ }, [registry]);
161
+ return /* @__PURE__ */ jsx(SensitiveFieldsContext.Provider, {
162
+ value: registry,
163
+ children
164
+ });
165
+ };
166
+ /**
167
+ * Register a field's sensitivity as declared by its renderer/shared field hook.
168
+ *
169
+ * Registration happens during commit, not render, so abandoned React renders
170
+ * cannot mutate the registry. Layout timing makes new registrations available
171
+ * before paint. Password detection uses the declared input type in
172
+ * useUniformField, so toggling the rendered type to text does not reveal debug
173
+ * values. Once registered, a path is never downgraded within this form instance.
174
+ *
175
+ * @param name - The field path used for form registration
176
+ * @param sensitive - Whether the renderer declares this field sensitive
177
+ */
178
+ const useSensitiveField = (name, sensitive) => {
179
+ const registry = useContext(SensitiveFieldsContext);
180
+ useLayoutEffect(() => {
181
+ if (sensitive) registry?.register(name);
182
+ }, [
183
+ registry,
184
+ name,
185
+ sensitive
186
+ ]);
187
+ };
188
+ /**
189
+ * Observe sensitivity metadata for rendering diagnostic copies.
190
+ *
191
+ * This subscription contains neither passwords nor RHF's mutable value objects.
192
+ * The debug viewer keeps its existing value subscription and applies these paths
193
+ * when handing values/errors to Json; getValues and onSubmit stay untouched.
194
+ * Callers must honor ready before exposing an initial diagnostic payload.
195
+ */
196
+ const useSensitiveDebug = () => {
197
+ const registry = useContext(SensitiveFieldsContext) ?? defaultSensitiveFields;
198
+ return useSyncExternalStore(registry.subscribe, registry.getSnapshot, registry.getSnapshot);
199
+ };
200
+ //#endregion
201
+ //#region src/helpers/disabledFields/disabledFields.ts
202
+ /** Removes one path by copying only its ancestors, leaving stored values and array indices intact. */
203
+ const omitPath = (value, [key, ...rest]) => {
204
+ if (!value || typeof value !== "object" || key === void 0 || !Object.getOwnPropertyDescriptor(value, key)) return value;
205
+ const copy = Array.isArray(value) ? value.slice() : { ...value };
206
+ if (rest.length) copy[key] = omitPath(copy[key], rest);
207
+ else delete copy[key];
208
+ return copy;
209
+ };
210
+ /** Omits disabled fields from normalized validation/submission data without changing form state. */
211
+ const omitDisabledValues = (values, names) => {
212
+ return names.reduce((data, name) => {
213
+ const path = name.replace(/\[(\d+)\]/g, ".$1").split(".").filter((part) => {
214
+ return part !== flatArrayKey;
215
+ });
216
+ return omitPath(data, path);
217
+ }, values);
218
+ };
219
+ //#endregion
220
+ //#region src/Form/subcomponents/FormResolver.ts
221
+ /**
222
+ * Hook that manages client validation schemas state.
223
+ *
224
+ * Provides a centralized way to add/remove dynamic validation schemas
225
+ * that can be combined with base form validation.
226
+ *
227
+ * @returns Object with client validation state and memoized setter function
228
+ */
229
+ const useClientValidationManager = () => {
230
+ const [clientValidationSchemas, setClientValidationSchemas] = useState({});
231
+ return {
232
+ clientValidationSchemas,
233
+ setClientValidationSchema: useMemo(() => {
234
+ return (key, schema) => {
235
+ setClientValidationSchemas((prev) => {
236
+ if (!prev[key] && !schema) return prev;
237
+ if (!schema) {
238
+ const { [key]: _removed, ...rest } = prev;
239
+ return rest;
240
+ }
241
+ return {
242
+ ...prev,
243
+ [key]: schema
244
+ };
245
+ });
246
+ };
247
+ }, [])
248
+ };
249
+ };
250
+ /**
251
+ * Hook that creates an extended validation instance combining base Veto validation with dynamic client validation.
252
+ *
253
+ * @param baseValidation - Optional base Veto validation schema
254
+ * @returns Combined validation instance and client schema setter
255
+ */
256
+ const useExtendedValidation = (baseValidation) => {
257
+ const { clientValidationSchemas, setClientValidationSchema } = useClientValidationManager();
258
+ const clientSchemaValues = useMemo(() => {
259
+ return Object.keys(clientValidationSchemas).sort().map((key) => {
260
+ return clientValidationSchemas[key];
261
+ }).filter((schema) => {
262
+ return Boolean(schema);
263
+ });
264
+ }, [clientValidationSchemas]);
265
+ return {
266
+ extendedValidation: useMemo(() => {
267
+ const hasBaseValidation = !!baseValidation;
268
+ const hasClientSchemas = clientSchemaValues.length > 0;
269
+ if (!hasBaseValidation && !hasClientSchemas) return;
270
+ if (!hasClientSchemas) return baseValidation;
271
+ const clientSchemasCombined = clientSchemaValues.reduce((combined, clientSchema) => {
272
+ return combined ? and(combined, clientSchema) : clientSchema;
273
+ }, null);
274
+ if (baseValidation && clientSchemasCombined) {
275
+ const baseSchema = baseValidation.schema;
276
+ return veto(and(clientSchemasCombined, baseSchema));
277
+ }
278
+ if (clientSchemasCombined) return veto(clientSchemasCombined);
279
+ return baseValidation;
280
+ }, [baseValidation, clientSchemaValues]),
281
+ setClientValidationSchema
282
+ };
283
+ };
284
+ /**
285
+ * Creates a React Hook Form resolver from an extended validation instance and
286
+ * stores its latest formatted Veto errors as React state.
287
+ *
288
+ * Bind the owning RHF control before validation runs. Each resolver call omits
289
+ * disabled values from normalized input and validated output while preserving
290
+ * stored form values. The schema stays unchanged, so required fields can still
291
+ * report missing-value errors and defaults cannot restore disabled output.
292
+ *
293
+ * Keeping the resolver errors in state lets Uniform context consumers re-render
294
+ * when validation output changes, while the hash prevents repeated validations
295
+ * with equivalent errors from causing unnecessary updates.
296
+ *
297
+ * @param extendedValidation - Extended validation instance from useExtendedValidation
298
+ * @returns Resolver, validation error state, and a binder for the owning RHF control
299
+ */
300
+ const useFormResolver = (extendedValidation) => {
301
+ const control = useRef(null);
302
+ const bindControl = useCallback((instance) => {
303
+ control.current = instance;
304
+ return () => {
305
+ if (control.current === instance) control.current = null;
306
+ };
307
+ }, []);
308
+ const [validationErrorsState, setValidationErrorsState] = useState({
309
+ errors: void 0,
310
+ hash: void 0
311
+ });
312
+ /**
313
+ * Updates resolver error state only when the formatted validation result
314
+ * actually changes. Veto/RHF may create new error objects for equivalent
315
+ * validation output, so the hash is the guard against avoidable context
316
+ * refreshes.
317
+ */
318
+ const updateValidationErrors = useCallback((errors) => {
319
+ const nextHash = JSON.stringify(errors);
320
+ setValidationErrorsState((current) => {
321
+ if (current.hash === nextHash) return current;
322
+ return {
323
+ errors,
324
+ hash: nextHash
325
+ };
326
+ });
327
+ }, []);
328
+ return {
329
+ bindControl,
330
+ resolver: useMemo(() => {
331
+ if (!extendedValidation) return;
332
+ return async (values) => {
333
+ const validationValues = toValidationFormat(values) ?? {};
334
+ const disabledFields = [...control.current?._names.disabled ?? []];
335
+ const validationInput = omitDisabledValues(validationValues, disabledFields);
336
+ const result = await extendedValidation.validateAsync(validationInput);
337
+ updateValidationErrors(result.errors ?? void 0);
338
+ const submissionValues = omitDisabledValues(result.data ?? {}, disabledFields);
339
+ if (result.errors) return {
340
+ errors: result.errors,
341
+ values: {}
342
+ };
343
+ return {
344
+ errors: {},
345
+ values: submissionValues
346
+ };
347
+ };
348
+ }, [extendedValidation, updateValidationErrors]),
349
+ validationErrors: validationErrorsState.errors,
350
+ validationErrorsHash: validationErrorsState.hash
351
+ };
352
+ };
353
+ //#endregion
354
+ //#region src/Form/subcomponents/FormContext.tsx
355
+ const debug = createDebug("uniform:FormContext");
356
+ const DEBUG_MODE_LOCAL_STORAGE_KEY_DEFAULT = "uniform:debug-mode";
357
+ if (!window.__UNIFORM_CONTEXT__) {
358
+ window.__UNIFORM_CONTEXT__ = React.createContext({
359
+ debugMode: "off",
360
+ formReset: {
361
+ subscribe: () => {
362
+ return () => {};
363
+ },
364
+ notify: () => {}
365
+ },
366
+ preventSubmit: () => {},
367
+ setDebugMode: () => {},
368
+ triggerSubmit: () => {},
369
+ userChange: {
370
+ subscribe: () => {
371
+ return () => {};
372
+ },
373
+ notify: () => {}
374
+ },
375
+ validation: { setClientValidationSchema: () => {} }
376
+ });
377
+ debug("Creating new UniformContext instance");
378
+ } else debug("Reusing existing UniformContext instance from window.__UNIFORM_CONTEXT__");
379
+ const UniformContext = window.__UNIFORM_CONTEXT__;
380
+ debug("UniformContext exported", {
381
+ contextExists: !!UniformContext,
382
+ windowContextExists: !!window.__UNIFORM_CONTEXT__,
383
+ contextsMatch: UniformContext === window.__UNIFORM_CONTEXT__
384
+ });
385
+ /**
386
+ * FormProvider component provides:
387
+ * - Veto validation schema context
388
+ * - Resolver-backed validation error state
389
+ * - RHF control binding for disabled-value omission without changing schema rules
390
+ * - Client validation schema management
391
+ * - Submit handler with automatic data conversion and submission control with preventSubmit
392
+ * - Form Debug Mode state
393
+ * - Form reset pub/sub notifications (`formReset`)
394
+ * - User change pub/sub notifications (`userChange`)
395
+ * - React Hook Form context
396
+ */
397
+ const FormProvider$1 = ({ children, debugModeSettings = void 0, initialValues = void 0, onSubmit, validation: baseValidation = void 0, validationTrigger }) => {
398
+ const sensitiveFields = useMemo(() => {
399
+ return createSensitiveFields();
400
+ }, []);
401
+ const [debugMode, setDebugMode] = useLocalStorage(debugModeSettings?.localStorageKey ?? DEBUG_MODE_LOCAL_STORAGE_KEY_DEFAULT, "off");
402
+ const { extendedValidation, setClientValidationSchema } = useExtendedValidation(baseValidation);
403
+ const { bindControl, resolver, validationErrors, validationErrorsHash } = useFormResolver(extendedValidation);
404
+ const methods = useForm({
405
+ defaultValues: initialValues ? toFormFormat(initialValues) : initialValues,
406
+ mode: validationTrigger,
407
+ resolver
408
+ });
409
+ useLayoutEffect(() => {
410
+ return bindControl(methods.control);
411
+ }, [bindControl, methods.control]);
412
+ const isValid = methods.formState?.isValid;
413
+ const [preventSubmit, setPreventSubmit] = useState(false);
414
+ const formResetListenersRef = useRef(/* @__PURE__ */ new Set());
415
+ const subscribeFormReset = useCallback((listener) => {
416
+ formResetListenersRef.current.add(listener);
417
+ return () => {
418
+ formResetListenersRef.current.delete(listener);
419
+ };
420
+ }, []);
421
+ const notifyFormReset = useCallback(() => {
422
+ formResetListenersRef.current.forEach((listener) => {
423
+ listener();
424
+ });
425
+ }, []);
426
+ const userChangeListenersRef = useRef(/* @__PURE__ */ new Set());
427
+ const subscribeUserChange = useCallback((listener) => {
428
+ userChangeListenersRef.current.add(listener);
429
+ return () => {
430
+ userChangeListenersRef.current.delete(listener);
431
+ };
432
+ }, []);
433
+ const notifyUserChange = useCallback((fieldName, value) => {
434
+ userChangeListenersRef.current.forEach((listener) => {
435
+ listener(fieldName, value);
436
+ });
437
+ }, []);
438
+ const handleSubmit = async (e) => {
439
+ debug("handleSubmit called", {
440
+ preventSubmit,
441
+ formStateIsValid: methods.formState.isValid,
442
+ validationErrors: sensitiveFields.redact(methods.formState.errors),
443
+ validationTrigger,
444
+ formValues: sensitiveFields.redact(methods.getValues())
445
+ });
446
+ if (methods.formState.isValid && preventSubmit) {
447
+ debug("⛔ Form submit PREVENTED", {
448
+ formStateIsValid: methods.formState.isValid,
449
+ preventSubmit
450
+ });
451
+ console.warn("[FormProvider] form submit was prevented because preventSubmit is true...");
452
+ e?.preventDefault();
453
+ return Promise.resolve();
454
+ }
455
+ debug("✓ Form submit ALLOWED", {
456
+ formStateIsValid: methods.formState.isValid,
457
+ preventSubmit,
458
+ reason: !methods.formState.isValid ? "Form is invalid (will trigger validation and show errors)" : "Form is valid and preventSubmit is false"
459
+ });
460
+ const wrappedOnSubmit = (data, event) => {
461
+ const submitData = toSubmitFormat(data) ?? {};
462
+ debug("onSubmit callback called", { submitData: toSubmitFormat(sensitiveFields.redact(data)) ?? {} });
463
+ return onSubmit(submitData, event);
464
+ };
465
+ await methods.handleSubmit(wrappedOnSubmit)(e);
466
+ debug("handleSubmit completed");
467
+ };
468
+ const contextValue = useMemo(() => {
469
+ return {
470
+ debugMode: debugModeSettings?.disable ? "disabled" : debugMode,
471
+ preventSubmit: (prevent) => {
472
+ debug("preventSubmit called", {
473
+ previousValue: preventSubmit,
474
+ newValue: prevent,
475
+ formStateIsValid: methods.formState.isValid,
476
+ validationErrors: sensitiveFields.redact(methods.formState.errors)
477
+ });
478
+ setPreventSubmit(prevent);
479
+ },
480
+ setClientValidationSchema,
481
+ setDebugMode,
482
+ triggerSubmit: handleSubmit,
483
+ formReset: {
484
+ subscribe: subscribeFormReset,
485
+ notify: notifyFormReset
486
+ },
487
+ userChange: {
488
+ subscribe: subscribeUserChange,
489
+ notify: notifyUserChange
490
+ },
491
+ validation: {
492
+ baseInstance: baseValidation,
493
+ instance: extendedValidation,
494
+ errors: validationErrors,
495
+ setClientValidationSchema
496
+ }
497
+ };
498
+ }, [
499
+ debugMode,
500
+ debugModeSettings?.disable,
501
+ validationErrorsHash
502
+ ]);
503
+ return /* @__PURE__ */ jsx(SensitiveFieldsProvider, {
504
+ registry: sensitiveFields,
505
+ children: /* @__PURE__ */ jsx(UniformContext.Provider, {
506
+ value: contextValue,
507
+ children: /* @__PURE__ */ jsx(FormProvider, {
508
+ ...methods,
509
+ children: children({
510
+ handleSubmit,
511
+ isValid
512
+ })
513
+ })
514
+ })
515
+ });
516
+ };
517
+ //#endregion
518
+ export { useSensitiveField as a, useSensitiveDebug as i, UniformContext as n, redactDebugData as r, FormProvider$1 as t };
519
+
520
+ //# sourceMappingURL=FormContext-CHctWFAP.mjs.map