@fuf-stack/uniform 1.26.1 → 1.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Checkboxes/index.d.mts +8 -8
- package/dist/Checkboxes/index.d.mts.map +1 -1
- package/dist/Checkboxes/index.mjs +2 -1
- package/dist/Checkboxes/index.mjs.map +1 -1
- package/dist/DatePicker/index.d.mts +19 -19
- package/dist/DatePicker/index.d.mts.map +1 -1
- package/dist/DatePicker/index.mjs +2 -1
- package/dist/DatePicker/index.mjs.map +1 -1
- package/dist/FieldArray/index.d.mts +10 -10
- package/dist/FieldArray/index.d.mts.map +1 -1
- package/dist/FieldArray/index.mjs +3 -5
- package/dist/FieldArray/index.mjs.map +1 -1
- package/dist/FieldCard/index.d.mts +8 -8
- package/dist/FieldCard/index.d.mts.map +1 -1
- package/dist/FieldCard/index.mjs +5 -3
- package/dist/FieldCard/index.mjs.map +1 -1
- package/dist/FieldCopyTestIdButton-CRJBix9D.mjs.map +1 -1
- package/dist/Form/index.d.mts +13 -13
- package/dist/Form/index.d.mts.map +1 -1
- package/dist/Form/index.mjs +5 -3
- package/dist/Form/index.mjs.map +1 -1
- package/dist/Input/index.d.mts +11 -11
- package/dist/Input/index.mjs +2 -1
- package/dist/Input/index.mjs.map +1 -1
- package/dist/RadioBoxes/index.d.mts +19 -19
- package/dist/RadioBoxes/index.d.mts.map +1 -1
- package/dist/RadioBoxes/index.mjs +5 -3
- package/dist/RadioBoxes/index.mjs.map +1 -1
- package/dist/RadioTabs/index.d.mts +8 -8
- package/dist/RadioTabs/index.d.mts.map +1 -1
- package/dist/RadioTabs/index.mjs +3 -2
- package/dist/RadioTabs/index.mjs.map +1 -1
- package/dist/Radios/index.d.mts +13 -13
- package/dist/Radios/index.d.mts.map +1 -1
- package/dist/Radios/index.mjs +2 -1
- package/dist/Radios/index.mjs.map +1 -1
- package/dist/Select/index.d.mts +25 -25
- package/dist/Select/index.d.mts.map +1 -1
- package/dist/Select/index.mjs +5 -3
- package/dist/Select/index.mjs.map +1 -1
- package/dist/Slider/index.d.mts +47 -44
- package/dist/Slider/index.d.mts.map +1 -1
- package/dist/Slider/index.mjs +16 -6
- package/dist/Slider/index.mjs.map +1 -1
- package/dist/Switch/index.d.mts +19 -19
- package/dist/Switch/index.d.mts.map +1 -1
- package/dist/Switch/index.mjs +2 -1
- package/dist/Switch/index.mjs.map +1 -1
- package/dist/SwitchBox/index.d.mts +2 -2
- package/dist/SwitchBox/index.d.mts.map +1 -1
- package/dist/SwitchBox/index.mjs +3 -2
- package/dist/SwitchBox/index.mjs.map +1 -1
- package/dist/TextArea/index.d.mts +11 -11
- package/dist/TextArea/index.mjs +2 -1
- package/dist/TextArea/index.mjs.map +1 -1
- package/dist/Time/index.d.mts +19 -19
- package/dist/Time/index.d.mts.map +1 -1
- package/dist/Time/index.mjs +8 -3
- package/dist/Time/index.mjs.map +1 -1
- package/dist/helpers/index.d.mts +10 -11
- package/dist/helpers/index.d.mts.map +1 -1
- package/dist/hooks/useClientValidation/index.d.mts +2 -3
- package/dist/hooks/useClientValidation/index.d.mts.map +1 -1
- package/dist/hooks/useClientValidation/index.mjs +3 -2
- package/dist/hooks/useClientValidation/index.mjs.map +1 -1
- package/dist/hooks/useFormContext/index.mjs +1 -1
- package/dist/hooks/useInputValueDebounce/index.d.mts +3 -4
- package/dist/hooks/useInputValueDebounce/index.d.mts.map +1 -1
- package/dist/hooks/useInputValueDebounce/index.mjs +6 -4
- package/dist/hooks/useInputValueDebounce/index.mjs.map +1 -1
- package/dist/hooks/useUniformField/index.d.mts +3 -4
- package/dist/hooks/useUniformField/index.d.mts.map +1 -1
- package/dist/hooks/useUniformField/index.mjs +3 -2
- package/dist/hooks/useUniformField/index.mjs.map +1 -1
- package/dist/hooks/useUniformFieldArray/index.d.mts +2 -3
- package/dist/hooks/useUniformFieldArray/index.d.mts.map +1 -1
- package/dist/hooks/useUniformFieldArray/index.mjs +1 -1
- package/dist/hooks/useWatchFormReset/index.d.mts +2 -3
- package/dist/hooks/useWatchFormReset/index.d.mts.map +1 -1
- package/dist/hooks/useWatchFormReset/index.mjs +1 -1
- package/dist/hooks/useWatchUserChange/index.d.mts +2 -3
- package/dist/hooks/useWatchUserChange/index.d.mts.map +1 -1
- package/dist/hooks/useWatchUserChange/index.mjs +25 -13
- package/dist/hooks/useWatchUserChange/index.mjs.map +1 -1
- package/dist/{useFormContext-Bw4LokAf.mjs → useFormContext-fYWtlnpE.mjs} +5 -3
- package/dist/{useFormContext-Bw4LokAf.mjs.map → useFormContext-fYWtlnpE.mjs.map} +1 -1
- package/package.json +7 -7
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
//#region src/hooks/useInputValueDebounce/useInputValueDebounce.d.ts
|
|
2
|
-
interface UseInputValueDebounceOptions<TValue = unknown> {
|
|
2
|
+
export interface UseInputValueDebounceOptions<TValue = unknown> {
|
|
3
3
|
/** Debounce delay in milliseconds (default: 300) */
|
|
4
4
|
debounceDelay?: number;
|
|
5
5
|
/** Field name for triggering validation after debounced value commits */
|
|
@@ -11,7 +11,7 @@ interface UseInputValueDebounceOptions<TValue = unknown> {
|
|
|
11
11
|
/** The field value */
|
|
12
12
|
value: TValue;
|
|
13
13
|
}
|
|
14
|
-
interface UseInputValueDebounceReturn<TValue = unknown> {
|
|
14
|
+
export interface UseInputValueDebounceReturn<TValue = unknown> {
|
|
15
15
|
/** Enhanced onChange function with debouncing */
|
|
16
16
|
onChange: (...event: any[]) => void;
|
|
17
17
|
/** Enhanced onBlur function that flushes current value immediately */
|
|
@@ -54,7 +54,6 @@ interface UseInputValueDebounceReturn<TValue = unknown> {
|
|
|
54
54
|
* });
|
|
55
55
|
* ```
|
|
56
56
|
*/
|
|
57
|
-
declare const useInputValueDebounce: <TValue = unknown>({ debounceDelay, name, onBlur, onChange, value }: UseInputValueDebounceOptions<TValue>) => UseInputValueDebounceReturn<TValue>;
|
|
57
|
+
export declare const useInputValueDebounce: <TValue = unknown>({ debounceDelay, name, onBlur, onChange, value }: UseInputValueDebounceOptions<TValue>) => UseInputValueDebounceReturn<TValue>;
|
|
58
58
|
//#endregion
|
|
59
|
-
export { UseInputValueDebounceOptions, UseInputValueDebounceReturn, useInputValueDebounce };
|
|
60
59
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/hooks/useInputValueDebounce/useInputValueDebounce.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/hooks/useInputValueDebounce/useInputValueDebounce.ts"],"mappings":";iBAIiB,6BAA6B;;EAE5C;;EAEA;;EAEA;;EAGA,cAAc;;EAEd,OAAO;;iBAGQ,4BAA4B;;EAG3C,cAAc;;EAEd;;EAEA,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAsCI,wBAAyB,oBAAkB,eAAA,MAAA,QAAA,UAAA,SAMrD,6BAA6B,YAAU,4BAA4B"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as useFormContext } from "../../useFormContext-
|
|
2
|
-
import { useCallback,
|
|
1
|
+
import { n as useFormContext } from "../../useFormContext-fYWtlnpE.mjs";
|
|
2
|
+
import { useCallback, useRef, useState } from "react";
|
|
3
3
|
//#region src/hooks/useInputValueDebounce/useInputValueDebounce.ts
|
|
4
4
|
/**
|
|
5
5
|
* Custom hook for debouncing value changes with immediate blur support.
|
|
@@ -39,10 +39,12 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
|
|
39
39
|
const useInputValueDebounce = ({ debounceDelay = 300, name, onBlur, onChange, value }) => {
|
|
40
40
|
const { trigger } = useFormContext();
|
|
41
41
|
const [currentValue, setCurrentValue] = useState(value);
|
|
42
|
+
const [lastExternalValue, setLastExternalValue] = useState(value);
|
|
42
43
|
const timeoutRef = useRef(null);
|
|
43
|
-
|
|
44
|
+
if (!Object.is(lastExternalValue, value)) {
|
|
45
|
+
setLastExternalValue(value);
|
|
44
46
|
setCurrentValue(value);
|
|
45
|
-
}
|
|
47
|
+
}
|
|
46
48
|
return {
|
|
47
49
|
onChange: useCallback((...event) => {
|
|
48
50
|
const newValue = event[0]?.target?.value ?? event[0];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/hooks/useInputValueDebounce/useInputValueDebounce.ts","../../../src/hooks/useInputValueDebounce/index.ts"],"sourcesContent":["import { useCallback,
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/hooks/useInputValueDebounce/useInputValueDebounce.ts","../../../src/hooks/useInputValueDebounce/index.ts"],"sourcesContent":["import { useCallback, useRef, useState } from 'react';\n\nimport { useFormContext } from '../useFormContext';\n\nexport interface UseInputValueDebounceOptions<TValue = unknown> {\n /** Debounce delay in milliseconds (default: 300) */\n debounceDelay?: number;\n /** Field name for triggering validation after debounced value commits */\n name: string;\n /** The onBlur function to call after flushing debounced value */\n onBlur: () => void;\n /** The onChange function to call with debounced value */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onChange: (...event: any[]) => void;\n /** The field value */\n value: TValue;\n}\n\nexport interface UseInputValueDebounceReturn<TValue = unknown> {\n /** Enhanced onChange function with debouncing */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onChange: (...event: any[]) => void;\n /** Enhanced onBlur function that flushes current value immediately */\n onBlur: () => void;\n /** The field value that is displayed - updates immediately */\n value: TValue;\n}\n\n/**\n * Custom hook for debouncing value changes with immediate blur support.\n *\n * Provides immediate visual feedback by updating the value instantly,\n * while debouncing the actual onChange calls. When focus is lost,\n * any pending debounced changes are immediately flushed.\n *\n * **Key Features:**\n * - **Debouncing**: Delays onChange calls until user stops typing\n * - **Generic type support**: Works with any data type (strings, numbers, arrays, objects)\n * - **Immediate value updates**: UI stays responsive during debouncing\n * - **Blur flushing**: Immediately applies pending changes on blur\n *\n * **Note:** Value transformations should be handled at the `useUniformField` level,\n * not in this hook. This hook only handles debouncing timing.\n *\n * @param options Configuration for debounced value handling\n * @param options.debounceDelay Delay in milliseconds (default: 300)\n * @param options.onBlur Function to call after flushing debounced value\n * @param options.onChange Function to call with debounced value\n * @param options.value The field value\n * @returns Object containing enhanced onChange, onBlur, and immediate value\n *\n * @example\n * Basic usage with debouncing:\n * ```tsx\n * const { onChange, onBlur, value } = useInputValueDebounce({\n * debounceDelay: 300,\n * name: 'fieldName',\n * onBlur: field.onBlur,\n * onChange: field.onChange,\n * value: field.value,\n * });\n * ```\n */\nexport const useInputValueDebounce = <TValue = unknown>({\n debounceDelay = 300,\n name,\n onBlur,\n onChange,\n value,\n}: UseInputValueDebounceOptions<TValue>): UseInputValueDebounceReturn<TValue> => {\n const { trigger } = useFormContext();\n\n // Track value for synchronous updates\n const [currentValue, setCurrentValue] = useState<TValue>(value);\n const [lastExternalValue, setLastExternalValue] = useState<TValue>(value);\n\n const timeoutRef = useRef<NodeJS.Timeout | null>(null);\n\n // Keep the displayed value in sync during the same render when the form\n // replaces it (for example after reset), without an extra effect render.\n if (!Object.is(lastExternalValue, value)) {\n setLastExternalValue(value);\n setCurrentValue(value);\n }\n\n // Enhanced onChange handler with debouncing\n const handleChange = useCallback(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (...event: any[]) => {\n // Extract the raw value\n const newValue = (event[0]?.target?.value ?? event[0]) as TValue;\n setCurrentValue(newValue);\n\n // Clear existing timeout\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n\n const executeOnChange = () => {\n // Preserve event structure if original was an event\n if (event[0]?.target) {\n const convertedEvent = {\n ...event[0],\n target: {\n ...event[0].target,\n value: newValue,\n },\n };\n onChange(convertedEvent, ...event.slice(1));\n } else {\n onChange(newValue);\n }\n // Trigger validation after debounced value commits\n // This ensures errors are updated immediately when field becomes valid\n trigger(name);\n };\n\n // Execute immediately or after delay\n if (debounceDelay <= 0) {\n executeOnChange();\n } else {\n timeoutRef.current = setTimeout(executeOnChange, debounceDelay);\n }\n },\n [onChange, debounceDelay, trigger, name],\n );\n\n // Enhanced blur handler\n const handleBlur = useCallback(() => {\n // Flush pending changes\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n onChange(currentValue);\n }\n onBlur();\n }, [onChange, onBlur, currentValue]);\n\n return {\n onChange: handleChange,\n onBlur: handleBlur,\n value: currentValue,\n };\n};\n","/* v8 ignore start */\n\nexport * from './useInputValueDebounce';\n\n/* v8 ignore stop */\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,MAAa,yBAA2C,EACtD,gBAAgB,KAChB,MACA,QACA,UACA,YAC+E;CAC/E,MAAM,EAAE,YAAY,eAAe;CAGnC,MAAM,CAAC,cAAc,mBAAmB,SAAiB,KAAK;CAC9D,MAAM,CAAC,mBAAmB,wBAAwB,SAAiB,KAAK;CAExE,MAAM,aAAa,OAA8B,IAAI;CAIrD,IAAI,CAAC,OAAO,GAAG,mBAAmB,KAAK,GAAG;EACxC,qBAAqB,KAAK;EAC1B,gBAAgB,KAAK;CACvB;CAuDA,OAAO;EACL,UArDmB,aAElB,GAAG,UAAiB;GAEnB,MAAM,WAAY,MAAM,EAAE,EAAE,QAAQ,SAAS,MAAM;GACnD,gBAAgB,QAAQ;GAGxB,IAAI,WAAW,SACb,aAAa,WAAW,OAAO;GAGjC,MAAM,wBAAwB;IAE5B,IAAI,MAAM,EAAE,EAAE,QAQZ,SAAS;KANP,GAAG,MAAM;KACT,QAAQ;MACN,GAAG,MAAM,EAAE,CAAC;MACZ,OAAO;KACT;IAEoB,GAAG,GAAG,MAAM,MAAM,CAAC,CAAC;SAE1C,SAAS,QAAQ;IAInB,QAAQ,IAAI;GACd;GAGA,IAAI,iBAAiB,GACnB,gBAAgB;QAEhB,WAAW,UAAU,WAAW,iBAAiB,aAAa;EAElE,GACA;GAAC;GAAU;GAAe;GAAS;EAAI,CAelB;EACrB,QAZiB,kBAAkB;GAEnC,IAAI,WAAW,SAAS;IACtB,aAAa,WAAW,OAAO;IAC/B,WAAW,UAAU;IACrB,SAAS,YAAY;GACvB;GACA,OAAO;EACT,GAAG;GAAC;GAAU;GAAQ;EAAY,CAIf;EACjB,OAAO;CACT;AACF"}
|
|
@@ -5,7 +5,7 @@ import { t as useInput } from "../../useInput-ClpHDPdr.mjs";
|
|
|
5
5
|
import { ReactNode } from "react";
|
|
6
6
|
import { FieldError, FieldValues, Path } from "react-hook-form";
|
|
7
7
|
//#region src/hooks/useUniformField/useUniformField.d.ts
|
|
8
|
-
interface UseUniformFieldParams<TFieldValues extends FieldValues = FieldValues, TDisplay = unknown> {
|
|
8
|
+
export interface UseUniformFieldParams<TFieldValues extends FieldValues = FieldValues, TDisplay = unknown> {
|
|
9
9
|
/** Form field name */
|
|
10
10
|
name: Path<TFieldValues> & string;
|
|
11
11
|
/** Custom aria-label for accessibility. If not provided, falls back to field name when no visible label exists */
|
|
@@ -23,7 +23,7 @@ interface UseUniformFieldParams<TFieldValues extends FieldValues = FieldValues,
|
|
|
23
23
|
/** Input type for special number handling */
|
|
24
24
|
type?: 'text' | 'number' | 'password';
|
|
25
25
|
}
|
|
26
|
-
interface UseUniformFieldReturn<TFieldValues extends FieldValues = FieldValues> {
|
|
26
|
+
export interface UseUniformFieldReturn<TFieldValues extends FieldValues = FieldValues> {
|
|
27
27
|
/** Computed aria-label fallback (field name) when no visible label exists. Components can override based on their accessibility needs (e.g., if placeholder provides sufficient context) */
|
|
28
28
|
ariaLabel: string | undefined;
|
|
29
29
|
/** react-hook-form control instance for advanced integrations */
|
|
@@ -93,7 +93,6 @@ interface UseUniformFieldReturn<TFieldValues extends FieldValues = FieldValues>
|
|
|
93
93
|
* - Presentation helpers: `getLabelProps`, `getErrorMessageProps`,
|
|
94
94
|
* `getHelperWrapperProps` for consistent wiring to underlying UI components
|
|
95
95
|
*/
|
|
96
|
-
declare const useUniformField: <TFieldValues extends FieldValues = FieldValues, TDisplay = unknown>(params: UseUniformFieldParams<TFieldValues, TDisplay>) => UseUniformFieldReturn<TFieldValues>;
|
|
96
|
+
export declare const useUniformField: <TFieldValues extends FieldValues = FieldValues, TDisplay = unknown>(params: UseUniformFieldParams<TFieldValues, TDisplay>) => UseUniformFieldReturn<TFieldValues>;
|
|
97
97
|
//#endregion
|
|
98
|
-
export { UseUniformFieldParams, UseUniformFieldReturn, useUniformField };
|
|
99
98
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/hooks/useUniformField/useUniformField.tsx"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/hooks/useUniformField/useUniformField.tsx"],"mappings":";;;;;;;iBAgBiB,sBACf,qBAAqB,cAAc,aACnC;;EAGA,MAAM,KAAK;;EAEX;;EAEA;;EAEA;;EAEA,QAAQ;;EAER;;EAEA,YAAY,oBAAoB;;EAEhC;;iBAGe,sBACf,qBAAqB,cAAc;;EAGnC;;EAEA,SAAS,kBAAkB,iBAAe;;EAE1C,WAAW,kBAAkB,iBAAe;;EAE5C;;EAEA;;EAEA,OAAO;;EAEP,cAAc;;EAEd,OAAO,kBAAkB,gBAAc;;EAEvC,sBAAsB,kBAAkB;;EAExC,uBAAuB,kBAAkB;;EAEzC,eAAe,kBAAkB;;EAEjC,WAAW,kBAAkB,iBAAe;;EAE5C;;EAEA,OAAO;;EAEP,QAAQ,kBAAkB,gBAAc;;EAExC,UAAU,kBAAkB,gBAAc;;EAE1C,KAAK,kBAAkB,gBAAc;;EAErC;;EAEA,YAAY,kBAAkB,iBAAe;;EAE7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA+BW,kBACX,qBAAqB,cAAc,aACnC,oBAEA,QAAQ,sBAAsB,cAAc,cAC3C,sBAAsB"}
|
|
@@ -2,7 +2,7 @@ import { flattenFieldErrors, isValueEmpty } from "../../helpers/index.mjs";
|
|
|
2
2
|
import { t as FieldCopyTestIdButton_default } from "../../FieldCopyTestIdButton-CRJBix9D.mjs";
|
|
3
3
|
import { t as FieldValidationError_default } from "../../FieldValidationError-ByRoIxaM.mjs";
|
|
4
4
|
import { t as useController } from "../../useController-CK39i6HI.mjs";
|
|
5
|
-
import { n as useFormContext } from "../../useFormContext-
|
|
5
|
+
import { n as useFormContext } from "../../useFormContext-fYWtlnpE.mjs";
|
|
6
6
|
import { t as useInput } from "../../useInput-C0aJaAGe.mjs";
|
|
7
7
|
import { t as useInputValueTransform } from "../../useInputValueTransform-DJ5zkqSy.mjs";
|
|
8
8
|
import "react";
|
|
@@ -87,8 +87,9 @@ const useUniformField = (params) => {
|
|
|
87
87
|
const showTestIdCopyButton = debugMode === "debug-testids";
|
|
88
88
|
const labelNode = !!label || showTestIdCopyButton ? /* @__PURE__ */ jsxs(Fragment, { children: [label !== false ? label : null, showTestIdCopyButton ? /* @__PURE__ */ jsx(FieldCopyTestIdButton_default, { testId }) : null] }) : null;
|
|
89
89
|
const error = isArrayValue ? flattenFieldErrors(rawError) : rawError;
|
|
90
|
+
const normalizedError = flattenFieldErrors(rawError);
|
|
90
91
|
const errorMessage = /* @__PURE__ */ jsx(FieldValidationError_default, {
|
|
91
|
-
error:
|
|
92
|
+
error: normalizedError,
|
|
92
93
|
testId
|
|
93
94
|
});
|
|
94
95
|
const { getErrorMessageProps, getLabelProps, getHelperWrapperProps } = useInput({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["FieldCopyTestIdButton","FieldValidationError"],"sources":["../../../src/hooks/useUniformField/useUniformField.tsx","../../../src/hooks/useUniformField/index.ts"],"sourcesContent":["import type { ReactNode } from 'react';\nimport type { FieldError, FieldValues, Path } from 'react-hook-form';\nimport type { InputValueTransform } from '../useInputValueTransform/useInputValueTransform';\n\nimport React from 'react';\n\nimport { useDebounce } from '@fuf-stack/pixels';\n\nimport { flattenFieldErrors, isValueEmpty } from '../../helpers';\nimport FieldCopyTestIdButton from '../../partials/FieldCopyTestIdButton';\nimport FieldValidationError from '../../partials/FieldValidationError';\nimport { useController } from '../useController/useController';\nimport { useFormContext } from '../useFormContext/useFormContext';\nimport { useInput } from '../useInput/useInput';\nimport { useInputValueTransform } from '../useInputValueTransform/useInputValueTransform';\n\nexport interface UseUniformFieldParams<\n TFieldValues extends FieldValues = FieldValues,\n TDisplay = unknown,\n> {\n /** Form field name */\n name: Path<TFieldValues> & string;\n /** Custom aria-label for accessibility. If not provided, falls back to field name when no visible label exists */\n ariaLabel?: string;\n /** Disable the field */\n disabled?: boolean;\n /** Normalize nested RHF errors into a flat array for array-like fields */\n isArrayValue?: boolean;\n /** Optional label content */\n label?: ReactNode;\n /** Optional explicit test id used to build stable test ids */\n testId?: string;\n /** Optional value transformation between form and display values */\n transform?: InputValueTransform<TDisplay>;\n /** Input type for special number handling */\n type?: 'text' | 'number' | 'password';\n}\n\nexport interface UseUniformFieldReturn<\n TFieldValues extends FieldValues = FieldValues,\n> {\n /** Computed aria-label fallback (field name) when no visible label exists. Components can override based on their accessibility needs (e.g., if placeholder provides sufficient context) */\n ariaLabel: string | undefined;\n /** react-hook-form control instance for advanced integrations */\n control: ReturnType<typeof useFormContext<TFieldValues>>['control'];\n /** Debug mode from Uniform provider */\n debugMode: ReturnType<typeof useFormContext<TFieldValues>>['debugMode'];\n /** Current value used to initialize uncontrolled components */\n defaultValue: unknown;\n /** Whether the field is currently disabled (from RHF) */\n disabled: boolean | undefined;\n /** Validation errors from form state; flattened only when `isArrayValue` is enabled */\n error: FieldError[] | undefined;\n /** Pre-built errorMessage node to plug into components */\n errorMessage: ReactNode | null;\n /** RHF controller field with transformed value/onChange (use this for simple components) */\n field: ReturnType<typeof useController<TFieldValues>>['field'];\n /** Helper to spread standardized error message props to underlying components */\n getErrorMessageProps: ReturnType<typeof useInput>['getErrorMessageProps'];\n /** Helper to spread standardized helper wrapper props (for spacing/animation) */\n getHelperWrapperProps: ReturnType<typeof useInput>['getHelperWrapperProps'];\n /** Helper to spread standardized label props to underlying components */\n getLabelProps: ReturnType<typeof useInput>['getLabelProps'];\n /** Access current form values (converted to validation-friendly format) */\n getValues: ReturnType<typeof useFormContext<TFieldValues>>['getValues'];\n /** Whether the field should show invalid state (debounced for smooth animations). True when field is invalid AND (dirty OR touched OR submitted) */\n invalid: boolean;\n /** Computed label node including optional test id copy button */\n label: ReactNode | null;\n /** onBlur handler from controller */\n onBlur: ReturnType<typeof useController<TFieldValues>>['field']['onBlur'];\n /** onChange handler from controller (with transform applied) */\n onChange: ReturnType<typeof useController<TFieldValues>>['field']['onChange'];\n /** Ref to forward to underlying control */\n ref: ReturnType<typeof useController<TFieldValues>>['field']['ref'];\n /** Whether the field is required according to validation schema */\n required: boolean;\n /** Reset a specific field in the form */\n resetField: ReturnType<typeof useFormContext<TFieldValues>>['resetField'];\n /** Generated HTML data-testid for the field */\n testId: string;\n}\n\n/**\n * Combines frequently used form field logic into a single hook.\n *\n * Provides:\n * - Enhanced form context (validation-aware state, `testId`, value transforms)\n * - Controller field with nullish conversion handling\n * - Value transformation via `transform` prop:\n * • Allows disentangled display and form values (e.g., string ↔ object, boolean ↔ array)\n * • Automatically applies `toDisplayValue` to field value for components\n * • Automatically applies `toFormValue` to display value when onChange is called\n * • Works with `type` prop for automatic number/string conversion\n * • Examples: storing objects while displaying strings, storing booleans as arrays, enriching values with metadata\n * - Debounced `invalid` state with smart timing:\n * • `true` (field becomes invalid): applies immediately so errors show right away\n * • `false` (field becomes valid): delayed 200ms to allow smooth exit animations\n * • Respects `prefers-reduced-motion` by skipping delays when user prefers reduced motion\n * - Smart `invalid` visibility (via `showInvalid`):\n * • Shows errors when field is dirty OR touched OR form has been submitted\n * • Prevents showing errors on pristine/untouched fields for better UX\n * • Works well for all field types (text inputs, checkboxes, radios, arrays)\n * - Prebuilt `errorMessage` React node (with optional array-error normalization via `isArrayValue`)\n * - Computed `label` node which appends a `FieldCopyTestIdButton` in\n * `debug-testids` mode\n * - `defaultValue` for uncontrolled defaults and all usual field handlers\n * - Access to form utilities: `control`, `getValues`, `resetField`\n * - Presentation helpers: `getLabelProps`, `getErrorMessageProps`,\n * `getHelperWrapperProps` for consistent wiring to underlying UI components\n */\nexport const useUniformField = <\n TFieldValues extends FieldValues = FieldValues,\n TDisplay = unknown,\n>(\n params: UseUniformFieldParams<TFieldValues, TDisplay>,\n): UseUniformFieldReturn<TFieldValues> => {\n const {\n name,\n ariaLabel: customAriaLabel,\n disabled = false,\n isArrayValue = false,\n 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: rawError,\n invalid: rawInvalid,\n isDirty,\n isTouched,\n required,\n testId,\n } = getFieldState(name, explicitTestId);\n\n const { field } = useController<TFieldValues>({\n control,\n disabled,\n name,\n });\n const {\n onChange: fieldOnChange,\n value: fieldValue,\n disabled: isDisabled,\n onBlur,\n ref,\n } = field;\n\n // Get transform utilities (but don't apply them automatically)\n // Components can choose how to use them (directly or via useInputValueDebounce)\n const { toDisplayValue, toFormValue } = useInputValueTransform<TDisplay>({\n type,\n transform,\n });\n\n // For components without special needs: apply transform to value and onChange\n const transformedValue = toDisplayValue(fieldValue);\n const transformedOnChange = (eventOrValue: TDisplay | React.ChangeEvent) => {\n // Extract value from event or use value directly\n const displayValue =\n (eventOrValue as React.ChangeEvent<HTMLInputElement>)?.target?.value ??\n eventOrValue;\n const formValue = toFormValue(displayValue as TDisplay);\n fieldOnChange(formValue);\n };\n\n const defaultValue = (getValues() as Record<string, unknown>)?.[\n name as string\n ];\n\n /**\n * Determine when to show the invalid state to the user.\n *\n * Show errors when the field is invalid AND any of these conditions are met:\n * - Field has a user-entered value (show validation errors like format/length while typing)\n * - Field is touched (focused and blurred) - good for text inputs\n * - Form has been submitted - shows all errors after submit attempt\n *\n * Note: `hasValue` is gated by `isDirty` so invalid initial values do not\n * show errors just because resolver-backed validation state is available.\n * Newly added empty array elements can be dirty, but stay hidden until blur\n * because they do not have a value yet.\n *\n * This prevents showing errors on pristine/untouched/empty fields for better UX.\n * Examples:\n * - Text input: User loads form with empty required field → no error shown yet\n * - Text input: User types invalid content → error shows immediately (has value)\n * - Text input: User focuses and blurs without typing → error shows (via isTouched)\n * - Checkbox/radio: User selects option → error shows immediately (has value)\n * - Field array: User adds element → no error yet; after blur → error shows\n * - Any field: User submits form → all errors show (via submitCount)\n *\n * The entire condition is debounced to prevent flickering and allow smooth animations.\n */\n\n // isValueEmpty handles marker strings, flat array wrappers, empty arrays, and empty objects\n const hasValue = !isValueEmpty(fieldValue);\n const showInvalid =\n rawInvalid && ((isDirty && hasValue) || isTouched || submitCount > 0);\n // Debounce to prevent flickering during rapid state changes\n const invalid = useDebounce(showInvalid, 200);\n\n // Build a label node that:\n // - shows the provided label (unless explicitly set to false)\n // - appends a copy-to-clipboard button for the test id in `debug-testids` mode\n // Consumers can pass this directly to component `label` props\n const showTestIdCopyButton = debugMode === 'debug-testids';\n const labelNode: ReactNode | null =\n !!label || showTestIdCopyButton ? (\n <>\n {label !== false ? label : null}\n {showTestIdCopyButton ? (\n <FieldCopyTestIdButton testId={testId} />\n ) : null}\n </>\n ) : null;\n\n // Array-like fields can receive nested RHF error objects (index keys, _errors).\n // Opt-in flattening keeps backward compatibility for components that rely on\n // object-shaped errors (e.g. FieldCard/FieldArray).\n const error = isArrayValue ? flattenFieldErrors(rawError) : rawError;\n const normalizedError = flattenFieldErrors(rawError);\n\n // Ready-to-render error message; consumers can drop this into their\n // component `errorMessage` prop without repeating mapping/markup\n const errorMessage = (\n <FieldValidationError error={normalizedError} testId={testId} />\n );\n\n // Generate standardized props for label, helper wrapper and error message\n // so consumers can spread them directly into UI components (e.g. HeroUI),\n // keeping animations/spacing consistent across fields\n const { getErrorMessageProps, getLabelProps, getHelperWrapperProps } =\n useInput({\n ref,\n classNames: {\n // set padding to 0 for error message exit animation\n helperWrapper: 'p-0',\n },\n errorMessage: JSON.stringify(error),\n isInvalid: invalid,\n isRequired: required,\n label,\n labelPlacement: 'outside',\n });\n\n // Compute aria-label: prefer custom prop, then use string label if available, otherwise field name\n // Components can further override this based on their specific accessibility needs\n // (e.g., Input/TextArea may skip this if they have a meaningful placeholder)\n const ariaLabel =\n customAriaLabel ?? (typeof label === 'string' ? label : name);\n\n return {\n ariaLabel,\n control,\n debugMode,\n defaultValue,\n disabled: isDisabled,\n error,\n errorMessage,\n field: {\n ...field,\n value: transformedValue as typeof field.value,\n onChange: transformedOnChange as typeof field.onChange,\n },\n getErrorMessageProps,\n getHelperWrapperProps,\n getLabelProps,\n getValues,\n invalid,\n label: labelNode,\n onBlur,\n onChange: transformedOnChange as typeof field.onChange,\n ref,\n required,\n resetField,\n testId,\n };\n};\n","/* v8 ignore start */\n\nexport * from './useUniformField';\n\n/* v8 ignore stop */\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+GA,MAAa,mBAIX,WACwC;CACxC,MAAM,EACJ,MACA,WAAW,iBACX,WAAW,OACX,eAAe,OACf,QAAQ,gBACR,OACA,MACA,cACE;CAEJ,MAAM,EACJ,SACA,WACA,WAAW,EAAE,eACb,eACA,WACA,eACE,eAA6B;CAEjC,MAAM,EACJ,OAAO,UACP,SAAS,YACT,SACA,WACA,UACA,WACE,cAAc,MAAM,cAAc;CAEtC,MAAM,EAAE,UAAU,cAA4B;EAC5C;EACA;EACA;CACF,CAAC;CACD,MAAM,EACJ,UAAU,eACV,OAAO,YACP,UAAU,YACV,QACA,QACE;CAIJ,MAAM,EAAE,gBAAgB,gBAAgB,uBAAiC;EACvE;EACA;CACF,CAAC;CAGD,MAAM,mBAAmB,eAAe,UAAU;CAClD,MAAM,uBAAuB,iBAA+C;EAE1E,MAAM,eACH,cAAsD,QAAQ,SAC/D;EACF,MAAM,YAAY,YAAY,YAAwB;EACtD,cAAc,SAAS;CACzB;CAEA,MAAM,eAAgB,UAAU,CAAC,GAC/B;;;;;;;;;;;;;;;;;;;;;;;;;CA6BF,MAAM,WAAW,CAAC,aAAa,UAAU;CAIzC,MAAM,UAAU,YAFd,eAAgB,WAAW,YAAa,aAAa,cAAc,IAE5B,GAAG;CAM5C,MAAM,uBAAuB,cAAc;CAC3C,MAAM,YACJ,CAAC,CAAC,SAAS,uBACT,qBAAA,UAAA,EAAA,UAAA,CACG,UAAU,QAAQ,QAAQ,MAC1B,uBACC,oBAACA,+BAAD,EAA+B,OAAS,CAAA,IACtC,IACJ,EAAA,CAAA,IACA;CAKN,MAAM,QAAQ,eAAe,mBAAmB,QAAQ,IAAI;CAK5D,MAAM,eACJ,oBAACC,8BAAD;EAAsB,OALA,mBAAmB,QAKE;EAAW;CAAS,CAAA;CAMjE,MAAM,EAAE,sBAAsB,eAAe,0BAC3C,SAAS;EACP;EACA,YAAY,EAEV,eAAe,MACjB;EACA,cAAc,KAAK,UAAU,KAAK;EAClC,WAAW;EACX,YAAY;EACZ;EACA,gBAAgB;CAClB,CAAC;CAQH,OAAO;EACL,WAHA,oBAAoB,OAAO,UAAU,WAAW,QAAQ;EAIxD;EACA;EACA;EACA,UAAU;EACV;EACA;EACA,OAAO;GACL,GAAG;GACH,OAAO;GACP,UAAU;EACZ;EACA;EACA;EACA;EACA;EACA;EACA,OAAO;EACP;EACA,UAAU;EACV;EACA;EACA;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["FieldCopyTestIdButton","FieldValidationError"],"sources":["../../../src/hooks/useUniformField/useUniformField.tsx","../../../src/hooks/useUniformField/index.ts"],"sourcesContent":["import type { ReactNode } from 'react';\nimport type { FieldError, FieldValues, Path } from 'react-hook-form';\nimport type { InputValueTransform } from '../useInputValueTransform/useInputValueTransform';\n\nimport React from 'react';\n\nimport { useDebounce } from '@fuf-stack/pixels';\n\nimport { flattenFieldErrors, isValueEmpty } from '../../helpers';\nimport FieldCopyTestIdButton from '../../partials/FieldCopyTestIdButton';\nimport FieldValidationError from '../../partials/FieldValidationError';\nimport { useController } from '../useController/useController';\nimport { useFormContext } from '../useFormContext/useFormContext';\nimport { useInput } from '../useInput/useInput';\nimport { useInputValueTransform } from '../useInputValueTransform/useInputValueTransform';\n\nexport interface UseUniformFieldParams<\n TFieldValues extends FieldValues = FieldValues,\n TDisplay = unknown,\n> {\n /** Form field name */\n name: Path<TFieldValues> & string;\n /** Custom aria-label for accessibility. If not provided, falls back to field name when no visible label exists */\n ariaLabel?: string;\n /** Disable the field */\n disabled?: boolean;\n /** Normalize nested RHF errors into a flat array for array-like fields */\n isArrayValue?: boolean;\n /** Optional label content */\n label?: ReactNode;\n /** Optional explicit test id used to build stable test ids */\n testId?: string;\n /** Optional value transformation between form and display values */\n transform?: InputValueTransform<TDisplay>;\n /** Input type for special number handling */\n type?: 'text' | 'number' | 'password';\n}\n\nexport interface UseUniformFieldReturn<\n TFieldValues extends FieldValues = FieldValues,\n> {\n /** Computed aria-label fallback (field name) when no visible label exists. Components can override based on their accessibility needs (e.g., if placeholder provides sufficient context) */\n ariaLabel: string | undefined;\n /** react-hook-form control instance for advanced integrations */\n control: ReturnType<typeof useFormContext<TFieldValues>>['control'];\n /** Debug mode from Uniform provider */\n debugMode: ReturnType<typeof useFormContext<TFieldValues>>['debugMode'];\n /** Current value used to initialize uncontrolled components */\n defaultValue: unknown;\n /** Whether the field is currently disabled (from RHF) */\n disabled: boolean | undefined;\n /** Validation errors from form state; flattened only when `isArrayValue` is enabled */\n error: FieldError[] | undefined;\n /** Pre-built errorMessage node to plug into components */\n errorMessage: ReactNode | null;\n /** RHF controller field with transformed value/onChange (use this for simple components) */\n field: ReturnType<typeof useController<TFieldValues>>['field'];\n /** Helper to spread standardized error message props to underlying components */\n getErrorMessageProps: ReturnType<typeof useInput>['getErrorMessageProps'];\n /** Helper to spread standardized helper wrapper props (for spacing/animation) */\n getHelperWrapperProps: ReturnType<typeof useInput>['getHelperWrapperProps'];\n /** Helper to spread standardized label props to underlying components */\n getLabelProps: ReturnType<typeof useInput>['getLabelProps'];\n /** Access current form values (converted to validation-friendly format) */\n getValues: ReturnType<typeof useFormContext<TFieldValues>>['getValues'];\n /** Whether the field should show invalid state (debounced for smooth animations). True when field is invalid AND (dirty OR touched OR submitted) */\n invalid: boolean;\n /** Computed label node including optional test id copy button */\n label: ReactNode | null;\n /** onBlur handler from controller */\n onBlur: ReturnType<typeof useController<TFieldValues>>['field']['onBlur'];\n /** onChange handler from controller (with transform applied) */\n onChange: ReturnType<typeof useController<TFieldValues>>['field']['onChange'];\n /** Ref to forward to underlying control */\n ref: ReturnType<typeof useController<TFieldValues>>['field']['ref'];\n /** Whether the field is required according to validation schema */\n required: boolean;\n /** Reset a specific field in the form */\n resetField: ReturnType<typeof useFormContext<TFieldValues>>['resetField'];\n /** Generated HTML data-testid for the field */\n testId: string;\n}\n\n/**\n * Combines frequently used form field logic into a single hook.\n *\n * Provides:\n * - Enhanced form context (validation-aware state, `testId`, value transforms)\n * - Controller field with nullish conversion handling\n * - Value transformation via `transform` prop:\n * • Allows disentangled display and form values (e.g., string ↔ object, boolean ↔ array)\n * • Automatically applies `toDisplayValue` to field value for components\n * • Automatically applies `toFormValue` to display value when onChange is called\n * • Works with `type` prop for automatic number/string conversion\n * • Examples: storing objects while displaying strings, storing booleans as arrays, enriching values with metadata\n * - Debounced `invalid` state with smart timing:\n * • `true` (field becomes invalid): applies immediately so errors show right away\n * • `false` (field becomes valid): delayed 200ms to allow smooth exit animations\n * • Respects `prefers-reduced-motion` by skipping delays when user prefers reduced motion\n * - Smart `invalid` visibility (via `showInvalid`):\n * • Shows errors when field is dirty OR touched OR form has been submitted\n * • Prevents showing errors on pristine/untouched fields for better UX\n * • Works well for all field types (text inputs, checkboxes, radios, arrays)\n * - Prebuilt `errorMessage` React node (with optional array-error normalization via `isArrayValue`)\n * - Computed `label` node which appends a `FieldCopyTestIdButton` in\n * `debug-testids` mode\n * - `defaultValue` for uncontrolled defaults and all usual field handlers\n * - Access to form utilities: `control`, `getValues`, `resetField`\n * - Presentation helpers: `getLabelProps`, `getErrorMessageProps`,\n * `getHelperWrapperProps` for consistent wiring to underlying UI components\n */\nexport const useUniformField = <\n TFieldValues extends FieldValues = FieldValues,\n TDisplay = unknown,\n>(\n params: UseUniformFieldParams<TFieldValues, TDisplay>,\n): UseUniformFieldReturn<TFieldValues> => {\n const {\n name,\n ariaLabel: customAriaLabel,\n disabled = false,\n isArrayValue = false,\n 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: rawError,\n invalid: rawInvalid,\n isDirty,\n isTouched,\n required,\n testId,\n } = getFieldState(name, explicitTestId);\n\n const { field } = useController<TFieldValues>({\n control,\n disabled,\n name,\n });\n const {\n onChange: fieldOnChange,\n value: fieldValue,\n disabled: isDisabled,\n onBlur,\n ref,\n } = field;\n\n // Get transform utilities (but don't apply them automatically)\n // Components can choose how to use them (directly or via useInputValueDebounce)\n const { toDisplayValue, toFormValue } = useInputValueTransform<TDisplay>({\n type,\n transform,\n });\n\n // For components without special needs: apply transform to value and onChange\n const transformedValue = toDisplayValue(fieldValue);\n const transformedOnChange = (eventOrValue: TDisplay | React.ChangeEvent) => {\n // Extract value from event or use value directly\n const displayValue =\n (eventOrValue as React.ChangeEvent<HTMLInputElement>)?.target?.value ??\n eventOrValue;\n const formValue = toFormValue(displayValue as TDisplay);\n fieldOnChange(formValue);\n };\n\n const defaultValue = (getValues() as Record<string, unknown>)?.[\n name as string\n ];\n\n /**\n * Determine when to show the invalid state to the user.\n *\n * Show errors when the field is invalid AND any of these conditions are met:\n * - Field has a user-entered value (show validation errors like format/length while typing)\n * - Field is touched (focused and blurred) - good for text inputs\n * - Form has been submitted - shows all errors after submit attempt\n *\n * Note: `hasValue` is gated by `isDirty` so invalid initial values do not\n * show errors just because resolver-backed validation state is available.\n * Newly added empty array elements can be dirty, but stay hidden until blur\n * because they do not have a value yet.\n *\n * This prevents showing errors on pristine/untouched/empty fields for better UX.\n * Examples:\n * - Text input: User loads form with empty required field → no error shown yet\n * - Text input: User types invalid content → error shows immediately (has value)\n * - Text input: User focuses and blurs without typing → error shows (via isTouched)\n * - Checkbox/radio: User selects option → error shows immediately (has value)\n * - Field array: User adds element → no error yet; after blur → error shows\n * - Any field: User submits form → all errors show (via submitCount)\n *\n * The entire condition is debounced to prevent flickering and allow smooth animations.\n */\n\n // isValueEmpty handles marker strings, flat array wrappers, empty arrays, and empty objects\n const hasValue = !isValueEmpty(fieldValue);\n const showInvalid =\n rawInvalid && ((isDirty && hasValue) || isTouched || submitCount > 0);\n // Debounce to prevent flickering during rapid state changes\n const invalid = useDebounce(showInvalid, 200);\n\n // Build a label node that:\n // - shows the provided label (unless explicitly set to false)\n // - appends a copy-to-clipboard button for the test id in `debug-testids` mode\n // Consumers can pass this directly to component `label` props\n const showTestIdCopyButton = debugMode === 'debug-testids';\n const labelNode: ReactNode | null =\n !!label || showTestIdCopyButton ? (\n <>\n {label !== false ? label : null}\n {showTestIdCopyButton ? (\n <FieldCopyTestIdButton testId={testId} />\n ) : null}\n </>\n ) : null;\n\n // Array-like fields can receive nested RHF error objects (index keys, _errors).\n // Opt-in flattening keeps backward compatibility for components that rely on\n // object-shaped errors (e.g. FieldCard/FieldArray).\n const error = isArrayValue ? flattenFieldErrors(rawError) : rawError;\n const normalizedError = flattenFieldErrors(rawError);\n\n // Ready-to-render error message; consumers can drop this into their\n // component `errorMessage` prop without repeating mapping/markup\n const errorMessage = (\n <FieldValidationError error={normalizedError} testId={testId} />\n );\n\n // Generate standardized props for label, helper wrapper and error message\n // so consumers can spread them directly into UI components (e.g. HeroUI),\n // keeping animations/spacing consistent across fields\n const { getErrorMessageProps, getLabelProps, getHelperWrapperProps } =\n useInput({\n ref,\n classNames: {\n // set padding to 0 for error message exit animation\n helperWrapper: 'p-0',\n },\n errorMessage: JSON.stringify(error),\n isInvalid: invalid,\n isRequired: required,\n label,\n labelPlacement: 'outside',\n });\n\n // Compute aria-label: prefer custom prop, then use string label if available, otherwise field name\n // Components can further override this based on their specific accessibility needs\n // (e.g., Input/TextArea may skip this if they have a meaningful placeholder)\n const ariaLabel =\n customAriaLabel ?? (typeof label === 'string' ? label : name);\n\n return {\n ariaLabel,\n control,\n debugMode,\n defaultValue,\n disabled: isDisabled,\n error,\n errorMessage,\n field: {\n ...field,\n value: transformedValue as typeof field.value,\n onChange: transformedOnChange as typeof field.onChange,\n },\n getErrorMessageProps,\n getHelperWrapperProps,\n getLabelProps,\n getValues,\n invalid,\n label: labelNode,\n onBlur,\n onChange: transformedOnChange as typeof field.onChange,\n ref,\n required,\n resetField,\n testId,\n };\n};\n","/* v8 ignore start */\n\nexport * from './useUniformField';\n\n/* v8 ignore stop */\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+GA,MAAa,mBAIX,WACwC;CACxC,MAAM,EACJ,MACA,WAAW,iBACX,WAAW,OACX,eAAe,OACf,QAAQ,gBACR,OACA,MACA,cACE;CAEJ,MAAM,EACJ,SACA,WACA,WAAW,EAAE,eACb,eACA,WACA,eACE,eAA6B;CAEjC,MAAM,EACJ,OAAO,UACP,SAAS,YACT,SACA,WACA,UACA,WACE,cAAc,MAAM,cAAc;CAEtC,MAAM,EAAE,UAAU,cAA4B;EAC5C;EACA;EACA;CACF,CAAC;CACD,MAAM,EACJ,UAAU,eACV,OAAO,YACP,UAAU,YACV,QACA,QACE;CAIJ,MAAM,EAAE,gBAAgB,gBAAgB,uBAAiC;EACvE;EACA;CACF,CAAC;CAGD,MAAM,mBAAmB,eAAe,UAAU;CAClD,MAAM,uBAAuB,iBAA+C;EAE1E,MAAM,eACH,cAAsD,QAAQ,SAC/D;EACF,MAAM,YAAY,YAAY,YAAwB;EACtD,cAAc,SAAS;CACzB;CAEA,MAAM,eAAgB,UAAU,CAAC,GAC/B;;;;;;;;;;;;;;;;;;;;;;;;;CA6BF,MAAM,WAAW,CAAC,aAAa,UAAU;CAIzC,MAAM,UAAU,YAFd,eAAgB,WAAW,YAAa,aAAa,cAAc,IAE5B,GAAG;CAM5C,MAAM,uBAAuB,cAAc;CAC3C,MAAM,YACJ,CAAC,CAAC,SAAS,uBACT,qBAAA,UAAA,EAAA,UAAA,CACG,UAAU,QAAQ,QAAQ,MAC1B,uBACC,oBAACA,+BAAD,EAA+B,OAAS,CAAA,IACtC,IACJ,EAAA,CAAA,IACA;CAKN,MAAM,QAAQ,eAAe,mBAAmB,QAAQ,IAAI;CAC5D,MAAM,kBAAkB,mBAAmB,QAAQ;CAInD,MAAM,eACJ,oBAACC,8BAAD;EAAsB,OAAO;EAAyB;CAAS,CAAA;CAMjE,MAAM,EAAE,sBAAsB,eAAe,0BAC3C,SAAS;EACP;EACA,YAAY,EAEV,eAAe,MACjB;EACA,cAAc,KAAK,UAAU,KAAK;EAClC,WAAW;EACX,YAAY;EACZ;EACA,gBAAgB;CAClB,CAAC;CAQH,OAAO;EACL,WAHA,oBAAoB,OAAO,UAAU,WAAW,QAAQ;EAIxD;EACA;EACA;EACA,UAAU;EACV;EACA;EACA,OAAO;GACL,GAAG;GACH,OAAO;GACP,UAAU;EACZ;EACA;EACA;EACA;EACA;EACA;EACA,OAAO;EACP;EACA,UAAU;EACV;EACA;EACA;EACA;CACF;AACF"}
|
|
@@ -5,7 +5,7 @@ import "../../index-D5HVU2jP.mjs";
|
|
|
5
5
|
import { ReactNode } from "react";
|
|
6
6
|
import { ArrayPath, FieldValues } from "react-hook-form";
|
|
7
7
|
//#region src/hooks/useUniformFieldArray/useUniformFieldArray.d.ts
|
|
8
|
-
interface UseUniformFieldArrayProps<TFieldValues extends FieldValues = FieldValues> {
|
|
8
|
+
export interface UseUniformFieldArrayProps<TFieldValues extends FieldValues = FieldValues> {
|
|
9
9
|
/** Field name for the array */
|
|
10
10
|
name: ArrayPath<TFieldValues>;
|
|
11
11
|
/** Whether this is a flat array (array of primitives) */
|
|
@@ -35,7 +35,7 @@ interface UseUniformFieldArrayProps<TFieldValues extends FieldValues = FieldValu
|
|
|
35
35
|
*
|
|
36
36
|
* @see https://react-hook-form.com/docs/usefieldarray
|
|
37
37
|
*/
|
|
38
|
-
declare const useUniformFieldArray: <TFieldValues extends FieldValues = FieldValues>({ name, flat, elementInitialValue: _elementInitialValue, lastElementNotRemovable, disabled, testId: explicitTestId, label }: UseUniformFieldArrayProps<TFieldValues>) => {
|
|
38
|
+
export declare const useUniformFieldArray: <TFieldValues extends FieldValues = FieldValues>({ name, flat, elementInitialValue: _elementInitialValue, lastElementNotRemovable, disabled, testId: explicitTestId, label }: UseUniformFieldArrayProps<TFieldValues>) => {
|
|
39
39
|
ariaLabel: string | undefined;
|
|
40
40
|
control: import("react-hook-form").Control<TFieldValues, any, TFieldValues>;
|
|
41
41
|
debugMode: ReturnType<typeof useFormContext$1<TFieldValues_1>>["debugMode"];
|
|
@@ -70,5 +70,4 @@ declare const useUniformFieldArray: <TFieldValues extends FieldValues = FieldVal
|
|
|
70
70
|
elementInitialValue: {};
|
|
71
71
|
};
|
|
72
72
|
//#endregion
|
|
73
|
-
export { UseUniformFieldArrayProps, useUniformFieldArray };
|
|
74
73
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/hooks/useUniformFieldArray/useUniformFieldArray.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/hooks/useUniformFieldArray/useUniformFieldArray.ts"],"mappings":";;;;;;;iBAaiB,0BACf,qBAAqB,cAAc;;EAGnC,MAAM,UAAU;;EAEhB;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,QAAQ;;;;;;;;;;;;;;;;qBAiBG,uBACX,qBAAqB,cAAc,eACnC,MAAA,MAAA,qBAAA,sBAAA,yBAAA,UAAA,QAAA,gBAAA,SAQC,0BAA0B;;;;;;;;;IAnCX,cAAG;;;;;;;;;EAsEmC,QAAA;EAIxC,UAAA,kBAJwC;EAKL,KAAA,kBADnC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { flatArrayKey, isValueEmpty } from "../../helpers/index.mjs";
|
|
2
|
-
import { n as useFormContext$1 } from "../../useFormContext-
|
|
2
|
+
import { n as useFormContext$1 } from "../../useFormContext-fYWtlnpE.mjs";
|
|
3
3
|
import { useUniformField } from "../useUniformField/index.mjs";
|
|
4
4
|
import { useWatchFormReset } from "../useWatchFormReset/index.mjs";
|
|
5
5
|
import { useEffect, useMemo, useRef, useState } from "react";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
//#region src/hooks/useWatchFormReset/useWatchFormReset.d.ts
|
|
2
|
-
interface UseWatchFormResetOptions {
|
|
2
|
+
export interface UseWatchFormResetOptions {
|
|
3
3
|
/**
|
|
4
4
|
* Callback that runs whenever a programmatic form reset is observed.
|
|
5
5
|
*
|
|
@@ -30,7 +30,6 @@ interface UseWatchFormResetOptions {
|
|
|
30
30
|
* placeholder rows. It normalizes only on reset and does not collapse rows
|
|
31
31
|
* during normal editing.
|
|
32
32
|
*/
|
|
33
|
-
declare const useWatchFormReset: ({ onReset }: UseWatchFormResetOptions) => void;
|
|
33
|
+
export declare const useWatchFormReset: ({ onReset }: UseWatchFormResetOptions) => void;
|
|
34
34
|
//#endregion
|
|
35
|
-
export { UseWatchFormResetOptions, useWatchFormReset };
|
|
36
35
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/hooks/useWatchFormReset/useWatchFormReset.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/hooks/useWatchFormReset/useWatchFormReset.ts"],"mappings":";iBAIiB;;;;;;;;;;;EAWf;;;;;;;;;;;;;;;;;;;;qBAqBW,sBAAqB,WAAa"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { FieldValues, Path, UseFormReset, UseFormResetField, UseFormSetValue } from "react-hook-form";
|
|
2
2
|
//#region src/hooks/useWatchUserChange/useWatchUserChange.d.ts
|
|
3
|
-
interface UseWatchUserChangeOptions<TFieldValues extends FieldValues> {
|
|
3
|
+
export interface UseWatchUserChangeOptions<TFieldValues extends FieldValues> {
|
|
4
4
|
/** Field name to watch for user changes */
|
|
5
5
|
watch: Path<TFieldValues>;
|
|
6
6
|
/**
|
|
@@ -70,7 +70,6 @@ interface UseWatchUserChangeOptions<TFieldValues extends FieldValues> {
|
|
|
70
70
|
* });
|
|
71
71
|
* ```
|
|
72
72
|
*/
|
|
73
|
-
declare const useWatchUserChange: <TFieldValues extends FieldValues = FieldValues>({ watch: watchField, onChange }: UseWatchUserChangeOptions<TFieldValues>) => void;
|
|
73
|
+
export declare const useWatchUserChange: <TFieldValues extends FieldValues = FieldValues>({ watch: watchField, onChange }: UseWatchUserChangeOptions<TFieldValues>) => void;
|
|
74
74
|
//#endregion
|
|
75
|
-
export { UseWatchUserChangeOptions, useWatchUserChange };
|
|
76
75
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/hooks/useWatchUserChange/useWatchUserChange.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/hooks/useWatchUserChange/useWatchUserChange.ts"],"mappings":";;iBAYiB,0BAA0B,qBAAqB;;EAE9D,OAAO,KAAK;;;;;EAKZ,WACE,gBACA;IACE,UAAU,gBAAgB;IAC1B,YAAY,kBAAkB;IAC9B,OAAO,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA8Db,qBACX,qBAAqB,cAAc,eACnC,OAAA,YAAA,YAGC,0BAA0B"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as useFormContext } from "../../useFormContext-
|
|
2
|
-
import { useEffect } from "react";
|
|
1
|
+
import { n as useFormContext } from "../../useFormContext-fYWtlnpE.mjs";
|
|
2
|
+
import { useEffect, useRef } from "react";
|
|
3
3
|
//#region src/hooks/useWatchUserChange/useWatchUserChange.ts
|
|
4
4
|
/**
|
|
5
5
|
* Hook that watches for user changes on a specific form field.
|
|
@@ -60,23 +60,35 @@ import { useEffect } from "react";
|
|
|
60
60
|
*/
|
|
61
61
|
const useWatchUserChange = ({ watch: watchField, onChange }) => {
|
|
62
62
|
const { setValue, resetField, reset, userChange } = useFormContext();
|
|
63
|
+
const callbackRef = useRef({
|
|
64
|
+
onChange,
|
|
65
|
+
reset,
|
|
66
|
+
resetField,
|
|
67
|
+
setValue
|
|
68
|
+
});
|
|
63
69
|
useEffect(() => {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
});
|
|
70
|
+
callbackRef.current = {
|
|
71
|
+
onChange,
|
|
72
|
+
reset,
|
|
73
|
+
resetField,
|
|
74
|
+
setValue
|
|
70
75
|
};
|
|
71
|
-
return userChange.subscribe(listener);
|
|
72
76
|
}, [
|
|
73
|
-
watchField,
|
|
74
77
|
onChange,
|
|
75
|
-
setValue,
|
|
76
|
-
resetField,
|
|
77
78
|
reset,
|
|
78
|
-
|
|
79
|
+
resetField,
|
|
80
|
+
setValue
|
|
79
81
|
]);
|
|
82
|
+
const { subscribe } = userChange;
|
|
83
|
+
useEffect(() => {
|
|
84
|
+
const listener = (fieldName, value) => {
|
|
85
|
+
if (fieldName === watchField) {
|
|
86
|
+
const { onChange: callback, ...helpers } = callbackRef.current;
|
|
87
|
+
callback(value, helpers);
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
return subscribe(listener);
|
|
91
|
+
}, [subscribe, watchField]);
|
|
80
92
|
};
|
|
81
93
|
//#endregion
|
|
82
94
|
//#region src/hooks/useWatchUserChange/index.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/hooks/useWatchUserChange/useWatchUserChange.ts","../../../src/hooks/useWatchUserChange/index.ts"],"sourcesContent":["import type {\n FieldValues,\n Path,\n UseFormReset,\n UseFormResetField,\n UseFormSetValue,\n} from 'react-hook-form';\n\nimport { useEffect } from 'react';\n\nimport { useFormContext } from '../useFormContext/useFormContext';\n\nexport interface UseWatchUserChangeOptions<TFieldValues extends FieldValues> {\n /** Field name to watch for user changes */\n watch: Path<TFieldValues>;\n /**\n * Callback when watched field is changed by user input.\n * Receives the new value and form helpers (setValue, resetField, reset).\n */\n onChange: (\n value: unknown,\n helpers: {\n setValue: UseFormSetValue<TFieldValues>;\n resetField: UseFormResetField<TFieldValues>;\n reset: UseFormReset<TFieldValues>;\n },\n ) => void;\n}\n\n/**\n * Hook that watches for user changes on a specific form field.\n *\n * Only triggers on manual user input (typing, clicking, selecting),\n * NOT on programmatic changes like form.reset() or form.setValue().\n * Also does NOT trigger when selecting the same value (e.g., clicking\n * an already-selected option in a Select).\n *\n * This hook subscribes to field changes at the source (useController),\n * ensuring immediate and accurate detection of user interactions.\n *\n * Use cases:\n * - Reset dependent fields when parent field changes\n * - Set mode-specific default values when a toggle changes\n * - Clear form sections based on user selections\n * - Trigger side effects only on user interaction\n *\n * Note: To watch multiple fields, call this hook multiple times.\n *\n * @example\n * ```tsx\n * // Reset city and address when user changes country\n * useWatchUserChange({\n * watch: 'country',\n * onChange: (value, { resetField }) => {\n * resetField('city');\n * resetField('address');\n * },\n * });\n *\n * // Set defaults when user changes payment method\n * useWatchUserChange({\n * watch: 'paymentMethod',\n * onChange: (value, { setValue }) => {\n * if (value === 'credit') {\n * setValue('installments', 3);\n * } else {\n * setValue('installments', 1);\n * }\n * },\n * });\n *\n * // Watch multiple fields by calling the hook multiple times\n * useWatchUserChange({\n * watch: 'category',\n * onChange: (value, { resetField }) => {\n * resetField('productId');\n * },\n * });\n * useWatchUserChange({\n * watch: 'brand',\n * onChange: (value, { resetField }) => {\n * resetField('productId');\n * },\n * });\n * ```\n */\nexport const useWatchUserChange = <\n TFieldValues extends FieldValues = FieldValues,\n>({\n watch: watchField,\n onChange,\n}: UseWatchUserChangeOptions<TFieldValues>) => {\n const { setValue, resetField, reset, userChange } =\n useFormContext<TFieldValues>();\n\n useEffect(() => {\n // Create listener that checks if changed field is the one we're watching\n const listener = (fieldName: Path<TFieldValues>, value: unknown) => {\n // Check if this is the field we're watching\n if (fieldName === watchField) {\n //
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/hooks/useWatchUserChange/useWatchUserChange.ts","../../../src/hooks/useWatchUserChange/index.ts"],"sourcesContent":["import type {\n FieldValues,\n Path,\n UseFormReset,\n UseFormResetField,\n UseFormSetValue,\n} from 'react-hook-form';\n\nimport { useEffect, useRef } from 'react';\n\nimport { useFormContext } from '../useFormContext/useFormContext';\n\nexport interface UseWatchUserChangeOptions<TFieldValues extends FieldValues> {\n /** Field name to watch for user changes */\n watch: Path<TFieldValues>;\n /**\n * Callback when watched field is changed by user input.\n * Receives the new value and form helpers (setValue, resetField, reset).\n */\n onChange: (\n value: unknown,\n helpers: {\n setValue: UseFormSetValue<TFieldValues>;\n resetField: UseFormResetField<TFieldValues>;\n reset: UseFormReset<TFieldValues>;\n },\n ) => void;\n}\n\n/**\n * Hook that watches for user changes on a specific form field.\n *\n * Only triggers on manual user input (typing, clicking, selecting),\n * NOT on programmatic changes like form.reset() or form.setValue().\n * Also does NOT trigger when selecting the same value (e.g., clicking\n * an already-selected option in a Select).\n *\n * This hook subscribes to field changes at the source (useController),\n * ensuring immediate and accurate detection of user interactions.\n *\n * Use cases:\n * - Reset dependent fields when parent field changes\n * - Set mode-specific default values when a toggle changes\n * - Clear form sections based on user selections\n * - Trigger side effects only on user interaction\n *\n * Note: To watch multiple fields, call this hook multiple times.\n *\n * @example\n * ```tsx\n * // Reset city and address when user changes country\n * useWatchUserChange({\n * watch: 'country',\n * onChange: (value, { resetField }) => {\n * resetField('city');\n * resetField('address');\n * },\n * });\n *\n * // Set defaults when user changes payment method\n * useWatchUserChange({\n * watch: 'paymentMethod',\n * onChange: (value, { setValue }) => {\n * if (value === 'credit') {\n * setValue('installments', 3);\n * } else {\n * setValue('installments', 1);\n * }\n * },\n * });\n *\n * // Watch multiple fields by calling the hook multiple times\n * useWatchUserChange({\n * watch: 'category',\n * onChange: (value, { resetField }) => {\n * resetField('productId');\n * },\n * });\n * useWatchUserChange({\n * watch: 'brand',\n * onChange: (value, { resetField }) => {\n * resetField('productId');\n * },\n * });\n * ```\n */\nexport const useWatchUserChange = <\n TFieldValues extends FieldValues = FieldValues,\n>({\n watch: watchField,\n onChange,\n}: UseWatchUserChangeOptions<TFieldValues>) => {\n const { setValue, resetField, reset, userChange } =\n useFormContext<TFieldValues>();\n\n // Callers commonly pass an inline callback, and useFormContext may return new\n // helper wrappers after a form render. Keep their latest values in a ref so\n // those identity changes do not tear down and recreate the subscription.\n const callbackRef = useRef({ onChange, reset, resetField, setValue });\n\n useEffect(() => {\n callbackRef.current = { onChange, reset, resetField, setValue };\n }, [onChange, reset, resetField, setValue]);\n\n // The subscribe function is stable even when the surrounding userChange\n // object is reconstructed. Depending on it directly keeps one active listener.\n const { subscribe } = userChange;\n\n useEffect(() => {\n // Create listener that checks if changed field is the one we're watching\n const listener = (fieldName: Path<TFieldValues>, value: unknown) => {\n // Check if this is the field we're watching\n if (fieldName === watchField) {\n // Read at notification time so the stable listener never closes over a\n // stale callback or stale form helpers.\n const { onChange: callback, ...helpers } = callbackRef.current;\n callback(value, helpers);\n }\n };\n\n // Subscribe to user changes\n const unsubscribe = subscribe(listener);\n\n // Cleanup on unmount\n return unsubscribe;\n }, [subscribe, watchField]);\n};\n","/* v8 ignore start */\n\nexport * from './useWatchUserChange';\n\n/* v8 ignore stop */\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsFA,MAAa,sBAEX,EACA,OAAO,YACP,eAC6C;CAC7C,MAAM,EAAE,UAAU,YAAY,OAAO,eACnC,eAA6B;CAK/B,MAAM,cAAc,OAAO;EAAE;EAAU;EAAO;EAAY;CAAS,CAAC;CAEpE,gBAAgB;EACd,YAAY,UAAU;GAAE;GAAU;GAAO;GAAY;EAAS;CAChE,GAAG;EAAC;EAAU;EAAO;EAAY;CAAQ,CAAC;CAI1C,MAAM,EAAE,cAAc;CAEtB,gBAAgB;EAEd,MAAM,YAAY,WAA+B,UAAmB;GAElE,IAAI,cAAc,YAAY;IAG5B,MAAM,EAAE,UAAU,UAAU,GAAG,YAAY,YAAY;IACvD,SAAS,OAAO,OAAO;GACzB;EACF;EAMA,OAHoB,UAAU,QAGb;CACnB,GAAG,CAAC,WAAW,UAAU,CAAC;AAC5B"}
|
|
@@ -95,10 +95,12 @@ const useFormContext$1 = () => {
|
|
|
95
95
|
* the internal nullish string conversion system or flat array wrapping manually.
|
|
96
96
|
*/
|
|
97
97
|
const getValues = ((...args) => {
|
|
98
|
-
|
|
98
|
+
const result = getValuesOrig(...args);
|
|
99
|
+
return toValidationFormat(result);
|
|
99
100
|
});
|
|
100
101
|
const watch = ((...args) => {
|
|
101
|
-
|
|
102
|
+
const result = watchOrig(...args);
|
|
103
|
+
return toValidationFormat(result);
|
|
102
104
|
});
|
|
103
105
|
const subscribe = ((...args) => {
|
|
104
106
|
const [options] = args;
|
|
@@ -132,4 +134,4 @@ const useFormContext$1 = () => {
|
|
|
132
134
|
//#endregion
|
|
133
135
|
export { useFormContext$1 as n, checkFieldIsRequired as t };
|
|
134
136
|
|
|
135
|
-
//# sourceMappingURL=useFormContext-
|
|
137
|
+
//# sourceMappingURL=useFormContext-fYWtlnpE.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useFormContext-
|
|
1
|
+
{"version":3,"file":"useFormContext-fYWtlnpE.mjs","names":["useFormContext","useHookFormContext"],"sources":["../src/hooks/useFormContext/useFormContext.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { VetoFormattedError, VetoInstance } from '@fuf-stack/veto';\nimport type { FieldError, FieldValues, Path } from 'react-hook-form';\n\nimport { useContext } from 'react';\nimport { useFormContext as useHookFormContext } from 'react-hook-form';\n\nimport { UniformContext } from '../../Form/subcomponents/FormContext';\nimport { flatArrayKey, nameToTestId, toValidationFormat } from '../../helpers';\n\n/** Schema check whether a field is required or optional */\nexport const checkFieldIsRequired = (\n validation: VetoInstance,\n path: string[],\n): boolean => {\n // Handle flat array paths: strip the flatArrayKey to check the array element schema\n // e.g., ['arrayField', '0', '__FLAT__'] -> check schema at ['arrayField', '0']\n const checkPath =\n path[path.length - 1] === flatArrayKey ? path.slice(0, -1) : path;\n\n const checkRequired = (schema: any) => {\n // arrays ...\n if (schema.type === 'array') {\n // ... if array is optional or nullable it is not required\n if (schema.isOptional || schema.isNullable) {\n return false;\n }\n // ... otherwise arrays are required (display logic wise -> no asterisk in the label)\n return true;\n }\n\n // all other fields are required if they are\n // not optional and not nullable\n return !schema.isOptional && !schema.isNullable;\n };\n\n return validation.checkSchemaPath(checkRequired, checkPath);\n};\n\n/**\n * Resolve validation errors for a given field path.\n *\n * Traverses a nested `VetoFormattedError` structure using a dotted path\n * (for example: \"user.address.0.street\") and returns the matching\n * `FieldError[]` if present. If no error exists at the path, returns\n * `undefined`.\n *\n * @param errors - The formatted validation errors from Uniform's context\n * @param name - The dotted field path to resolve\n * @returns An array of `FieldError` entries for the field, or `undefined`\n */\nconst getValidationErrorsByName = (\n errors: VetoFormattedError,\n name: string,\n) => {\n // Traverse nested error structure; ignore flat array wrapper key\n const keys = name.split('.').filter((k) => {\n return k !== flatArrayKey;\n });\n let current: unknown = errors;\n keys.forEach((key) => {\n if (current && typeof current === 'object') {\n current = (current as Record<string, unknown>)[key];\n } else {\n current = undefined;\n }\n });\n return current as FieldError[] | undefined;\n};\n\n/**\n * Custom hook that extends react-hook-form's useFormContext to add validation and state management.\n *\n * Key features:\n * - Enhanced `getFieldState` that includes validation schema-based \"required\" status and testId generation\n * - Automatic conversion of form values via `getValues`, `watch`, and `subscribe`:\n * - Unwraps flat array wrappers (`{ __FLAT__: value }` → `value`)\n * - Converts nullish string markers (`__NULL__` → `null`, `__FALSE__` → `false`, `__ZERO__` → `0`)\n * - Filters out empty/null values\n */\nexport const useFormContext = <\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n>() => {\n const {\n formState,\n // some methods that will be enhanced below\n getFieldState: getFieldStateOrig,\n getValues: getValuesOrig,\n watch: watchOrig,\n subscribe: subscribeOrig,\n reset: resetOrig,\n // the rest of the methods pass through unchanged\n ...otherMethods\n } = useHookFormContext<TFieldValues, TContext, TTransformedValues>();\n\n const uniformContext = useContext(UniformContext);\n\n /**\n * Wrap react-hook-form's `reset` so the uniform context is notified about\n * programmatic resets. Field components (e.g. FieldArray) use this signal to\n * normalize their state on reset instead of inferring it from field contents.\n */\n const notifyReset = uniformContext?.formReset?.notify;\n const reset = ((...args: Parameters<typeof resetOrig>) => {\n resetOrig(...args);\n notifyReset?.();\n }) as typeof resetOrig;\n\n /**\n * Updated getFieldState method which returns:\n * - Whether the field is required by checking the validation schema\n * - Existing field state information (errors, etc.)\n * - A testId generated from the field name (with flat array keys removed and slugified)\n *\n * @param name - The field path (string or array)\n * @param testId - Optional explicit testId. If provided, will be slugified. If not provided, generated from name.\n */\n const getFieldState = (name: Path<TFieldValues>, testId?: string) => {\n const fieldPath =\n typeof name === 'string' ? name.replace(/\\[\\d+\\]/g, '').split('.') : name;\n\n // Use base validation instance for checking \"required\" status\n // Client validation often uses .nullish() which would incorrectly mark fields as optional\n const validationInstance =\n uniformContext?.validation.baseInstance ??\n uniformContext?.validation.instance;\n\n // Check if the field is required using the validation schema\n const required = validationInstance\n ? checkFieldIsRequired(validationInstance, fieldPath)\n : false;\n\n const error = getValidationErrorsByName(\n uniformContext?.validation.errors ?? {},\n name,\n );\n\n // Get everything but the error from the original field state\n const fieldState = getFieldStateOrig(name, formState);\n\n return {\n ...fieldState,\n error,\n invalid: !!error,\n required,\n testId: nameToTestId(testId ?? name),\n };\n };\n\n /**\n * Wrap form value accessor methods to automatically convert from internal storage format\n * to component-friendly format:\n *\n * - Unwrap flat array wrappers: `{ __FLAT__: value }` → `value`\n * - Convert nullish string markers: `__NULL__` → `null`, `__FALSE__` → `false`, `__ZERO__` → `0`\n * - Filter out empty/null values: fields with converted null/empty values are removed entirely\n *\n * This ensures components receive clean, predictable data without needing to handle\n * the internal nullish string conversion system or flat array wrapping manually.\n */\n const getValues = ((...args: any[]) => {\n const result = (getValuesOrig as any)(...args);\n return toValidationFormat(result);\n }) as typeof getValuesOrig;\n\n const watch = ((...args: any[]) => {\n const result = (watchOrig as any)(...args);\n return toValidationFormat(result);\n }) as typeof watchOrig;\n\n const subscribe = ((...args: any[]) => {\n // For subscribe, we need to wrap the callback to convert the values property\n const [options] = args;\n if (options?.callback) {\n const originalCallback = options.callback;\n const wrappedOptions = {\n ...options,\n callback: (subscribeFormState: any) => {\n // Convert the values property if it exists\n const convertedFormState = {\n ...subscribeFormState,\n ...(subscribeFormState.values && {\n values: toValidationFormat(subscribeFormState.values),\n }),\n };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return originalCallback(convertedFormState);\n },\n };\n return subscribeOrig(wrappedOptions);\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return (subscribeOrig as any)(...args);\n }) as typeof subscribeOrig;\n\n return {\n ...otherMethods,\n ...uniformContext,\n formState,\n getFieldState,\n getValues,\n reset,\n subscribe,\n watch,\n };\n};\n"],"mappings":";;;;;;AAYA,MAAa,wBACX,YACA,SACY;CAGZ,MAAM,YACJ,KAAK,KAAK,SAAS,OAAA,aAAsB,KAAK,MAAM,GAAG,EAAE,IAAI;CAE/D,MAAM,iBAAiB,WAAgB;EAErC,IAAI,OAAO,SAAS,SAAS;GAE3B,IAAI,OAAO,cAAc,OAAO,YAC9B,OAAO;GAGT,OAAO;EACT;EAIA,OAAO,CAAC,OAAO,cAAc,CAAC,OAAO;CACvC;CAEA,OAAO,WAAW,gBAAgB,eAAe,SAAS;AAC5D;;;;;;;;;;;;;AAcA,MAAM,6BACJ,QACA,SACG;CAEH,MAAM,OAAO,KAAK,MAAM,GAAG,CAAC,CAAC,QAAQ,MAAM;EACzC,OAAO,MAAM;CACf,CAAC;CACD,IAAI,UAAmB;CACvB,KAAK,SAAS,QAAQ;EACpB,IAAI,WAAW,OAAO,YAAY,UAChC,UAAW,QAAoC;OAE/C,UAAU,KAAA;CAEd,CAAC;CACD,OAAO;AACT;;;;;;;;;;;AAYA,MAAaA,yBAIN;CACL,MAAM,EACJ,WAEA,eAAe,mBACf,WAAW,eACX,OAAO,WACP,WAAW,eACX,OAAO,WAEP,GAAG,iBACDC,eAA+D;CAEnE,MAAM,iBAAiB,WAAW,cAAc;;;;;;CAOhD,MAAM,cAAc,gBAAgB,WAAW;CAC/C,MAAM,UAAU,GAAG,SAAuC;EACxD,UAAU,GAAG,IAAI;EACjB,cAAc;CAChB;;;;;;;;;;CAWA,MAAM,iBAAiB,MAA0B,WAAoB;EACnE,MAAM,YACJ,OAAO,SAAS,WAAW,KAAK,QAAQ,YAAY,EAAE,CAAC,CAAC,MAAM,GAAG,IAAI;EAIvE,MAAM,qBACJ,gBAAgB,WAAW,gBAC3B,gBAAgB,WAAW;EAG7B,MAAM,WAAW,qBACb,qBAAqB,oBAAoB,SAAS,IAClD;EAEJ,MAAM,QAAQ,0BACZ,gBAAgB,WAAW,UAAU,CAAC,GACtC,IACF;EAKA,OAAO;GACL,GAHiB,kBAAkB,MAAM,SAG7B;GACZ;GACA,SAAS,CAAC,CAAC;GACX;GACA,QAAQ,aAAa,UAAU,IAAI;EACrC;CACF;;;;;;;;;;;;CAaA,MAAM,cAAc,GAAG,SAAgB;EACrC,MAAM,SAAU,cAAsB,GAAG,IAAI;EAC7C,OAAO,mBAAmB,MAAM;CAClC;CAEA,MAAM,UAAU,GAAG,SAAgB;EACjC,MAAM,SAAU,UAAkB,GAAG,IAAI;EACzC,OAAO,mBAAmB,MAAM;CAClC;CAEA,MAAM,cAAc,GAAG,SAAgB;EAErC,MAAM,CAAC,WAAW;EAClB,IAAI,SAAS,UAAU;GACrB,MAAM,mBAAmB,QAAQ;GACjC,MAAM,iBAAiB;IACrB,GAAG;IACH,WAAW,uBAA4B;KAErC,MAAM,qBAAqB;MACzB,GAAG;MACH,GAAI,mBAAmB,UAAU,EAC/B,QAAQ,mBAAmB,mBAAmB,MAAM,EACtD;KACF;KAEA,OAAO,iBAAiB,kBAAkB;IAC5C;GACF;GACA,OAAO,cAAc,cAAc;EACrC;EAEA,OAAQ,cAAsB,GAAG,IAAI;CACvC;CAEA,OAAO;EACL,GAAG;EACH,GAAG;EACH;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fuf-stack/uniform",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.27.0",
|
|
4
4
|
"description": "fuf react form library",
|
|
5
5
|
"author": "Fröhlich ∧ Frei",
|
|
6
6
|
"homepage": "https://github.com/fuf-stack/pixels#readme",
|
|
@@ -68,10 +68,10 @@
|
|
|
68
68
|
"@dnd-kit/modifiers": "9.0.0",
|
|
69
69
|
"@dnd-kit/sortable": "10.0.0",
|
|
70
70
|
"@dnd-kit/utilities": "3.2.2",
|
|
71
|
-
"@fuf-stack/pixel-motion": "1.
|
|
71
|
+
"@fuf-stack/pixel-motion": "1.4.0",
|
|
72
72
|
"@fuf-stack/pixel-utils": "1.4.0",
|
|
73
|
-
"@fuf-stack/pixels": "1.
|
|
74
|
-
"@fuf-stack/veto": "1.
|
|
73
|
+
"@fuf-stack/pixels": "1.14.0",
|
|
74
|
+
"@fuf-stack/veto": "1.11.0",
|
|
75
75
|
"@heroui/button": "2.2.32",
|
|
76
76
|
"@heroui/checkbox": "2.3.32",
|
|
77
77
|
"@heroui/date-input": "2.3.32",
|
|
@@ -84,7 +84,7 @@
|
|
|
84
84
|
"@heroui/switch": "2.2.27",
|
|
85
85
|
"@heroui/system": "2.4.28",
|
|
86
86
|
"@heroui/theme": "2.4.26",
|
|
87
|
-
"@internationalized/date": "3.12.
|
|
87
|
+
"@internationalized/date": "3.12.4",
|
|
88
88
|
"@react-aria/visually-hidden": "3.9.1",
|
|
89
89
|
"debug": "4.4.3",
|
|
90
90
|
"framer-motion": "12.43.0",
|
|
@@ -95,9 +95,9 @@
|
|
|
95
95
|
"devDependencies": {
|
|
96
96
|
"@types/debug": "4.1.13",
|
|
97
97
|
"@types/react": "19.2.18",
|
|
98
|
-
"@types/react-dom": "19.2.
|
|
98
|
+
"@types/react-dom": "19.2.7",
|
|
99
99
|
"react": "19.2.8",
|
|
100
100
|
"react-dom": "19.2.8"
|
|
101
101
|
},
|
|
102
|
-
"gitHead": "
|
|
102
|
+
"gitHead": "ce8395ec7be03495876e5da7c3cb3649c0e6fc40"
|
|
103
103
|
}
|