@fuf-stack/uniform 1.8.1 → 1.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Checkboxes/index.cjs +10 -10
- package/dist/Checkboxes/index.js +9 -9
- package/dist/FieldArray/index.cjs +10 -10
- package/dist/FieldArray/index.js +9 -9
- package/dist/Form/index.cjs +10 -10
- package/dist/Form/index.js +9 -9
- package/dist/Input/index.cjs +10 -10
- package/dist/Input/index.js +9 -9
- package/dist/RadioBoxes/index.cjs +10 -10
- package/dist/RadioBoxes/index.js +9 -9
- package/dist/RadioTabs/index.cjs +10 -10
- package/dist/RadioTabs/index.js +9 -9
- package/dist/Radios/index.cjs +10 -10
- package/dist/Radios/index.js +9 -9
- package/dist/Select/index.cjs +10 -10
- package/dist/Select/index.js +9 -9
- package/dist/SubmitButton/index.cjs +10 -10
- package/dist/SubmitButton/index.js +9 -9
- package/dist/Switch/index.cjs +10 -10
- package/dist/Switch/index.js +9 -9
- package/dist/TextArea/index.cjs +10 -10
- package/dist/TextArea/index.js +9 -9
- package/dist/{chunk-U45RW4FC.js → chunk-2BWUTUVE.js} +5 -5
- package/dist/chunk-2BWUTUVE.js.map +1 -0
- package/dist/{chunk-LKR6D3RL.js → chunk-2YHO6FBK.js} +2 -2
- package/dist/{chunk-S3H432Z2.cjs → chunk-4UBIV2LI.cjs} +3 -3
- package/dist/{chunk-S3H432Z2.cjs.map → chunk-4UBIV2LI.cjs.map} +1 -1
- package/dist/{chunk-KQQAESO7.js → chunk-5ASOVFNF.js} +4 -4
- package/dist/{chunk-K33E67GR.js → chunk-5RNATZD6.js} +3 -3
- package/dist/{chunk-5RPUTRV5.js → chunk-64YW5GV2.js} +3 -3
- package/dist/{chunk-4TQ53WAY.js → chunk-6NJJHUKF.js} +3 -3
- package/dist/{chunk-BUJNCVUR.js → chunk-BGNZCW7J.js} +2 -2
- package/dist/{chunk-6LQ2O6SC.cjs → chunk-C2JPKUCY.cjs} +11 -11
- package/dist/chunk-C2JPKUCY.cjs.map +1 -0
- package/dist/{chunk-ZFZK6EM2.cjs → chunk-CHBLPOFP.cjs} +3 -3
- package/dist/{chunk-ZFZK6EM2.cjs.map → chunk-CHBLPOFP.cjs.map} +1 -1
- package/dist/{chunk-IFBKJ5UZ.cjs → chunk-CUVHORQH.cjs} +7 -7
- package/dist/{chunk-IFBKJ5UZ.cjs.map → chunk-CUVHORQH.cjs.map} +1 -1
- package/dist/{chunk-EUO4VWRX.js → chunk-DFVZ4AV5.js} +2 -2
- package/dist/{chunk-ZEJ45LLM.cjs → chunk-FBH7RW4U.cjs} +3 -3
- package/dist/{chunk-ZEJ45LLM.cjs.map → chunk-FBH7RW4U.cjs.map} +1 -1
- package/dist/{chunk-EUTTXFWA.cjs → chunk-FP5KRDUN.cjs} +5 -5
- package/dist/{chunk-EUTTXFWA.cjs.map → chunk-FP5KRDUN.cjs.map} +1 -1
- package/dist/{chunk-EGFB5WEK.js → chunk-G3A7AEDA.js} +3 -3
- package/dist/{chunk-VUW522KH.js → chunk-GNK45IFM.js} +2 -2
- package/dist/{chunk-FND5Z5BW.js → chunk-HH7YK5QR.js} +4 -4
- package/dist/{chunk-OQUTHTOK.cjs → chunk-IXJISVRO.cjs} +5 -5
- package/dist/{chunk-OQUTHTOK.cjs.map → chunk-IXJISVRO.cjs.map} +1 -1
- package/dist/{chunk-N24A7PIL.js → chunk-K6TW2OY3.js} +2 -2
- package/dist/{chunk-4L3JXJ62.cjs → chunk-KQEM5HFD.cjs} +5 -5
- package/dist/{chunk-4L3JXJ62.cjs.map → chunk-KQEM5HFD.cjs.map} +1 -1
- package/dist/{chunk-6F5EZ6QN.cjs → chunk-LB6GH6FJ.cjs} +3 -3
- package/dist/{chunk-6F5EZ6QN.cjs.map → chunk-LB6GH6FJ.cjs.map} +1 -1
- package/dist/{chunk-OJGPW4Z6.cjs → chunk-M5CEG4RM.cjs} +3 -3
- package/dist/{chunk-OJGPW4Z6.cjs.map → chunk-M5CEG4RM.cjs.map} +1 -1
- package/dist/{chunk-ZLTMRO6X.cjs → chunk-MKANLM7V.cjs} +3 -3
- package/dist/{chunk-ZLTMRO6X.cjs.map → chunk-MKANLM7V.cjs.map} +1 -1
- package/dist/{chunk-SWPFSD3Y.js → chunk-MUKDMHP6.js} +2 -2
- package/dist/{chunk-7KEUEGRC.cjs → chunk-MZIVLP3U.cjs} +7 -7
- package/dist/chunk-MZIVLP3U.cjs.map +1 -0
- package/dist/{chunk-CST35FDK.cjs → chunk-NAHYXRGT.cjs} +5 -5
- package/dist/{chunk-CST35FDK.cjs.map → chunk-NAHYXRGT.cjs.map} +1 -1
- package/dist/{chunk-76KOVUDN.js → chunk-O2XJNQQK.js} +18 -2
- package/dist/chunk-O2XJNQQK.js.map +1 -0
- package/dist/{chunk-PY4GCAFN.js → chunk-O56EUQR7.js} +2 -2
- package/dist/{chunk-Z353BLWI.cjs → chunk-OKJWLH7T.cjs} +18 -2
- package/dist/chunk-OKJWLH7T.cjs.map +1 -0
- package/dist/{chunk-KGN5JQGG.js → chunk-QOBWD4QR.js} +3 -3
- package/dist/{chunk-UT6VUGFP.cjs → chunk-ROFP3IVU.cjs} +9 -9
- package/dist/{chunk-UT6VUGFP.cjs.map → chunk-ROFP3IVU.cjs.map} +1 -1
- package/dist/{chunk-4F45XA7Y.cjs → chunk-SDHZAPPA.cjs} +3 -3
- package/dist/{chunk-4F45XA7Y.cjs.map → chunk-SDHZAPPA.cjs.map} +1 -1
- package/dist/{chunk-GEJUMUTH.js → chunk-TGYJUEO2.js} +2 -2
- package/dist/{chunk-TJY5FK4B.cjs → chunk-TJK2MERL.cjs} +5 -5
- package/dist/{chunk-TJY5FK4B.cjs.map → chunk-TJK2MERL.cjs.map} +1 -1
- package/dist/{chunk-WWGKXYZB.js → chunk-TPZTWRPL.js} +2 -2
- package/dist/{chunk-4CWB5XBW.cjs → chunk-TZSGJQNR.cjs} +3 -3
- package/dist/{chunk-4CWB5XBW.cjs.map → chunk-TZSGJQNR.cjs.map} +1 -1
- package/dist/{chunk-EB3RNELT.cjs → chunk-XOXGE2E3.cjs} +5 -5
- package/dist/{chunk-EB3RNELT.cjs.map → chunk-XOXGE2E3.cjs.map} +1 -1
- package/dist/{chunk-GKP3ONKO.js → chunk-ZLFYOJ4M.js} +4 -4
- package/dist/{chunk-GKP3ONKO.js.map → chunk-ZLFYOJ4M.js.map} +1 -1
- package/dist/helpers/index.cjs +4 -2
- package/dist/helpers/index.cjs.map +1 -1
- package/dist/helpers/index.d.cts +21 -1
- package/dist/helpers/index.d.ts +21 -1
- package/dist/helpers/index.js +3 -1
- package/dist/hooks/index.cjs +9 -9
- package/dist/hooks/index.d.cts +1 -1
- package/dist/hooks/index.d.ts +1 -1
- package/dist/hooks/index.js +8 -8
- package/dist/hooks/useClientValidation/index.cjs +5 -5
- package/dist/hooks/useClientValidation/index.d.cts +2 -2
- package/dist/hooks/useClientValidation/index.d.ts +2 -2
- package/dist/hooks/useClientValidation/index.js +4 -4
- package/dist/hooks/useController/index.cjs +4 -4
- package/dist/hooks/useController/index.js +3 -3
- package/dist/hooks/useFormContext/index.cjs +4 -4
- package/dist/hooks/useFormContext/index.d.cts +7 -0
- package/dist/hooks/useFormContext/index.d.ts +7 -0
- package/dist/hooks/useFormContext/index.js +3 -3
- package/dist/hooks/useUniformField/index.cjs +6 -6
- package/dist/hooks/useUniformField/index.js +5 -5
- package/dist/hooks/useUniformFieldArray/index.cjs +7 -7
- package/dist/hooks/useUniformFieldArray/index.js +6 -6
- package/dist/hooks/useWatchUserChange/index.cjs +5 -5
- package/dist/hooks/useWatchUserChange/index.js +4 -4
- package/dist/index.cjs +22 -20
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +21 -19
- package/package.json +13 -11
- package/dist/chunk-6LQ2O6SC.cjs.map +0 -1
- package/dist/chunk-76KOVUDN.js.map +0 -1
- package/dist/chunk-7KEUEGRC.cjs.map +0 -1
- package/dist/chunk-U45RW4FC.js.map +0 -1
- package/dist/chunk-Z353BLWI.cjs.map +0 -1
- /package/dist/{chunk-LKR6D3RL.js.map → chunk-2YHO6FBK.js.map} +0 -0
- /package/dist/{chunk-KQQAESO7.js.map → chunk-5ASOVFNF.js.map} +0 -0
- /package/dist/{chunk-K33E67GR.js.map → chunk-5RNATZD6.js.map} +0 -0
- /package/dist/{chunk-5RPUTRV5.js.map → chunk-64YW5GV2.js.map} +0 -0
- /package/dist/{chunk-4TQ53WAY.js.map → chunk-6NJJHUKF.js.map} +0 -0
- /package/dist/{chunk-BUJNCVUR.js.map → chunk-BGNZCW7J.js.map} +0 -0
- /package/dist/{chunk-EUO4VWRX.js.map → chunk-DFVZ4AV5.js.map} +0 -0
- /package/dist/{chunk-EGFB5WEK.js.map → chunk-G3A7AEDA.js.map} +0 -0
- /package/dist/{chunk-VUW522KH.js.map → chunk-GNK45IFM.js.map} +0 -0
- /package/dist/{chunk-FND5Z5BW.js.map → chunk-HH7YK5QR.js.map} +0 -0
- /package/dist/{chunk-N24A7PIL.js.map → chunk-K6TW2OY3.js.map} +0 -0
- /package/dist/{chunk-SWPFSD3Y.js.map → chunk-MUKDMHP6.js.map} +0 -0
- /package/dist/{chunk-PY4GCAFN.js.map → chunk-O56EUQR7.js.map} +0 -0
- /package/dist/{chunk-KGN5JQGG.js.map → chunk-QOBWD4QR.js.map} +0 -0
- /package/dist/{chunk-GEJUMUTH.js.map → chunk-TGYJUEO2.js.map} +0 -0
- /package/dist/{chunk-WWGKXYZB.js.map → chunk-TPZTWRPL.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-IFBKJ5UZ.cjs","../src/hooks/useUniformFieldArray/useUniformFieldArray.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA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G,CAAC,CAAA;AAAA,QACN;AAAA,MACF;AAAA,IACF,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,CAAC,eAAe;AAAA,EAClB,CAAA;AAEA,EAAA,OAAO,8CAAA;AAAA;AAAA,IAEL,MAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,IAAA;AAAA,IACA,gBAAA;AAAA,IACA;AAAA,EAAA,CAAA,EAEG,YAAA,CAAA;AAEP,CAAA;ADvFA;AACA;AACE;AACF,oDAAC","file":"/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-IFBKJ5UZ.cjs","sourcesContent":[null,"import type { ReactNode } from 'react';\nimport type { ArrayPath, FieldValues, Path } from 'react-hook-form';\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 } from '../../helpers';\nimport { useFormContext } from '../useFormContext/useFormContext';\nimport { useUniformField } from '../useUniformField/useUniformField';\n\nexport interface UseUniformFieldArrayProps<\n TFieldValues extends FieldValues = FieldValues,\n> {\n /** Field name for the array */\n name: ArrayPath<TFieldValues>;\n /** Whether this is a flat array (array of primitives) */\n flat?: boolean;\n /** Initial value for new array elements */\n elementInitialValue?: unknown;\n /** Whether the last element cannot be removed (always maintain at least one element) */\n lastElementNotRemovable?: boolean;\n /** Disable the field */\n disabled?: boolean;\n /** Optional explicit test id used to build stable test ids */\n testId?: string;\n /** Optional label content; pass false to suppress label entirely */\n label?: ReactNode | false;\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 * - Animation control (disabled during initialization)\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>) => {\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 } = useRHFFieldArray({\n control,\n name,\n });\n\n const { trigger, setValue } = useFormContext<TFieldValues>();\n\n // Determine if initialization is needed (initially or after reset).\n // This flag automatically handles both scenarios:\n // - Initial mount: fields.length starts at 0\n // - Form reset: fields.length becomes 0 again\n // Additional initialization conditions can be added here later (e.g., minElements > 0)\n // Using useMemo ensures this value is properly tracked by React and effects can depend on it\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 // Skip validation during initialization/re-initialization to avoid showing errors prematurely.\n useEffect(() => {\n if (hasInitialized.current) {\n setTimeout(() => {\n // Trigger validation so min/max errors appear instantly when user adds/removes items\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 // Initialization/Re-initialization: Add initial element when needed.\n // This handles both initial mount and form reset scenarios by reacting to needsInitialize.\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"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-CUVHORQH.cjs","../src/hooks/useUniformFieldArray/useUniformFieldArray.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACVA,8BAAqD;AACrD,gDAAkD;AAElD,sDAAiC;AAqC1B,IAAM,qBAAA,EAAuB,CAElC;AAAA,EACA,IAAA;AAAA,EACA,KAAA,EAAO,KAAA;AAAA,EACP,mBAAA,EAAqB,qBAAA,EAAuB,IAAA;AAAA,EAC5C,wBAAA,EAA0B,KAAA;AAAA,EAC1B,QAAA;AAAA,EACA,MAAA,EAAQ,cAAA;AAAA,EACR;AACF,CAAA,EAAA,GAA+C;AAE7C,EAAA,MAAM,aAAA,EAAe,+CAAA;AAA8B,IACjD,IAAA;AAAA,IACA,QAAA;AAAA,IACA,MAAA,EAAQ,cAAA;AAAA,IACR;AAAA,EACF,CAAC,CAAA;AAED,EAAA,MAAM,EAAE,QAAQ,EAAA,EAAI,YAAA;AAEpB,EAAA,MAAM,EAAE,MAAA,EAAQ,MAAA,EAAQ,MAAA,EAAQ,MAAA,EAAQ,KAAK,EAAA,EAAI,0CAAA;AAAiB,IAChE,OAAA;AAAA,IACA;AAAA,EACF,CAAC,CAAA;AAED,EAAA,MAAM,EAAE,OAAA,EAAS,SAAS,EAAA,EAAI,8CAAA,CAA6B;AAQ3D,EAAA,MAAM,gBAAA,EAAkB,4BAAA,CAAQ,EAAA,GAAM;AACpC,IAAA,OAAO,wBAAA,GAA2B,MAAA,CAAO,OAAA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A,8BAAA;AAAA,IACE,CAAA,EAAA,GAAM;AACJ,MAAA,GAAA,CAAI,eAAA,EAAiB;AAGnB,QAAA,QAAA,CAAS,IAAA,EAA4B,CAAC,mBAAmB,CAAA,EAAU;AAAA,UACjE,WAAA,EAAa,KAAA;AAAA,UACb,WAAA,EAAa;AAAA,QACf,CAAC,CAAA;AAGD,QAAA,cAAA,CAAe,QAAA,EAAU,IAAA;AAKzB,QAAA,GAAA,CAAI,CAAC,qBAAA,GAAwB,gBAAA,EAAkB;AAC7C,UAAA,UAAA,CAAW,CAAA,EAAA,GAAM;AACf,YAAA,mBAAA,CAAoB,KAAK,CAAA;AAAA,UAC3B,CAAA,EAAG,CAAC,CAAA;AAAA,QACN;AAAA,MACF;AAAA,IACF,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,CAAC,eAAe;AAAA,EAClB,CAAA;AAEA,EAAA,OAAO,8CAAA;AAAA;AAAA,IAEL,MAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,IAAA;AAAA,IACA,gBAAA;AAAA,IACA;AAAA,EAAA,CAAA,EAEG,YAAA,CAAA;AAEP,CAAA;ADvFA;AACA;AACE;AACF,oDAAC","file":"/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-CUVHORQH.cjs","sourcesContent":[null,"import type { ReactNode } from 'react';\nimport type { ArrayPath, FieldValues, Path } from 'react-hook-form';\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 } from '../../helpers';\nimport { useFormContext } from '../useFormContext/useFormContext';\nimport { useUniformField } from '../useUniformField/useUniformField';\n\nexport interface UseUniformFieldArrayProps<\n TFieldValues extends FieldValues = FieldValues,\n> {\n /** Field name for the array */\n name: ArrayPath<TFieldValues>;\n /** Whether this is a flat array (array of primitives) */\n flat?: boolean;\n /** Initial value for new array elements */\n elementInitialValue?: unknown;\n /** Whether the last element cannot be removed (always maintain at least one element) */\n lastElementNotRemovable?: boolean;\n /** Disable the field */\n disabled?: boolean;\n /** Optional explicit test id used to build stable test ids */\n testId?: string;\n /** Optional label content; pass false to suppress label entirely */\n label?: ReactNode | false;\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 * - Animation control (disabled during initialization)\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>) => {\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 } = useRHFFieldArray({\n control,\n name,\n });\n\n const { trigger, setValue } = useFormContext<TFieldValues>();\n\n // Determine if initialization is needed (initially or after reset).\n // This flag automatically handles both scenarios:\n // - Initial mount: fields.length starts at 0\n // - Form reset: fields.length becomes 0 again\n // Additional initialization conditions can be added here later (e.g., minElements > 0)\n // Using useMemo ensures this value is properly tracked by React and effects can depend on it\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 // Skip validation during initialization/re-initialization to avoid showing errors prematurely.\n useEffect(() => {\n if (hasInitialized.current) {\n setTimeout(() => {\n // Trigger validation so min/max errors appear instantly when user adds/removes items\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 // Initialization/Re-initialization: Add initial element when needed.\n // This handles both initial mount and form reset scenarios by reacting to needsInitialize.\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"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useUniformField
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-G3A7AEDA.js";
|
|
4
4
|
import {
|
|
5
5
|
__objRest,
|
|
6
6
|
__spreadValues
|
|
@@ -144,4 +144,4 @@ export {
|
|
|
144
144
|
RadioTabs_default,
|
|
145
145
|
RadioTabs_default2
|
|
146
146
|
};
|
|
147
|
-
//# sourceMappingURL=chunk-
|
|
147
|
+
//# sourceMappingURL=chunk-DFVZ4AV5.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkC2JPKUCYcjs = require('./chunk-C2JPKUCY.cjs');
|
|
4
4
|
|
|
5
5
|
// src/SubmitButton/SubmitButton.tsx
|
|
6
6
|
var _pixelutils = require('@fuf-stack/pixel-utils');
|
|
@@ -19,7 +19,7 @@ var SubmitButton = ({
|
|
|
19
19
|
const {
|
|
20
20
|
formState: { isSubmitting },
|
|
21
21
|
triggerSubmit
|
|
22
|
-
} =
|
|
22
|
+
} = _chunkC2JPKUCYcjs.useFormContext.call(void 0, );
|
|
23
23
|
return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
|
|
24
24
|
_pixels.Button,
|
|
25
25
|
{
|
|
@@ -46,4 +46,4 @@ var SubmitButton_default2 = SubmitButton_default;
|
|
|
46
46
|
|
|
47
47
|
|
|
48
48
|
exports.SubmitButton_default = SubmitButton_default; exports.SubmitButton_default2 = SubmitButton_default2;
|
|
49
|
-
//# sourceMappingURL=chunk-
|
|
49
|
+
//# sourceMappingURL=chunk-FBH7RW4U.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-FBH7RW4U.cjs","../src/SubmitButton/SubmitButton.tsx","../src/SubmitButton/index.ts"],"names":["SubmitButton_default"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACDA,oDAA4B;AAC5B,2CAAuB;AA0CnB,+CAAA;AAhBJ,IAAM,aAAA,EAAe,CAAC;AAAA,EACpB,UAAA,EAAY,aAAA;AAAA,EACZ,SAAA,EAAW,QAAA;AAAA,EACX,UAAA,EAAY,KAAA,CAAA;AAAA,EACZ,MAAA,EAAQ,SAAA;AAAA,EACR,KAAA,EAAO,KAAA,CAAA;AAAA,EACP,QAAA,EAAU,KAAA;AAAA,EACV,KAAA,EAAO,IAAA;AAAA,EACP,OAAA,EAAS;AACX,CAAA,EAAA,GAAyB;AACvB,EAAA,MAAM;AAAA,IACJ,SAAA,EAAW,EAAE,aAAa,CAAA;AAAA,IAC1B;AAAA,EACF,EAAA,EAAI,8CAAA,CAAe;AAEnB,EAAA,uBACE,6BAAA;AAAA,IAAC,cAAA;AAAA,IAAA;AAAA,MACC,SAAA;AAAA,MACA,SAAA,EAAW,4BAAA,SAAY,CAAA;AAAA,MACvB,KAAA;AAAA,MACA,QAAA,EAAU,YAAA;AAAA,MACV,IAAA;AAAA,MACA,OAAA,EAAS,QAAA,GAAW,YAAA;AAAA,MAIpB,OAAA,EAAS,aAAA;AAAA,MACT,IAAA;AAAA,MACA,MAAA,EAAQ,iCAAA,MAAQ,EAAQ,EAAE,WAAA,EAAa,KAAK,CAAC,CAAA;AAAA,MAC7C,IAAA,EAAK,QAAA;AAAA,MAEJ;AAAA,IAAA;AAAA,EACH,CAAA;AAEJ,CAAA;AAEA,IAAO,qBAAA,EAAQ,YAAA;AD1Bf;AACA;AEnCA,IAAOA,sBAAAA,EAAQ,oBAAA;AFqCf;AACA;AACE;AACA;AACF,2GAAC","file":"/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-FBH7RW4U.cjs","sourcesContent":[null,"import type { ButtonProps } from '@fuf-stack/pixels';\nimport type { ReactNode } from 'react';\n\nimport { cn, slugify } from '@fuf-stack/pixel-utils';\nimport { Button } from '@fuf-stack/pixels';\n\nimport { useFormContext } from '../hooks';\n\nexport interface SubmitButtonProps {\n /** sets HTML aria-label attribute */\n ariaLabel?: string;\n /** child components */\n children?: ReactNode;\n /** CSS class name */\n className?: string;\n /** color of the submit button */\n color?: ButtonProps['color'];\n /** icon of the submit button */\n icon?: ButtonProps['icon'];\n /** If set loading animation is shown */\n loading?: boolean;\n /** size of the submit button */\n size?: ButtonProps['size'];\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n}\n\n/**\n * From SubmitButton\n */\nconst SubmitButton = ({\n ariaLabel = 'Submit form',\n children = 'Submit',\n className = undefined,\n color = 'success',\n icon = undefined,\n loading = false,\n size = 'md',\n testId = 'form_submit_button',\n}: SubmitButtonProps) => {\n const {\n formState: { isSubmitting },\n triggerSubmit,\n } = useFormContext();\n\n return (\n <Button\n ariaLabel={ariaLabel}\n className={cn(className)}\n color={color}\n disabled={isSubmitting}\n icon={icon}\n loading={loading || isSubmitting}\n // @ts-expect-error we use form context triggerSubmit\n // here so that submit button also works in special\n // scenarios (e.g. when used in modal)\n onClick={triggerSubmit}\n size={size}\n testId={slugify(testId, { replaceDots: true })}\n type=\"submit\"\n >\n {children}\n </Button>\n );\n};\n\nexport default SubmitButton;\n","import SubmitButton from './SubmitButton';\n\nexport type { SubmitButtonProps } from './SubmitButton';\n\nexport { SubmitButton };\n\nexport default SubmitButton;\n"]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkC2JPKUCYcjs = require('./chunk-C2JPKUCY.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunkOKJWLH7Tcjs = require('./chunk-OKJWLH7T.cjs');
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
var _chunk555JRYCScjs = require('./chunk-555JRYCS.cjs');
|
|
@@ -17,7 +17,7 @@ var useClientValidation = (data, schemaFactory, options) => {
|
|
|
17
17
|
formState: { touchedFields },
|
|
18
18
|
validation: { setClientValidationSchema },
|
|
19
19
|
trigger
|
|
20
|
-
} =
|
|
20
|
+
} = _chunkC2JPKUCYcjs.useFormContext.call(void 0, );
|
|
21
21
|
const autoGeneratedKey = _react.useId.call(void 0, );
|
|
22
22
|
const key = (_a = options == null ? void 0 : options.key) != null ? _a : autoGeneratedKey;
|
|
23
23
|
const dataHash = JSON.stringify(data);
|
|
@@ -45,7 +45,7 @@ var clientValidationSchemaByName = (name, fieldSchema) => {
|
|
|
45
45
|
for (let i = segments.length - 1; i >= 0; i -= 1) {
|
|
46
46
|
const segment = segments[i];
|
|
47
47
|
const isNumeric = /^\d+$/.test(segment);
|
|
48
|
-
const isFlatArrayKey = segment ===
|
|
48
|
+
const isFlatArrayKey = segment === _chunkOKJWLH7Tcjs.flatArrayKey;
|
|
49
49
|
if (isFlatArrayKey) {
|
|
50
50
|
continue;
|
|
51
51
|
}
|
|
@@ -65,4 +65,4 @@ var clientValidationSchemaByName = (name, fieldSchema) => {
|
|
|
65
65
|
|
|
66
66
|
|
|
67
67
|
exports.useClientValidation = useClientValidation; exports.clientValidationSchemaByName = clientValidationSchemaByName;
|
|
68
|
-
//# sourceMappingURL=chunk-
|
|
68
|
+
//# sourceMappingURL=chunk-FP5KRDUN.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-EUTTXFWA.cjs","../src/hooks/useClientValidation/useClientValidation.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACRA,8BAAiC;AAEjC,uCAAmC;AA8D5B,IAAM,oBAAA,EAAsB,CACjC,IAAA,EACA,aAAA,EACA,OAAA,EAAA,GACS;AAtEX,EAAA,IAAA,EAAA;AAuEE,EAAA,MAAM;AAAA,IACJ,SAAA,EAAW,EAAE,cAAc,CAAA;AAAA,IAC3B,UAAA,EAAY,EAAE,0BAA0B,CAAA;AAAA,IACxC;AAAA,EACF,EAAA,EAAI,8CAAA,CAAe;AAGnB,EAAA,MAAM,iBAAA,EAAmB,0BAAA,CAAM;AAC/B,EAAA,MAAM,IAAA,EAAA,CAAM,GAAA,EAAA,QAAA,GAAA,KAAA,EAAA,KAAA,EAAA,EAAA,OAAA,CAAS,GAAA,EAAA,GAAT,KAAA,EAAA,GAAA,EAAgB,gBAAA;AAI5B,EAAA,MAAM,SAAA,EAAW,IAAA,CAAK,SAAA,CAAU,IAAI,CAAA;AAGpC,EAAA,8BAAA,CAAU,EAAA,GAAM;AAEd,IAAA,GAAA,CAAI,KAAA,GAAQ,IAAA,EAAM;AAChB,MAAA,MAAM,iBAAA,EAAmB,aAAA,CAAc,IAAI,CAAA;AAC3C,MAAA,yBAAA,CAA0B,GAAA,EAAK,gBAAgB,CAAA;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AA,IAClC,EAAA,KAAO;AAGL,MAAA,MAAM,IAAA,EAAM,+BAAA;AAAY,QACtB,CAAC,OAAO,CAAA,EAAG;AAAA,MACb,CAAC,CAAA;AACD,MAAA,OAAA,EAAS,EAAA,EAAI,EAAA,EAAI,GAAA,CAAI,QAAA,CAAS,EAAA,EAAI,GAAA;AAAA,IACpC;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT,CAAA;AD3KA;AACA;AACE;AACA;AACF,uHAAC","file":"/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-EUTTXFWA.cjs","sourcesContent":[null,"import type { VetoTypeAny } from '@fuf-stack/veto';\n\nimport { useEffect, useId } from 'react';\n\nimport { array, objectLoose } from '@fuf-stack/veto';\n\nimport { flatArrayKey } from '../../helpers';\nimport { useFormContext } from '../useFormContext/useFormContext';\n\n/**\n * Hook for adding dynamic client-side validation to forms.\n *\n * Client validation is used for context-dependent validation rules that require external data\n * (e.g., checking if a username already exists). It complements base validation (passed to Form),\n * which handles static rules like \"required\", min/max length, format, etc.\n *\n * **Typical pattern:**\n * - Base validation: Static, always-on rules (required, format, length constraints)\n * - Client validation: Dynamic rules based on external data (uniqueness, business logic)\n * - Client schemas should use `.nullish()` to allow empty values (base validation handles \"required\")\n *\n * Automatically manages validation schema lifecycle: sets schema when data is provided,\n * clears schema when data is null/undefined, and cleans up on unmount. When the client\n * validation schema changes, automatically re-validates all touched fields.\n *\n * @param data - Data to create validation schema from (or null/undefined to clear validation)\n * @param schemaFactory - Function that creates a validation schema from the data. Schemas should typically use `.nullish()`.\n * @param options - Optional configuration object\n * @param options.key - Optional custom key for registration. Useful when multiple instances should share validation (e.g., in field arrays)\n *\n * @example\n * ```tsx\n * // Base validation handles \"required\" and format\n * const baseSchema = veto({ username: vt.string({ min: 3 }) });\n *\n * // Client validation adds dynamic uniqueness check\n * const { data: teamData } = useTeamQuery(teamId);\n * useClientValidation(teamData, (data) =>\n * vt.objectLoose({\n * username: vt.string()\n * .refine(\n * (value) => !data.existingUsers.includes(value),\n * { message: 'Username already exists' }\n * )\n * .nullish() // Allow empty - base validation handles \"required\"\n * })\n * );\n * ```\n *\n * @example\n * ```tsx\n * // Using custom key in a field array to avoid multiple registrations\n * fields.map((field, index) => (\n * useClientValidation(\n * userData,\n * (data) => clientValidationSchemaByName(\n * `items.${index}.name`,\n * vt.string()\n * .refine((val) => !data.forbidden.includes(val), { message: 'Name not allowed' })\n * .nullish()\n * ),\n * { key: 'items-validation' } // All instances share the same key\n * )\n * ));\n * ```\n */\nexport const useClientValidation = <TData = unknown>(\n data: TData | null | undefined,\n schemaFactory: (data: TData) => VetoTypeAny,\n options?: { key?: string },\n): void => {\n const {\n formState: { touchedFields },\n validation: { setClientValidationSchema },\n trigger,\n } = useFormContext();\n\n // Use provided key or auto-generate unique key\n const autoGeneratedKey = useId();\n const key = options?.key ?? autoGeneratedKey;\n\n // Use data hash instead of object reference to avoid unnecessary re-runs\n // when data object reference changes but data remains the same\n const dataHash = JSON.stringify(data);\n\n // Single effect to manage validation schema lifecycle\n useEffect(() => {\n // Set validation schema when data is available\n if (data != null) {\n const validationSchema = schemaFactory(data);\n setClientValidationSchema(key, validationSchema);\n } else {\n // Clear validation schema when no data\n setClientValidationSchema(key, null);\n }\n\n // Re-validate all touched fields when client validation schema changes\n const touchedFieldNames = Object.keys(touchedFields);\n if (touchedFieldNames.length > 0) {\n // Use setTimeout to ensure the client validation schema update has propagated\n // before triggering re-validation (fixes race condition)\n setTimeout(async () => {\n return trigger(touchedFieldNames);\n }, 1);\n }\n\n // Cleanup on unmount or when dependencies change\n return () => {\n setClientValidationSchema(key, null);\n };\n // Only re-run when data (dataHash) or key changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [dataHash, key]);\n};\n\n/**\n * Helper function to create a veto looseObject schema for a single field with nested path support.\n *\n * Parses field paths (dot-notation) and creates properly nested loose object schemas with array support.\n * All intermediate objects and arrays are marked as optional to allow partial data structures.\n * Numeric segments in the path are treated as array indices, and the parent field is wrapped in an array schema.\n * Supports flat arrays (arrays of primitives) via the special `__FLAT__` key.\n *\n * **Important:** The fieldSchema should typically use `.nullish()` to allow empty values. This is because:\n * - Base validation (passed to Form) handles \"required\" constraints\n * - Client validation adds dynamic, context-dependent rules (e.g., \"username already exists\")\n * - Form data processing converts empty strings in flat arrays to `null` (not `undefined`)\n * - `.nullish()` accepts both `null` and `undefined`, while `.optional()` only accepts `undefined`\n *\n * This pattern ensures client validation only validates non-empty values, while base validation\n * enforces required fields and basic constraints (min length, format, etc.).\n *\n * @param name - The dot-separated path to the field (e.g., 'username', 'user.profile.email', 'items.0.name', 'tags.0.__FLAT__')\n * @param fieldSchema - The veto validation schema for the field. Should typically use `.nullish()` to allow empty values.\n * @returns A nested loose object schema matching the field path structure with proper type inference\n *\n * @example\n * ```tsx\n * // Typical usage: base validation handles \"required\", client validation adds dynamic rules\n * // Base validation (in Form component)\n * const baseSchema = veto({ username: vt.string({ min: 3 }) }); // Required + min length\n *\n * // Client validation (dynamic check for existing usernames)\n * const { data: userData } = useUserQuery(userId);\n * useClientValidation(userData, (data) =>\n * clientValidationSchemaByName(\n * 'username',\n * vt.string()\n * .refine(\n * (value) => !data.existingUsernames.includes(value),\n * { message: 'Username already taken' }\n * )\n * .nullish() // Allow empty - base validation handles \"required\"\n * )\n * );\n * ```\n *\n * @example\n * ```tsx\n * // Nested field path with dynamic validation\n * clientValidationSchemaByName(\n * 'user.profile.email',\n * vt.string()\n * .refine(\n * (value) => !reservedEmails.includes(value),\n * { message: 'This email is reserved' }\n * )\n * .nullish()\n * )\n * // => objectLoose({ user: objectLoose({ profile: objectLoose({ email: ... }).optional() }).optional() })\n * ```\n *\n * @example\n * ```tsx\n * // Array of objects with dynamic validation\n * clientValidationSchemaByName(\n * 'items.0.tag',\n * vt.string()\n * .refine((value) => !forbiddenTags.includes(value), { message: 'Tag not allowed' })\n * .nullish()\n * )\n * // => objectLoose({ items: array(objectLoose({ tag: ... })).optional() })\n * ```\n *\n * @example\n * ```tsx\n * // Flat array (array of primitives) with dynamic validation\n * clientValidationSchemaByName(\n * 'tags.0.__FLAT__',\n * vt.string()\n * .refine((value) => !forbiddenWords.includes(value), { message: 'Word not allowed' })\n * .nullish()\n * )\n * // => objectLoose({ tags: array(vt.string().refine(...).nullish()).optional() })\n * ```\n */\nexport const clientValidationSchemaByName = <T extends VetoTypeAny>(\n name: string,\n fieldSchema: T,\n) => {\n const segments = name.split('.');\n\n // Build schema from innermost to outermost\n let schema: VetoTypeAny = fieldSchema;\n\n // Process segments in reverse order to build nested structure\n for (let i = segments.length - 1; i >= 0; i -= 1) {\n const segment = segments[i];\n\n const isNumeric = /^\\d+$/.test(segment);\n const isFlatArrayKey = segment === flatArrayKey;\n\n if (isFlatArrayKey) {\n // Skip the __FLAT__ key - it's just a marker for flat arrays\n // The schema is already correct (primitive type), just continue\n // eslint-disable-next-line no-continue\n continue;\n }\n\n if (isNumeric) {\n // Current segment is an array index - wrap current schema in optional array\n schema = array(schema).optional();\n } else {\n // Current segment is a field name - wrap in objectLoose\n // Make it optional if it's an intermediate object (not the root)\n const obj = objectLoose({\n [segment]: schema,\n });\n schema = i > 0 ? obj.optional() : obj;\n }\n }\n\n return schema;\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-FP5KRDUN.cjs","../src/hooks/useClientValidation/useClientValidation.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACRA,8BAAiC;AAEjC,uCAAmC;AA8D5B,IAAM,oBAAA,EAAsB,CACjC,IAAA,EACA,aAAA,EACA,OAAA,EAAA,GACS;AAtEX,EAAA,IAAA,EAAA;AAuEE,EAAA,MAAM;AAAA,IACJ,SAAA,EAAW,EAAE,cAAc,CAAA;AAAA,IAC3B,UAAA,EAAY,EAAE,0BAA0B,CAAA;AAAA,IACxC;AAAA,EACF,EAAA,EAAI,8CAAA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AG1B,EAAA,IAAA,CAAA,IAAS,EAAA,EAAI,QAAA,CAAS,OAAA,EAAS,CAAA,EAAG,EAAA,GAAK,CAAA,EAAG,EAAA,GAAK,CAAA,EAAG;AAChD,IAAA,MAAM,QAAA,EAAU,QAAA,CAAS,CAAC,CAAA;AAE1B,IAAA,MAAM,UAAA,EAAY,OAAA,CAAQ,IAAA,CAAK,OAAO,CAAA;AACtC,IAAA,MAAM,eAAA,EAAiB,QAAA,IAAY,8BAAA;AAEnC,IAAA,GAAA,CAAI,cAAA,EAAgB;AAIlB,MAAA,QAAA;AAAA,IACF;AAEA,IAAA,GAAA,CAAI,SAAA,EAAW;AAEb,MAAA,OAAA,EAAS,yBAAA,MAAY,CAAA,CAAE,QAAA,CAAS,CAAA;AAAA,IAClC,EAAA,KAAO;AAGL,MAAA,MAAM,IAAA,EAAM,+BAAA;AAAY,QACtB,CAAC,OAAO,CAAA,EAAG;AAAA,MACb,CAAC,CAAA;AACD,MAAA,OAAA,EAAS,EAAA,EAAI,EAAA,EAAI,GAAA,CAAI,QAAA,CAAS,EAAA,EAAI,GAAA;AAAA,IACpC;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT,CAAA;AD3KA;AACA;AACE;AACA;AACF,uHAAC","file":"/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-FP5KRDUN.cjs","sourcesContent":[null,"import type { VetoTypeAny } from '@fuf-stack/veto';\n\nimport { useEffect, useId } from 'react';\n\nimport { array, objectLoose } from '@fuf-stack/veto';\n\nimport { flatArrayKey } from '../../helpers';\nimport { useFormContext } from '../useFormContext/useFormContext';\n\n/**\n * Hook for adding dynamic client-side validation to forms.\n *\n * Client validation is used for context-dependent validation rules that require external data\n * (e.g., checking if a username already exists). It complements base validation (passed to Form),\n * which handles static rules like \"required\", min/max length, format, etc.\n *\n * **Typical pattern:**\n * - Base validation: Static, always-on rules (required, format, length constraints)\n * - Client validation: Dynamic rules based on external data (uniqueness, business logic)\n * - Client schemas should use `.nullish()` to allow empty values (base validation handles \"required\")\n *\n * Automatically manages validation schema lifecycle: sets schema when data is provided,\n * clears schema when data is null/undefined, and cleans up on unmount. When the client\n * validation schema changes, automatically re-validates all touched fields.\n *\n * @param data - Data to create validation schema from (or null/undefined to clear validation)\n * @param schemaFactory - Function that creates a validation schema from the data. Schemas should typically use `.nullish()`.\n * @param options - Optional configuration object\n * @param options.key - Optional custom key for registration. Useful when multiple instances should share validation (e.g., in field arrays)\n *\n * @example\n * ```tsx\n * // Base validation handles \"required\" and format\n * const baseSchema = veto({ username: vt.string({ min: 3 }) });\n *\n * // Client validation adds dynamic uniqueness check\n * const { data: teamData } = useTeamQuery(teamId);\n * useClientValidation(teamData, (data) =>\n * vt.objectLoose({\n * username: vt.string()\n * .refine(\n * (value) => !data.existingUsers.includes(value),\n * { message: 'Username already exists' }\n * )\n * .nullish() // Allow empty - base validation handles \"required\"\n * })\n * );\n * ```\n *\n * @example\n * ```tsx\n * // Using custom key in a field array to avoid multiple registrations\n * fields.map((field, index) => (\n * useClientValidation(\n * userData,\n * (data) => clientValidationSchemaByName(\n * `items.${index}.name`,\n * vt.string()\n * .refine((val) => !data.forbidden.includes(val), { message: 'Name not allowed' })\n * .nullish()\n * ),\n * { key: 'items-validation' } // All instances share the same key\n * )\n * ));\n * ```\n */\nexport const useClientValidation = <TData = unknown>(\n data: TData | null | undefined,\n schemaFactory: (data: TData) => VetoTypeAny,\n options?: { key?: string },\n): void => {\n const {\n formState: { touchedFields },\n validation: { setClientValidationSchema },\n trigger,\n } = useFormContext();\n\n // Use provided key or auto-generate unique key\n const autoGeneratedKey = useId();\n const key = options?.key ?? autoGeneratedKey;\n\n // Use data hash instead of object reference to avoid unnecessary re-runs\n // when data object reference changes but data remains the same\n const dataHash = JSON.stringify(data);\n\n // Single effect to manage validation schema lifecycle\n useEffect(() => {\n // Set validation schema when data is available\n if (data != null) {\n const validationSchema = schemaFactory(data);\n setClientValidationSchema(key, validationSchema);\n } else {\n // Clear validation schema when no data\n setClientValidationSchema(key, null);\n }\n\n // Re-validate all touched fields when client validation schema changes\n const touchedFieldNames = Object.keys(touchedFields);\n if (touchedFieldNames.length > 0) {\n // Use setTimeout to ensure the client validation schema update has propagated\n // before triggering re-validation (fixes race condition)\n setTimeout(async () => {\n return trigger(touchedFieldNames);\n }, 1);\n }\n\n // Cleanup on unmount or when dependencies change\n return () => {\n setClientValidationSchema(key, null);\n };\n // Only re-run when data (dataHash) or key changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [dataHash, key]);\n};\n\n/**\n * Helper function to create a veto looseObject schema for a single field with nested path support.\n *\n * Parses field paths (dot-notation) and creates properly nested loose object schemas with array support.\n * All intermediate objects and arrays are marked as optional to allow partial data structures.\n * Numeric segments in the path are treated as array indices, and the parent field is wrapped in an array schema.\n * Supports flat arrays (arrays of primitives) via the special `__FLAT__` key.\n *\n * **Important:** The fieldSchema should typically use `.nullish()` to allow empty values. This is because:\n * - Base validation (passed to Form) handles \"required\" constraints\n * - Client validation adds dynamic, context-dependent rules (e.g., \"username already exists\")\n * - Form data processing converts empty strings in flat arrays to `null` (not `undefined`)\n * - `.nullish()` accepts both `null` and `undefined`, while `.optional()` only accepts `undefined`\n *\n * This pattern ensures client validation only validates non-empty values, while base validation\n * enforces required fields and basic constraints (min length, format, etc.).\n *\n * @param name - The dot-separated path to the field (e.g., 'username', 'user.profile.email', 'items.0.name', 'tags.0.__FLAT__')\n * @param fieldSchema - The veto validation schema for the field. Should typically use `.nullish()` to allow empty values.\n * @returns A nested loose object schema matching the field path structure with proper type inference\n *\n * @example\n * ```tsx\n * // Typical usage: base validation handles \"required\", client validation adds dynamic rules\n * // Base validation (in Form component)\n * const baseSchema = veto({ username: vt.string({ min: 3 }) }); // Required + min length\n *\n * // Client validation (dynamic check for existing usernames)\n * const { data: userData } = useUserQuery(userId);\n * useClientValidation(userData, (data) =>\n * clientValidationSchemaByName(\n * 'username',\n * vt.string()\n * .refine(\n * (value) => !data.existingUsernames.includes(value),\n * { message: 'Username already taken' }\n * )\n * .nullish() // Allow empty - base validation handles \"required\"\n * )\n * );\n * ```\n *\n * @example\n * ```tsx\n * // Nested field path with dynamic validation\n * clientValidationSchemaByName(\n * 'user.profile.email',\n * vt.string()\n * .refine(\n * (value) => !reservedEmails.includes(value),\n * { message: 'This email is reserved' }\n * )\n * .nullish()\n * )\n * // => objectLoose({ user: objectLoose({ profile: objectLoose({ email: ... }).optional() }).optional() })\n * ```\n *\n * @example\n * ```tsx\n * // Array of objects with dynamic validation\n * clientValidationSchemaByName(\n * 'items.0.tag',\n * vt.string()\n * .refine((value) => !forbiddenTags.includes(value), { message: 'Tag not allowed' })\n * .nullish()\n * )\n * // => objectLoose({ items: array(objectLoose({ tag: ... })).optional() })\n * ```\n *\n * @example\n * ```tsx\n * // Flat array (array of primitives) with dynamic validation\n * clientValidationSchemaByName(\n * 'tags.0.__FLAT__',\n * vt.string()\n * .refine((value) => !forbiddenWords.includes(value), { message: 'Word not allowed' })\n * .nullish()\n * )\n * // => objectLoose({ tags: array(vt.string().refine(...).nullish()).optional() })\n * ```\n */\nexport const clientValidationSchemaByName = <T extends VetoTypeAny>(\n name: string,\n fieldSchema: T,\n) => {\n const segments = name.split('.');\n\n // Build schema from innermost to outermost\n let schema: VetoTypeAny = fieldSchema;\n\n // Process segments in reverse order to build nested structure\n for (let i = segments.length - 1; i >= 0; i -= 1) {\n const segment = segments[i];\n\n const isNumeric = /^\\d+$/.test(segment);\n const isFlatArrayKey = segment === flatArrayKey;\n\n if (isFlatArrayKey) {\n // Skip the __FLAT__ key - it's just a marker for flat arrays\n // The schema is already correct (primitive type), just continue\n // eslint-disable-next-line no-continue\n continue;\n }\n\n if (isNumeric) {\n // Current segment is an array index - wrap current schema in optional array\n schema = array(schema).optional();\n } else {\n // Current segment is a field name - wrap in objectLoose\n // Make it optional if it's an intermediate object (not the root)\n const obj = objectLoose({\n [segment]: schema,\n });\n schema = i > 0 ? obj.optional() : obj;\n }\n }\n\n return schema;\n};\n"]}
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-ELYGQTXB.js";
|
|
7
7
|
import {
|
|
8
8
|
useController
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-ZLFYOJ4M.js";
|
|
10
10
|
import {
|
|
11
11
|
useInput
|
|
12
12
|
} from "./chunk-AHJJIANM.js";
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
} from "./chunk-CNTOODUQ.js";
|
|
16
16
|
import {
|
|
17
17
|
useFormContext
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-2BWUTUVE.js";
|
|
19
19
|
import {
|
|
20
20
|
__spreadProps,
|
|
21
21
|
__spreadValues
|
|
@@ -129,4 +129,4 @@ function useUniformField(params) {
|
|
|
129
129
|
export {
|
|
130
130
|
useUniformField
|
|
131
131
|
};
|
|
132
|
-
//# sourceMappingURL=chunk-
|
|
132
|
+
//# sourceMappingURL=chunk-G3A7AEDA.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useFormContext
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-2BWUTUVE.js";
|
|
4
4
|
|
|
5
5
|
// src/SubmitButton/SubmitButton.tsx
|
|
6
6
|
import { cn, slugify } from "@fuf-stack/pixel-utils";
|
|
@@ -46,4 +46,4 @@ export {
|
|
|
46
46
|
SubmitButton_default,
|
|
47
47
|
SubmitButton_default2
|
|
48
48
|
};
|
|
49
|
-
//# sourceMappingURL=chunk-
|
|
49
|
+
//# sourceMappingURL=chunk-GNK45IFM.js.map
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useUniformField
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-G3A7AEDA.js";
|
|
4
4
|
import {
|
|
5
5
|
useFormContext
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-2BWUTUVE.js";
|
|
7
7
|
import {
|
|
8
8
|
flatArrayKey
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-O2XJNQQK.js";
|
|
10
10
|
import {
|
|
11
11
|
__spreadValues
|
|
12
12
|
} from "./chunk-K2V4ULA2.js";
|
|
@@ -100,4 +100,4 @@ var useUniformFieldArray = ({
|
|
|
100
100
|
export {
|
|
101
101
|
useUniformFieldArray
|
|
102
102
|
};
|
|
103
|
-
//# sourceMappingURL=chunk-
|
|
103
|
+
//# sourceMappingURL=chunk-HH7YK5QR.js.map
|
|
@@ -6,7 +6,7 @@ var _chunkOE5BOGGXcjs = require('./chunk-OE5BOGGX.cjs');
|
|
|
6
6
|
var _chunkNHEZXA4Hcjs = require('./chunk-NHEZXA4H.cjs');
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
var
|
|
9
|
+
var _chunkMZIVLP3Ucjs = require('./chunk-MZIVLP3U.cjs');
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
var _chunkPCTYJUY7cjs = require('./chunk-PCTYJUY7.cjs');
|
|
@@ -15,7 +15,7 @@ var _chunkPCTYJUY7cjs = require('./chunk-PCTYJUY7.cjs');
|
|
|
15
15
|
var _chunk56TQOKG7cjs = require('./chunk-56TQOKG7.cjs');
|
|
16
16
|
|
|
17
17
|
|
|
18
|
-
var
|
|
18
|
+
var _chunkC2JPKUCYcjs = require('./chunk-C2JPKUCY.cjs');
|
|
19
19
|
|
|
20
20
|
|
|
21
21
|
|
|
@@ -47,7 +47,7 @@ function useUniformField(params) {
|
|
|
47
47
|
getFieldState,
|
|
48
48
|
getValues,
|
|
49
49
|
resetField
|
|
50
|
-
} =
|
|
50
|
+
} = _chunkC2JPKUCYcjs.useFormContext.call(void 0, );
|
|
51
51
|
const {
|
|
52
52
|
error,
|
|
53
53
|
invalid: rawInvalid,
|
|
@@ -56,7 +56,7 @@ function useUniformField(params) {
|
|
|
56
56
|
required,
|
|
57
57
|
testId
|
|
58
58
|
} = getFieldState(name, explicitTestId);
|
|
59
|
-
const { field } =
|
|
59
|
+
const { field } = _chunkMZIVLP3Ucjs.useController.call(void 0, {
|
|
60
60
|
control,
|
|
61
61
|
disabled,
|
|
62
62
|
name
|
|
@@ -129,4 +129,4 @@ function useUniformField(params) {
|
|
|
129
129
|
|
|
130
130
|
|
|
131
131
|
exports.useUniformField = useUniformField;
|
|
132
|
-
//# sourceMappingURL=chunk-
|
|
132
|
+
//# sourceMappingURL=chunk-IXJISVRO.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-OQUTHTOK.cjs","../src/hooks/useUniformField/useUniformField.tsx"],"names":["_a"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACjBA,sDAAiC;AACjC,2CAA4B;AAoNtB,+CAAA;AAjMN,IAAM,oBAAA,EAAsB,CAAC,OAAA,EAAkB,OAAA,EAAA,GAAoB;AACjE,EAAA,MAAM,qBAAA,EAAuB,2CAAA,CAAiB;AAC9C,EAAA,MAAM,iBAAA,EAAmB,iCAAA,OAAY,EAAS,OAAO,CAAA;AAGrD,EAAA,OAAO,qBAAA,EAAuB,QAAA,EAAU,gBAAA;AAC1C,CAAA;AA2FO,SAAS,eAAA,CAId,MAAA,EACqC;AAhIvC,EAAA,IAAA,EAAA;AAiIE,EAAA,MAAM;AAAA,IACJ,IAAA;AAAA,IACA,SAAA,EAAW,KAAA;AAAA,IACX,MAAA,EAAQ,cAAA;AAAA,IACR,KAAA;AAAA,IACA,IAAA;AAAA,IACA;AAAA,EACF,EAAA,EAAI,MAAA;AAEJ,EAAA,MAAM;AAAA,IACJ,OAAA;AAAA,IACA,SAAA;AAAA,IACA,SAAA,EAAW,EAAE,YAAY,CAAA;AAAA,IACzB,aAA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AAAA,MACP,QAAA,EAAU;AAAA,IACZ,CAAA,CAAA;AAAA,IACA,oBAAA;AAAA,IACA,qBAAA;AAAA,IACA,aAAA;AAAA,IACA,SAAA;AAAA,IACA,OAAA;AAAA,IACA,KAAA,EAAO,SAAA;AAAA,IACP,MAAA;AAAA,IACA,QAAA,EAAU,mBAAA;AAAA,IACV,GAAA;AAAA,IACA,QAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,EACF,CAAA;AACF;ADlJA;AACA;AACE;AACF,0CAAC","file":"/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-OQUTHTOK.cjs","sourcesContent":[null,"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 { useReducedMotion } from '@fuf-stack/pixel-motion';\nimport { useDebounce } from '@fuf-stack/pixels';\n\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\n/**\n * Debounce invalid state changes for smooth UI transitions while respecting accessibility.\n *\n * Behavior:\n * - Specifically intended for validation invalid flags: debounces both\n * true → false and false → true transitions by `delayMs` to prevent\n * flicker and allow enter/exit animations to complete.\n * - If the user prefers reduced motion (via `useReducedMotion` from\n * `@fuf-stack/pixel-motion`), updates apply immediately with no delay.\n */\nconst useDebouncedInvalid = (invalid: boolean, delayMs: number) => {\n const prefersReducedMotion = useReducedMotion();\n const debouncedInvalid = useDebounce(invalid, delayMs);\n\n // If user prefers reduced motion, return invalid immediately without debouncing\n return prefersReducedMotion ? invalid : debouncedInvalid;\n};\n\nexport interface UseUniformFieldParams<\n TFieldValues extends FieldValues = FieldValues,\n TDisplay = unknown,\n> {\n /** Form field name */\n name: Path<TFieldValues> & string;\n /** Disable the field */\n disabled?: boolean;\n /** Optional explicit test id used to build stable test ids */\n testId?: string;\n /** Optional label content; pass false to suppress label entirely */\n label?: ReactNode | false;\n /** Input type for special number handling */\n type?: 'text' | 'number' | 'password';\n /** Optional value transformation between form and display values */\n transform?: InputValueTransform<TDisplay>;\n}\n\nexport interface UseUniformFieldReturn<\n TFieldValues extends FieldValues = FieldValues,\n> {\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 error(s) for the field */\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 /** 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 using `FieldValidationError`\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 function useUniformField<\n TFieldValues extends FieldValues = FieldValues,\n TDisplay = unknown,\n>(\n params: UseUniformFieldParams<TFieldValues, TDisplay>,\n): UseUniformFieldReturn<TFieldValues> {\n const {\n name,\n disabled = false,\n testId: explicitTestId,\n label,\n type,\n transform,\n } = params;\n\n const {\n control,\n debugMode,\n formState: { submitCount },\n getFieldState,\n getValues,\n resetField,\n } = useFormContext<TFieldValues>();\n\n const {\n error,\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 as typeof fieldValue);\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 is dirty (value changed from initial) - good for checkboxes/radios/arrays\n * - Field is touched (focused and blurred) - good for text inputs\n * - Form has been submitted - shows all errors after submit attempt\n *\n * This prevents showing errors on pristine/untouched fields for better UX.\n * Examples:\n * - Text input: User loads form with empty required field → no error shown yet\n * - Text input: User focuses and blurs → error shows (via isTouched)\n * - Checkbox group: User clicks first checkbox → error shows immediately (via isDirty)\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 * when any of the states (invalid, isDirty, isTouched, submitCount) change.\n */\n const showInvalid = rawInvalid && (isDirty || isTouched || submitCount > 0);\n const invalid = useDebouncedInvalid(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 // Ready-to-render error message; consumers can drop this into their\n // component `errorMessage` prop without repeating mapping/markup\n const errorMessage = <FieldValidationError error={error} testId={testId} />;\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 return {\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 ref,\n required,\n resetField,\n testId,\n };\n}\n\nexport default useUniformField;\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-IXJISVRO.cjs","../src/hooks/useUniformField/useUniformField.tsx"],"names":["_a"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACjBA,sDAAiC;AACjC,2CAA4B;AAoNtB,+CAAA;AAjMN,IAAM,oBAAA,EAAsB,CAAC,OAAA,EAAkB,OAAA,EAAA,GAAoB;AACjE,EAAA,MAAM,qBAAA,EAAuB,2CAAA,CAAiB;AAC9C,EAAA,MAAM,iBAAA,EAAmB,iCAAA,OAAY,EAAS,OAAO,CAAA;AAGrD,EAAA,OAAO,qBAAA,EAAuB,QAAA,EA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K,CAAA;AAAA,IAClC,SAAA,EAAW,OAAA;AAAA,IACX,UAAA,EAAY,QAAA;AAAA,IACZ,KAAA;AAAA,IACA,cAAA,EAAgB;AAAA,EAClB,CAAC,CAAA;AAEH,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,SAAA;AAAA,IACA,YAAA;AAAA,IACA,QAAA,EAAU,UAAA;AAAA,IACV,KAAA;AAAA,IACA,YAAA;AAAA,IACA,KAAA,EAAO,6CAAA,8CAAA,CAAA,CAAA,EACF,KAAA,CAAA,EADE;AAAA,MAEL,KAAA,EAAO,gBAAA;AAAA,MACP,QAAA,EAAU;AAAA,IACZ,CAAA,CAAA;AAAA,IACA,oBAAA;AAAA,IACA,qBAAA;AAAA,IACA,aAAA;AAAA,IACA,SAAA;AAAA,IACA,OAAA;AAAA,IACA,KAAA,EAAO,SAAA;AAAA,IACP,MAAA;AAAA,IACA,QAAA,EAAU,mBAAA;AAAA,IACV,GAAA;AAAA,IACA,QAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,EACF,CAAA;AACF;ADlJA;AACA;AACE;AACF,0CAAC","file":"/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-IXJISVRO.cjs","sourcesContent":[null,"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 { useReducedMotion } from '@fuf-stack/pixel-motion';\nimport { useDebounce } from '@fuf-stack/pixels';\n\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\n/**\n * Debounce invalid state changes for smooth UI transitions while respecting accessibility.\n *\n * Behavior:\n * - Specifically intended for validation invalid flags: debounces both\n * true → false and false → true transitions by `delayMs` to prevent\n * flicker and allow enter/exit animations to complete.\n * - If the user prefers reduced motion (via `useReducedMotion` from\n * `@fuf-stack/pixel-motion`), updates apply immediately with no delay.\n */\nconst useDebouncedInvalid = (invalid: boolean, delayMs: number) => {\n const prefersReducedMotion = useReducedMotion();\n const debouncedInvalid = useDebounce(invalid, delayMs);\n\n // If user prefers reduced motion, return invalid immediately without debouncing\n return prefersReducedMotion ? invalid : debouncedInvalid;\n};\n\nexport interface UseUniformFieldParams<\n TFieldValues extends FieldValues = FieldValues,\n TDisplay = unknown,\n> {\n /** Form field name */\n name: Path<TFieldValues> & string;\n /** Disable the field */\n disabled?: boolean;\n /** Optional explicit test id used to build stable test ids */\n testId?: string;\n /** Optional label content; pass false to suppress label entirely */\n label?: ReactNode | false;\n /** Input type for special number handling */\n type?: 'text' | 'number' | 'password';\n /** Optional value transformation between form and display values */\n transform?: InputValueTransform<TDisplay>;\n}\n\nexport interface UseUniformFieldReturn<\n TFieldValues extends FieldValues = FieldValues,\n> {\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 error(s) for the field */\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 /** 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 using `FieldValidationError`\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 function useUniformField<\n TFieldValues extends FieldValues = FieldValues,\n TDisplay = unknown,\n>(\n params: UseUniformFieldParams<TFieldValues, TDisplay>,\n): UseUniformFieldReturn<TFieldValues> {\n const {\n name,\n disabled = false,\n testId: explicitTestId,\n label,\n type,\n transform,\n } = params;\n\n const {\n control,\n debugMode,\n formState: { submitCount },\n getFieldState,\n getValues,\n resetField,\n } = useFormContext<TFieldValues>();\n\n const {\n error,\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 as typeof fieldValue);\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 is dirty (value changed from initial) - good for checkboxes/radios/arrays\n * - Field is touched (focused and blurred) - good for text inputs\n * - Form has been submitted - shows all errors after submit attempt\n *\n * This prevents showing errors on pristine/untouched fields for better UX.\n * Examples:\n * - Text input: User loads form with empty required field → no error shown yet\n * - Text input: User focuses and blurs → error shows (via isTouched)\n * - Checkbox group: User clicks first checkbox → error shows immediately (via isDirty)\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 * when any of the states (invalid, isDirty, isTouched, submitCount) change.\n */\n const showInvalid = rawInvalid && (isDirty || isTouched || submitCount > 0);\n const invalid = useDebouncedInvalid(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 // Ready-to-render error message; consumers can drop this into their\n // component `errorMessage` prop without repeating mapping/markup\n const errorMessage = <FieldValidationError error={error} testId={testId} />;\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 return {\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 ref,\n required,\n resetField,\n testId,\n };\n}\n\nexport default useUniformField;\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useUniformField
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-G3A7AEDA.js";
|
|
4
4
|
import {
|
|
5
5
|
__objRest,
|
|
6
6
|
__spreadValues
|
|
@@ -113,4 +113,4 @@ export {
|
|
|
113
113
|
Radios_default,
|
|
114
114
|
Radios_default2
|
|
115
115
|
};
|
|
116
|
-
//# sourceMappingURL=chunk-
|
|
116
|
+
//# sourceMappingURL=chunk-K6TW2OY3.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var
|
|
4
|
+
var _chunkOKJWLH7Tcjs = require('./chunk-OKJWLH7T.cjs');
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
@@ -92,7 +92,7 @@ var useFormResolver = (extendedValidation) => {
|
|
|
92
92
|
}
|
|
93
93
|
return (values) => _chunk555JRYCScjs.__async.call(void 0, null, null, function* () {
|
|
94
94
|
var _a, _b, _c, _d;
|
|
95
|
-
const validationValues = (_a =
|
|
95
|
+
const validationValues = (_a = _chunkOKJWLH7Tcjs.toValidationFormat.call(void 0, values)) != null ? _a : {};
|
|
96
96
|
const result = yield extendedValidation.validateAsync(validationValues);
|
|
97
97
|
validationErrors.current = (_b = result.errors) != null ? _b : void 0;
|
|
98
98
|
return {
|
|
@@ -160,7 +160,7 @@ var FormProvider = ({
|
|
|
160
160
|
const { extendedValidation, setClientValidationSchema } = useExtendedValidation(baseValidation);
|
|
161
161
|
const { resolver, validationErrors, validationErrorsHash } = useFormResolver(extendedValidation);
|
|
162
162
|
const methods = _reacthookform.useForm.call(void 0, {
|
|
163
|
-
defaultValues: initialValues ?
|
|
163
|
+
defaultValues: initialValues ? _chunkOKJWLH7Tcjs.toFormFormat.call(void 0, initialValues) : initialValues,
|
|
164
164
|
// set rhf mode
|
|
165
165
|
// see: https://react-hook-form.com/docs/useform#mode
|
|
166
166
|
mode: validationTrigger,
|
|
@@ -196,7 +196,7 @@ var FormProvider = ({
|
|
|
196
196
|
}
|
|
197
197
|
const wrappedOnSubmit = (data, event) => {
|
|
198
198
|
var _a2;
|
|
199
|
-
const submitData = (_a2 =
|
|
199
|
+
const submitData = (_a2 = _chunkOKJWLH7Tcjs.toValidationFormat.call(void 0, data)) != null ? _a2 : {};
|
|
200
200
|
return onSubmit(submitData, event);
|
|
201
201
|
};
|
|
202
202
|
yield methods.handleSubmit(wrappedOnSubmit)(e);
|
|
@@ -236,4 +236,4 @@ var FormContext_default = FormProvider;
|
|
|
236
236
|
|
|
237
237
|
|
|
238
238
|
exports.UniformContext = UniformContext; exports.FormContext_default = FormContext_default;
|
|
239
|
-
//# sourceMappingURL=chunk-
|
|
239
|
+
//# sourceMappingURL=chunk-KQEM5HFD.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-4L3JXJ62.cjs","../src/Form/subcomponents/FormContext.tsx","../src/Form/subcomponents/FormResolver.ts"],"names":["useState","useRef","_a","useMemo"],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACJA,4EAA8D;AAC9D,gDAA0D;AAE1D,2CAAgC;ADKhC;AACA;AEVA;AAEA,uCAA0B;AAYnB,IAAM,2BAAA,EAA6B,CAAA,EAAA,GAAM;AAE9C,EAAA,MAAM,CAAC,uBAAA,EAAyB,0BAA0B,EAAA,EAAI,6BAAA,CAE3D,CAAC,CAAA;AAGJ,EAAA,MAAM,0BAAA,EAA4B,4BAAA,CAAQ,EAAA,GAAM;AAC9C,IAAA,OAAO,CAAC,GAAA,EAAa,MAAA,EAAA,GAA+B;AAElD,MAAA,0BAAA,CAA2B,CAAC,IAAA,EAAA,GAAS;AAEnC,QAAA,GAAA,CAAI,CAAC,IAAA,CAAK,GAAG,EAAA,GAAK,CAAC,MAAA,EAAQ;AACzB,UAAA,OAAO,IAAA;AAAA,QACT;AAEA,QAAA,GAAA,CAAI,CAAC,MAAA,EAAQ;AACX,UAAA,MAAqC,GAAA,EAAA,IAAA,EAA5B,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AA;AAAA,IACF,CAAA;AAAA;AAAA,IAEA,CAAC,SAAA,EAAW,kBAAA,GAAA,KAAA,EAAA,KAAA,EAAA,EAAA,iBAAA,CAAmB,OAAA,EAAS,oBAAoB;AAAA,EAC9D,CAAA;AAEA,EAAA,uBACE,6BAAA,cAAC,CAAe,QAAA,EAAf,EAAwB,KAAA,EAAO,YAAA,EAE9B,QAAA,kBAAA,6BAAA,2BAAC,EAAA,6CAAA,8CAAA,CAAA,CAAA,EAAqB,OAAA,CAAA,EAArB,EACE,QAAA,EAAA,QAAA,CAAS,EAAE,YAAA,EAAc,QAAQ,CAAC,EAAA,CAAA,CACrC,EAAA,CACF,CAAA;AAEJ,CAAA;AAEA,IAAO,oBAAA,EAAQ,YAAA;ADxFf;AACA;AACE;AACA;AACF,2FAAC","file":"/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-4L3JXJ62.cjs","sourcesContent":[null,"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, { useCallback, useMemo, useRef, useState } from 'react';\nimport { FormProvider as HookFormProvider, useForm } from 'react-hook-form';\n\nimport { useLocalStorage } from '@fuf-stack/pixels';\n\nimport { toFormFormat, toValidationFormat } from '../../helpers';\nimport { useExtendedValidation, useFormResolver } from './FormResolver';\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/**\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 *\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 from debug mode */\n debugModeSettings?: DebugModeSettings;\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 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}\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\n// Define props for the FormProvider component, extending HookForm's props\ninterface FormProviderProps {\n /** children form render function */\n children: (childProps: {\n handleSubmit: (e?: BaseSyntheticEvent) => Promise<void>;\n isValid: boolean;\n }) => ReactNode;\n /** settings for from 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 * - Client validation schema management\n * - Submit handler with automatic data conversion and submission control with preventSubmit\n * - Form Debug Mode state\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 // 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 + get current validation errors\n const { 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 // 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 // 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 // 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 console.warn(\n '[FormProvider] form submit was prevented because preventSubmit is true...',\n );\n e?.preventDefault();\n return Promise.resolve();\n }\n\n // Convert nullish strings and filter out empty values before submission\n const wrappedOnSubmit = (data: FieldValues, event?: BaseSyntheticEvent) => {\n const submitData = toValidationFormat(data) ?? {};\n return onSubmit(submitData, event);\n };\n\n await methods.handleSubmit(wrappedOnSubmit)(e);\n };\n\n // Memoize the context value to prevent re-renders\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 setPreventSubmit(prevent);\n },\n setClientValidationSchema,\n setDebugMode,\n triggerSubmit: handleSubmit,\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 <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 );\n};\n\nexport default FormProvider;\n","import type {\n VetoFormattedError,\n VetoInstance,\n VetoTypeAny,\n} from '@fuf-stack/veto';\nimport type { FieldValues } from 'react-hook-form';\n\nimport { useMemo, useRef, useState } from 'react';\n\nimport { and, veto } from '@fuf-stack/veto';\n\nimport { toValidationFormat } from '../../helpers';\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(\n () => {\n const keys = Object.keys(clientValidationSchemas).sort();\n return keys\n .map((key) => {\n return clientValidationSchemas[key];\n })\n .filter(Boolean);\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 = clientSchemaValues.reduce(\n // @ts-expect-error is ok, because initially it is null\n (combined, clientSchema) => {\n return combined ? and(combined, clientSchema) : clientSchema;\n },\n null,\n );\n\n // return combined validation\n if (hasBaseValidation && clientSchemasCombined) {\n return veto(and(baseValidation.schema, clientSchemasCombined));\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 * Hook that creates a React Hook Form resolver from an extended validation instance.\n *\n * @param extendedValidation - Extended validation instance from useExtendedValidation\n * @returns Object containing resolver function, current validation errors, and optimization hash\n */\nexport const useFormResolver = (extendedValidation?: VetoInstance) => {\n // Use ref to store validation errors without triggering re-renders\n const validationErrors = useRef<VetoFormattedError>(undefined);\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 const result = await extendedValidation.validateAsync(validationValues);\n validationErrors.current = result.errors ?? undefined;\n\n // Transform veto result to React Hook Form format\n return {\n values: result.data ?? {},\n errors: result.errors ?? {},\n };\n };\n }, [extendedValidation]);\n\n // Hash for memo dependency optimization in consuming components\n const validationErrorsHash = JSON.stringify(validationErrors.current);\n\n return {\n resolver,\n validationErrors: validationErrors.current,\n validationErrorsHash,\n };\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-KQEM5HFD.cjs","../src/Form/subcomponents/FormContext.tsx","../src/Form/subcomponents/FormResolver.ts"],"names":["useState","useRef","_a","useMemo"],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACJA,4EAA8D;AAC9D,gDAA0D;AAE1D,2CAAgC;ADKhC;AACA;AEVA;AAEA,uCAA0B;AA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GAAA,KAAA,EAAA,KAAA,EAAA,EAAA,iBAAA,CAAmB,OAAA,EAAA,EAAU,WAAA,EAAa,SAAA;AAAA,QACrD,aAAA,EAAe,CAAC,OAAA,EAAA,GAAqB;AACnC,UAAA,gBAAA,CAAiB,OAAO,CAAA;AAAA,QAC1B,CAAA;AAAA,QACA,yBAAA;AAAA,QACA,YAAA;AAAA,QACA,aAAA,EAAe,YAAA;AAAA,QACf,UAAA,EAAY;AAAA,UACV,SAAA,EAAW,mBAAA;AAAA,UACX,MAAA,EAAQ;AAAA,QACV,CAAA;AAAA,QACA,UAAA,EAAY;AAAA,UACV,YAAA,EAAc,cAAA;AAAA,UACd,QAAA,EAAU,kBAAA;AAAA,UACV,MAAA,EAAQ,gBAAA;AAAA,UACR;AAAA,QACF;AAAA,MACF,CAAA;AAAA,IACF,CAAA;AAAA;AAAA,IAEA,CAAC,SAAA,EAAW,kBAAA,GAAA,KAAA,EAAA,KAAA,EAAA,EAAA,iBAAA,CAAmB,OAAA,EAAS,oBAAoB;AAAA,EAC9D,CAAA;AAEA,EAAA,uBACE,6BAAA,cAAC,CAAe,QAAA,EAAf,EAAwB,KAAA,EAAO,YAAA,EAE9B,QAAA,kBAAA,6BAAA,2BAAC,EAAA,6CAAA,8CAAA,CAAA,CAAA,EAAqB,OAAA,CAAA,EAArB,EACE,QAAA,EAAA,QAAA,CAAS,EAAE,YAAA,EAAc,QAAQ,CAAC,EAAA,CAAA,CACrC,EAAA,CACF,CAAA;AAEJ,CAAA;AAEA,IAAO,oBAAA,EAAQ,YAAA;ADxFf;AACA;AACE;AACA;AACF,2FAAC","file":"/home/runner/work/pixels/pixels/packages/uniform/dist/chunk-KQEM5HFD.cjs","sourcesContent":[null,"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, { useCallback, useMemo, useRef, useState } from 'react';\nimport { FormProvider as HookFormProvider, useForm } from 'react-hook-form';\n\nimport { useLocalStorage } from '@fuf-stack/pixels';\n\nimport { toFormFormat, toValidationFormat } from '../../helpers';\nimport { useExtendedValidation, useFormResolver } from './FormResolver';\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/**\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 *\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 from debug mode */\n debugModeSettings?: DebugModeSettings;\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 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}\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\n// Define props for the FormProvider component, extending HookForm's props\ninterface FormProviderProps {\n /** children form render function */\n children: (childProps: {\n handleSubmit: (e?: BaseSyntheticEvent) => Promise<void>;\n isValid: boolean;\n }) => ReactNode;\n /** settings for from 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 * - Client validation schema management\n * - Submit handler with automatic data conversion and submission control with preventSubmit\n * - Form Debug Mode state\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 // 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 + get current validation errors\n const { 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 // 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 // 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 // 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 console.warn(\n '[FormProvider] form submit was prevented because preventSubmit is true...',\n );\n e?.preventDefault();\n return Promise.resolve();\n }\n\n // Convert nullish strings and filter out empty values before submission\n const wrappedOnSubmit = (data: FieldValues, event?: BaseSyntheticEvent) => {\n const submitData = toValidationFormat(data) ?? {};\n return onSubmit(submitData, event);\n };\n\n await methods.handleSubmit(wrappedOnSubmit)(e);\n };\n\n // Memoize the context value to prevent re-renders\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 setPreventSubmit(prevent);\n },\n setClientValidationSchema,\n setDebugMode,\n triggerSubmit: handleSubmit,\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 <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 );\n};\n\nexport default FormProvider;\n","import type {\n VetoFormattedError,\n VetoInstance,\n VetoTypeAny,\n} from '@fuf-stack/veto';\nimport type { FieldValues } from 'react-hook-form';\n\nimport { useMemo, useRef, useState } from 'react';\n\nimport { and, veto } from '@fuf-stack/veto';\n\nimport { toValidationFormat } from '../../helpers';\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(\n () => {\n const keys = Object.keys(clientValidationSchemas).sort();\n return keys\n .map((key) => {\n return clientValidationSchemas[key];\n })\n .filter(Boolean);\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 = clientSchemaValues.reduce(\n // @ts-expect-error is ok, because initially it is null\n (combined, clientSchema) => {\n return combined ? and(combined, clientSchema) : clientSchema;\n },\n null,\n );\n\n // return combined validation\n if (hasBaseValidation && clientSchemasCombined) {\n return veto(and(baseValidation.schema, clientSchemasCombined));\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 * Hook that creates a React Hook Form resolver from an extended validation instance.\n *\n * @param extendedValidation - Extended validation instance from useExtendedValidation\n * @returns Object containing resolver function, current validation errors, and optimization hash\n */\nexport const useFormResolver = (extendedValidation?: VetoInstance) => {\n // Use ref to store validation errors without triggering re-renders\n const validationErrors = useRef<VetoFormattedError>(undefined);\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 const result = await extendedValidation.validateAsync(validationValues);\n validationErrors.current = result.errors ?? undefined;\n\n // Transform veto result to React Hook Form format\n return {\n values: result.data ?? {},\n errors: result.errors ?? {},\n };\n };\n }, [extendedValidation]);\n\n // Hash for memo dependency optimization in consuming components\n const validationErrorsHash = JSON.stringify(validationErrors.current);\n\n return {\n resolver,\n validationErrors: validationErrors.current,\n validationErrorsHash,\n };\n};\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkIXJISVROcjs = require('./chunk-IXJISVRO.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
|
|
@@ -69,7 +69,7 @@ var RadioTabs = (_a) => {
|
|
|
69
69
|
label,
|
|
70
70
|
required,
|
|
71
71
|
testId
|
|
72
|
-
} =
|
|
72
|
+
} = _chunkIXJISVROcjs.useUniformField.call(void 0, _chunk555JRYCScjs.__spreadValues.call(void 0, {
|
|
73
73
|
name
|
|
74
74
|
}, uniformFieldProps));
|
|
75
75
|
const tabOptions = options.map((option) => {
|
|
@@ -144,4 +144,4 @@ var RadioTabs_default2 = RadioTabs_default;
|
|
|
144
144
|
|
|
145
145
|
|
|
146
146
|
exports.RadioTabs_default = RadioTabs_default; exports.RadioTabs_default2 = RadioTabs_default2;
|
|
147
|
-
//# sourceMappingURL=chunk-
|
|
147
|
+
//# sourceMappingURL=chunk-LB6GH6FJ.cjs.map
|