@fuf-stack/uniform 1.30.0 → 2.0.0-next.3

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 +0 -6
  2. package/dist/Checkboxes/index.d.mts +178 -274
  3. package/dist/Checkboxes/index.d.mts.map +1 -1
  4. package/dist/Checkboxes/index.mjs +294 -94
  5. package/dist/Checkboxes/index.mjs.map +1 -1
  6. package/dist/DatePicker/index.d.mts +1963 -148
  7. package/dist/DatePicker/index.d.mts.map +1 -1
  8. package/dist/DatePicker/index.mjs +401 -82
  9. package/dist/DatePicker/index.mjs.map +1 -1
  10. package/dist/FieldArray/index.d.mts +102 -97
  11. package/dist/FieldArray/index.d.mts.map +1 -1
  12. package/dist/FieldArray/index.mjs +340 -195
  13. package/dist/FieldArray/index.mjs.map +1 -1
  14. package/dist/FieldCard/index.d.mts +34 -34
  15. package/dist/FieldCard/index.d.mts.map +1 -1
  16. package/dist/FieldCard/index.mjs +181 -127
  17. package/dist/FieldCard/index.mjs.map +1 -1
  18. package/dist/{FieldCopyTestIdButton-Y9SfvaM9.mjs → FieldCopyTestIdButton-D3_jZYJ1.mjs} +4 -2
  19. package/dist/FieldCopyTestIdButton-D3_jZYJ1.mjs.map +1 -0
  20. package/dist/FieldDescription-X_0s1Lhu.mjs +35 -0
  21. package/dist/FieldDescription-X_0s1Lhu.mjs.map +1 -0
  22. package/dist/FieldLabel-DrNWJIVh.mjs +128 -0
  23. package/dist/FieldLabel-DrNWJIVh.mjs.map +1 -0
  24. package/dist/FieldLayout-DcvQU0zN.mjs +45 -0
  25. package/dist/FieldLayout-DcvQU0zN.mjs.map +1 -0
  26. package/dist/FieldReset/index.d.mts +17 -12
  27. package/dist/FieldReset/index.d.mts.map +1 -1
  28. package/dist/FieldReset/index.mjs +50 -33
  29. package/dist/FieldReset/index.mjs.map +1 -1
  30. package/dist/FieldValidationError-iAayfTEw.mjs +75 -0
  31. package/dist/FieldValidationError-iAayfTEw.mjs.map +1 -0
  32. package/dist/Form/index.d.mts +2 -2
  33. package/dist/Form/index.d.mts.map +1 -1
  34. package/dist/Form/index.mjs +9 -7
  35. package/dist/Form/index.mjs.map +1 -1
  36. package/dist/{FormContext-Dvt3MiKq.d.mts → FormContext-BnNJYZOo.d.mts} +3 -3
  37. package/dist/{FormContext-Dvt3MiKq.d.mts.map → FormContext-BnNJYZOo.d.mts.map} +1 -1
  38. package/dist/{FormContext-B8G_Xxd6.mjs → FormContext-PXkVlBdU.mjs} +6 -2
  39. package/dist/FormContext-PXkVlBdU.mjs.map +1 -0
  40. package/dist/Grid/index.mjs +1 -1
  41. package/dist/{Grid-Us2JFczS.mjs → Grid-DBL29Kwb.mjs} +4 -2
  42. package/dist/Grid-DBL29Kwb.mjs.map +1 -0
  43. package/dist/Input/index.d.mts +734 -47
  44. package/dist/Input/index.d.mts.map +1 -1
  45. package/dist/Input/index.mjs +411 -168
  46. package/dist/Input/index.mjs.map +1 -1
  47. package/dist/RadioBoxes/index.d.mts +300 -98
  48. package/dist/RadioBoxes/index.d.mts.map +1 -1
  49. package/dist/RadioBoxes/index.mjs +156 -119
  50. package/dist/RadioBoxes/index.mjs.map +1 -1
  51. package/dist/RadioTabs/index.d.mts +302 -76
  52. package/dist/RadioTabs/index.d.mts.map +1 -1
  53. package/dist/RadioTabs/index.mjs +274 -87
  54. package/dist/RadioTabs/index.mjs.map +1 -1
  55. package/dist/Radios/index.d.mts +314 -78
  56. package/dist/Radios/index.d.mts.map +1 -1
  57. package/dist/Radios/index.mjs +90 -44
  58. package/dist/Radios/index.mjs.map +1 -1
  59. package/dist/Select/index.d.mts +410 -142
  60. package/dist/Select/index.d.mts.map +1 -1
  61. package/dist/Select/index.mjs +284 -157
  62. package/dist/Select/index.mjs.map +1 -1
  63. package/dist/Slider/index.d.mts +382 -63
  64. package/dist/Slider/index.d.mts.map +1 -1
  65. package/dist/Slider/index.mjs +269 -90
  66. package/dist/Slider/index.mjs.map +1 -1
  67. package/dist/SubmitButton/index.d.mts.map +1 -1
  68. package/dist/SubmitButton/index.mjs +4 -1
  69. package/dist/SubmitButton/index.mjs.map +1 -1
  70. package/dist/Switch/index.d.mts +2 -427
  71. package/dist/Switch/index.mjs +167 -72
  72. package/dist/Switch/index.mjs.map +1 -1
  73. package/dist/Switch-Db2dpGz7.d.mts +648 -0
  74. package/dist/Switch-Db2dpGz7.d.mts.map +1 -0
  75. package/dist/SwitchBox/index.d.mts +191 -91
  76. package/dist/SwitchBox/index.d.mts.map +1 -1
  77. package/dist/SwitchBox/index.mjs +142 -88
  78. package/dist/SwitchBox/index.mjs.map +1 -1
  79. package/dist/TextArea/index.d.mts +347 -29
  80. package/dist/TextArea/index.d.mts.map +1 -1
  81. package/dist/TextArea/index.mjs +195 -47
  82. package/dist/TextArea/index.mjs.map +1 -1
  83. package/dist/Time/index.d.mts +1373 -139
  84. package/dist/Time/index.d.mts.map +1 -1
  85. package/dist/Time/index.mjs +160 -77
  86. package/dist/Time/index.mjs.map +1 -1
  87. package/dist/helpers/index.d.mts +1 -1
  88. package/dist/helpers/index.mjs +1 -1
  89. package/dist/helpers/index.mjs.map +1 -1
  90. package/dist/hooks/useClientValidation/index.mjs +1 -1
  91. package/dist/hooks/useController/index.d.mts +29 -2
  92. package/dist/hooks/useController/index.d.mts.map +1 -0
  93. package/dist/hooks/useController/index.mjs +1 -1
  94. package/dist/hooks/useFormContext/index.d.mts +44 -2
  95. package/dist/hooks/useFormContext/index.d.mts.map +1 -0
  96. package/dist/hooks/useFormContext/index.mjs +1 -1
  97. package/dist/hooks/useInputValueDebounce/index.d.mts +9 -3
  98. package/dist/hooks/useInputValueDebounce/index.d.mts.map +1 -1
  99. package/dist/hooks/useInputValueDebounce/index.mjs +27 -5
  100. package/dist/hooks/useInputValueDebounce/index.mjs.map +1 -1
  101. package/dist/hooks/useInputValueTransform/index.d.mts +1 -2
  102. package/dist/hooks/useInputValueTransform/index.mjs +1 -1
  103. package/dist/hooks/useWatchFormReset/index.mjs +1 -1
  104. package/dist/hooks/useWatchUserChange/index.mjs +1 -1
  105. package/dist/{useInputValueTransform-cevZBrIN.d.mts → index-cevZBrIN.d.mts} +1 -1
  106. package/dist/index-cevZBrIN.d.mts.map +1 -0
  107. package/dist/partials/FieldCopyTestIdButton/index.mjs +1 -1
  108. package/dist/partials/FieldValidationError/index.d.mts +637 -3
  109. package/dist/partials/FieldValidationError/index.d.mts.map +1 -1
  110. package/dist/partials/FieldValidationError/index.mjs +1 -1
  111. package/dist/radioControlVariants-BYRfaD6y.mjs +187 -0
  112. package/dist/radioControlVariants-BYRfaD6y.mjs.map +1 -0
  113. package/dist/switchVariants-D16b2VaT.mjs +67 -0
  114. package/dist/switchVariants-D16b2VaT.mjs.map +1 -0
  115. package/dist/timeVariants-CtXyNKmW.mjs +58 -0
  116. package/dist/timeVariants-CtXyNKmW.mjs.map +1 -0
  117. package/dist/{useController-CJjMqXU5.mjs → useController-JtIeurpw.mjs} +2 -2
  118. package/dist/{useController-CJjMqXU5.mjs.map → useController-JtIeurpw.mjs.map} +1 -1
  119. package/dist/{useFormContext-BEjPBdzb.mjs → useFormContext-piqnN2L-.mjs} +2 -2
  120. package/dist/{useFormContext-BEjPBdzb.mjs.map → useFormContext-piqnN2L-.mjs.map} +1 -1
  121. package/dist/{useInputValueTransform-D44BLp1Z.mjs → useInputValueTransform-CXWWFhy_.mjs} +2 -2
  122. package/dist/{useInputValueTransform-D44BLp1Z.mjs.map → useInputValueTransform-CXWWFhy_.mjs.map} +1 -1
  123. package/package.json +13 -25
  124. package/dist/FieldCopyTestIdButton-Y9SfvaM9.mjs.map +0 -1
  125. package/dist/FieldValidationError-BcUV0r1I.mjs +0 -48
  126. package/dist/FieldValidationError-BcUV0r1I.mjs.map +0 -1
  127. package/dist/FormContext-B8G_Xxd6.mjs.map +0 -1
  128. package/dist/Grid-Us2JFczS.mjs.map +0 -1
  129. package/dist/Switch/index.d.mts.map +0 -1
  130. package/dist/hooks/useInput/index.d.mts +0 -2
  131. package/dist/hooks/useInput/index.mjs +0 -5
  132. package/dist/hooks/useInput/index.mjs.map +0 -1
  133. package/dist/hooks/useUniformField/index.d.mts +0 -2
  134. package/dist/hooks/useUniformField/index.mjs +0 -141
  135. package/dist/hooks/useUniformField/index.mjs.map +0 -1
  136. package/dist/hooks/useUniformFieldArray/index.d.mts +0 -47
  137. package/dist/hooks/useUniformFieldArray/index.d.mts.map +0 -1
  138. package/dist/hooks/useUniformFieldArray/index.mjs +0 -99
  139. package/dist/hooks/useUniformFieldArray/index.mjs.map +0 -1
  140. package/dist/index-CaxrMD1A.d.mts +0 -1
  141. package/dist/index-DsB0_365.d.mts +0 -106
  142. package/dist/index-DsB0_365.d.mts.map +0 -1
  143. package/dist/useController-CdFEp-Wa.d.mts +0 -30
  144. package/dist/useController-CdFEp-Wa.d.mts.map +0 -1
  145. package/dist/useFormContext-BSSUZ0Md.d.mts +0 -45
  146. package/dist/useFormContext-BSSUZ0Md.d.mts.map +0 -1
  147. package/dist/useInput-ClpHDPdr.d.mts +0 -2
  148. package/dist/useInput-NPbS4w_n.mjs +0 -1
  149. package/dist/useInputValueTransform-cevZBrIN.d.mts.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"FieldCopyTestIdButton-Y9SfvaM9.mjs","names":[],"sources":["../src/partials/FieldCopyTestIdButton/FieldCopyTestIdButton.tsx","../src/partials/FieldCopyTestIdButton/index.ts"],"sourcesContent":["import { FaBullseye } from 'react-icons/fa6';\n\nimport { cn } from '@fuf-stack/pixel-utils';\nimport { Button } from '@fuf-stack/pixels';\n\nexport interface FieldCopyTestIdButtonProps {\n /** CSS class name */\n className?: string;\n /** HTML data-testid attribute used in e2e tests */\n testId: string;\n}\n\nconst FieldCopyTestIdButton = ({\n className = undefined,\n testId,\n}: FieldCopyTestIdButtonProps) => {\n const copyToClipboard = () => {\n // This component runs in the browser; the Node compatibility rule cannot\n // distinguish the DOM Clipboard API from Node's global navigator.\n // eslint-disable-next-line n/no-unsupported-features/node-builtins\n navigator.clipboard.writeText(testId).catch((err) => {\n console.error('Error copying TestId to clipboard', err);\n });\n };\n\n return (\n <Button\n className={cn(className, 'pointer-events-auto')}\n icon={<FaBullseye />}\n onClick={copyToClipboard}\n size=\"sm\"\n variant=\"light\"\n />\n );\n};\nexport default FieldCopyTestIdButton;\n","import FieldCopyTestIdButton from './FieldCopyTestIdButton';\n\nexport type { FieldCopyTestIdButtonProps } from './FieldCopyTestIdButton';\n\nexport default FieldCopyTestIdButton;\n"],"mappings":";;;;;AAYA,MAAM,yBAAyB,EAC7B,YAAY,KAAA,GACZ,aACgC;CAChC,MAAM,wBAAwB;EAI5B,UAAU,UAAU,UAAU,MAAM,CAAC,CAAC,OAAO,QAAQ;GACnD,QAAQ,MAAM,qCAAqC,GAAG;EACxD,CAAC;CACH;CAEA,OACE,oBAAC,QAAD;EACE,WAAW,GAAG,WAAW,qBAAqB;EAC9C,MAAM,oBAAC,YAAD,CAAa,CAAA;EACnB,SAAS;EACT,MAAK;EACL,SAAQ;CACT,CAAA;AAEL;;AC9BA,IAAA,gCAAe"}
