@fuf-stack/uniform 1.22.7 → 1.22.9
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 +2 -6
- package/dist/Checkboxes/index.cjs.map +1 -1
- package/dist/Checkboxes/index.d.cts +6 -6
- package/dist/Checkboxes/index.d.cts.map +1 -1
- package/dist/Checkboxes/index.d.ts +6 -6
- package/dist/Checkboxes/index.d.ts.map +1 -1
- package/dist/Checkboxes/index.js +2 -6
- package/dist/Checkboxes/index.js.map +1 -1
- package/dist/DatePicker/index.d.cts +11 -11
- package/dist/DatePicker/index.d.ts +11 -11
- package/dist/FieldArray/index.d.cts +6 -6
- package/dist/FieldArray/index.d.cts.map +1 -1
- package/dist/FieldArray/index.d.ts +6 -6
- package/dist/FieldArray/index.d.ts.map +1 -1
- package/dist/FieldCard/index.d.cts +6 -6
- package/dist/FieldCard/index.d.cts.map +1 -1
- package/dist/FieldCard/index.d.ts +6 -6
- package/dist/FieldCard/index.d.ts.map +1 -1
- package/dist/Form/index.cjs +14 -19
- package/dist/Form/index.cjs.map +1 -1
- package/dist/Form/index.js +15 -20
- package/dist/Form/index.js.map +1 -1
- package/dist/Input/index.d.cts +11 -11
- package/dist/Input/index.d.cts.map +1 -1
- package/dist/Input/index.d.ts +11 -11
- package/dist/Input/index.d.ts.map +1 -1
- package/dist/RadioBoxes/index.d.cts +17 -17
- package/dist/RadioBoxes/index.d.ts +17 -17
- package/dist/RadioTabs/index.d.cts +10 -10
- package/dist/RadioTabs/index.d.cts.map +1 -1
- package/dist/RadioTabs/index.d.ts +10 -10
- package/dist/RadioTabs/index.d.ts.map +1 -1
- package/dist/Radios/index.d.cts +11 -11
- package/dist/Radios/index.d.ts +11 -11
- package/dist/Select/index.cjs +36 -29
- package/dist/Select/index.cjs.map +1 -1
- package/dist/Select/index.d.cts +23 -23
- package/dist/Select/index.d.cts.map +1 -1
- package/dist/Select/index.d.ts +23 -23
- package/dist/Select/index.d.ts.map +1 -1
- package/dist/Select/index.js +36 -29
- package/dist/Select/index.js.map +1 -1
- package/dist/Slider/index.d.cts +23 -23
- package/dist/Slider/index.d.ts +23 -23
- package/dist/Switch/index.d.cts +23 -23
- package/dist/Switch/index.d.ts +23 -23
- package/dist/SwitchBox/index.d.cts +35 -35
- package/dist/SwitchBox/index.d.cts.map +1 -1
- package/dist/SwitchBox/index.d.ts +35 -35
- package/dist/SwitchBox/index.d.ts.map +1 -1
- package/dist/TextArea/index.d.cts +11 -11
- package/dist/TextArea/index.d.ts +11 -11
- package/dist/Time/index.d.cts +17 -17
- package/dist/Time/index.d.ts +17 -17
- package/dist/helpers/index.cjs +33 -0
- package/dist/helpers/index.cjs.map +1 -1
- package/dist/helpers/index.d.cts +15 -1
- package/dist/helpers/index.d.cts.map +1 -1
- package/dist/helpers/index.d.ts +15 -1
- package/dist/helpers/index.d.ts.map +1 -1
- package/dist/helpers/index.js +33 -1
- package/dist/helpers/index.js.map +1 -1
- package/dist/hooks/useUniformField/index.cjs +5 -4
- package/dist/hooks/useUniformField/index.cjs.map +1 -1
- package/dist/hooks/useUniformField/index.d.cts +4 -2
- package/dist/hooks/useUniformField/index.d.cts.map +1 -1
- package/dist/hooks/useUniformField/index.d.ts +4 -2
- package/dist/hooks/useUniformField/index.d.ts.map +1 -1
- package/dist/hooks/useUniformField/index.js +6 -5
- package/dist/hooks/useUniformField/index.js.map +1 -1
- package/dist/hooks/useUniformFieldArray/index.d.cts.map +1 -1
- package/dist/hooks/useUniformFieldArray/index.d.ts.map +1 -1
- package/package.json +4 -4
package/dist/helpers/index.cjs
CHANGED
|
@@ -43,6 +43,38 @@ const createOptionValueConverter = (options) => {
|
|
|
43
43
|
};
|
|
44
44
|
};
|
|
45
45
|
//#endregion
|
|
46
|
+
//#region src/helpers/flattenFieldErrors/flattenFieldErrors.ts
|
|
47
|
+
/**
|
|
48
|
+
* Narrow an unknown value to a react-hook-form `FieldError`.
|
|
49
|
+
*
|
|
50
|
+
* RHF `FieldError` entries carry metadata like `message` and/or `type`,
|
|
51
|
+
* while container nodes (objects keyed by index, `_errors`, etc.) do not.
|
|
52
|
+
* This guard distinguishes leaf errors from nested wrappers.
|
|
53
|
+
*/
|
|
54
|
+
const isFieldError = (error) => {
|
|
55
|
+
return typeof error === "object" && error !== null && ("message" in error || "type" in error);
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Normalize RHF validation payloads to a flat `FieldError[]`.
|
|
59
|
+
*
|
|
60
|
+
* Depending on field shape, RHF may return:
|
|
61
|
+
* - a single `FieldError`
|
|
62
|
+
* - an array of `FieldError`
|
|
63
|
+
* - nested objects keyed by array indices
|
|
64
|
+
* - objects containing `_errors` arrays for array/object-level issues
|
|
65
|
+
*/
|
|
66
|
+
const flattenFieldErrors = (error) => {
|
|
67
|
+
if (!error) return [];
|
|
68
|
+
if (Array.isArray(error)) return error.flatMap((item) => {
|
|
69
|
+
return flattenFieldErrors(item);
|
|
70
|
+
});
|
|
71
|
+
if (isFieldError(error)) return [error];
|
|
72
|
+
if (typeof error === "object") return Object.values(error).flatMap((item) => {
|
|
73
|
+
return flattenFieldErrors(item);
|
|
74
|
+
});
|
|
75
|
+
return [];
|
|
76
|
+
};
|
|
77
|
+
//#endregion
|
|
46
78
|
//#region src/helpers/nullishFields/nullishFields.ts
|
|
47
79
|
/** Key used to wrap flat array elements when converting to form format */
|
|
48
80
|
const flatArrayKey = "__FLAT__";
|
|
@@ -386,6 +418,7 @@ const nameToTestId = (name) => {
|
|
|
386
418
|
//#endregion
|
|
387
419
|
exports.createOptionValueConverter = createOptionValueConverter;
|
|
388
420
|
exports.flatArrayKey = flatArrayKey;
|
|
421
|
+
exports.flattenFieldErrors = flattenFieldErrors;
|
|
389
422
|
exports.fromNullishString = fromNullishString;
|
|
390
423
|
exports.isValueEmpty = isValueEmpty;
|
|
391
424
|
exports.nameToTestId = nameToTestId;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["record"],"sources":["../../src/helpers/createOptionValueConverter/createOptionValueConverter.ts","../../src/helpers/nullishFields/nullishFields.ts"],"sourcesContent":["/* eslint-disable import-x/prefer-default-export */\n\n/**\n * Creates a converter function that preserves the original type (string, number, or boolean)\n * of option values when converting from string keys back to their original type.\n *\n * This is useful for radio/select components where the underlying UI library\n * uses string keys internally, but we want to preserve number/boolean values in the form state.\n *\n * @param options - Array of options with a value property that can be string, number, or boolean\n * @returns An object with:\n * - `convertToOriginalType`: Function to convert a string key back to its original type\n * - `numberValueKeys`: Set of string representations of number values (for internal use)\n * - `booleanValueKeys`: Map of string representations to boolean values (for internal use)\n */\nexport const createOptionValueConverter = <\n T extends { value: string | number | boolean },\n>(\n options: T[],\n) => {\n // Create a set of string keys that represent number values\n const numberValueKeys = new Set(\n options\n .filter((option) => {\n return typeof option.value === 'number';\n })\n .map((option) => {\n return String(option.value);\n }),\n );\n\n // Create a map of string keys to boolean values\n const booleanValueKeys = new Map(\n options\n .filter((option) => {\n return typeof option.value === 'boolean';\n })\n .map((option) => {\n return [String(option.value), option.value as boolean];\n }),\n );\n\n /**\n * Converts a string key back to its original type (string, number, or boolean)\n * based on whether the original option value was a number or boolean\n */\n const convertToOriginalType = (\n key: string | number | boolean,\n ): string | number | boolean => {\n const keyStr = String(key);\n const booleanValue = booleanValueKeys.get(keyStr);\n if (booleanValue !== undefined) {\n return booleanValue;\n }\n if (numberValueKeys.has(keyStr)) {\n return Number(keyStr);\n }\n return keyStr;\n };\n\n return {\n booleanValueKeys,\n convertToOriginalType,\n numberValueKeys,\n };\n};\n","import { slugify } from '@fuf-stack/pixel-utils';\n\n/** Key used to wrap flat array elements when converting to form format */\nexport const flatArrayKey = '__FLAT__';\n\n/**\n * String markers used to preserve null, false, and 0 values during JSON processing\n */\nconst nullString = '__NULL__';\nconst falseString = '__FALSE__';\nconst zeroString = '__ZERO__';\n\n/**\n * Checks if a value is considered \"empty\" for validation display purposes.\n *\n * Used by useUniformField to determine when to show validation errors.\n * Empty values don't trigger immediate error display (user must interact first).\n *\n * Handles:\n * - Primitives: null, undefined, ''\n * - Marker strings: __NULL__, __FALSE__, __ZERO__ (converted via fromNullishString)\n * - Empty arrays: []\n * - Objects with all empty values: {a: null, b: ''}\n * - Flat array wrappers: {__FLAT__: null} or {__FLAT__: ''}\n *\n * @param value - The value to check (will be converted via fromNullishString first)\n * @returns true if the value is empty\n *\n * @example\n * isValueEmpty(null) // true\n * isValueEmpty('') // true\n * isValueEmpty('__NULL__') // true (marker string)\n * isValueEmpty([]) // true (empty array)\n * isValueEmpty({a: null}) // true (object with all empty values)\n * isValueEmpty({__FLAT__: null}) // true (flat array wrapper with empty value)\n * isValueEmpty({__FLAT__: ''}) // true\n * isValueEmpty('hello') // false\n * isValueEmpty([1, 2]) // false\n * isValueEmpty({a: 'value'}) // false\n * isValueEmpty({__FLAT__: 'value'}) // false\n */\nexport const isValueEmpty = (value: unknown): boolean => {\n // Convert marker strings first\n const converted = fromNullishString(value);\n\n if (converted === undefined || converted === null || converted === '') {\n return true;\n }\n if (Array.isArray(converted)) {\n return converted.length === 0;\n }\n if (typeof converted === 'object' && converted !== null) {\n const record = converted as Record<string, unknown>;\n // Handle flat array wrapper: { __FLAT__: innerValue }\n if (flatArrayKey in record) {\n return isValueEmpty(record[flatArrayKey]);\n }\n // For objects (e.g., FieldCard), check if all values are null/undefined/empty\n const values = Object.values(record);\n return values.length === 0 || values.every(isValueEmpty);\n }\n return false;\n};\n\n/**\n * Converts marker strings back to their original values when processing arrays\n */\nexport const fromNullishString = (value: unknown): unknown => {\n // Support arrays: unwrap flat wrappers and convert marker strings per entry\n if (Array.isArray(value)) {\n return (value as unknown[]).map((entry) => {\n if (entry && typeof entry === 'object') {\n const record = entry as Record<string, unknown>;\n if (flatArrayKey in record) {\n const inner = record[flatArrayKey];\n // For arrays, treat empty string as null (placeholder input)\n if (inner === '') {\n return null;\n }\n return fromNullishString(inner);\n }\n }\n return fromNullishString(entry);\n });\n }\n\n if (typeof value !== 'string') {\n return value;\n }\n\n switch (value) {\n case nullString:\n return null;\n case falseString:\n return false;\n case zeroString:\n return 0;\n default:\n return value;\n }\n};\n\n/**\n * Converts null/falsy values to marker strings for JSON processing\n */\nexport const toNullishString = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n // Only wrap arrays of primitives; leave arrays of objects as-is\n const isPrimitive = (v: unknown) => {\n return v === null || ['string', 'number', 'boolean'].includes(typeof v);\n };\n const isPrimitiveArray = (value as unknown[]).every(isPrimitive);\n if (isPrimitiveArray) {\n return (value as unknown[]).map((v) => {\n // Store raw primitive; do not convert to marker strings inside the wrapper\n return { [flatArrayKey]: v };\n });\n }\n return value;\n }\n if (value === null || value === '') {\n return nullString;\n }\n if (value === false) {\n return falseString;\n }\n if (value === 0) {\n return zeroString;\n }\n return value;\n};\n\n/**\n * Converts field values to a format suitable for forms by:\n * - Wrapping arrays of primitives as objects using the flatArrayKey `__FLAT__`\n * to satisfy RHF's requirement that array fields contain objects\n * - Removing empty strings and null values from objects\n *\n * This conversion is required because React Hook Form does not support arrays with\n * flat values (string, number, boolean, null). Array fields must contain objects.\n * We work around this by wrapping primitive entries: `{ __FLAT__: <value> }`.\n *\n * @example\n * const fields = {\n * name: 'John',\n * scores: [0, null, 75, false],\n * scoresDetailed: [\n * { score: 1 },\n * { score: null },\n * { score: 0 },\n * { score: false },\n * { score: '' },\n * ],\n * contact: {\n * email: '',\n * phone: null,\n * address: '123 Main St'\n * }\n * };\n *\n * // Result:\n * {\n * name: 'John',\n * scores: [\n * { __FLAT__: 0 },\n * { __FLAT__: null },\n * { __FLAT__: 75 },\n * { __FLAT__: false }\n * ],\n * // Arrays of objects are left as objects; empty/null properties are removed\n * scoresDetailed: [\n * { score: 1 },\n * {}, // null score removed\n * { score: 0 },\n * { score: false },\n * {}, // empty string removed\n * ],\n * contact: {\n * address: '123 Main St'\n * }\n * }\n */\nexport const toFormFormat = (fields: Record<string, unknown>) => {\n const formFormatJson = JSON.stringify(fields, (_, value) => {\n if (Array.isArray(value)) {\n // Delegate to toNullishString to ensure consistent handling\n return toNullishString(value);\n }\n\n if (value && typeof value === 'object') {\n // Preserve flat-array wrappers as-is (do not filter their inner values here)\n const record = value as Record<string, unknown>;\n if (flatArrayKey in record) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n }\n return Object.fromEntries(\n Object.entries(value).filter(([_key, v]) => {\n return v !== '' && v !== null;\n }),\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n });\n\n return JSON.parse(formFormatJson) as Record<string, unknown>;\n};\n\n/**\n * Converts form state to a format suitable for validation by:\n * - Unwrapping flat array wrappers `{ __FLAT__: <value> }` back to primitives\n * - Converting legacy string markers (__NULL__, __FALSE__, __ZERO__) back to their original values\n * - Removing fields whose converted value is empty string or null\n * - Removing empty arrays\n *\n * @example\n * const formState = {\n * name: 'John',\n * scores: [\n * { __FLAT__: 75 },\n * { __FLAT__: 0 },\n * { __FLAT__: null },\n * { __FLAT__: false }\n * ],\n * emptyArray: [],\n * scoresDetailed: [\n * { score: 1 },\n * {},\n * { score: 0 },\n * { score: false },\n * {},\n * ],\n * contact: {\n * address: '123 Main St',\n * fax: null\n * }\n * };\n *\n * // Result:\n * {\n * name: 'John',\n * scores: [75, 0, null, false],\n * // emptyArray is removed\n * // Objects inside arrays remain objects; empty entries remain empty objects\n * scoresDetailed: [\n * { score: 1 },\n * {},\n * { score: 0 },\n * { score: false },\n * {},\n * ],\n * contact: {\n * address: '123 Main St'\n * }\n * }\n */\nexport const toValidationFormat = (\n formState: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | null | undefined => {\n // Handle null or undefined input\n if (formState === undefined || formState === null) {\n return formState;\n }\n\n const validationFormatJson = JSON.stringify(formState, (_, value) => {\n if (Array.isArray(value)) {\n return value.map((v) => {\n // Unwrap new wrapper format { __FLAT__: <value> }\n if (v && typeof v === 'object') {\n const record = v as Record<string, unknown>;\n if (flatArrayKey in record) {\n const inner = record[flatArrayKey];\n // Treat empty string from forms as null in validation format\n if (inner === '') {\n return null;\n }\n return fromNullishString(inner);\n }\n }\n // Backward compatibility for string markers\n return fromNullishString(v);\n });\n }\n\n if (value && typeof value === 'object') {\n // Object branch: remove keys that resolve to empty/null after marker conversion\n // and unwrap flat-array wrappers if present.\n //\n // Why this shape?\n // - Forms may contain objects with placeholder/empty values that should not\n // be part of the validation payload (e.g. \"\" or __NULL__ markers).\n // - Arrays of primitives are stored as wrapper objects { __FLAT__: <value> }\n // to satisfy RHF structure constraints. When converting back for\n // validation, we need to treat wrappers whose inner value resolves to\n // empty/null as removable, and unwrap non-empty wrappers to the primitive.\n return Object.fromEntries(\n Object.entries(value)\n .filter(([_key, v]) => {\n // If this is a flat-array wrapper, convert the inner value first and\n // drop the key when the inner resolves to empty string or null.\n if (v && typeof v === 'object') {\n const record = v as Record<string, unknown>;\n if (flatArrayKey in record) {\n const convertedInner = fromNullishString(record[flatArrayKey]);\n return convertedInner !== '' && convertedInner !== null;\n }\n }\n // Drop empty arrays\n if (Array.isArray(v) && v.length === 0) {\n return false;\n }\n // For regular values, convert markers and drop when empty/null.\n const converted = fromNullishString(v);\n return converted !== '' && converted !== null;\n })\n .map(([k, v]) => {\n // Unwrap flat-array wrappers to raw primitives after conversion.\n if (v && typeof v === 'object') {\n const record = v as Record<string, unknown>;\n if (flatArrayKey in record) {\n return [k, fromNullishString(record[flatArrayKey])];\n }\n }\n // For other values, just convert markers.\n return [k, fromNullishString(v)];\n }),\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n });\n\n return JSON.parse(validationFormatJson) as Record<string, unknown>;\n};\n\n/**\n * Helper function to check if a value is an empty object (not an array).\n */\nconst isEmptyObject = (value: unknown): boolean => {\n return (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n Object.keys(value).length === 0\n );\n};\n\n/**\n * Recursively removes empty objects from a data structure.\n * - Filters empty objects from arrays\n * - Removes properties with empty object values\n * - Removes arrays that become empty after filtering\n */\nconst removeEmptyObjects = (obj: unknown): unknown => {\n if (Array.isArray(obj)) {\n // Filter out empty objects from arrays, then recursively process remaining items\n return obj\n .filter((item) => {\n return !isEmptyObject(item);\n })\n .map((item) => {\n return removeEmptyObjects(item);\n });\n }\n\n if (obj !== null && typeof obj === 'object') {\n return Object.fromEntries(\n Object.entries(obj)\n .map(([key, value]) => {\n return [key, removeEmptyObjects(value)] as [string, unknown];\n })\n .filter(([_, processed]) => {\n // Skip empty objects\n if (isEmptyObject(processed)) {\n return false;\n }\n // Skip arrays that are now empty after filtering\n if (Array.isArray(processed) && processed.length === 0) {\n return false;\n }\n return true;\n }),\n );\n }\n\n return obj;\n};\n\n/**\n * Converts form state to a format suitable for submission by:\n * - Applying all transformations from toValidationFormat\n * - Additionally removing empty objects from the result\n * - Filtering empty objects from arrays\n * - Recursively cleaning nested structures\n *\n * **Why separate from toValidationFormat?**\n *\n * Empty objects must be preserved during validation so that custom refinements\n * can run. For example, a FieldCard with \"at least email or phone required\"\n * validation needs the object to exist (even if empty) for the refine to execute.\n *\n * However, for submission, empty objects are meaningless and should be removed\n * to produce clean data for APIs.\n *\n * @example\n * const formState = {\n * name: 'John',\n * contact: {}, // Empty FieldCard - will be removed\n * tags: [{}, {}, {}], // All empty - array will be removed\n * items: [\n * { value: 'a' },\n * {}, // Empty entry - will be filtered out\n * { value: 'b' }\n * ],\n * nested: {\n * deep: {} // Nested empty - will be removed recursively\n * }\n * };\n *\n * // Result:\n * {\n * name: 'John',\n * items: [{ value: 'a' }, { value: 'b' }]\n * }\n */\nexport const toSubmitFormat = (\n formState: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | null | undefined => {\n const validated = toValidationFormat(formState);\n if (!validated) {\n return validated;\n }\n return removeEmptyObjects(validated) as Record<string, unknown>;\n};\n\n/**\n * Converts a field name to a testId by removing flat array key segments and slugifying.\n * Removes all occurrences of `flatArrayKey` from the field name and applies slugify transformation.\n *\n * This is used to generate stable testIds for form fields that don't include\n * the internal `__FLAT__` marker used for flat arrays.\n *\n * @param name - The field name as a string (e.g., 'tags.0.__FLAT__') or array path (e.g., ['tags', '0', '__FLAT__'])\n * @returns The slugified field name with all flat array key segments removed (e.g., 'tags_0')\n *\n * @example\n * ```ts\n * nameToTestId('tags.0.__FLAT__') // => 'tags_0'\n * nameToTestId('array.0.__FLAT__') // => 'array_0'\n * nameToTestId('nested.array.0.__FLAT__.field') // => 'nested_array_0_field'\n * nameToTestId('simple.field') // => 'simple_field'\n * nameToTestId(['tags', '0', '__FLAT__']) // => 'tags_0'\n * ```\n */\nexport const nameToTestId = (name: string | readonly string[]): string => {\n let cleanName: string;\n\n // Handle array paths - filter out flatArrayKey and join with dots\n if (Array.isArray(name)) {\n cleanName = name\n .filter((segment: string) => {\n return segment !== flatArrayKey;\n })\n .join('.');\n } else {\n // Handle string paths - split by dots and filter out flatArrayKey segments\n const segments = (name as string).split('.');\n cleanName = segments\n .filter((segment: string) => {\n return segment !== flatArrayKey;\n })\n .join('.');\n }\n\n // Apply slugify transformation\n return slugify(cleanName, { replaceDots: true });\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,MAAa,8BAGX,YACG;CAEH,MAAM,kBAAkB,IAAI,IAC1B,QACG,QAAQ,WAAW;EAClB,OAAO,OAAO,OAAO,UAAU;CACjC,CAAC,EACA,KAAK,WAAW;EACf,OAAO,OAAO,OAAO,KAAK;CAC5B,CAAC,CACL;CAGA,MAAM,mBAAmB,IAAI,IAC3B,QACG,QAAQ,WAAW;EAClB,OAAO,OAAO,OAAO,UAAU;CACjC,CAAC,EACA,KAAK,WAAW;EACf,OAAO,CAAC,OAAO,OAAO,KAAK,GAAG,OAAO,KAAgB;CACvD,CAAC,CACL;;;;;CAMA,MAAM,yBACJ,QAC8B;EAC9B,MAAM,SAAS,OAAO,GAAG;EACzB,MAAM,eAAe,iBAAiB,IAAI,MAAM;EAChD,IAAI,iBAAiB,KAAA,GACnB,OAAO;EAET,IAAI,gBAAgB,IAAI,MAAM,GAC5B,OAAO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,OAAO;CACT,CAAC,CACL;CAGF,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,kBACX,cAC+C;CAC/C,MAAM,YAAY,mBAAmB,SAAS;CAC9C,IAAI,CAAC,WACH,OAAO;CAET,OAAO,mBAAmB,SAAS;AACrC;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,gBAAgB,SAA6C;CACxE,IAAI;CAGJ,IAAI,MAAM,QAAQ,IAAI,GACpB,YAAY,KACT,QAAQ,YAAoB;EAC3B,OAAO,YAAY;CACrB,CAAC,EACA,KAAK,GAAG;MAIX,YADkB,KAAgB,MAAM,GACrB,EAChB,QAAQ,YAAoB;EAC3B,OAAO,YAAY;CACrB,CAAC,EACA,KAAK,GAAG;CAIb,QAAA,GAAA,uBAAA,SAAe,WAAW,EAAE,aAAa,KAAK,CAAC;AACjD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["record"],"sources":["../../src/helpers/createOptionValueConverter/createOptionValueConverter.ts","../../src/helpers/flattenFieldErrors/flattenFieldErrors.ts","../../src/helpers/nullishFields/nullishFields.ts"],"sourcesContent":["/* eslint-disable import-x/prefer-default-export */\n\n/**\n * Creates a converter function that preserves the original type (string, number, or boolean)\n * of option values when converting from string keys back to their original type.\n *\n * This is useful for radio/select components where the underlying UI library\n * uses string keys internally, but we want to preserve number/boolean values in the form state.\n *\n * @param options - Array of options with a value property that can be string, number, or boolean\n * @returns An object with:\n * - `convertToOriginalType`: Function to convert a string key back to its original type\n * - `numberValueKeys`: Set of string representations of number values (for internal use)\n * - `booleanValueKeys`: Map of string representations to boolean values (for internal use)\n */\nexport const createOptionValueConverter = <\n T extends { value: string | number | boolean },\n>(\n options: T[],\n) => {\n // Create a set of string keys that represent number values\n const numberValueKeys = new Set(\n options\n .filter((option) => {\n return typeof option.value === 'number';\n })\n .map((option) => {\n return String(option.value);\n }),\n );\n\n // Create a map of string keys to boolean values\n const booleanValueKeys = new Map(\n options\n .filter((option) => {\n return typeof option.value === 'boolean';\n })\n .map((option) => {\n return [String(option.value), option.value as boolean];\n }),\n );\n\n /**\n * Converts a string key back to its original type (string, number, or boolean)\n * based on whether the original option value was a number or boolean\n */\n const convertToOriginalType = (\n key: string | number | boolean,\n ): string | number | boolean => {\n const keyStr = String(key);\n const booleanValue = booleanValueKeys.get(keyStr);\n if (booleanValue !== undefined) {\n return booleanValue;\n }\n if (numberValueKeys.has(keyStr)) {\n return Number(keyStr);\n }\n return keyStr;\n };\n\n return {\n booleanValueKeys,\n convertToOriginalType,\n numberValueKeys,\n };\n};\n","/* eslint-disable import-x/prefer-default-export */\n\nimport type { FieldError } from 'react-hook-form';\n\n/**\n * Narrow an unknown value to a react-hook-form `FieldError`.\n *\n * RHF `FieldError` entries carry metadata like `message` and/or `type`,\n * while container nodes (objects keyed by index, `_errors`, etc.) do not.\n * This guard distinguishes leaf errors from nested wrappers.\n */\nconst isFieldError = (error: unknown): error is FieldError => {\n return (\n typeof error === 'object' &&\n error !== null &&\n ('message' in error || 'type' in error)\n );\n};\n\n/**\n * Normalize RHF validation payloads to a flat `FieldError[]`.\n *\n * Depending on field shape, RHF may return:\n * - a single `FieldError`\n * - an array of `FieldError`\n * - nested objects keyed by array indices\n * - objects containing `_errors` arrays for array/object-level issues\n */\nexport const flattenFieldErrors = (error: unknown): FieldError[] => {\n if (!error) {\n return [];\n }\n\n if (Array.isArray(error)) {\n return error.flatMap((item) => {\n return flattenFieldErrors(item);\n });\n }\n\n if (isFieldError(error)) {\n return [error];\n }\n\n if (typeof error === 'object') {\n return Object.values(error as Record<string, unknown>).flatMap((item) => {\n return flattenFieldErrors(item);\n });\n }\n\n return [];\n};\n","import { slugify } from '@fuf-stack/pixel-utils';\n\n/** Key used to wrap flat array elements when converting to form format */\nexport const flatArrayKey = '__FLAT__';\n\n/**\n * String markers used to preserve null, false, and 0 values during JSON processing\n */\nconst nullString = '__NULL__';\nconst falseString = '__FALSE__';\nconst zeroString = '__ZERO__';\n\n/**\n * Checks if a value is considered \"empty\" for validation display purposes.\n *\n * Used by useUniformField to determine when to show validation errors.\n * Empty values don't trigger immediate error display (user must interact first).\n *\n * Handles:\n * - Primitives: null, undefined, ''\n * - Marker strings: __NULL__, __FALSE__, __ZERO__ (converted via fromNullishString)\n * - Empty arrays: []\n * - Objects with all empty values: {a: null, b: ''}\n * - Flat array wrappers: {__FLAT__: null} or {__FLAT__: ''}\n *\n * @param value - The value to check (will be converted via fromNullishString first)\n * @returns true if the value is empty\n *\n * @example\n * isValueEmpty(null) // true\n * isValueEmpty('') // true\n * isValueEmpty('__NULL__') // true (marker string)\n * isValueEmpty([]) // true (empty array)\n * isValueEmpty({a: null}) // true (object with all empty values)\n * isValueEmpty({__FLAT__: null}) // true (flat array wrapper with empty value)\n * isValueEmpty({__FLAT__: ''}) // true\n * isValueEmpty('hello') // false\n * isValueEmpty([1, 2]) // false\n * isValueEmpty({a: 'value'}) // false\n * isValueEmpty({__FLAT__: 'value'}) // false\n */\nexport const isValueEmpty = (value: unknown): boolean => {\n // Convert marker strings first\n const converted = fromNullishString(value);\n\n if (converted === undefined || converted === null || converted === '') {\n return true;\n }\n if (Array.isArray(converted)) {\n return converted.length === 0;\n }\n if (typeof converted === 'object' && converted !== null) {\n const record = converted as Record<string, unknown>;\n // Handle flat array wrapper: { __FLAT__: innerValue }\n if (flatArrayKey in record) {\n return isValueEmpty(record[flatArrayKey]);\n }\n // For objects (e.g., FieldCard), check if all values are null/undefined/empty\n const values = Object.values(record);\n return values.length === 0 || values.every(isValueEmpty);\n }\n return false;\n};\n\n/**\n * Converts marker strings back to their original values when processing arrays\n */\nexport const fromNullishString = (value: unknown): unknown => {\n // Support arrays: unwrap flat wrappers and convert marker strings per entry\n if (Array.isArray(value)) {\n return (value as unknown[]).map((entry) => {\n if (entry && typeof entry === 'object') {\n const record = entry as Record<string, unknown>;\n if (flatArrayKey in record) {\n const inner = record[flatArrayKey];\n // For arrays, treat empty string as null (placeholder input)\n if (inner === '') {\n return null;\n }\n return fromNullishString(inner);\n }\n }\n return fromNullishString(entry);\n });\n }\n\n if (typeof value !== 'string') {\n return value;\n }\n\n switch (value) {\n case nullString:\n return null;\n case falseString:\n return false;\n case zeroString:\n return 0;\n default:\n return value;\n }\n};\n\n/**\n * Converts null/falsy values to marker strings for JSON processing\n */\nexport const toNullishString = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n // Only wrap arrays of primitives; leave arrays of objects as-is\n const isPrimitive = (v: unknown) => {\n return v === null || ['string', 'number', 'boolean'].includes(typeof v);\n };\n const isPrimitiveArray = (value as unknown[]).every(isPrimitive);\n if (isPrimitiveArray) {\n return (value as unknown[]).map((v) => {\n // Store raw primitive; do not convert to marker strings inside the wrapper\n return { [flatArrayKey]: v };\n });\n }\n return value;\n }\n if (value === null || value === '') {\n return nullString;\n }\n if (value === false) {\n return falseString;\n }\n if (value === 0) {\n return zeroString;\n }\n return value;\n};\n\n/**\n * Converts field values to a format suitable for forms by:\n * - Wrapping arrays of primitives as objects using the flatArrayKey `__FLAT__`\n * to satisfy RHF's requirement that array fields contain objects\n * - Removing empty strings and null values from objects\n *\n * This conversion is required because React Hook Form does not support arrays with\n * flat values (string, number, boolean, null). Array fields must contain objects.\n * We work around this by wrapping primitive entries: `{ __FLAT__: <value> }`.\n *\n * @example\n * const fields = {\n * name: 'John',\n * scores: [0, null, 75, false],\n * scoresDetailed: [\n * { score: 1 },\n * { score: null },\n * { score: 0 },\n * { score: false },\n * { score: '' },\n * ],\n * contact: {\n * email: '',\n * phone: null,\n * address: '123 Main St'\n * }\n * };\n *\n * // Result:\n * {\n * name: 'John',\n * scores: [\n * { __FLAT__: 0 },\n * { __FLAT__: null },\n * { __FLAT__: 75 },\n * { __FLAT__: false }\n * ],\n * // Arrays of objects are left as objects; empty/null properties are removed\n * scoresDetailed: [\n * { score: 1 },\n * {}, // null score removed\n * { score: 0 },\n * { score: false },\n * {}, // empty string removed\n * ],\n * contact: {\n * address: '123 Main St'\n * }\n * }\n */\nexport const toFormFormat = (fields: Record<string, unknown>) => {\n const formFormatJson = JSON.stringify(fields, (_, value) => {\n if (Array.isArray(value)) {\n // Delegate to toNullishString to ensure consistent handling\n return toNullishString(value);\n }\n\n if (value && typeof value === 'object') {\n // Preserve flat-array wrappers as-is (do not filter their inner values here)\n const record = value as Record<string, unknown>;\n if (flatArrayKey in record) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n }\n return Object.fromEntries(\n Object.entries(value).filter(([_key, v]) => {\n return v !== '' && v !== null;\n }),\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n });\n\n return JSON.parse(formFormatJson) as Record<string, unknown>;\n};\n\n/**\n * Converts form state to a format suitable for validation by:\n * - Unwrapping flat array wrappers `{ __FLAT__: <value> }` back to primitives\n * - Converting legacy string markers (__NULL__, __FALSE__, __ZERO__) back to their original values\n * - Removing fields whose converted value is empty string or null\n * - Removing empty arrays\n *\n * @example\n * const formState = {\n * name: 'John',\n * scores: [\n * { __FLAT__: 75 },\n * { __FLAT__: 0 },\n * { __FLAT__: null },\n * { __FLAT__: false }\n * ],\n * emptyArray: [],\n * scoresDetailed: [\n * { score: 1 },\n * {},\n * { score: 0 },\n * { score: false },\n * {},\n * ],\n * contact: {\n * address: '123 Main St',\n * fax: null\n * }\n * };\n *\n * // Result:\n * {\n * name: 'John',\n * scores: [75, 0, null, false],\n * // emptyArray is removed\n * // Objects inside arrays remain objects; empty entries remain empty objects\n * scoresDetailed: [\n * { score: 1 },\n * {},\n * { score: 0 },\n * { score: false },\n * {},\n * ],\n * contact: {\n * address: '123 Main St'\n * }\n * }\n */\nexport const toValidationFormat = (\n formState: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | null | undefined => {\n // Handle null or undefined input\n if (formState === undefined || formState === null) {\n return formState;\n }\n\n const validationFormatJson = JSON.stringify(formState, (_, value) => {\n if (Array.isArray(value)) {\n return value.map((v) => {\n // Unwrap new wrapper format { __FLAT__: <value> }\n if (v && typeof v === 'object') {\n const record = v as Record<string, unknown>;\n if (flatArrayKey in record) {\n const inner = record[flatArrayKey];\n // Treat empty string from forms as null in validation format\n if (inner === '') {\n return null;\n }\n return fromNullishString(inner);\n }\n }\n // Backward compatibility for string markers\n return fromNullishString(v);\n });\n }\n\n if (value && typeof value === 'object') {\n // Object branch: remove keys that resolve to empty/null after marker conversion\n // and unwrap flat-array wrappers if present.\n //\n // Why this shape?\n // - Forms may contain objects with placeholder/empty values that should not\n // be part of the validation payload (e.g. \"\" or __NULL__ markers).\n // - Arrays of primitives are stored as wrapper objects { __FLAT__: <value> }\n // to satisfy RHF structure constraints. When converting back for\n // validation, we need to treat wrappers whose inner value resolves to\n // empty/null as removable, and unwrap non-empty wrappers to the primitive.\n return Object.fromEntries(\n Object.entries(value)\n .filter(([_key, v]) => {\n // If this is a flat-array wrapper, convert the inner value first and\n // drop the key when the inner resolves to empty string or null.\n if (v && typeof v === 'object') {\n const record = v as Record<string, unknown>;\n if (flatArrayKey in record) {\n const convertedInner = fromNullishString(record[flatArrayKey]);\n return convertedInner !== '' && convertedInner !== null;\n }\n }\n // Drop empty arrays\n if (Array.isArray(v) && v.length === 0) {\n return false;\n }\n // For regular values, convert markers and drop when empty/null.\n const converted = fromNullishString(v);\n return converted !== '' && converted !== null;\n })\n .map(([k, v]) => {\n // Unwrap flat-array wrappers to raw primitives after conversion.\n if (v && typeof v === 'object') {\n const record = v as Record<string, unknown>;\n if (flatArrayKey in record) {\n return [k, fromNullishString(record[flatArrayKey])];\n }\n }\n // For other values, just convert markers.\n return [k, fromNullishString(v)];\n }),\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n });\n\n return JSON.parse(validationFormatJson) as Record<string, unknown>;\n};\n\n/**\n * Helper function to check if a value is an empty object (not an array).\n */\nconst isEmptyObject = (value: unknown): boolean => {\n return (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n Object.keys(value).length === 0\n );\n};\n\n/**\n * Recursively removes empty objects from a data structure.\n * - Filters empty objects from arrays\n * - Removes properties with empty object values\n * - Removes arrays that become empty after filtering\n */\nconst removeEmptyObjects = (obj: unknown): unknown => {\n if (Array.isArray(obj)) {\n // Filter out empty objects from arrays, then recursively process remaining items\n return obj\n .filter((item) => {\n return !isEmptyObject(item);\n })\n .map((item) => {\n return removeEmptyObjects(item);\n });\n }\n\n if (obj !== null && typeof obj === 'object') {\n return Object.fromEntries(\n Object.entries(obj)\n .map(([key, value]) => {\n return [key, removeEmptyObjects(value)] as [string, unknown];\n })\n .filter(([_, processed]) => {\n // Skip empty objects\n if (isEmptyObject(processed)) {\n return false;\n }\n // Skip arrays that are now empty after filtering\n if (Array.isArray(processed) && processed.length === 0) {\n return false;\n }\n return true;\n }),\n );\n }\n\n return obj;\n};\n\n/**\n * Converts form state to a format suitable for submission by:\n * - Applying all transformations from toValidationFormat\n * - Additionally removing empty objects from the result\n * - Filtering empty objects from arrays\n * - Recursively cleaning nested structures\n *\n * **Why separate from toValidationFormat?**\n *\n * Empty objects must be preserved during validation so that custom refinements\n * can run. For example, a FieldCard with \"at least email or phone required\"\n * validation needs the object to exist (even if empty) for the refine to execute.\n *\n * However, for submission, empty objects are meaningless and should be removed\n * to produce clean data for APIs.\n *\n * @example\n * const formState = {\n * name: 'John',\n * contact: {}, // Empty FieldCard - will be removed\n * tags: [{}, {}, {}], // All empty - array will be removed\n * items: [\n * { value: 'a' },\n * {}, // Empty entry - will be filtered out\n * { value: 'b' }\n * ],\n * nested: {\n * deep: {} // Nested empty - will be removed recursively\n * }\n * };\n *\n * // Result:\n * {\n * name: 'John',\n * items: [{ value: 'a' }, { value: 'b' }]\n * }\n */\nexport const toSubmitFormat = (\n formState: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | null | undefined => {\n const validated = toValidationFormat(formState);\n if (!validated) {\n return validated;\n }\n return removeEmptyObjects(validated) as Record<string, unknown>;\n};\n\n/**\n * Converts a field name to a testId by removing flat array key segments and slugifying.\n * Removes all occurrences of `flatArrayKey` from the field name and applies slugify transformation.\n *\n * This is used to generate stable testIds for form fields that don't include\n * the internal `__FLAT__` marker used for flat arrays.\n *\n * @param name - The field name as a string (e.g., 'tags.0.__FLAT__') or array path (e.g., ['tags', '0', '__FLAT__'])\n * @returns The slugified field name with all flat array key segments removed (e.g., 'tags_0')\n *\n * @example\n * ```ts\n * nameToTestId('tags.0.__FLAT__') // => 'tags_0'\n * nameToTestId('array.0.__FLAT__') // => 'array_0'\n * nameToTestId('nested.array.0.__FLAT__.field') // => 'nested_array_0_field'\n * nameToTestId('simple.field') // => 'simple_field'\n * nameToTestId(['tags', '0', '__FLAT__']) // => 'tags_0'\n * ```\n */\nexport const nameToTestId = (name: string | readonly string[]): string => {\n let cleanName: string;\n\n // Handle array paths - filter out flatArrayKey and join with dots\n if (Array.isArray(name)) {\n cleanName = name\n .filter((segment: string) => {\n return segment !== flatArrayKey;\n })\n .join('.');\n } else {\n // Handle string paths - split by dots and filter out flatArrayKey segments\n const segments = (name as string).split('.');\n cleanName = segments\n .filter((segment: string) => {\n return segment !== flatArrayKey;\n })\n .join('.');\n }\n\n // Apply slugify transformation\n return slugify(cleanName, { replaceDots: true });\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,MAAa,8BAGX,YACG;CAEH,MAAM,kBAAkB,IAAI,IAC1B,QACG,QAAQ,WAAW;EAClB,OAAO,OAAO,OAAO,UAAU;CACjC,CAAC,EACA,KAAK,WAAW;EACf,OAAO,OAAO,OAAO,KAAK;CAC5B,CAAC,CACL;CAGA,MAAM,mBAAmB,IAAI,IAC3B,QACG,QAAQ,WAAW;EAClB,OAAO,OAAO,OAAO,UAAU;CACjC,CAAC,EACA,KAAK,WAAW;EACf,OAAO,CAAC,OAAO,OAAO,KAAK,GAAG,OAAO,KAAgB;CACvD,CAAC,CACL;;;;;CAMA,MAAM,yBACJ,QAC8B;EAC9B,MAAM,SAAS,OAAO,GAAG;EACzB,MAAM,eAAe,iBAAiB,IAAI,MAAM;EAChD,IAAI,iBAAiB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AK,KAAK,EAAE,WAAW;AAElC;;;;;;;AAQA,MAAM,sBAAsB,QAA0B;CACpD,IAAI,MAAM,QAAQ,GAAG,GAEnB,OAAO,IACJ,QAAQ,SAAS;EAChB,OAAO,CAAC,cAAc,IAAI;CAC5B,CAAC,EACA,KAAK,SAAS;EACb,OAAO,mBAAmB,IAAI;CAChC,CAAC;CAGL,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UACjC,OAAO,OAAO,YACZ,OAAO,QAAQ,GAAG,EACf,KAAK,CAAC,KAAK,WAAW;EACrB,OAAO,CAAC,KAAK,mBAAmB,KAAK,CAAC;CACxC,CAAC,EACA,QAAQ,CAAC,GAAG,eAAe;EAE1B,IAAI,cAAc,SAAS,GACzB,OAAO;EAGT,IAAI,MAAM,QAAQ,SAAS,KAAK,UAAU,WAAW,GACnD,OAAO;EAET,OAAO;CACT,CAAC,CACL;CAGF,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,kBACX,cAC+C;CAC/C,MAAM,YAAY,mBAAmB,SAAS;CAC9C,IAAI,CAAC,WACH,OAAO;CAET,OAAO,mBAAmB,SAAS;AACrC;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,gBAAgB,SAA6C;CACxE,IAAI;CAGJ,IAAI,MAAM,QAAQ,IAAI,GACpB,YAAY,KACT,QAAQ,YAAoB;EAC3B,OAAO,YAAY;CACrB,CAAC,EACA,KAAK,GAAG;MAIX,YADkB,KAAgB,MAAM,GACrB,EAChB,QAAQ,YAAoB;EAC3B,OAAO,YAAY;CACrB,CAAC,EACA,KAAK,GAAG;CAIb,QAAA,GAAA,uBAAA,SAAe,WAAW,EAAE,aAAa,KAAK,CAAC;AACjD"}
|
package/dist/helpers/index.d.cts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { FieldError } from "react-hook-form";
|
|
2
|
+
|
|
1
3
|
//#region src/helpers/createOptionValueConverter/createOptionValueConverter.d.ts
|
|
2
4
|
/**
|
|
3
5
|
* Creates a converter function that preserves the original type (string, number, or boolean)
|
|
@@ -20,6 +22,18 @@ declare const createOptionValueConverter: <T extends {
|
|
|
20
22
|
numberValueKeys: Set<string>;
|
|
21
23
|
};
|
|
22
24
|
//#endregion
|
|
25
|
+
//#region src/helpers/flattenFieldErrors/flattenFieldErrors.d.ts
|
|
26
|
+
/**
|
|
27
|
+
* Normalize RHF validation payloads to a flat `FieldError[]`.
|
|
28
|
+
*
|
|
29
|
+
* Depending on field shape, RHF may return:
|
|
30
|
+
* - a single `FieldError`
|
|
31
|
+
* - an array of `FieldError`
|
|
32
|
+
* - nested objects keyed by array indices
|
|
33
|
+
* - objects containing `_errors` arrays for array/object-level issues
|
|
34
|
+
*/
|
|
35
|
+
declare const flattenFieldErrors: (error: unknown) => FieldError[];
|
|
36
|
+
//#endregion
|
|
23
37
|
//#region src/helpers/nullishFields/nullishFields.d.ts
|
|
24
38
|
/** Key used to wrap flat array elements when converting to form format */
|
|
25
39
|
declare const flatArrayKey = "__FLAT__";
|
|
@@ -220,5 +234,5 @@ declare const toSubmitFormat: (formState: Record<string, unknown> | null | undef
|
|
|
220
234
|
*/
|
|
221
235
|
declare const nameToTestId: (name: string | readonly string[]) => string;
|
|
222
236
|
//#endregion
|
|
223
|
-
export { createOptionValueConverter, flatArrayKey, fromNullishString, isValueEmpty, nameToTestId, toFormFormat, toNullishString, toSubmitFormat, toValidationFormat };
|
|
237
|
+
export { createOptionValueConverter, flatArrayKey, flattenFieldErrors, fromNullishString, isValueEmpty, nameToTestId, toFormFormat, toNullishString, toSubmitFormat, toValidationFormat };
|
|
224
238
|
//# sourceMappingURL=index.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/helpers/createOptionValueConverter/createOptionValueConverter.ts","../../src/helpers/nullishFields/nullishFields.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/helpers/createOptionValueConverter/createOptionValueConverter.ts","../../src/helpers/flattenFieldErrors/flattenFieldErrors.ts","../../src/helpers/nullishFields/nullishFields.ts"],"mappings":";;;;;;AAeA;;;;;;;;;;cAAa,0BAAA;EACC,KAAA;AAAA,GAEZ,OAAA,EAAS,CAAA;;;;;;;;;AAHX;;;;;;;cCaa,kBAAA,GAAsB,KAAA,cAAiB,UAAU;;;;cCzBjD,YAAA;;AFYb;;;;;;;;;;;;;;;;;;;;;;;ACaA;;;;AAA8D;cCajD,YAAA,GAAgB,KAAc;;;AAtC3C;cAgEa,iBAAA,GAAqB,KAAc;;;AAhEvB;cAsGZ,eAAA,GAAmB,KAAc;;;;AAhEH;AA0B3C;;;;AAAgD;AAsChD;;;;AAA8C;AA6E9C;;;;;;;;AAwB6C;AAmD7C;;;;;;;;AAES;AAuKT;;;;;;;;AAES;AA2BT;;;;AAA6D;;;;;cAjRhD,YAAA,GAAgB,MAAA,EAAQ,MAAA,sBAwBE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAmDhC,kBAAA,GACX,SAAA,EAAW,MAAA,yCACV,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAuKI,cAAA,GACX,SAAA,EAAW,MAAA,yCACV,MAAM;;;;;;;;;;;;;;;;;;;;cA2BI,YAAA,GAAgB,IAAgC"}
|
package/dist/helpers/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { FieldError } from "react-hook-form";
|
|
2
|
+
|
|
1
3
|
//#region src/helpers/createOptionValueConverter/createOptionValueConverter.d.ts
|
|
2
4
|
/**
|
|
3
5
|
* Creates a converter function that preserves the original type (string, number, or boolean)
|
|
@@ -20,6 +22,18 @@ declare const createOptionValueConverter: <T extends {
|
|
|
20
22
|
numberValueKeys: Set<string>;
|
|
21
23
|
};
|
|
22
24
|
//#endregion
|
|
25
|
+
//#region src/helpers/flattenFieldErrors/flattenFieldErrors.d.ts
|
|
26
|
+
/**
|
|
27
|
+
* Normalize RHF validation payloads to a flat `FieldError[]`.
|
|
28
|
+
*
|
|
29
|
+
* Depending on field shape, RHF may return:
|
|
30
|
+
* - a single `FieldError`
|
|
31
|
+
* - an array of `FieldError`
|
|
32
|
+
* - nested objects keyed by array indices
|
|
33
|
+
* - objects containing `_errors` arrays for array/object-level issues
|
|
34
|
+
*/
|
|
35
|
+
declare const flattenFieldErrors: (error: unknown) => FieldError[];
|
|
36
|
+
//#endregion
|
|
23
37
|
//#region src/helpers/nullishFields/nullishFields.d.ts
|
|
24
38
|
/** Key used to wrap flat array elements when converting to form format */
|
|
25
39
|
declare const flatArrayKey = "__FLAT__";
|
|
@@ -220,5 +234,5 @@ declare const toSubmitFormat: (formState: Record<string, unknown> | null | undef
|
|
|
220
234
|
*/
|
|
221
235
|
declare const nameToTestId: (name: string | readonly string[]) => string;
|
|
222
236
|
//#endregion
|
|
223
|
-
export { createOptionValueConverter, flatArrayKey, fromNullishString, isValueEmpty, nameToTestId, toFormFormat, toNullishString, toSubmitFormat, toValidationFormat };
|
|
237
|
+
export { createOptionValueConverter, flatArrayKey, flattenFieldErrors, fromNullishString, isValueEmpty, nameToTestId, toFormFormat, toNullishString, toSubmitFormat, toValidationFormat };
|
|
224
238
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/helpers/createOptionValueConverter/createOptionValueConverter.ts","../../src/helpers/nullishFields/nullishFields.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/helpers/createOptionValueConverter/createOptionValueConverter.ts","../../src/helpers/flattenFieldErrors/flattenFieldErrors.ts","../../src/helpers/nullishFields/nullishFields.ts"],"mappings":";;;;;;AAeA;;;;;;;;;;cAAa,0BAAA;EACC,KAAA;AAAA,GAEZ,OAAA,EAAS,CAAA;;;;;;;;;AAHX;;;;;;;cCaa,kBAAA,GAAsB,KAAA,cAAiB,UAAU;;;;cCzBjD,YAAA;;AFYb;;;;;;;;;;;;;;;;;;;;;;;ACaA;;;;AAA8D;cCajD,YAAA,GAAgB,KAAc;;;AAtC3C;cAgEa,iBAAA,GAAqB,KAAc;;;AAhEvB;cAsGZ,eAAA,GAAmB,KAAc;;;;AAhEH;AA0B3C;;;;AAAgD;AAsChD;;;;AAA8C;AA6E9C;;;;;;;;AAwB6C;AAmD7C;;;;;;;;AAES;AAuKT;;;;;;;;AAES;AA2BT;;;;AAA6D;;;;;cAjRhD,YAAA,GAAgB,MAAA,EAAQ,MAAA,sBAwBE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAmDhC,kBAAA,GACX,SAAA,EAAW,MAAA,yCACV,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAuKI,cAAA,GACX,SAAA,EAAW,MAAA,yCACV,MAAM;;;;;;;;;;;;;;;;;;;;cA2BI,YAAA,GAAgB,IAAgC"}
|
package/dist/helpers/index.js
CHANGED
|
@@ -42,6 +42,38 @@ const createOptionValueConverter = (options) => {
|
|
|
42
42
|
};
|
|
43
43
|
};
|
|
44
44
|
//#endregion
|
|
45
|
+
//#region src/helpers/flattenFieldErrors/flattenFieldErrors.ts
|
|
46
|
+
/**
|
|
47
|
+
* Narrow an unknown value to a react-hook-form `FieldError`.
|
|
48
|
+
*
|
|
49
|
+
* RHF `FieldError` entries carry metadata like `message` and/or `type`,
|
|
50
|
+
* while container nodes (objects keyed by index, `_errors`, etc.) do not.
|
|
51
|
+
* This guard distinguishes leaf errors from nested wrappers.
|
|
52
|
+
*/
|
|
53
|
+
const isFieldError = (error) => {
|
|
54
|
+
return typeof error === "object" && error !== null && ("message" in error || "type" in error);
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Normalize RHF validation payloads to a flat `FieldError[]`.
|
|
58
|
+
*
|
|
59
|
+
* Depending on field shape, RHF may return:
|
|
60
|
+
* - a single `FieldError`
|
|
61
|
+
* - an array of `FieldError`
|
|
62
|
+
* - nested objects keyed by array indices
|
|
63
|
+
* - objects containing `_errors` arrays for array/object-level issues
|
|
64
|
+
*/
|
|
65
|
+
const flattenFieldErrors = (error) => {
|
|
66
|
+
if (!error) return [];
|
|
67
|
+
if (Array.isArray(error)) return error.flatMap((item) => {
|
|
68
|
+
return flattenFieldErrors(item);
|
|
69
|
+
});
|
|
70
|
+
if (isFieldError(error)) return [error];
|
|
71
|
+
if (typeof error === "object") return Object.values(error).flatMap((item) => {
|
|
72
|
+
return flattenFieldErrors(item);
|
|
73
|
+
});
|
|
74
|
+
return [];
|
|
75
|
+
};
|
|
76
|
+
//#endregion
|
|
45
77
|
//#region src/helpers/nullishFields/nullishFields.ts
|
|
46
78
|
/** Key used to wrap flat array elements when converting to form format */
|
|
47
79
|
const flatArrayKey = "__FLAT__";
|
|
@@ -383,6 +415,6 @@ const nameToTestId = (name) => {
|
|
|
383
415
|
return slugify(cleanName, { replaceDots: true });
|
|
384
416
|
};
|
|
385
417
|
//#endregion
|
|
386
|
-
export { createOptionValueConverter, flatArrayKey, fromNullishString, isValueEmpty, nameToTestId, toFormFormat, toNullishString, toSubmitFormat, toValidationFormat };
|
|
418
|
+
export { createOptionValueConverter, flatArrayKey, flattenFieldErrors, fromNullishString, isValueEmpty, nameToTestId, toFormFormat, toNullishString, toSubmitFormat, toValidationFormat };
|
|
387
419
|
|
|
388
420
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["record"],"sources":["../../src/helpers/createOptionValueConverter/createOptionValueConverter.ts","../../src/helpers/nullishFields/nullishFields.ts"],"sourcesContent":["/* eslint-disable import-x/prefer-default-export */\n\n/**\n * Creates a converter function that preserves the original type (string, number, or boolean)\n * of option values when converting from string keys back to their original type.\n *\n * This is useful for radio/select components where the underlying UI library\n * uses string keys internally, but we want to preserve number/boolean values in the form state.\n *\n * @param options - Array of options with a value property that can be string, number, or boolean\n * @returns An object with:\n * - `convertToOriginalType`: Function to convert a string key back to its original type\n * - `numberValueKeys`: Set of string representations of number values (for internal use)\n * - `booleanValueKeys`: Map of string representations to boolean values (for internal use)\n */\nexport const createOptionValueConverter = <\n T extends { value: string | number | boolean },\n>(\n options: T[],\n) => {\n // Create a set of string keys that represent number values\n const numberValueKeys = new Set(\n options\n .filter((option) => {\n return typeof option.value === 'number';\n })\n .map((option) => {\n return String(option.value);\n }),\n );\n\n // Create a map of string keys to boolean values\n const booleanValueKeys = new Map(\n options\n .filter((option) => {\n return typeof option.value === 'boolean';\n })\n .map((option) => {\n return [String(option.value), option.value as boolean];\n }),\n );\n\n /**\n * Converts a string key back to its original type (string, number, or boolean)\n * based on whether the original option value was a number or boolean\n */\n const convertToOriginalType = (\n key: string | number | boolean,\n ): string | number | boolean => {\n const keyStr = String(key);\n const booleanValue = booleanValueKeys.get(keyStr);\n if (booleanValue !== undefined) {\n return booleanValue;\n }\n if (numberValueKeys.has(keyStr)) {\n return Number(keyStr);\n }\n return keyStr;\n };\n\n return {\n booleanValueKeys,\n convertToOriginalType,\n numberValueKeys,\n };\n};\n","import { slugify } from '@fuf-stack/pixel-utils';\n\n/** Key used to wrap flat array elements when converting to form format */\nexport const flatArrayKey = '__FLAT__';\n\n/**\n * String markers used to preserve null, false, and 0 values during JSON processing\n */\nconst nullString = '__NULL__';\nconst falseString = '__FALSE__';\nconst zeroString = '__ZERO__';\n\n/**\n * Checks if a value is considered \"empty\" for validation display purposes.\n *\n * Used by useUniformField to determine when to show validation errors.\n * Empty values don't trigger immediate error display (user must interact first).\n *\n * Handles:\n * - Primitives: null, undefined, ''\n * - Marker strings: __NULL__, __FALSE__, __ZERO__ (converted via fromNullishString)\n * - Empty arrays: []\n * - Objects with all empty values: {a: null, b: ''}\n * - Flat array wrappers: {__FLAT__: null} or {__FLAT__: ''}\n *\n * @param value - The value to check (will be converted via fromNullishString first)\n * @returns true if the value is empty\n *\n * @example\n * isValueEmpty(null) // true\n * isValueEmpty('') // true\n * isValueEmpty('__NULL__') // true (marker string)\n * isValueEmpty([]) // true (empty array)\n * isValueEmpty({a: null}) // true (object with all empty values)\n * isValueEmpty({__FLAT__: null}) // true (flat array wrapper with empty value)\n * isValueEmpty({__FLAT__: ''}) // true\n * isValueEmpty('hello') // false\n * isValueEmpty([1, 2]) // false\n * isValueEmpty({a: 'value'}) // false\n * isValueEmpty({__FLAT__: 'value'}) // false\n */\nexport const isValueEmpty = (value: unknown): boolean => {\n // Convert marker strings first\n const converted = fromNullishString(value);\n\n if (converted === undefined || converted === null || converted === '') {\n return true;\n }\n if (Array.isArray(converted)) {\n return converted.length === 0;\n }\n if (typeof converted === 'object' && converted !== null) {\n const record = converted as Record<string, unknown>;\n // Handle flat array wrapper: { __FLAT__: innerValue }\n if (flatArrayKey in record) {\n return isValueEmpty(record[flatArrayKey]);\n }\n // For objects (e.g., FieldCard), check if all values are null/undefined/empty\n const values = Object.values(record);\n return values.length === 0 || values.every(isValueEmpty);\n }\n return false;\n};\n\n/**\n * Converts marker strings back to their original values when processing arrays\n */\nexport const fromNullishString = (value: unknown): unknown => {\n // Support arrays: unwrap flat wrappers and convert marker strings per entry\n if (Array.isArray(value)) {\n return (value as unknown[]).map((entry) => {\n if (entry && typeof entry === 'object') {\n const record = entry as Record<string, unknown>;\n if (flatArrayKey in record) {\n const inner = record[flatArrayKey];\n // For arrays, treat empty string as null (placeholder input)\n if (inner === '') {\n return null;\n }\n return fromNullishString(inner);\n }\n }\n return fromNullishString(entry);\n });\n }\n\n if (typeof value !== 'string') {\n return value;\n }\n\n switch (value) {\n case nullString:\n return null;\n case falseString:\n return false;\n case zeroString:\n return 0;\n default:\n return value;\n }\n};\n\n/**\n * Converts null/falsy values to marker strings for JSON processing\n */\nexport const toNullishString = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n // Only wrap arrays of primitives; leave arrays of objects as-is\n const isPrimitive = (v: unknown) => {\n return v === null || ['string', 'number', 'boolean'].includes(typeof v);\n };\n const isPrimitiveArray = (value as unknown[]).every(isPrimitive);\n if (isPrimitiveArray) {\n return (value as unknown[]).map((v) => {\n // Store raw primitive; do not convert to marker strings inside the wrapper\n return { [flatArrayKey]: v };\n });\n }\n return value;\n }\n if (value === null || value === '') {\n return nullString;\n }\n if (value === false) {\n return falseString;\n }\n if (value === 0) {\n return zeroString;\n }\n return value;\n};\n\n/**\n * Converts field values to a format suitable for forms by:\n * - Wrapping arrays of primitives as objects using the flatArrayKey `__FLAT__`\n * to satisfy RHF's requirement that array fields contain objects\n * - Removing empty strings and null values from objects\n *\n * This conversion is required because React Hook Form does not support arrays with\n * flat values (string, number, boolean, null). Array fields must contain objects.\n * We work around this by wrapping primitive entries: `{ __FLAT__: <value> }`.\n *\n * @example\n * const fields = {\n * name: 'John',\n * scores: [0, null, 75, false],\n * scoresDetailed: [\n * { score: 1 },\n * { score: null },\n * { score: 0 },\n * { score: false },\n * { score: '' },\n * ],\n * contact: {\n * email: '',\n * phone: null,\n * address: '123 Main St'\n * }\n * };\n *\n * // Result:\n * {\n * name: 'John',\n * scores: [\n * { __FLAT__: 0 },\n * { __FLAT__: null },\n * { __FLAT__: 75 },\n * { __FLAT__: false }\n * ],\n * // Arrays of objects are left as objects; empty/null properties are removed\n * scoresDetailed: [\n * { score: 1 },\n * {}, // null score removed\n * { score: 0 },\n * { score: false },\n * {}, // empty string removed\n * ],\n * contact: {\n * address: '123 Main St'\n * }\n * }\n */\nexport const toFormFormat = (fields: Record<string, unknown>) => {\n const formFormatJson = JSON.stringify(fields, (_, value) => {\n if (Array.isArray(value)) {\n // Delegate to toNullishString to ensure consistent handling\n return toNullishString(value);\n }\n\n if (value && typeof value === 'object') {\n // Preserve flat-array wrappers as-is (do not filter their inner values here)\n const record = value as Record<string, unknown>;\n if (flatArrayKey in record) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n }\n return Object.fromEntries(\n Object.entries(value).filter(([_key, v]) => {\n return v !== '' && v !== null;\n }),\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n });\n\n return JSON.parse(formFormatJson) as Record<string, unknown>;\n};\n\n/**\n * Converts form state to a format suitable for validation by:\n * - Unwrapping flat array wrappers `{ __FLAT__: <value> }` back to primitives\n * - Converting legacy string markers (__NULL__, __FALSE__, __ZERO__) back to their original values\n * - Removing fields whose converted value is empty string or null\n * - Removing empty arrays\n *\n * @example\n * const formState = {\n * name: 'John',\n * scores: [\n * { __FLAT__: 75 },\n * { __FLAT__: 0 },\n * { __FLAT__: null },\n * { __FLAT__: false }\n * ],\n * emptyArray: [],\n * scoresDetailed: [\n * { score: 1 },\n * {},\n * { score: 0 },\n * { score: false },\n * {},\n * ],\n * contact: {\n * address: '123 Main St',\n * fax: null\n * }\n * };\n *\n * // Result:\n * {\n * name: 'John',\n * scores: [75, 0, null, false],\n * // emptyArray is removed\n * // Objects inside arrays remain objects; empty entries remain empty objects\n * scoresDetailed: [\n * { score: 1 },\n * {},\n * { score: 0 },\n * { score: false },\n * {},\n * ],\n * contact: {\n * address: '123 Main St'\n * }\n * }\n */\nexport const toValidationFormat = (\n formState: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | null | undefined => {\n // Handle null or undefined input\n if (formState === undefined || formState === null) {\n return formState;\n }\n\n const validationFormatJson = JSON.stringify(formState, (_, value) => {\n if (Array.isArray(value)) {\n return value.map((v) => {\n // Unwrap new wrapper format { __FLAT__: <value> }\n if (v && typeof v === 'object') {\n const record = v as Record<string, unknown>;\n if (flatArrayKey in record) {\n const inner = record[flatArrayKey];\n // Treat empty string from forms as null in validation format\n if (inner === '') {\n return null;\n }\n return fromNullishString(inner);\n }\n }\n // Backward compatibility for string markers\n return fromNullishString(v);\n });\n }\n\n if (value && typeof value === 'object') {\n // Object branch: remove keys that resolve to empty/null after marker conversion\n // and unwrap flat-array wrappers if present.\n //\n // Why this shape?\n // - Forms may contain objects with placeholder/empty values that should not\n // be part of the validation payload (e.g. \"\" or __NULL__ markers).\n // - Arrays of primitives are stored as wrapper objects { __FLAT__: <value> }\n // to satisfy RHF structure constraints. When converting back for\n // validation, we need to treat wrappers whose inner value resolves to\n // empty/null as removable, and unwrap non-empty wrappers to the primitive.\n return Object.fromEntries(\n Object.entries(value)\n .filter(([_key, v]) => {\n // If this is a flat-array wrapper, convert the inner value first and\n // drop the key when the inner resolves to empty string or null.\n if (v && typeof v === 'object') {\n const record = v as Record<string, unknown>;\n if (flatArrayKey in record) {\n const convertedInner = fromNullishString(record[flatArrayKey]);\n return convertedInner !== '' && convertedInner !== null;\n }\n }\n // Drop empty arrays\n if (Array.isArray(v) && v.length === 0) {\n return false;\n }\n // For regular values, convert markers and drop when empty/null.\n const converted = fromNullishString(v);\n return converted !== '' && converted !== null;\n })\n .map(([k, v]) => {\n // Unwrap flat-array wrappers to raw primitives after conversion.\n if (v && typeof v === 'object') {\n const record = v as Record<string, unknown>;\n if (flatArrayKey in record) {\n return [k, fromNullishString(record[flatArrayKey])];\n }\n }\n // For other values, just convert markers.\n return [k, fromNullishString(v)];\n }),\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n });\n\n return JSON.parse(validationFormatJson) as Record<string, unknown>;\n};\n\n/**\n * Helper function to check if a value is an empty object (not an array).\n */\nconst isEmptyObject = (value: unknown): boolean => {\n return (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n Object.keys(value).length === 0\n );\n};\n\n/**\n * Recursively removes empty objects from a data structure.\n * - Filters empty objects from arrays\n * - Removes properties with empty object values\n * - Removes arrays that become empty after filtering\n */\nconst removeEmptyObjects = (obj: unknown): unknown => {\n if (Array.isArray(obj)) {\n // Filter out empty objects from arrays, then recursively process remaining items\n return obj\n .filter((item) => {\n return !isEmptyObject(item);\n })\n .map((item) => {\n return removeEmptyObjects(item);\n });\n }\n\n if (obj !== null && typeof obj === 'object') {\n return Object.fromEntries(\n Object.entries(obj)\n .map(([key, value]) => {\n return [key, removeEmptyObjects(value)] as [string, unknown];\n })\n .filter(([_, processed]) => {\n // Skip empty objects\n if (isEmptyObject(processed)) {\n return false;\n }\n // Skip arrays that are now empty after filtering\n if (Array.isArray(processed) && processed.length === 0) {\n return false;\n }\n return true;\n }),\n );\n }\n\n return obj;\n};\n\n/**\n * Converts form state to a format suitable for submission by:\n * - Applying all transformations from toValidationFormat\n * - Additionally removing empty objects from the result\n * - Filtering empty objects from arrays\n * - Recursively cleaning nested structures\n *\n * **Why separate from toValidationFormat?**\n *\n * Empty objects must be preserved during validation so that custom refinements\n * can run. For example, a FieldCard with \"at least email or phone required\"\n * validation needs the object to exist (even if empty) for the refine to execute.\n *\n * However, for submission, empty objects are meaningless and should be removed\n * to produce clean data for APIs.\n *\n * @example\n * const formState = {\n * name: 'John',\n * contact: {}, // Empty FieldCard - will be removed\n * tags: [{}, {}, {}], // All empty - array will be removed\n * items: [\n * { value: 'a' },\n * {}, // Empty entry - will be filtered out\n * { value: 'b' }\n * ],\n * nested: {\n * deep: {} // Nested empty - will be removed recursively\n * }\n * };\n *\n * // Result:\n * {\n * name: 'John',\n * items: [{ value: 'a' }, { value: 'b' }]\n * }\n */\nexport const toSubmitFormat = (\n formState: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | null | undefined => {\n const validated = toValidationFormat(formState);\n if (!validated) {\n return validated;\n }\n return removeEmptyObjects(validated) as Record<string, unknown>;\n};\n\n/**\n * Converts a field name to a testId by removing flat array key segments and slugifying.\n * Removes all occurrences of `flatArrayKey` from the field name and applies slugify transformation.\n *\n * This is used to generate stable testIds for form fields that don't include\n * the internal `__FLAT__` marker used for flat arrays.\n *\n * @param name - The field name as a string (e.g., 'tags.0.__FLAT__') or array path (e.g., ['tags', '0', '__FLAT__'])\n * @returns The slugified field name with all flat array key segments removed (e.g., 'tags_0')\n *\n * @example\n * ```ts\n * nameToTestId('tags.0.__FLAT__') // => 'tags_0'\n * nameToTestId('array.0.__FLAT__') // => 'array_0'\n * nameToTestId('nested.array.0.__FLAT__.field') // => 'nested_array_0_field'\n * nameToTestId('simple.field') // => 'simple_field'\n * nameToTestId(['tags', '0', '__FLAT__']) // => 'tags_0'\n * ```\n */\nexport const nameToTestId = (name: string | readonly string[]): string => {\n let cleanName: string;\n\n // Handle array paths - filter out flatArrayKey and join with dots\n if (Array.isArray(name)) {\n cleanName = name\n .filter((segment: string) => {\n return segment !== flatArrayKey;\n })\n .join('.');\n } else {\n // Handle string paths - split by dots and filter out flatArrayKey segments\n const segments = (name as string).split('.');\n cleanName = segments\n .filter((segment: string) => {\n return segment !== flatArrayKey;\n })\n .join('.');\n }\n\n // Apply slugify transformation\n return slugify(cleanName, { replaceDots: true });\n};\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAa,8BAGX,YACG;CAEH,MAAM,kBAAkB,IAAI,IAC1B,QACG,QAAQ,WAAW;EAClB,OAAO,OAAO,OAAO,UAAU;CACjC,CAAC,EACA,KAAK,WAAW;EACf,OAAO,OAAO,OAAO,KAAK;CAC5B,CAAC,CACL;CAGA,MAAM,mBAAmB,IAAI,IAC3B,QACG,QAAQ,WAAW;EAClB,OAAO,OAAO,OAAO,UAAU;CACjC,CAAC,EACA,KAAK,WAAW;EACf,OAAO,CAAC,OAAO,OAAO,KAAK,GAAG,OAAO,KAAgB;CACvD,CAAC,CACL;;;;;CAMA,MAAM,yBACJ,QAC8B;EAC9B,MAAM,SAAS,OAAO,GAAG;EACzB,MAAM,eAAe,iBAAiB,IAAI,MAAM;EAChD,IAAI,iBAAiB,KAAA,GACnB,OAAO;EAET,IAAI,gBAAgB,IAAI,MAAM,GAC5B,OAAO,OAAO,MAAM;EAEtB,OAAO;CACT;CAEA,OAAO;EACL;EACA;EACA;CACF;AACF;;;;AC9DA,MAAa,eAAe;;;;AAK5B,MAAM,aAAa;AACnB,MAAM,cAAc;AACpB,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BnB,MAAa,gBAAgB,UAA4B;CAEvD,MAAM,YAAY,kBAAkB,KAAK;CAEzC,IAAI,cAAc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AI;CAGJ,IAAI,MAAM,QAAQ,IAAI,GACpB,YAAY,KACT,QAAQ,YAAoB;EAC3B,OAAO,YAAY;CACrB,CAAC,EACA,KAAK,GAAG;MAIX,YADkB,KAAgB,MAAM,GACrB,EAChB,QAAQ,YAAoB;EAC3B,OAAO,YAAY;CACrB,CAAC,EACA,KAAK,GAAG;CAIb,OAAO,QAAQ,WAAW,EAAE,aAAa,KAAK,CAAC;AACjD"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["record"],"sources":["../../src/helpers/createOptionValueConverter/createOptionValueConverter.ts","../../src/helpers/flattenFieldErrors/flattenFieldErrors.ts","../../src/helpers/nullishFields/nullishFields.ts"],"sourcesContent":["/* eslint-disable import-x/prefer-default-export */\n\n/**\n * Creates a converter function that preserves the original type (string, number, or boolean)\n * of option values when converting from string keys back to their original type.\n *\n * This is useful for radio/select components where the underlying UI library\n * uses string keys internally, but we want to preserve number/boolean values in the form state.\n *\n * @param options - Array of options with a value property that can be string, number, or boolean\n * @returns An object with:\n * - `convertToOriginalType`: Function to convert a string key back to its original type\n * - `numberValueKeys`: Set of string representations of number values (for internal use)\n * - `booleanValueKeys`: Map of string representations to boolean values (for internal use)\n */\nexport const createOptionValueConverter = <\n T extends { value: string | number | boolean },\n>(\n options: T[],\n) => {\n // Create a set of string keys that represent number values\n const numberValueKeys = new Set(\n options\n .filter((option) => {\n return typeof option.value === 'number';\n })\n .map((option) => {\n return String(option.value);\n }),\n );\n\n // Create a map of string keys to boolean values\n const booleanValueKeys = new Map(\n options\n .filter((option) => {\n return typeof option.value === 'boolean';\n })\n .map((option) => {\n return [String(option.value), option.value as boolean];\n }),\n );\n\n /**\n * Converts a string key back to its original type (string, number, or boolean)\n * based on whether the original option value was a number or boolean\n */\n const convertToOriginalType = (\n key: string | number | boolean,\n ): string | number | boolean => {\n const keyStr = String(key);\n const booleanValue = booleanValueKeys.get(keyStr);\n if (booleanValue !== undefined) {\n return booleanValue;\n }\n if (numberValueKeys.has(keyStr)) {\n return Number(keyStr);\n }\n return keyStr;\n };\n\n return {\n booleanValueKeys,\n convertToOriginalType,\n numberValueKeys,\n };\n};\n","/* eslint-disable import-x/prefer-default-export */\n\nimport type { FieldError } from 'react-hook-form';\n\n/**\n * Narrow an unknown value to a react-hook-form `FieldError`.\n *\n * RHF `FieldError` entries carry metadata like `message` and/or `type`,\n * while container nodes (objects keyed by index, `_errors`, etc.) do not.\n * This guard distinguishes leaf errors from nested wrappers.\n */\nconst isFieldError = (error: unknown): error is FieldError => {\n return (\n typeof error === 'object' &&\n error !== null &&\n ('message' in error || 'type' in error)\n );\n};\n\n/**\n * Normalize RHF validation payloads to a flat `FieldError[]`.\n *\n * Depending on field shape, RHF may return:\n * - a single `FieldError`\n * - an array of `FieldError`\n * - nested objects keyed by array indices\n * - objects containing `_errors` arrays for array/object-level issues\n */\nexport const flattenFieldErrors = (error: unknown): FieldError[] => {\n if (!error) {\n return [];\n }\n\n if (Array.isArray(error)) {\n return error.flatMap((item) => {\n return flattenFieldErrors(item);\n });\n }\n\n if (isFieldError(error)) {\n return [error];\n }\n\n if (typeof error === 'object') {\n return Object.values(error as Record<string, unknown>).flatMap((item) => {\n return flattenFieldErrors(item);\n });\n }\n\n return [];\n};\n","import { slugify } from '@fuf-stack/pixel-utils';\n\n/** Key used to wrap flat array elements when converting to form format */\nexport const flatArrayKey = '__FLAT__';\n\n/**\n * String markers used to preserve null, false, and 0 values during JSON processing\n */\nconst nullString = '__NULL__';\nconst falseString = '__FALSE__';\nconst zeroString = '__ZERO__';\n\n/**\n * Checks if a value is considered \"empty\" for validation display purposes.\n *\n * Used by useUniformField to determine when to show validation errors.\n * Empty values don't trigger immediate error display (user must interact first).\n *\n * Handles:\n * - Primitives: null, undefined, ''\n * - Marker strings: __NULL__, __FALSE__, __ZERO__ (converted via fromNullishString)\n * - Empty arrays: []\n * - Objects with all empty values: {a: null, b: ''}\n * - Flat array wrappers: {__FLAT__: null} or {__FLAT__: ''}\n *\n * @param value - The value to check (will be converted via fromNullishString first)\n * @returns true if the value is empty\n *\n * @example\n * isValueEmpty(null) // true\n * isValueEmpty('') // true\n * isValueEmpty('__NULL__') // true (marker string)\n * isValueEmpty([]) // true (empty array)\n * isValueEmpty({a: null}) // true (object with all empty values)\n * isValueEmpty({__FLAT__: null}) // true (flat array wrapper with empty value)\n * isValueEmpty({__FLAT__: ''}) // true\n * isValueEmpty('hello') // false\n * isValueEmpty([1, 2]) // false\n * isValueEmpty({a: 'value'}) // false\n * isValueEmpty({__FLAT__: 'value'}) // false\n */\nexport const isValueEmpty = (value: unknown): boolean => {\n // Convert marker strings first\n const converted = fromNullishString(value);\n\n if (converted === undefined || converted === null || converted === '') {\n return true;\n }\n if (Array.isArray(converted)) {\n return converted.length === 0;\n }\n if (typeof converted === 'object' && converted !== null) {\n const record = converted as Record<string, unknown>;\n // Handle flat array wrapper: { __FLAT__: innerValue }\n if (flatArrayKey in record) {\n return isValueEmpty(record[flatArrayKey]);\n }\n // For objects (e.g., FieldCard), check if all values are null/undefined/empty\n const values = Object.values(record);\n return values.length === 0 || values.every(isValueEmpty);\n }\n return false;\n};\n\n/**\n * Converts marker strings back to their original values when processing arrays\n */\nexport const fromNullishString = (value: unknown): unknown => {\n // Support arrays: unwrap flat wrappers and convert marker strings per entry\n if (Array.isArray(value)) {\n return (value as unknown[]).map((entry) => {\n if (entry && typeof entry === 'object') {\n const record = entry as Record<string, unknown>;\n if (flatArrayKey in record) {\n const inner = record[flatArrayKey];\n // For arrays, treat empty string as null (placeholder input)\n if (inner === '') {\n return null;\n }\n return fromNullishString(inner);\n }\n }\n return fromNullishString(entry);\n });\n }\n\n if (typeof value !== 'string') {\n return value;\n }\n\n switch (value) {\n case nullString:\n return null;\n case falseString:\n return false;\n case zeroString:\n return 0;\n default:\n return value;\n }\n};\n\n/**\n * Converts null/falsy values to marker strings for JSON processing\n */\nexport const toNullishString = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n // Only wrap arrays of primitives; leave arrays of objects as-is\n const isPrimitive = (v: unknown) => {\n return v === null || ['string', 'number', 'boolean'].includes(typeof v);\n };\n const isPrimitiveArray = (value as unknown[]).every(isPrimitive);\n if (isPrimitiveArray) {\n return (value as unknown[]).map((v) => {\n // Store raw primitive; do not convert to marker strings inside the wrapper\n return { [flatArrayKey]: v };\n });\n }\n return value;\n }\n if (value === null || value === '') {\n return nullString;\n }\n if (value === false) {\n return falseString;\n }\n if (value === 0) {\n return zeroString;\n }\n return value;\n};\n\n/**\n * Converts field values to a format suitable for forms by:\n * - Wrapping arrays of primitives as objects using the flatArrayKey `__FLAT__`\n * to satisfy RHF's requirement that array fields contain objects\n * - Removing empty strings and null values from objects\n *\n * This conversion is required because React Hook Form does not support arrays with\n * flat values (string, number, boolean, null). Array fields must contain objects.\n * We work around this by wrapping primitive entries: `{ __FLAT__: <value> }`.\n *\n * @example\n * const fields = {\n * name: 'John',\n * scores: [0, null, 75, false],\n * scoresDetailed: [\n * { score: 1 },\n * { score: null },\n * { score: 0 },\n * { score: false },\n * { score: '' },\n * ],\n * contact: {\n * email: '',\n * phone: null,\n * address: '123 Main St'\n * }\n * };\n *\n * // Result:\n * {\n * name: 'John',\n * scores: [\n * { __FLAT__: 0 },\n * { __FLAT__: null },\n * { __FLAT__: 75 },\n * { __FLAT__: false }\n * ],\n * // Arrays of objects are left as objects; empty/null properties are removed\n * scoresDetailed: [\n * { score: 1 },\n * {}, // null score removed\n * { score: 0 },\n * { score: false },\n * {}, // empty string removed\n * ],\n * contact: {\n * address: '123 Main St'\n * }\n * }\n */\nexport const toFormFormat = (fields: Record<string, unknown>) => {\n const formFormatJson = JSON.stringify(fields, (_, value) => {\n if (Array.isArray(value)) {\n // Delegate to toNullishString to ensure consistent handling\n return toNullishString(value);\n }\n\n if (value && typeof value === 'object') {\n // Preserve flat-array wrappers as-is (do not filter their inner values here)\n const record = value as Record<string, unknown>;\n if (flatArrayKey in record) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n }\n return Object.fromEntries(\n Object.entries(value).filter(([_key, v]) => {\n return v !== '' && v !== null;\n }),\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n });\n\n return JSON.parse(formFormatJson) as Record<string, unknown>;\n};\n\n/**\n * Converts form state to a format suitable for validation by:\n * - Unwrapping flat array wrappers `{ __FLAT__: <value> }` back to primitives\n * - Converting legacy string markers (__NULL__, __FALSE__, __ZERO__) back to their original values\n * - Removing fields whose converted value is empty string or null\n * - Removing empty arrays\n *\n * @example\n * const formState = {\n * name: 'John',\n * scores: [\n * { __FLAT__: 75 },\n * { __FLAT__: 0 },\n * { __FLAT__: null },\n * { __FLAT__: false }\n * ],\n * emptyArray: [],\n * scoresDetailed: [\n * { score: 1 },\n * {},\n * { score: 0 },\n * { score: false },\n * {},\n * ],\n * contact: {\n * address: '123 Main St',\n * fax: null\n * }\n * };\n *\n * // Result:\n * {\n * name: 'John',\n * scores: [75, 0, null, false],\n * // emptyArray is removed\n * // Objects inside arrays remain objects; empty entries remain empty objects\n * scoresDetailed: [\n * { score: 1 },\n * {},\n * { score: 0 },\n * { score: false },\n * {},\n * ],\n * contact: {\n * address: '123 Main St'\n * }\n * }\n */\nexport const toValidationFormat = (\n formState: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | null | undefined => {\n // Handle null or undefined input\n if (formState === undefined || formState === null) {\n return formState;\n }\n\n const validationFormatJson = JSON.stringify(formState, (_, value) => {\n if (Array.isArray(value)) {\n return value.map((v) => {\n // Unwrap new wrapper format { __FLAT__: <value> }\n if (v && typeof v === 'object') {\n const record = v as Record<string, unknown>;\n if (flatArrayKey in record) {\n const inner = record[flatArrayKey];\n // Treat empty string from forms as null in validation format\n if (inner === '') {\n return null;\n }\n return fromNullishString(inner);\n }\n }\n // Backward compatibility for string markers\n return fromNullishString(v);\n });\n }\n\n if (value && typeof value === 'object') {\n // Object branch: remove keys that resolve to empty/null after marker conversion\n // and unwrap flat-array wrappers if present.\n //\n // Why this shape?\n // - Forms may contain objects with placeholder/empty values that should not\n // be part of the validation payload (e.g. \"\" or __NULL__ markers).\n // - Arrays of primitives are stored as wrapper objects { __FLAT__: <value> }\n // to satisfy RHF structure constraints. When converting back for\n // validation, we need to treat wrappers whose inner value resolves to\n // empty/null as removable, and unwrap non-empty wrappers to the primitive.\n return Object.fromEntries(\n Object.entries(value)\n .filter(([_key, v]) => {\n // If this is a flat-array wrapper, convert the inner value first and\n // drop the key when the inner resolves to empty string or null.\n if (v && typeof v === 'object') {\n const record = v as Record<string, unknown>;\n if (flatArrayKey in record) {\n const convertedInner = fromNullishString(record[flatArrayKey]);\n return convertedInner !== '' && convertedInner !== null;\n }\n }\n // Drop empty arrays\n if (Array.isArray(v) && v.length === 0) {\n return false;\n }\n // For regular values, convert markers and drop when empty/null.\n const converted = fromNullishString(v);\n return converted !== '' && converted !== null;\n })\n .map(([k, v]) => {\n // Unwrap flat-array wrappers to raw primitives after conversion.\n if (v && typeof v === 'object') {\n const record = v as Record<string, unknown>;\n if (flatArrayKey in record) {\n return [k, fromNullishString(record[flatArrayKey])];\n }\n }\n // For other values, just convert markers.\n return [k, fromNullishString(v)];\n }),\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n });\n\n return JSON.parse(validationFormatJson) as Record<string, unknown>;\n};\n\n/**\n * Helper function to check if a value is an empty object (not an array).\n */\nconst isEmptyObject = (value: unknown): boolean => {\n return (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n Object.keys(value).length === 0\n );\n};\n\n/**\n * Recursively removes empty objects from a data structure.\n * - Filters empty objects from arrays\n * - Removes properties with empty object values\n * - Removes arrays that become empty after filtering\n */\nconst removeEmptyObjects = (obj: unknown): unknown => {\n if (Array.isArray(obj)) {\n // Filter out empty objects from arrays, then recursively process remaining items\n return obj\n .filter((item) => {\n return !isEmptyObject(item);\n })\n .map((item) => {\n return removeEmptyObjects(item);\n });\n }\n\n if (obj !== null && typeof obj === 'object') {\n return Object.fromEntries(\n Object.entries(obj)\n .map(([key, value]) => {\n return [key, removeEmptyObjects(value)] as [string, unknown];\n })\n .filter(([_, processed]) => {\n // Skip empty objects\n if (isEmptyObject(processed)) {\n return false;\n }\n // Skip arrays that are now empty after filtering\n if (Array.isArray(processed) && processed.length === 0) {\n return false;\n }\n return true;\n }),\n );\n }\n\n return obj;\n};\n\n/**\n * Converts form state to a format suitable for submission by:\n * - Applying all transformations from toValidationFormat\n * - Additionally removing empty objects from the result\n * - Filtering empty objects from arrays\n * - Recursively cleaning nested structures\n *\n * **Why separate from toValidationFormat?**\n *\n * Empty objects must be preserved during validation so that custom refinements\n * can run. For example, a FieldCard with \"at least email or phone required\"\n * validation needs the object to exist (even if empty) for the refine to execute.\n *\n * However, for submission, empty objects are meaningless and should be removed\n * to produce clean data for APIs.\n *\n * @example\n * const formState = {\n * name: 'John',\n * contact: {}, // Empty FieldCard - will be removed\n * tags: [{}, {}, {}], // All empty - array will be removed\n * items: [\n * { value: 'a' },\n * {}, // Empty entry - will be filtered out\n * { value: 'b' }\n * ],\n * nested: {\n * deep: {} // Nested empty - will be removed recursively\n * }\n * };\n *\n * // Result:\n * {\n * name: 'John',\n * items: [{ value: 'a' }, { value: 'b' }]\n * }\n */\nexport const toSubmitFormat = (\n formState: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | null | undefined => {\n const validated = toValidationFormat(formState);\n if (!validated) {\n return validated;\n }\n return removeEmptyObjects(validated) as Record<string, unknown>;\n};\n\n/**\n * Converts a field name to a testId by removing flat array key segments and slugifying.\n * Removes all occurrences of `flatArrayKey` from the field name and applies slugify transformation.\n *\n * This is used to generate stable testIds for form fields that don't include\n * the internal `__FLAT__` marker used for flat arrays.\n *\n * @param name - The field name as a string (e.g., 'tags.0.__FLAT__') or array path (e.g., ['tags', '0', '__FLAT__'])\n * @returns The slugified field name with all flat array key segments removed (e.g., 'tags_0')\n *\n * @example\n * ```ts\n * nameToTestId('tags.0.__FLAT__') // => 'tags_0'\n * nameToTestId('array.0.__FLAT__') // => 'array_0'\n * nameToTestId('nested.array.0.__FLAT__.field') // => 'nested_array_0_field'\n * nameToTestId('simple.field') // => 'simple_field'\n * nameToTestId(['tags', '0', '__FLAT__']) // => 'tags_0'\n * ```\n */\nexport const nameToTestId = (name: string | readonly string[]): string => {\n let cleanName: string;\n\n // Handle array paths - filter out flatArrayKey and join with dots\n if (Array.isArray(name)) {\n cleanName = name\n .filter((segment: string) => {\n return segment !== flatArrayKey;\n })\n .join('.');\n } else {\n // Handle string paths - split by dots and filter out flatArrayKey segments\n const segments = (name as string).split('.');\n cleanName = segments\n .filter((segment: string) => {\n return segment !== flatArrayKey;\n })\n .join('.');\n }\n\n // Apply slugify transformation\n return slugify(cleanName, { replaceDots: true });\n};\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAa,8BAGX,YACG;CAEH,MAAM,kBAAkB,IAAI,IAC1B,QACG,QAAQ,WAAW;EAClB,OAAO,OAAO,OAAO,UAAU;CACjC,CAAC,EACA,KAAK,WAAW;EACf,OAAO,OAAO,OAAO,KAAK;CAC5B,CAAC,CACL;CAGA,MAAM,mBAAmB,IAAI,IAC3B,QACG,QAAQ,WAAW;EAClB,OAAO,OAAO,OAAO,UAAU;CACjC,CAAC,EACA,KAAK,WAAW;EACf,OAAO,CAAC,OAAO,OAAO,KAAK,GAAG,OAAO,KAAgB;CACvD,CAAC,CACL;;;;;CAMA,MAAM,yBACJ,QAC8B;EAC9B,MAAM,SAAS,OAAO,GAAG;EACzB,MAAM,eAAe,iBAAiB,IAAI,MAAM;EAChD,IAAI,iBAAiB,KAAA,GACnB,OAAO;EAET,IAAI,gBAAgB,IAAI,MAAM,GAC5B,OAAO,OAAO,MAAM;EAEtB,OAAO;CACT;CAEA,OAAO;EACL;EACA;EACA;CACF;AACF;;;;;;;;;;ACtDA,MAAM,gBAAgB,UAAwC;CAC5D,OACE,OAAO,UAAU,YACjB,UAAU,SACT,aAAa,SAAS,UAAU;AAErC;;;;;;;;;;AAWA,MAAa,sBAAsB,UAAiC;CAClE,IA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YACZ,OAAO,QAAQ,GAAG,EACf,KAAK,CAAC,KAAK,WAAW;EACrB,OAAO,CAAC,KAAK,mBAAmB,KAAK,CAAC;CACxC,CAAC,EACA,QAAQ,CAAC,GAAG,eAAe;EAE1B,IAAI,cAAc,SAAS,GACzB,OAAO;EAGT,IAAI,MAAM,QAAQ,SAAS,KAAK,UAAU,WAAW,GACnD,OAAO;EAET,OAAO;CACT,CAAC,CACL;CAGF,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,kBACX,cAC+C;CAC/C,MAAM,YAAY,mBAAmB,SAAS;CAC9C,IAAI,CAAC,WACH,OAAO;CAET,OAAO,mBAAmB,SAAS;AACrC;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,gBAAgB,SAA6C;CACxE,IAAI;CAGJ,IAAI,MAAM,QAAQ,IAAI,GACpB,YAAY,KACT,QAAQ,YAAoB;EAC3B,OAAO,YAAY;CACrB,CAAC,EACA,KAAK,GAAG;MAIX,YADkB,KAAgB,MAAM,GACrB,EAChB,QAAQ,YAAoB;EAC3B,OAAO,YAAY;CACrB,CAAC,EACA,KAAK,GAAG;CAIb,OAAO,QAAQ,WAAW,EAAE,aAAa,KAAK,CAAC;AACjD"}
|
|
@@ -32,7 +32,7 @@ let _heroui_input = require("@heroui/input");
|
|
|
32
32
|
* • Shows errors when field is dirty OR touched OR form has been submitted
|
|
33
33
|
* • Prevents showing errors on pristine/untouched fields for better UX
|
|
34
34
|
* • Works well for all field types (text inputs, checkboxes, radios, arrays)
|
|
35
|
-
* - Prebuilt `errorMessage` React node
|
|
35
|
+
* - Prebuilt `errorMessage` React node (with optional array-error normalization via `isArrayValue`)
|
|
36
36
|
* - Computed `label` node which appends a `FieldCopyTestIdButton` in
|
|
37
37
|
* `debug-testids` mode
|
|
38
38
|
* - `defaultValue` for uncontrolled defaults and all usual field handlers
|
|
@@ -41,9 +41,9 @@ let _heroui_input = require("@heroui/input");
|
|
|
41
41
|
* `getHelperWrapperProps` for consistent wiring to underlying UI components
|
|
42
42
|
*/
|
|
43
43
|
const useUniformField = (params) => {
|
|
44
|
-
const { name, ariaLabel: customAriaLabel, disabled = false, testId: explicitTestId, label, type, transform } = params;
|
|
44
|
+
const { name, ariaLabel: customAriaLabel, disabled = false, isArrayValue = false, testId: explicitTestId, label, type, transform } = params;
|
|
45
45
|
const { control, debugMode, formState: { submitCount }, getFieldState, getValues, resetField } = require_useFormContext.useFormContext();
|
|
46
|
-
const { error, invalid: rawInvalid, isDirty, isTouched, required, testId } = getFieldState(name, explicitTestId);
|
|
46
|
+
const { error: rawError, invalid: rawInvalid, isDirty, isTouched, required, testId } = getFieldState(name, explicitTestId);
|
|
47
47
|
const { field } = require_useController.useController({
|
|
48
48
|
control,
|
|
49
49
|
disabled,
|
|
@@ -87,8 +87,9 @@ const useUniformField = (params) => {
|
|
|
87
87
|
const invalid = (0, _fuf_stack_pixels.useDebounce)(rawInvalid && (isDirty && hasValue || isTouched || submitCount > 0), 200);
|
|
88
88
|
const showTestIdCopyButton = debugMode === "debug-testids";
|
|
89
89
|
const labelNode = !!label || showTestIdCopyButton ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [label !== false ? label : null, showTestIdCopyButton ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_FieldCopyTestIdButton.FieldCopyTestIdButton_default, { testId }) : null] }) : null;
|
|
90
|
+
const error = isArrayValue ? require_helpers_index.flattenFieldErrors(rawError) : rawError;
|
|
90
91
|
const errorMessage = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_FieldValidationError.FieldValidationError_default, {
|
|
91
|
-
error,
|
|
92
|
+
error: require_helpers_index.flattenFieldErrors(rawError),
|
|
92
93
|
testId
|
|
93
94
|
});
|
|
94
95
|
const { getErrorMessageProps, getLabelProps, getHelperWrapperProps } = (0, _heroui_input.useInput)({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["useFormContext","useController","useInputValueTransform","isValueEmpty","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 { 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 /** 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 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 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 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);\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 // 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 // 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6GA,MAAa,mBAIX,WACwC;CACxC,MAAM,EACJ,MACA,WAAW,iBACX,WAAW,OACX,QAAQ,gBACR,OACA,MACA,cACE;CAEJ,MAAM,EACJ,SACA,WACA,WAAW,EAAE,eACb,eACA,WACA,eACEA,uBAAAA,eAA6B;CAEjC,MAAM,EACJ,OACA,SAAS,YACT,SACA,WACA,UACA,WACE,cAAc,MAAM,cAAc;CAEtC,MAAM,EAAE,UAAUC,sBAAAA,cAA4B;EAC5C;EACA;EACA;CACF,CAAC;CACD,MAAM,EACJ,UAAU,eACV,OAAO,YACP,UAAU,YACV,QACA,QACE;CAIJ,MAAM,EAAE,gBAAgB,gBAAgBC,+BAAAA,uBAAiC;EACvE;EACA;CACF,CAAC;CAGD,MAAM,mBAAmB,eAAe,UAAU;CAClD,MAAM,uBAAuB,iBAA+C;EAM1E,cADkB,YAFf,cAAsD,QAAQ,SAC/D,YAEoB,CAAC;CACzB;CAEA,MAAM,eAAgB,UAAU,IAC9B;;;;;;;;;;;;;;;;;;;;;;;;;CA6BF,MAAM,WAAW,CAACC,sBAAAA,aAAa,UAAU;CAIzC,MAAM,WAAA,GAAA,kBAAA,aAFJ,eAAgB,WAAW,YAAa,aAAa,cAAc,IAE5B,GAAG;CAM5C,MAAM,uBAAuB,cAAc;CAC3C,MAAM,YACJ,CAAC,CAAC,SAAS,uBACT,iBAAA,GAAA,kBAAA,MAAA,kBAAA,UAAA,EAAA,UAAA,CACG,UAAU,QAAQ,QAAQ,MAC1B,uBACC,iBAAA,GAAA,kBAAA,KAACC,8BAAAA,+BAAD,EAA+B,OAAS,CAAA,IACtC,IACJ,EAAA,CAAA,IACA;CAIN,MAAM,eAAe,iBAAA,GAAA,kBAAA,KAACC,6BAAAA,8BAAD;EAA6B;EAAe;CAAS,CAAA;CAK1E,MAAM,EAAE,sBAAsB,eAAe,2BAAA,GAAA,cAAA,UAClC;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.cjs","names":["useFormContext","useController","useInputValueTransform","isValueEmpty","FieldCopyTestIdButton","flattenFieldErrors","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,eACEA,uBAAAA,eAA6B;CAEjC,MAAM,EACJ,OAAO,UACP,SAAS,YACT,SACA,WACA,UACA,WACE,cAAc,MAAM,cAAc;CAEtC,MAAM,EAAE,UAAUC,sBAAAA,cAA4B;EAC5C;EACA;EACA;CACF,CAAC;CACD,MAAM,EACJ,UAAU,eACV,OAAO,YACP,UAAU,YACV,QACA,QACE;CAIJ,MAAM,EAAE,gBAAgB,gBAAgBC,+BAAAA,uBAAiC;EACvE;EACA;CACF,CAAC;CAGD,MAAM,mBAAmB,eAAe,UAAU;CAClD,MAAM,uBAAuB,iBAA+C;EAM1E,cADkB,YAFf,cAAsD,QAAQ,SAC/D,YAEoB,CAAC;CACzB;CAEA,MAAM,eAAgB,UAAU,IAC9B;;;;;;;;;;;;;;;;;;;;;;;;;CA6BF,MAAM,WAAW,CAACC,sBAAAA,aAAa,UAAU;CAIzC,MAAM,WAAA,GAAA,kBAAA,aAFJ,eAAgB,WAAW,YAAa,aAAa,cAAc,IAE5B,GAAG;CAM5C,MAAM,uBAAuB,cAAc;CAC3C,MAAM,YACJ,CAAC,CAAC,SAAS,uBACT,iBAAA,GAAA,kBAAA,MAAA,kBAAA,UAAA,EAAA,UAAA,CACG,UAAU,QAAQ,QAAQ,MAC1B,uBACC,iBAAA,GAAA,kBAAA,KAACC,8BAAAA,+BAAD,EAA+B,OAAS,CAAA,IACtC,IACJ,EAAA,CAAA,IACA;CAKN,MAAM,QAAQ,eAAeC,sBAAAA,mBAAmB,QAAQ,IAAI;CAK5D,MAAM,eACJ,iBAAA,GAAA,kBAAA,KAACC,6BAAAA,8BAAD;EAAsB,OALAD,sBAAAA,mBAAmB,QAKE;EAAW;CAAS,CAAA;CAMjE,MAAM,EAAE,sBAAsB,eAAe,2BAAA,GAAA,cAAA,UAClC;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"}
|
|
@@ -13,6 +13,8 @@ interface UseUniformFieldParams<TFieldValues extends FieldValues = FieldValues,
|
|
|
13
13
|
ariaLabel?: string;
|
|
14
14
|
/** Disable the field */
|
|
15
15
|
disabled?: boolean;
|
|
16
|
+
/** Normalize nested RHF errors into a flat array for array-like fields */
|
|
17
|
+
isArrayValue?: boolean;
|
|
16
18
|
/** Optional label content */
|
|
17
19
|
label?: ReactNode;
|
|
18
20
|
/** Optional explicit test id used to build stable test ids */
|
|
@@ -33,7 +35,7 @@ interface UseUniformFieldReturn<TFieldValues extends FieldValues = FieldValues>
|
|
|
33
35
|
defaultValue: unknown;
|
|
34
36
|
/** Whether the field is currently disabled (from RHF) */
|
|
35
37
|
disabled: boolean | undefined;
|
|
36
|
-
/** Validation
|
|
38
|
+
/** Validation errors from form state; flattened only when `isArrayValue` is enabled */
|
|
37
39
|
error: FieldError[] | undefined;
|
|
38
40
|
/** Pre-built errorMessage node to plug into components */
|
|
39
41
|
errorMessage: ReactNode | null;
|
|
@@ -84,7 +86,7 @@ interface UseUniformFieldReturn<TFieldValues extends FieldValues = FieldValues>
|
|
|
84
86
|
* • Shows errors when field is dirty OR touched OR form has been submitted
|
|
85
87
|
* • Prevents showing errors on pristine/untouched fields for better UX
|
|
86
88
|
* • Works well for all field types (text inputs, checkboxes, radios, arrays)
|
|
87
|
-
* - Prebuilt `errorMessage` React node
|
|
89
|
+
* - Prebuilt `errorMessage` React node (with optional array-error normalization via `isArrayValue`)
|
|
88
90
|
* - Computed `label` node which appends a `FieldCopyTestIdButton` in
|
|
89
91
|
* `debug-testids` mode
|
|
90
92
|
* - `defaultValue` for uncontrolled defaults and all usual field handlers
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/hooks/useUniformField/useUniformField.tsx"],"mappings":";;;;;;;;UAgBiB,qBAAA,sBACM,WAAA,GAAc,WAAA;;EAInC,IAAA,EAAM,IAAA,CAAK,YAAA;EALyB;EAOpC,SAAA;EANqB;EAQrB,QAAA;EAJW;EAMX,KAAA,GAAQ,SAAA;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/hooks/useUniformField/useUniformField.tsx"],"mappings":";;;;;;;;UAgBiB,qBAAA,sBACM,WAAA,GAAc,WAAA;;EAInC,IAAA,EAAM,IAAA,CAAK,YAAA;EALyB;EAOpC,S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UniformFieldParams<TFieldValues extends FieldValues = FieldValues,
|
|
|
13
13
|
ariaLabel?: string;
|
|
14
14
|
/** Disable the field */
|
|
15
15
|
disabled?: boolean;
|
|
16
|
+
/** Normalize nested RHF errors into a flat array for array-like fields */
|
|
17
|
+
isArrayValue?: boolean;
|
|
16
18
|
/** Optional label content */
|
|
17
19
|
label?: ReactNode;
|
|
18
20
|
/** Optional explicit test id used to build stable test ids */
|
|
@@ -33,7 +35,7 @@ interface UseUniformFieldReturn<TFieldValues extends FieldValues = FieldValues>
|
|
|
33
35
|
defaultValue: unknown;
|
|
34
36
|
/** Whether the field is currently disabled (from RHF) */
|
|
35
37
|
disabled: boolean | undefined;
|
|
36
|
-
/** Validation
|
|
38
|
+
/** Validation errors from form state; flattened only when `isArrayValue` is enabled */
|
|
37
39
|
error: FieldError[] | undefined;
|
|
38
40
|
/** Pre-built errorMessage node to plug into components */
|
|
39
41
|
errorMessage: ReactNode | null;
|
|
@@ -84,7 +86,7 @@ interface UseUniformFieldReturn<TFieldValues extends FieldValues = FieldValues>
|
|
|
84
86
|
* • Shows errors when field is dirty OR touched OR form has been submitted
|
|
85
87
|
* • Prevents showing errors on pristine/untouched fields for better UX
|
|
86
88
|
* • Works well for all field types (text inputs, checkboxes, radios, arrays)
|
|
87
|
-
* - Prebuilt `errorMessage` React node
|
|
89
|
+
* - Prebuilt `errorMessage` React node (with optional array-error normalization via `isArrayValue`)
|
|
88
90
|
* - Computed `label` node which appends a `FieldCopyTestIdButton` in
|
|
89
91
|
* `debug-testids` mode
|
|
90
92
|
* - `defaultValue` for uncontrolled defaults and all usual field handlers
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/hooks/useUniformField/useUniformField.tsx"],"mappings":";;;;;;;;UAgBiB,qBAAA,sBACM,WAAA,GAAc,WAAA;;EAInC,IAAA,EAAM,IAAA,CAAK,YAAA;EALyB;EAOpC,SAAA;EANqB;EAQrB,QAAA;EAJW;EA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