@@ -1,48 +0,0 @@
1
- import { slugify } from "@fuf-stack/pixel-utils";
2
- import { jsx } from "react/jsx-runtime";
3
- import { AnimatePresence, motion, useReducedMotion } from "@fuf-stack/pixel-motion";
4
- // src/partials/FieldValidationError/FieldValidationError.tsx
5
- /**
6
- * Renders a validation error of a field
7
- */
8
- const FieldValidationError = ({ className = void 0, error = void 0, testId }) => {
9
- const disableAnimation = useReducedMotion();
10
- return /* @__PURE__ */ jsx("ul", {
11
- "aria-label": `Validation errors of field ${testId}`,
12
- className,
13
- "data-testid": slugify(`${testId}_error`),
14
- children: /* @__PURE__ */ jsx(AnimatePresence, {
15
- initial: !disableAnimation,
16
- children: error?.map(({ message }, i) => {
17
- return /* @__PURE__ */ jsx(motion.li, {
18
- animate: disableAnimation ? void 0 : {
19
- opacity: 1,
20
- height: "auto"
21
- },
22
- exit: disableAnimation ? void 0 : {
23
- opacity: 0,
24
- height: 0
25
- },
26
- initial: disableAnimation ? false : {
27
- height: 0,
28
- opacity: 0
29
- },
30
- style: { overflow: "hidden" },
31
- transition: {
32
- duration: .2,
33
- ease: "circOut"
34
- },
35
- children: /* @__PURE__ */ jsx("div", {
36
- className: "px-1 pt-1",
37
- children: message
38
- })
39
- }, slugify(`${testId}_error_${i}`));
40
- })
41
- })
42
- });
43
- };
44
- // src/partials/FieldValidationError/index.ts
45
- var FieldValidationError_default = FieldValidationError;
46
- export { FieldValidationError as n, FieldValidationError_default as t };
47
-
48
- //# sourceMappingURL=FieldValidationError-BcUV0r1I.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"FieldValidationError-BcUV0r1I.mjs","names":[],"sources":["../src/partials/FieldValidationError/FieldValidationError.tsx","../src/partials/FieldValidationError/index.ts"],"sourcesContent":["import type { FieldError } from 'react-hook-form';\n\nimport {\n AnimatePresence,\n motion,\n useReducedMotion,\n} from '@fuf-stack/pixel-motion';\nimport { slugify } from '@fuf-stack/pixel-utils';\n\nexport interface FieldValidationErrorProps {\n /** CSS class name */\n className?: string;\n /** Field errors */\n error?: FieldError[];\n /** HTML data-testid attribute used in e2e tests */\n testId: string;\n}\n\n/**\n * Renders a validation error of a field\n */\nconst FieldValidationError = ({\n className = undefined,\n error = undefined,\n testId,\n}: FieldValidationErrorProps) => {\n // disable all animation if user prefers reduced motion\n const disableAnimation = useReducedMotion();\n\n return (\n <ul\n aria-label={`Validation errors of field ${testId}`}\n className={className}\n data-testid={slugify(`${testId}_error`)}\n >\n <AnimatePresence initial={!disableAnimation}>\n {error?.map(({ message }, i) => {\n return (\n <motion.li\n key={slugify(`${testId}_error_${i}`)}\n animate={\n disableAnimation ? undefined : { opacity: 1, height: 'auto' }\n }\n exit={disableAnimation ? undefined : { opacity: 0, height: 0 }}\n initial={disableAnimation ? false : { height: 0, opacity: 0 }}\n style={{ overflow: 'hidden' }}\n transition={{ duration: 0.2, ease: 'circOut' }}\n >\n {/* wrap in div to apply padding and animation does not jump */}\n <div className=\"px-1 pt-1\">{message}</div>\n </motion.li>\n );\n })}\n </AnimatePresence>\n </ul>\n );\n};\n\nexport default FieldValidationError;\n","import FieldValidationError from './FieldValidationError';\n\nexport type { FieldValidationErrorProps } from './FieldValidationError';\n\nexport default FieldValidationError;\n"],"mappings":";;;;;;;AAqBA,MAAM,wBAAwB,EAC5B,YAAY,KAAA,GACZ,QAAQ,KAAA,GACR,aAC+B;CAE/B,MAAM,mBAAmB,iBAAiB;CAE1C,OACE,oBAAC,MAAD;EACE,cAAY,8BAA8B;EAC/B;EACX,eAAa,QAAQ,GAAG,OAAO,OAAO;EAEtC,UAAA,oBAAC,iBAAD;GAAiB,SAAS,CAAC;GACxB,UAAA,OAAO,KAAK,EAAE,WAAW,MAAM;IAC9B,OACE,oBAAC,OAAO,IAAR;KAEE,SACE,mBAAmB,KAAA,IAAY;MAAE,SAAS;MAAG,QAAQ;KAAO;KAE9D,MAAM,mBAAmB,KAAA,IAAY;MAAE,SAAS;MAAG,QAAQ;KAAE;KAC7D,SAAS,mBAAmB,QAAQ;MAAE,QAAQ;MAAG,SAAS;KAAE;KAC5D,OAAO,EAAE,UAAU,SAAS;KAC5B,YAAY;MAAE,UAAU;MAAK,MAAM;KAAU;KAG7C,UAAA,oBAAC,OAAD;MAAK,WAAU;MAAa,UAAA;KAAa,CAAA;IAChC,GAXJ,QAAQ,GAAG,OAAO,SAAS,GAAG,CAW1B;GAEf,CAAC;EACc,CAAA;CACf,CAAA;AAER;;ACpDA,IAAA,+BAAe"}
@@ -1 +0,0 @@
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,IACzB,MAAM,KAAK,SAAS;EAClB,OAAO,KACJ,QAAQ,cAAc,KAAK,CAAC,CAC5B,MAAM,GAAG,CAAC,CACV,QAAQ,SAAS;GAChB,OAAO,SAAS;EAClB,CAAC,CAAC,CACD,KAAK,GAAG;CACb,CAAC,CACH;CAGA,MAAM,yBAAS,IAAI,QAAyB;CAC5C,MAAM,SAAS,OAAgB,SAA0B;EAGvD,IAAI,eAAe,IAAI,IAAI,GACzB,OAAO;EAET,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B,OAAO;EAET,MAAM,WAAW,OAAO,IAAI,KAAK;EACjC,IAAI,UACF,OAAO;EAET,IAAI,MAAM,QAAQ,KAAK,GAAG;GACxB,MAAM,OAAkB,CAAC;GACzB,OAAO,IAAI,OAAO,IAAI;GACtB,MAAM,SAAS,MAAM,UAAU;IAC7B,KAAK,SAAS,MAAM,MAAM,OAAO,GAAG,KAAK,GAAG,UAAU,OAAO,KAAK,CAAC;GACrE,CAAC;GACD,OAAO,OAAO,KAAK;GACnB,OAAO;EACT;EAEA,MAAM,YAAqB,OAAO,eAAe,KAAK;EACtD,IAAI,cAAc,OAAO,aAAa,cAAc,MAClD,OAAO;EAET,MAAM,OAAgC,CAAC;EACvC,OAAO,IAAI,OAAO,IAAI;EACtB,OAAO,QAAQ,KAAgC,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;GAGzE,OAAO,eAAe,MAAM,KAAK;IAC/B,OAAO,MAAM,OAAO,OAAO,GAAG,KAAK,GAAG,QAAQ,GAAG;IACjD,YAAY;IACZ,UAAU;IACV,cAAc;GAChB,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EACK,CAAA;CACF,CAAA;AAE7B"}
@@ -1 +0,0 @@
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"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.mts","names":["HeroSwitchProps"],"sources":["../../src/Switch/Switch.tsx"],"mappings":";;;qBAaa,kBAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAyBtB,eAAe,eAAe;KAC9B,YAAY,mBAAmB;UAEnB,oBAAoB;;EAEnC;;EAEA,YAAY;;EAEZ;;EAEA,aAAa;;EAEb,QAAQ;;EAER;;EAEA;EAEA;;EAEA,eAAe;;EAEf;;EAEA,YAAYA;;;;;cAMR,WAAU,WAAA,YAAA,MAAA,MAAA,cAAA,cAAA,qBAQb,gCAAW,IAAA"}
@@ -1,2 +0,0 @@
1
- import { t as useInput } from "../../useInput-ClpHDPdr.mjs";
2
- export { useInput };
@@ -1,5 +0,0 @@
1
- // src/hooks/useInput/index.ts
2
- /* v8 ignore stop */
3
- export { t as useInput } from "../../useInput-NPbS4w_n.mjs";
4
-
5
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/hooks/useInput/index.ts"],"sourcesContent":["/* v8 ignore start */\n\nexport * from './useInput';\n\n/* v8 ignore stop */\n"],"mappings":""}
@@ -1,2 +0,0 @@
1
- import { n as UseUniformFieldReturn, r as useUniformField, t as UseUniformFieldParams } from "../../index-DsB0_365.mjs";
2
- export { UseUniformFieldParams, UseUniformFieldReturn, useUniformField };
@@ -1,141 +0,0 @@
1
- import { a as useSensitiveField } from "../../FormContext-B8G_Xxd6.mjs";
2
- import { flattenFieldErrors, isValueEmpty } from "../../helpers/index.mjs";
3
- import { t as FieldCopyTestIdButton_default } from "../../FieldCopyTestIdButton-Y9SfvaM9.mjs";
4
- import { t as FieldValidationError_default } from "../../FieldValidationError-BcUV0r1I.mjs";
5
- import { t as useController } from "../../useController-CJjMqXU5.mjs";
6
- import { n as useFormContext } from "../../useFormContext-BEjPBdzb.mjs";
7
- import { t as useInput } from "../../useInput-NPbS4w_n.mjs";
8
- import { t as useInputValueTransform } from "../../useInputValueTransform-D44BLp1Z.mjs";
9
- import "react";
10
- import { useDebounce } from "@fuf-stack/pixels";
11
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
12
- // src/hooks/useUniformField/useUniformField.tsx
13
- /**
14
- * Combines frequently used form field logic into a single hook.
15
- *
16
- * Provides:
17
- * - Enhanced form context (validation-aware state, `testId`, value transforms)
18
- * - Controller field with nullish conversion handling
19
- * - Value transformation via `transform` prop:
20
- * • Allows disentangled display and form values (e.g., string ↔ object, boolean ↔ array)
21
- * • Automatically applies `toDisplayValue` to field value for components
22
- * • Automatically applies `toFormValue` to display value when onChange is called
23
- * • Works with `type` prop for automatic number/string conversion
24
- * • Examples: storing objects while displaying strings, storing booleans as arrays, enriching values with metadata
25
- * - Debounced `invalid` state with smart timing:
26
- * • `true` (field becomes invalid): applies immediately so errors show right away
27
- * • `false` (field becomes valid): delayed 200ms to allow smooth exit animations
28
- * • Respects `prefers-reduced-motion` by skipping delays when user prefers reduced motion
29
- * - Smart `invalid` visibility (via `showInvalid`):
30
- * • Shows errors when field is dirty OR touched OR form has been submitted
31
- * • Prevents showing errors on pristine/untouched fields for better UX
32
- * • Works well for all field types (text inputs, checkboxes, radios, arrays)
33
- * - Prebuilt `errorMessage` React node (with optional array-error normalization via `isArrayValue`)
34
- * - Read-only support: `readOnly` is returned for components to render a
35
- * focusable, non-editable control; the field stays enabled in RHF, so its
36
- * value is validated and submitted
37
- * - Computed `label` node which appends a `FieldCopyTestIdButton` in
38
- * `debug-testids` mode
39
- * - `defaultValue` for uncontrolled defaults and all usual field handlers
40
- * - Access to form utilities: `control`, `getValues`, `resetField`
41
- * - Presentation helpers: `getLabelProps`, `getErrorMessageProps`,
42
- * `getHelperWrapperProps` for consistent wiring to underlying UI components
43
- */
44
- const useUniformField = (params) => {
45
- const { name, ariaLabel: customAriaLabel, disabled = false, isArrayValue = false, readOnly = false, sensitive = false, testId: explicitTestId, label, type, transform } = params;
46
- useSensitiveField(name, type === "password" || sensitive);
47
- const { control, debugMode, formState: { submitCount }, getFieldState, getValues, resetField } = useFormContext();
48
- const { error: rawError, invalid: rawInvalid, isDirty, isTouched, required, testId } = getFieldState(name, explicitTestId);
49
- const { field } = useController({
50
- control,
51
- disabled,
52
- name
53
- });
54
- const { onChange: fieldOnChange, value: fieldValue, disabled: isDisabled, onBlur, ref } = field;
55
- const { toDisplayValue, toFormValue } = useInputValueTransform({
56
- type,
57
- transform
58
- });
59
- const transformedValue = toDisplayValue(fieldValue);
60
- const transformedOnChange = (eventOrValue) => {
61
- const displayValue = eventOrValue?.target?.value ?? eventOrValue;
62
- const formValue = toFormValue(displayValue);
63
- fieldOnChange(formValue);
64
- };
65
- const defaultValue = getValues()?.[name];
66
- /**
67
- * Determine when to show the invalid state to the user.
68
- *
69
- * Show errors when the field is invalid AND any of these conditions are met:
70
- * - Field has a user-entered value (show validation errors like format/length while typing)
71
- * - Field is touched (focused and blurred) - good for text inputs
72
- * - Form has been submitted - shows all errors after submit attempt
73
- *
74
- * Note: `hasValue` is gated by `isDirty` so invalid initial values do not
75
- * show errors just because resolver-backed validation state is available.
76
- * Newly added empty array elements can be dirty, but stay hidden until blur
77
- * because they do not have a value yet.
78
- *
79
- * This prevents showing errors on pristine/untouched/empty fields for better UX.
80
- * Examples:
81
- * - Text input: User loads form with empty required field → no error shown yet
82
- * - Text input: User types invalid content → error shows immediately (has value)
83
- * - Text input: User focuses and blurs without typing → error shows (via isTouched)
84
- * - Checkbox/radio: User selects option → error shows immediately (has value)
85
- * - Field array: User adds element → no error yet; after blur → error shows
86
- * - Any field: User submits form → all errors show (via submitCount)
87
- *
88
- * The entire condition is debounced to prevent flickering and allow smooth animations.
89
- */
90
- const hasValue = !isValueEmpty(fieldValue);
91
- const invalid = useDebounce(rawInvalid && (isDirty && hasValue || isTouched || submitCount > 0), 200);
92
- const showTestIdCopyButton = debugMode === "debug-testids";
93
- const labelNode = !!label || showTestIdCopyButton ? /* @__PURE__ */ jsxs(Fragment, { children: [label !== false ? label : null, showTestIdCopyButton ? /* @__PURE__ */ jsx(FieldCopyTestIdButton_default, { testId }) : null] }) : null;
94
- const error = isArrayValue ? flattenFieldErrors(rawError) : rawError;
95
- const normalizedError = flattenFieldErrors(rawError);
96
- const errorMessage = /* @__PURE__ */ jsx(FieldValidationError_default, {
97
- error: normalizedError,
98
- testId
99
- });
100
- const { getErrorMessageProps, getLabelProps, getHelperWrapperProps } = useInput({
101
- ref,
102
- classNames: { helperWrapper: "p-0" },
103
- errorMessage: JSON.stringify(error),
104
- isInvalid: invalid,
105
- isRequired: required,
106
- label,
107
- labelPlacement: "outside"
108
- });
109
- return {
110
- ariaLabel: customAriaLabel ?? (typeof label === "string" ? label : name),
111
- control,
112
- debugMode,
113
- defaultValue,
114
- disabled: isDisabled,
115
- error,
116
- errorMessage,
117
- field: {
118
- ...field,
119
- value: transformedValue,
120
- onChange: transformedOnChange
121
- },
122
- getErrorMessageProps,
123
- getHelperWrapperProps,
124
- getLabelProps,
125
- getValues,
126
- invalid,
127
- label: labelNode,
128
- onBlur,
129
- onChange: transformedOnChange,
130
- readOnly,
131
- ref,
132
- required,
133
- resetField,
134
- testId
135
- };
136
- };
137
- // src/hooks/useUniformField/index.ts
138
- /* v8 ignore stop */
139
- export { useUniformField };
140
-
141
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","names":["FieldCopyTestIdButton","FieldValidationError"],"sources":["../../../src/hooks/useUniformField/useUniformField.tsx","../../../src/hooks/useUniformField/index.ts"],"sourcesContent":["import type { ReactNode } from 'react';\nimport type { FieldError, FieldValues, Path } from 'react-hook-form';\nimport type { InputValueTransform } from '../useInputValueTransform/useInputValueTransform';\n\nimport React from 'react';\n\nimport { useDebounce } from '@fuf-stack/pixels';\n\nimport { useSensitiveField } from '../../Form/subcomponents/SensitiveFields';\nimport { flattenFieldErrors, isValueEmpty } from '../../helpers';\nimport FieldCopyTestIdButton from '../../partials/FieldCopyTestIdButton';\nimport FieldValidationError from '../../partials/FieldValidationError';\nimport { useController } from '../useController/useController';\nimport { useFormContext } from '../useFormContext/useFormContext';\nimport { useInput } from '../useInput/useInput';\nimport { useInputValueTransform } from '../useInputValueTransform/useInputValueTransform';\n\nexport interface UseUniformFieldParams<\n TFieldValues extends FieldValues = FieldValues,\n TDisplay = unknown,\n> {\n /** Custom aria-label for accessibility. If not provided, falls back to field name when no visible label exists */\n ariaLabel?: string;\n /** Disables the field and omits its value from validation data and submission */\n disabled?: boolean;\n /** Normalize nested RHF errors into a flat array for array-like fields */\n isArrayValue?: boolean;\n /** Optional label content */\n label?: ReactNode;\n /** Form field name */\n name: Path<TFieldValues> & string;\n /** Makes the field read-only: users can focus and copy it but not change it; its value is still validated and submitted */\n readOnly?: boolean;\n /** Redacts the field value from Uniform debug output */\n sensitive?: boolean;\n /** Optional explicit test id used to build stable test ids */\n testId?: string;\n /** Optional value transformation between form and display values */\n transform?: InputValueTransform<TDisplay>;\n /** Input type for special number handling */\n type?: 'text' | 'number' | 'password';\n}\n\nexport interface UseUniformFieldReturn<\n TFieldValues extends FieldValues = FieldValues,\n> {\n /** Computed aria-label fallback (field name) when no visible label exists. Components can override based on their accessibility needs (e.g., if placeholder provides sufficient context) */\n ariaLabel: string | undefined;\n /** react-hook-form control instance for advanced integrations */\n control: ReturnType<typeof useFormContext<TFieldValues>>['control'];\n /** Debug mode from Uniform provider */\n debugMode: ReturnType<typeof useFormContext<TFieldValues>>['debugMode'];\n /** Current value used to initialize uncontrolled components */\n defaultValue: unknown;\n /** Whether the field is currently disabled (from RHF) */\n disabled: boolean | undefined;\n /** Validation errors from form state; flattened only when `isArrayValue` is enabled */\n error: FieldError[] | undefined;\n /** Pre-built errorMessage node to plug into components */\n errorMessage: ReactNode | null;\n /** RHF controller field with transformed value/onChange (use this for simple components) */\n field: ReturnType<typeof useController<TFieldValues>>['field'];\n /** Helper to spread standardized error message props to underlying components */\n getErrorMessageProps: ReturnType<typeof useInput>['getErrorMessageProps'];\n /** Helper to spread standardized helper wrapper props (for spacing/animation) */\n getHelperWrapperProps: ReturnType<typeof useInput>['getHelperWrapperProps'];\n /** Helper to spread standardized label props to underlying components */\n getLabelProps: ReturnType<typeof useInput>['getLabelProps'];\n /** Access current form values (converted to validation-friendly format) */\n getValues: ReturnType<typeof useFormContext<TFieldValues>>['getValues'];\n /** Whether the field should show invalid state (debounced for smooth animations). True when field is invalid AND (dirty OR touched OR submitted) */\n invalid: boolean;\n /** Computed label node including optional test id copy button */\n label: ReactNode | null;\n /** onBlur handler from controller */\n onBlur: ReturnType<typeof useController<TFieldValues>>['field']['onBlur'];\n /** onChange handler from controller (with transform applied) */\n onChange: ReturnType<typeof useController<TFieldValues>>['field']['onChange'];\n /** Whether the field is read-only; its value stays registered, validated and submitted */\n readOnly: boolean;\n /** Ref to forward to underlying control */\n ref: ReturnType<typeof useController<TFieldValues>>['field']['ref'];\n /** Whether the field is required according to validation schema */\n required: boolean;\n /** Reset a specific field in the form */\n resetField: ReturnType<typeof useFormContext<TFieldValues>>['resetField'];\n /** Generated HTML data-testid for the field */\n testId: string;\n}\n\n/**\n * Combines frequently used form field logic into a single hook.\n *\n * Provides:\n * - Enhanced form context (validation-aware state, `testId`, value transforms)\n * - Controller field with nullish conversion handling\n * - Value transformation via `transform` prop:\n * • Allows disentangled display and form values (e.g., string ↔ object, boolean ↔ array)\n * • Automatically applies `toDisplayValue` to field value for components\n * • Automatically applies `toFormValue` to display value when onChange is called\n * • Works with `type` prop for automatic number/string conversion\n * • Examples: storing objects while displaying strings, storing booleans as arrays, enriching values with metadata\n * - Debounced `invalid` state with smart timing:\n * • `true` (field becomes invalid): applies immediately so errors show right away\n * • `false` (field becomes valid): delayed 200ms to allow smooth exit animations\n * • Respects `prefers-reduced-motion` by skipping delays when user prefers reduced motion\n * - Smart `invalid` visibility (via `showInvalid`):\n * • Shows errors when field is dirty OR touched OR form has been submitted\n * • Prevents showing errors on pristine/untouched fields for better UX\n * • Works well for all field types (text inputs, checkboxes, radios, arrays)\n * - Prebuilt `errorMessage` React node (with optional array-error normalization via `isArrayValue`)\n * - Read-only support: `readOnly` is returned for components to render a\n * focusable, non-editable control; the field stays enabled in RHF, so its\n * value is validated and submitted\n * - Computed `label` node which appends a `FieldCopyTestIdButton` in\n * `debug-testids` mode\n * - `defaultValue` for uncontrolled defaults and all usual field handlers\n * - Access to form utilities: `control`, `getValues`, `resetField`\n * - Presentation helpers: `getLabelProps`, `getErrorMessageProps`,\n * `getHelperWrapperProps` for consistent wiring to underlying UI components\n */\nexport const useUniformField = <\n TFieldValues extends FieldValues = FieldValues,\n TDisplay = unknown,\n>(\n params: UseUniformFieldParams<TFieldValues, TDisplay>,\n): UseUniformFieldReturn<TFieldValues> => {\n const {\n name,\n ariaLabel: customAriaLabel,\n disabled = false,\n isArrayValue = false,\n readOnly = false,\n sensitive = false,\n testId: explicitTestId,\n label,\n type,\n transform,\n } = params;\n\n // Use the declared type, so revealing a password never disables redaction.\n useSensitiveField(name, type === 'password' || sensitive);\n\n const {\n control,\n debugMode,\n formState: { submitCount },\n getFieldState,\n getValues,\n resetField,\n } = useFormContext<TFieldValues>();\n\n const {\n error: rawError,\n invalid: rawInvalid,\n isDirty,\n isTouched,\n required,\n testId,\n } = getFieldState(name, explicitTestId);\n\n const { field } = useController<TFieldValues>({\n control,\n disabled,\n name,\n });\n const {\n onChange: fieldOnChange,\n value: fieldValue,\n disabled: isDisabled,\n onBlur,\n ref,\n } = field;\n\n // Get transform utilities (but don't apply them automatically)\n // Components can choose how to use them (directly or via useInputValueDebounce)\n const { toDisplayValue, toFormValue } = useInputValueTransform<TDisplay>({\n type,\n transform,\n });\n\n // For components without special needs: apply transform to value and onChange\n const transformedValue = toDisplayValue(fieldValue);\n const transformedOnChange = (eventOrValue: TDisplay | React.ChangeEvent) => {\n // Extract value from event or use value directly\n const displayValue =\n (eventOrValue as React.ChangeEvent<HTMLInputElement>)?.target?.value ??\n eventOrValue;\n const formValue = toFormValue(displayValue as TDisplay);\n fieldOnChange(formValue);\n };\n\n const defaultValue = (getValues() as Record<string, unknown>)?.[\n name as string\n ];\n\n /**\n * Determine when to show the invalid state to the user.\n *\n * Show errors when the field is invalid AND any of these conditions are met:\n * - Field has a user-entered value (show validation errors like format/length while typing)\n * - Field is touched (focused and blurred) - good for text inputs\n * - Form has been submitted - shows all errors after submit attempt\n *\n * Note: `hasValue` is gated by `isDirty` so invalid initial values do not\n * show errors just because resolver-backed validation state is available.\n * Newly added empty array elements can be dirty, but stay hidden until blur\n * because they do not have a value yet.\n *\n * This prevents showing errors on pristine/untouched/empty fields for better UX.\n * Examples:\n * - Text input: User loads form with empty required field → no error shown yet\n * - Text input: User types invalid content → error shows immediately (has value)\n * - Text input: User focuses and blurs without typing → error shows (via isTouched)\n * - Checkbox/radio: User selects option → error shows immediately (has value)\n * - Field array: User adds element → no error yet; after blur → error shows\n * - Any field: User submits form → all errors show (via submitCount)\n *\n * The entire condition is debounced to prevent flickering and allow smooth animations.\n */\n\n // isValueEmpty handles marker strings, flat array wrappers, empty arrays, and empty objects\n const hasValue = !isValueEmpty(fieldValue);\n const showInvalid =\n rawInvalid && ((isDirty && hasValue) || isTouched || submitCount > 0);\n // Debounce to prevent flickering during rapid state changes\n const invalid = useDebounce(showInvalid, 200);\n\n // Build a label node that:\n // - shows the provided label (unless explicitly set to false)\n // - appends a copy-to-clipboard button for the test id in `debug-testids` mode\n // Consumers can pass this directly to component `label` props\n const showTestIdCopyButton = debugMode === 'debug-testids';\n const labelNode: ReactNode | null =\n !!label || showTestIdCopyButton ? (\n <>\n {label !== false ? label : null}\n {showTestIdCopyButton ? (\n <FieldCopyTestIdButton testId={testId} />\n ) : null}\n </>\n ) : null;\n\n // Array-like fields can receive nested RHF error objects (index keys, _errors).\n // Opt-in flattening keeps backward compatibility for components that rely on\n // object-shaped errors (e.g. FieldCard/FieldArray).\n const error = isArrayValue ? flattenFieldErrors(rawError) : rawError;\n const normalizedError = flattenFieldErrors(rawError);\n\n // Ready-to-render error message; consumers can drop this into their\n // component `errorMessage` prop without repeating mapping/markup\n const errorMessage = (\n <FieldValidationError error={normalizedError} testId={testId} />\n );\n\n // Generate standardized props for label, helper wrapper and error message\n // so consumers can spread them directly into UI components (e.g. HeroUI),\n // keeping animations/spacing consistent across fields\n const { getErrorMessageProps, getLabelProps, getHelperWrapperProps } =\n useInput({\n ref,\n classNames: {\n // set padding to 0 for error message exit animation\n helperWrapper: 'p-0',\n },\n errorMessage: JSON.stringify(error),\n isInvalid: invalid,\n isRequired: required,\n label,\n labelPlacement: 'outside',\n });\n\n // Compute aria-label: prefer custom prop, then use string label if available, otherwise field name\n // Components can further override this based on their specific accessibility needs\n // (e.g., Input/TextArea may skip this if they have a meaningful placeholder)\n const ariaLabel =\n customAriaLabel ?? (typeof label === 'string' ? label : name);\n\n return {\n ariaLabel,\n control,\n debugMode,\n defaultValue,\n disabled: isDisabled,\n error,\n errorMessage,\n field: {\n ...field,\n value: transformedValue as typeof field.value,\n onChange: transformedOnChange as typeof field.onChange,\n },\n getErrorMessageProps,\n getHelperWrapperProps,\n getLabelProps,\n getValues,\n invalid,\n label: labelNode,\n onBlur,\n onChange: transformedOnChange as typeof field.onChange,\n readOnly,\n ref,\n required,\n resetField,\n testId,\n };\n};\n","/* v8 ignore start */\n\nexport * from './useUniformField';\n\n/* v8 ignore stop */\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyHA,MAAa,mBAIX,WACwC;CACxC,MAAM,EACJ,MACA,WAAW,iBACX,WAAW,OACX,eAAe,OACf,WAAW,OACX,YAAY,OACZ,QAAQ,gBACR,OACA,MACA,cACE;CAGJ,kBAAkB,MAAM,SAAS,cAAc,SAAS;CAExD,MAAM,EACJ,SACA,WACA,WAAW,EAAE,eACb,eACA,WACA,eACE,eAA6B;CAEjC,MAAM,EACJ,OAAO,UACP,SAAS,YACT,SACA,WACA,UACA,WACE,cAAc,MAAM,cAAc;CAEtC,MAAM,EAAE,UAAU,cAA4B;EAC5C;EACA;EACA;CACF,CAAC;CACD,MAAM,EACJ,UAAU,eACV,OAAO,YACP,UAAU,YACV,QACA,QACE;CAIJ,MAAM,EAAE,gBAAgB,gBAAgB,uBAAiC;EACvE;EACA;CACF,CAAC;CAGD,MAAM,mBAAmB,eAAe,UAAU;CAClD,MAAM,uBAAuB,iBAA+C;EAE1E,MAAM,eACH,cAAsD,QAAQ,SAC/D;EACF,MAAM,YAAY,YAAY,YAAwB;EACtD,cAAc,SAAS;CACzB;CAEA,MAAM,eAAgB,UAAU,CAAC,GAC/B;;;;;;;;;;;;;;;;;;;;;;;;;CA6BF,MAAM,WAAW,CAAC,aAAa,UAAU;CAIzC,MAAM,UAAU,YAFd,eAAgB,WAAW,YAAa,aAAa,cAAc,IAE5B,GAAG;CAM5C,MAAM,uBAAuB,cAAc;CAC3C,MAAM,YACJ,CAAC,CAAC,SAAS,uBACT,qBAAA,UAAA,EAAA,UAAA,CACG,UAAU,QAAQ,QAAQ,MAC1B,uBACC,oBAACA,+BAAD,EAA+B,OAAS,CAAA,IACtC,IACJ,EAAA,CAAA,IACA;CAKN,MAAM,QAAQ,eAAe,mBAAmB,QAAQ,IAAI;CAC5D,MAAM,kBAAkB,mBAAmB,QAAQ;CAInD,MAAM,eACJ,oBAACC,8BAAD;EAAsB,OAAO;EAAyB;CAAS,CAAA;CAMjE,MAAM,EAAE,sBAAsB,eAAe,0BAC3C,SAAS;EACP;EACA,YAAY,EAEV,eAAe,MACjB;EACA,cAAc,KAAK,UAAU,KAAK;EAClC,WAAW;EACX,YAAY;EACZ;EACA,gBAAgB;CAClB,CAAC;CAQH,OAAO;EACL,WAHA,oBAAoB,OAAO,UAAU,WAAW,QAAQ;EAIxD;EACA;EACA;EACA,UAAU;EACV;EACA;EACA,OAAO;GACL,GAAG;GACH,OAAO;GACP,UAAU;EACZ;EACA;EACA;EACA;EACA;EACA;EACA,OAAO;EACP;EACA,UAAU;EACV;EACA;EACA;EACA;EACA;CACF;AACF"}
@@ -1,47 +0,0 @@
1
- import { n as UseUniformFieldReturn } from "../../index-DsB0_365.mjs";
2
- import { ReactNode } from "react";
3
- import { ArrayPath, FieldValues, UseFieldArrayReturn } from "react-hook-form";
4
- export interface UseUniformFieldArrayProps<TFieldValues extends FieldValues = FieldValues> {
5
- /** Disable the field */
6
- disabled?: boolean;
7
- /** Initial value for new array elements */
8
- elementInitialValue?: unknown;
9
- /** Whether this is a flat array (array of primitives) */
10
- flat?: boolean;
11
- /** Optional label content */
12
- label?: ReactNode;
13
- /** Whether the last element cannot be removed (always maintain at least one element) */
14
- lastElementNotRemovable?: boolean;
15
- /** Field name for the array */
16
- name: ArrayPath<TFieldValues>;
17
- /** Optional explicit test id used to build stable test ids */
18
- testId?: string;
19
- }
20
- /**
21
- * Return type of `useUniformFieldArray`.
22
- *
23
- * Declared explicitly so the published declarations only reference types that
24
- * react-hook-form exports from its package root.
25
- */
26
- export type UseUniformFieldArrayReturn<TFieldValues extends FieldValues = FieldValues> = Pick<UseFieldArrayReturn<TFieldValues, ArrayPath<TFieldValues>>, 'append' | 'fields' | 'insert' | 'move' | 'remove'> & UseUniformFieldReturn<TFieldValues> & {
27
- /** Disables element animations during initialization, reset and reduced motion */
28
- disableAnimation: boolean;
29
- /** Value used for newly added array elements */
30
- elementInitialValue: NonNullable<unknown>;
31
- };
32
- /**
33
- * Enhanced useFieldArray hook with initialization and animation logic.
34
- * Based on React Hook Form's useFieldArray with additional features:
35
- * - Automatic initialization when lastElementNotRemovable is set
36
- * - Reset-only normalization for stale empty placeholder rows (via useWatchFormReset)
37
- * - Animation control (disabled during initialization)
38
- * - Temporary animation disable during reset normalization collapse
39
- * - Support for flat arrays (arrays of primitives)
40
- *
41
- * Note: Automatic validation triggering on length change is disabled to prevent
42
- * triggering form-wide validation. Array validation still runs on form submission.
43
- *
44
- * @see https://react-hook-form.com/docs/usefieldarray
45
- */
46
- export declare const useUniformFieldArray: <TFieldValues extends FieldValues = FieldValues>({ name, flat, elementInitialValue: _elementInitialValue, lastElementNotRemovable, disabled, testId: explicitTestId, label }: UseUniformFieldArrayProps<TFieldValues>) => UseUniformFieldArrayReturn<TFieldValues>;
47
- //# sourceMappingURL=index.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/hooks/useUniformFieldArray/useUniformFieldArray.ts"],"mappings":";;;iBAmBiB,0BACf,qBAAqB,cAAc;;EAGnC;;EAEA;;EAEA;;EAEA,QAAQ;;EAER;;EAEA,MAAM,UAAU;;EAEhB;;;;;;;;YASU,2BACV,qBAAqB,cAAc,eACjC,KACF,oBAAoB,cAAc,UAAU,sEAG5C,sBAAsB;;EAEpB;;EAEA,qBAAqB;;;;;;;;;;;;;;;;qBAiBZ,uBACX,qBAAqB,cAAc,eACnC,MAAA,MAAA,qBAAA,sBAAA,yBAAA,UAAA,QAAA,gBAAA,SAQC,0BAA0B,kBAAgB,2BAA2B"}
@@ -1,99 +0,0 @@
1
- import { flatArrayKey, isValueEmpty } from "../../helpers/index.mjs";
2
- import { n as useFormContext$1 } from "../../useFormContext-BEjPBdzb.mjs";
3
- import { useUniformField } from "../useUniformField/index.mjs";
4
- import { useWatchFormReset } from "../useWatchFormReset/index.mjs";
5
- import { useEffect, useMemo, useRef, useState } from "react";
6
- import { useReducedMotion } from "@fuf-stack/pixel-motion";
7
- import { useFieldArray } from "react-hook-form";
8
- // src/hooks/useUniformFieldArray/useUniformFieldArray.ts
9
- /**
10
- * Enhanced useFieldArray hook with initialization and animation logic.
11
- * Based on React Hook Form's useFieldArray with additional features:
12
- * - Automatic initialization when lastElementNotRemovable is set
13
- * - Reset-only normalization for stale empty placeholder rows (via useWatchFormReset)
14
- * - Animation control (disabled during initialization)
15
- * - Temporary animation disable during reset normalization collapse
16
- * - Support for flat arrays (arrays of primitives)
17
- *
18
- * Note: Automatic validation triggering on length change is disabled to prevent
19
- * triggering form-wide validation. Array validation still runs on form submission.
20
- *
21
- * @see https://react-hook-form.com/docs/usefieldarray
22
- */
23
- const useUniformFieldArray = ({ name, flat = false, elementInitialValue: _elementInitialValue = null, lastElementNotRemovable = false, disabled, testId: explicitTestId, label }) => {
24
- const uniformField = useUniformField({
25
- name,
26
- disabled,
27
- testId: explicitTestId,
28
- label
29
- });
30
- const { control } = uniformField;
31
- const { fields, append, remove, insert, move, replace } = useFieldArray({
32
- control,
33
- name
34
- });
35
- const { trigger, setValue, getValues } = useFormContext$1();
36
- const needsInitialize = useMemo(() => {
37
- return lastElementNotRemovable && fields.length === 0;
38
- }, [lastElementNotRemovable, fields.length]);
39
- const hasInitialized = useRef(!needsInitialize);
40
- useEffect(() => {
41
- if (needsInitialize) hasInitialized.current = false;
42
- }, [needsInitialize]);
43
- useEffect(() => {
44
- if (hasInitialized.current) setTimeout(() => {
45
- trigger(name);
46
- }, 200);
47
- }, [fields.length]);
48
- const [disableAnimation, setDisableAnimation] = useState(true);
49
- const prefersReducedMotion = useReducedMotion();
50
- useEffect(() => {
51
- if (hasInitialized.current) setDisableAnimation(!!prefersReducedMotion);
52
- }, [prefersReducedMotion]);
53
- const elementInitialValue = useMemo(() => {
54
- return flat ? { [flatArrayKey]: _elementInitialValue ?? null } : _elementInitialValue ?? {};
55
- }, [flat, _elementInitialValue]);
56
- useWatchFormReset({ onReset: () => {
57
- const currentValue = getValues(name);
58
- const valueIsArray = Array.isArray(currentValue);
59
- const arrayValue = valueIsArray ? currentValue : [];
60
- const normalizedLength = lastElementNotRemovable ? 1 : 0;
61
- const alreadyNormalized = valueIsArray && arrayValue.length === normalizedLength;
62
- if (!(!valueIsArray || arrayValue.length === 0 || arrayValue.every((entry) => {
63
- return isValueEmpty(entry);
64
- }))) return;
65
- if (alreadyNormalized) return;
66
- setDisableAnimation(true);
67
- replace(lastElementNotRemovable ? [elementInitialValue] : []);
68
- if (!prefersReducedMotion) setTimeout(() => {
69
- setDisableAnimation(false);
70
- }, 1);
71
- } });
72
- useEffect(() => {
73
- if (needsInitialize) {
74
- setValue(name, [elementInitialValue], {
75
- shouldDirty: false,
76
- shouldTouch: false
77
- });
78
- hasInitialized.current = true;
79
- if (!prefersReducedMotion && disableAnimation) setTimeout(() => {
80
- setDisableAnimation(false);
81
- }, 1);
82
- }
83
- }, [needsInitialize]);
84
- return {
85
- fields,
86
- append,
87
- remove,
88
- insert,
89
- move,
90
- disableAnimation,
91
- elementInitialValue,
92
- ...uniformField
93
- };
94
- };
95
- // src/hooks/useUniformFieldArray/index.ts
96
- /* v8 ignore stop */
97
- export { useUniformFieldArray };
98
-
99
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","names":["useRHFFieldArray","useFormContext"],"sources":["../../../src/hooks/useUniformFieldArray/useUniformFieldArray.ts","../../../src/hooks/useUniformFieldArray/index.ts"],"sourcesContent":["import type { ReactNode } from 'react';\nimport type {\n ArrayPath,\n FieldValues,\n Path,\n UseFieldArrayReturn,\n} from 'react-hook-form';\nimport type { UseUniformFieldReturn } from '../useUniformField';\n\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { useFieldArray as useRHFFieldArray } from 'react-hook-form';\n\nimport { useReducedMotion } from '@fuf-stack/pixel-motion';\n\nimport { flatArrayKey, isValueEmpty } from '../../helpers';\nimport { useFormContext } from '../useFormContext';\nimport { useUniformField } from '../useUniformField';\nimport { useWatchFormReset } from '../useWatchFormReset';\n\nexport interface UseUniformFieldArrayProps<\n TFieldValues extends FieldValues = FieldValues,\n> {\n /** Disable the field */\n disabled?: boolean;\n /** Initial value for new array elements */\n elementInitialValue?: unknown;\n /** Whether this is a flat array (array of primitives) */\n flat?: boolean;\n /** Optional label content */\n label?: ReactNode;\n /** Whether the last element cannot be removed (always maintain at least one element) */\n lastElementNotRemovable?: boolean;\n /** Field name for the array */\n name: ArrayPath<TFieldValues>;\n /** Optional explicit test id used to build stable test ids */\n testId?: string;\n}\n\n/**\n * Return type of `useUniformFieldArray`.\n *\n * Declared explicitly so the published declarations only reference types that\n * react-hook-form exports from its package root.\n */\nexport type UseUniformFieldArrayReturn<\n TFieldValues extends FieldValues = FieldValues,\n> = Pick<\n UseFieldArrayReturn<TFieldValues, ArrayPath<TFieldValues>>,\n 'append' | 'fields' | 'insert' | 'move' | 'remove'\n> &\n UseUniformFieldReturn<TFieldValues> & {\n /** Disables element animations during initialization, reset and reduced motion */\n disableAnimation: boolean;\n /** Value used for newly added array elements */\n elementInitialValue: NonNullable<unknown>;\n };\n\n/**\n * Enhanced useFieldArray hook with initialization and animation logic.\n * Based on React Hook Form's useFieldArray with additional features:\n * - Automatic initialization when lastElementNotRemovable is set\n * - Reset-only normalization for stale empty placeholder rows (via useWatchFormReset)\n * - Animation control (disabled during initialization)\n * - Temporary animation disable during reset normalization collapse\n * - Support for flat arrays (arrays of primitives)\n *\n * Note: Automatic validation triggering on length change is disabled to prevent\n * triggering form-wide validation. Array validation still runs on form submission.\n *\n * @see https://react-hook-form.com/docs/usefieldarray\n */\nexport const useUniformFieldArray = <\n TFieldValues extends FieldValues = FieldValues,\n>({\n name,\n flat = false,\n elementInitialValue: _elementInitialValue = null,\n lastElementNotRemovable = false,\n disabled,\n testId: explicitTestId,\n label,\n}: UseUniformFieldArrayProps<TFieldValues>): UseUniformFieldArrayReturn<TFieldValues> => {\n // Get uniform field state and utilities\n const uniformField = useUniformField<TFieldValues>({\n name: name as Path<TFieldValues> & string,\n disabled,\n testId: explicitTestId,\n label,\n });\n\n const { control } = uniformField;\n\n const { fields, append, remove, insert, move, replace } = useRHFFieldArray({\n control,\n name,\n });\n\n const { trigger, setValue, getValues } = useFormContext<TFieldValues>();\n\n // Determine if initialization is needed (initially or after reset).\n // lastElementNotRemovable is purely a minimum-count guarantee: when there are\n // no rows, add one. This handles both:\n // - Initial mount: fields.length starts at 0\n // - Form reset to an empty array: fields.length becomes 0 again\n // It intentionally does NOT inspect row contents, so manually added empty rows\n // are never collapsed.\n const needsInitialize = useMemo(() => {\n return lastElementNotRemovable && fields.length === 0;\n }, [lastElementNotRemovable, fields.length]);\n\n // Track whether initialization has completed. Initialized contextually:\n // - If initialization IS needed (needsInitialize = true): starts as false, set to true after init\n // - If initialization is NOT needed (needsInitialize = false): starts as true (already initialized)\n // This ref is used to:\n // 1. Skip validation during initialization/re-initialization\n // 2. Gate animation enabling until after initialization\n // 3. Gate motion preference effect until after initialization\n const hasInitialized = useRef(!needsInitialize);\n\n // Reset initialization flag when needsInitialize changes to true.\n // This handles form reset: when fields become empty (needsInitialize becomes true),\n // hasInitialized is reset to false, triggering re-initialization in the effect below.\n useEffect(() => {\n if (needsInitialize) {\n hasInitialized.current = false;\n }\n }, [needsInitialize]);\n\n // Validate array-level constraints (min/max items) when length changes.\n // This ensures min/max errors appear instantly when user adds/removes items.\n // Note: Child field validation also runs, but new empty fields won't show as invalid\n // because useFormContext only sets invalid=true for touched fields or after form submission.\n // Skip validation during initialization/re-initialization to avoid showing errors prematurely.\n useEffect(() => {\n if (hasInitialized.current) {\n setTimeout(() => {\n trigger(name as Path<TFieldValues>);\n }, 200);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [fields.length]);\n\n // Animation control: Start with animations disabled to prevent animating in initial elements.\n // Will be enabled after initialization completes (unless user prefers reduced motion).\n const [disableAnimation, setDisableAnimation] = useState(true);\n\n // Respond to user's motion preference changes (after initialization).\n // During initialization, animations stay disabled regardless of preference.\n const prefersReducedMotion = useReducedMotion();\n useEffect(() => {\n if (hasInitialized.current) {\n setDisableAnimation(!!prefersReducedMotion);\n }\n }, [prefersReducedMotion]);\n\n // Prepare initial element value based on mode\n // - flat=true: arrays of primitives → object with flatArrayKey and null value by default\n // - flat=false: arrays of objects → empty object by default\n const elementInitialValue = useMemo(() => {\n return flat\n ? { [flatArrayKey]: _elementInitialValue ?? null }\n : (_elementInitialValue ?? {});\n }, [flat, _elementInitialValue]);\n\n // Reset normalization:\n // Run ONLY when an actual form reset is emitted (via useWatchFormReset), not\n // on regular field edits. This does not collapse rows users add manually.\n //\n // Why this exists:\n // RHF can keep stale field-array rows after reset when array defaults are\n // missing (e.g. value becomes undefined or [null, null] while UI still has\n // multiple rows). We normalize this reset-only state to:\n // - one row when lastElementNotRemovable is enabled\n // - zero rows otherwise\n useWatchFormReset({\n onReset: () => {\n const currentValue = getValues(name as Path<TFieldValues>) as unknown;\n const valueIsArray = Array.isArray(currentValue);\n const arrayValue = valueIsArray ? (currentValue as unknown[]) : [];\n const normalizedLength = lastElementNotRemovable ? 1 : 0;\n const alreadyNormalized =\n valueIsArray && arrayValue.length === normalizedLength;\n\n // Treat these as \"effectively empty after reset\":\n // - value missing/not-array\n // - empty array\n // - array where all entries are empty placeholders\n const isEffectivelyEmptyAfterReset =\n !valueIsArray ||\n arrayValue.length === 0 ||\n arrayValue.every((entry) => {\n return isValueEmpty(entry);\n });\n\n // Nothing to fix when the reset restored real values (e.g. from defaults).\n if (!isEffectivelyEmptyAfterReset) {\n return;\n }\n\n // Already normalized to the target row count.\n if (alreadyNormalized) {\n return;\n }\n\n // Avoid collapse animation flicker during reset normalization.\n setDisableAnimation(true);\n\n // use replace so the RHF field-array length actually matches the target.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n replace((lastElementNotRemovable ? [elementInitialValue] : []) as any);\n\n // Restore normal animation state right after normalization.\n if (!prefersReducedMotion) {\n setTimeout(() => {\n setDisableAnimation(false);\n }, 1);\n }\n },\n });\n\n // Initialization/Re-initialization: add one element only when array length is 0.\n // This is the min-count behavior for lastElementNotRemovable and is intentionally\n // separate from reset normalization above.\n //\n // Reset behavior in this hook is split into two phases:\n // 1) Reset normalization (useWatchFormReset): collapse stale placeholder rows\n // left by reset edge cases.\n // 2) Length-based initialization (this effect): ensure a min-one array when\n // the field array is truly empty.\n // CRITICAL: This effect MUST be the LAST hook in this component.\n // It sets hasInitialized.current = true, which acts as a gate for other effects.\n // If this runs before other effects, hasInitialized will be true during their first run,\n // causing them to execute logic meant only for post-initialization (e.g., validation,\n // animation enabling). By placing this last, all other effects run first with\n // hasInitialized = false, allowing them to skip initialization-phase logic.\n useEffect(\n () => {\n if (needsInitialize) {\n // use setValue instead of append to avoid focusing the added element\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setValue(name as Path<TFieldValues>, [elementInitialValue] as any, {\n shouldDirty: false,\n shouldTouch: false,\n });\n\n // Mark initialization as complete\n hasInitialized.current = true;\n\n // Enable animations after a brief delay (unless user prefers reduced motion or animations are already enabled).\n // This only runs on initial mount when animations start disabled.\n // On reset, disableAnimation is typically false, so this setTimeout won't run and animations stay enabled.\n if (!prefersReducedMotion && disableAnimation) {\n setTimeout(() => {\n setDisableAnimation(false);\n }, 1);\n }\n }\n },\n // Run when needsInitialize changes (initial mount or reset)\n // needsInitialize is memoized based on fields.length and lastElementNotRemovable\n // Other dependencies are intentionally omitted:\n // - append, setValue, trigger, setDisableAnimation are stable refs/functions\n // - elementInitialValue, name, flat, prefersReducedMotion, disableAnimation are props/stable values\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [needsInitialize],\n );\n\n return {\n // Field array methods and state\n fields,\n append,\n remove,\n insert,\n move,\n disableAnimation,\n elementInitialValue,\n // Uniform field state and utilities (spread all)\n ...uniformField,\n };\n};\n","/* v8 ignore start */\n\nexport * from './useUniformFieldArray';\n\n/* v8 ignore stop */\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuEA,MAAa,wBAEX,EACA,MACA,OAAO,OACP,qBAAqB,uBAAuB,MAC5C,0BAA0B,OAC1B,UACA,QAAQ,gBACR,YACuF;CAEvF,MAAM,eAAe,gBAA8B;EAC3C;EACN;EACA,QAAQ;EACR;CACF,CAAC;CAED,MAAM,EAAE,YAAY;CAEpB,MAAM,EAAE,QAAQ,QAAQ,QAAQ,QAAQ,MAAM,YAAYA,cAAiB;EACzE;EACA;CACF,CAAC;CAED,MAAM,EAAE,SAAS,UAAU,cAAcC,iBAA6B;CAStE,MAAM,kBAAkB,cAAc;EACpC,OAAO,2BAA2B,OAAO,WAAW;CACtD,GAAG,CAAC,yBAAyB,OAAO,MAAM,CAAC;CAS3C,MAAM,iBAAiB,OAAO,CAAC,eAAe;CAK9C,gBAAgB;EACd,IAAI,iBACF,eAAe,UAAU;CAE7B,GAAG,CAAC,eAAe,CAAC;CAOpB,gBAAgB;EACd,IAAI,eAAe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