@fuf-stack/uniform 1.26.1 → 1.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +38 -0
  2. package/dist/Checkboxes/index.d.mts +8 -8
  3. package/dist/Checkboxes/index.d.mts.map +1 -1
  4. package/dist/Checkboxes/index.mjs +2 -1
  5. package/dist/Checkboxes/index.mjs.map +1 -1
  6. package/dist/DatePicker/index.d.mts +12 -12
  7. package/dist/DatePicker/index.d.mts.map +1 -1
  8. package/dist/DatePicker/index.mjs +2 -1
  9. package/dist/DatePicker/index.mjs.map +1 -1
  10. package/dist/FieldArray/index.d.mts +10 -10
  11. package/dist/FieldArray/index.d.mts.map +1 -1
  12. package/dist/FieldArray/index.mjs +3 -5
  13. package/dist/FieldArray/index.mjs.map +1 -1
  14. package/dist/FieldCard/index.d.mts +8 -8
  15. package/dist/FieldCard/index.d.mts.map +1 -1
  16. package/dist/FieldCard/index.mjs +5 -3
  17. package/dist/FieldCard/index.mjs.map +1 -1
  18. package/dist/{FieldCopyTestIdButton-CRJBix9D.mjs → FieldCopyTestIdButton-9xTF-DBW.mjs} +2 -2
  19. package/dist/FieldCopyTestIdButton-9xTF-DBW.mjs.map +1 -0
  20. package/dist/Form/index.d.mts +12 -12
  21. package/dist/Form/index.d.mts.map +1 -1
  22. package/dist/Form/index.mjs +11 -8
  23. package/dist/Form/index.mjs.map +1 -1
  24. package/dist/{FormContext-gHSwOlcy.mjs → FormContext-CB7Glm02.mjs} +213 -14
  25. package/dist/FormContext-CB7Glm02.mjs.map +1 -0
  26. package/dist/FormContext-CsFiNvuJ.d.mts.map +1 -1
  27. package/dist/Input/index.d.mts +20 -16
  28. package/dist/Input/index.d.mts.map +1 -1
  29. package/dist/Input/index.mjs +107 -10
  30. package/dist/Input/index.mjs.map +1 -1
  31. package/dist/RadioBoxes/index.d.mts +22 -22
  32. package/dist/RadioBoxes/index.d.mts.map +1 -1
  33. package/dist/RadioBoxes/index.mjs +5 -3
  34. package/dist/RadioBoxes/index.mjs.map +1 -1
  35. package/dist/RadioTabs/index.d.mts +8 -8
  36. package/dist/RadioTabs/index.d.mts.map +1 -1
  37. package/dist/RadioTabs/index.mjs +3 -2
  38. package/dist/RadioTabs/index.mjs.map +1 -1
  39. package/dist/Radios/index.d.mts +12 -12
  40. package/dist/Radios/index.d.mts.map +1 -1
  41. package/dist/Radios/index.mjs +2 -1
  42. package/dist/Radios/index.mjs.map +1 -1
  43. package/dist/Select/index.d.mts +24 -24
  44. package/dist/Select/index.d.mts.map +1 -1
  45. package/dist/Select/index.mjs +5 -3
  46. package/dist/Select/index.mjs.map +1 -1
  47. package/dist/Slider/index.d.mts +34 -31
  48. package/dist/Slider/index.d.mts.map +1 -1
  49. package/dist/Slider/index.mjs +16 -6
  50. package/dist/Slider/index.mjs.map +1 -1
  51. package/dist/Switch/index.d.mts +12 -12
  52. package/dist/Switch/index.d.mts.map +1 -1
  53. package/dist/Switch/index.mjs +2 -1
  54. package/dist/Switch/index.mjs.map +1 -1
  55. package/dist/SwitchBox/index.d.mts +12 -12
  56. package/dist/SwitchBox/index.d.mts.map +1 -1
  57. package/dist/SwitchBox/index.mjs +3 -2
  58. package/dist/SwitchBox/index.mjs.map +1 -1
  59. package/dist/TextArea/index.mjs +2 -1
  60. package/dist/TextArea/index.mjs.map +1 -1
  61. package/dist/Time/index.d.mts +12 -12
  62. package/dist/Time/index.d.mts.map +1 -1
  63. package/dist/Time/index.mjs +8 -3
  64. package/dist/Time/index.mjs.map +1 -1
  65. package/dist/helpers/index.d.mts +10 -11
  66. package/dist/helpers/index.d.mts.map +1 -1
  67. package/dist/hooks/useClientValidation/index.d.mts +2 -3
  68. package/dist/hooks/useClientValidation/index.d.mts.map +1 -1
  69. package/dist/hooks/useClientValidation/index.mjs +3 -2
  70. package/dist/hooks/useClientValidation/index.mjs.map +1 -1
  71. package/dist/hooks/useController/index.mjs +1 -1
  72. package/dist/hooks/useFormContext/index.d.mts +2 -2
  73. package/dist/hooks/useFormContext/index.mjs +1 -1
  74. package/dist/hooks/useInputValueDebounce/index.d.mts +3 -4
  75. package/dist/hooks/useInputValueDebounce/index.d.mts.map +1 -1
  76. package/dist/hooks/useInputValueDebounce/index.mjs +6 -4
  77. package/dist/hooks/useInputValueDebounce/index.mjs.map +1 -1
  78. package/dist/hooks/useUniformField/index.d.mts +6 -5
  79. package/dist/hooks/useUniformField/index.d.mts.map +1 -1
  80. package/dist/hooks/useUniformField/index.mjs +8 -5
  81. package/dist/hooks/useUniformField/index.mjs.map +1 -1
  82. package/dist/hooks/useUniformFieldArray/index.d.mts +4 -5
  83. package/dist/hooks/useUniformFieldArray/index.d.mts.map +1 -1
  84. package/dist/hooks/useUniformFieldArray/index.mjs +1 -1
  85. package/dist/hooks/useWatchFormReset/index.d.mts +2 -3
  86. package/dist/hooks/useWatchFormReset/index.d.mts.map +1 -1
  87. package/dist/hooks/useWatchFormReset/index.mjs +1 -1
  88. package/dist/hooks/useWatchUserChange/index.d.mts +2 -3
  89. package/dist/hooks/useWatchUserChange/index.d.mts.map +1 -1
  90. package/dist/hooks/useWatchUserChange/index.mjs +25 -13
  91. package/dist/hooks/useWatchUserChange/index.mjs.map +1 -1
  92. package/dist/index-CwJo1b4Z.d.mts +1 -0
  93. package/dist/partials/FieldCopyTestIdButton/index.mjs +1 -1
  94. package/dist/{useController-CK39i6HI.mjs → useController-BBSbeKbn.mjs} +2 -2
  95. package/dist/{useController-CK39i6HI.mjs.map → useController-BBSbeKbn.mjs.map} +1 -1
  96. package/dist/{useFormContext-B3QGVVaO.d.mts → useFormContext-BegmYvGA.d.mts} +3 -3
  97. package/dist/{useFormContext-B3QGVVaO.d.mts.map → useFormContext-BegmYvGA.d.mts.map} +1 -1
  98. package/dist/{useFormContext-Bw4LokAf.mjs → useFormContext-DNb_B8LQ.mjs} +6 -4
  99. package/dist/{useFormContext-Bw4LokAf.mjs.map → useFormContext-DNb_B8LQ.mjs.map} +1 -1
  100. package/package.json +8 -8
  101. package/dist/FieldCopyTestIdButton-CRJBix9D.mjs.map +0 -1
  102. package/dist/FormContext-gHSwOlcy.mjs.map +0 -1
  103. package/dist/index-D5HVU2jP.d.mts +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FormContext-CB7Glm02.mjs","names":["FormProvider","HookFormProvider"],"sources":["../src/Form/subcomponents/SensitiveFields.tsx","../src/Form/subcomponents/FormResolver.ts","../src/Form/subcomponents/FormContext.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport {\n createContext,\n useContext,\n useLayoutEffect,\n useSyncExternalStore,\n} from 'react';\n\n/**\n * Diagnostic redaction for explicitly registered form paths.\n *\n * Flow:\n * 1. FormProvider creates one registry for its form and supplies it through context.\n * 2. useUniformField calls useSensitiveField for declared password inputs and\n * fields marked sensitive. This module does not infer secrets from names,\n * inspect the DOM, or search strings for password-like content.\n * 3. Field layout effects register their paths before the provider marks the\n * initial registry ready. The debug viewer waits for that ready signal.\n * 4. The viewer and Uniform's debug logger redact diagnostic copies using the\n * same registry. JSON copy actions receive the viewer's redacted data too.\n *\n * This is protection against accidental disclosure in Uniform diagnostics,\n * not encryption or a boundary against browser inspection. Real values remain\n * available to inputs, validation, submission, and application callbacks.\n * Application logging and secrets embedded in unrelated paths/custom messages\n * are outside this path-based redaction mechanism.\n */\n\n// A fixed placeholder avoids exposing the secret's content, type, or length.\nconst REDACTED = '[REDACTED]';\n\n/**\n * Build a diagnostic copy with each registered field replaced by [REDACTED].\n *\n * Matching a field masks its entire subtree. For validation errors, that also\n * removes error metadata/messages beneath that field, which may contain input.\n * The source object is never changed: redacting form state itself would corrupt\n * validation and the values ultimately delivered to onSubmit.\n *\n * Paths use React Hook Form dot notation, with numeric bracket indices accepted\n * as well. Normalization removes Uniform's __FLAT__ transport wrapper so the\n * same registration covers raw form data and normalized/submitted array values.\n *\n * Traversal covers arrays and plain objects. Non-data instances such as dates\n * and DOM refs are preserved unless their path or an ancestor is sensitive.\n * This is deliberately not a general-purpose serializer or secret detector.\n *\n * @param data - Form values or errors destined for Uniform diagnostics\n * @param paths - Sensitive field paths registered for this form\n * @returns A diagnostic copy with registered fields replaced, or the unchanged\n * primitive/non-data instance when no traversal is necessary\n */\nexport const redactDebugData = (\n data: unknown,\n paths: readonly string[],\n): unknown => {\n const sensitivePaths = new Set(\n paths.map((path) => {\n return path\n .replace(/\\[(\\d+)\\]/g, '.$1')\n .split('.')\n .filter((part) => {\n return part !== '__FLAT__';\n })\n .join('.');\n }),\n );\n // Track only the current recursion's ancestors. This breaks traversal cycles\n // without reusing a differently redacted copy at another field path.\n const copies = new WeakMap<object, unknown>();\n const visit = (value: unknown, path: string): unknown => {\n // Check before descending or returning an object reference: a sensitive\n // field must be replaced wholesale, even when its value is an object.\n if (sensitivePaths.has(path)) {\n return REDACTED;\n }\n if (!value || typeof value !== 'object') {\n return value;\n }\n const existing = copies.get(value);\n if (existing) {\n return existing;\n }\n if (Array.isArray(value)) {\n const copy: unknown[] = [];\n copies.set(value, copy);\n value.forEach((item, index) => {\n copy[index] = visit(item, path ? `${path}.${index}` : String(index));\n });\n copies.delete(value);\n return copy;\n }\n // Preserve non-data objects, such as dates and refs in non-sensitive errors.\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n return value;\n }\n const copy: Record<string, unknown> = {};\n copies.set(value, copy);\n Object.entries(value as Record<string, unknown>).forEach(([key, entry]) => {\n // Define an own property rather than assigning through __proto__ or any\n // inherited setter when copying arbitrary form-data keys.\n Object.defineProperty(copy, key, {\n value: visit(entry, path ? `${path}.${key}` : key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n });\n // Cache only ancestors for cycle handling: shared objects at other paths\n // need their own redaction pass because sensitivity belongs to the path.\n copies.delete(value);\n return copy;\n };\n return visit(data, '');\n};\n\n/**\n * Create an isolated, append-only sensitivity registry for one form instance.\n *\n * Only field paths and readiness are stored here; the registry does not retain\n * password values. Paths intentionally survive input unmounts, resets, and a\n * later sensitive=false declaration because RHF can retain the original value.\n * A new form instance gets a fresh registry; there is no cross-form path sharing.\n *\n * Snapshot objects stay referentially stable until metadata actually changes.\n * useSyncExternalStore depends on that stability to avoid repeated renders.\n */\nexport const createSensitiveFields = () => {\n let snapshot: { paths: readonly string[]; ready: boolean } = {\n paths: [],\n ready: false,\n };\n const listeners = new Set<() => void>();\n const notify = () => {\n listeners.forEach((listener) => {\n listener();\n });\n };\n return {\n /** Return the current stable metadata snapshot, without reading form values. */\n getSnapshot: () => {\n return snapshot;\n },\n /** Subscribe to metadata changes; cleanup removes the listener, not paths. */\n subscribe: (listener: () => void) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n /** Mark a path once; duplicate registrations and Strict Mode repeats are safe. */\n register: (name: string) => {\n if (snapshot.paths.includes(name)) {\n return;\n }\n // RHF retains values for unmounted fields. Retain their sensitivity for\n // the form's lifetime too, so hiding an input never reveals its secret.\n snapshot = { ...snapshot, paths: [...snapshot.paths, name] };\n notify();\n },\n /** Allow the debug viewer to render after initial field registration finishes. */\n ready: () => {\n if (snapshot.ready) {\n return;\n }\n snapshot = { ...snapshot, ready: true };\n notify();\n },\n /** Use the latest paths for logs, even while the debug viewer is closed. */\n redact: (data: unknown) => {\n return redactDebugData(data, snapshot.paths);\n },\n };\n};\n\ntype SensitiveFields = ReturnType<typeof createSensitiveFields>;\n// An immutable-in-practice empty fallback supports isolated viewer tests and\n// consumers without this provider. useSensitiveField never writes to it, so it\n// cannot leak registrations between unrelated forms or component tests.\nconst defaultSensitiveFields = createSensitiveFields();\ndefaultSensitiveFields.ready();\nconst SensitiveFieldsContext = createContext<SensitiveFields | undefined>(\n undefined,\n);\n\n/**\n * Supply the form-owned registry and release the initial debug-render gate.\n *\n * React runs descendant layout effects before this provider's layout effect,\n * so initially mounted fields register before ready becomes true. The viewer\n * must not render raw values while ready is false, even if debug mode was\n * restored from localStorage before the form's first render.\n */\nexport const SensitiveFieldsProvider = ({\n children,\n registry,\n}: {\n children: ReactNode;\n registry: SensitiveFields;\n}) => {\n // Child layout effects register initial fields before debug data is shown.\n useLayoutEffect(() => {\n registry.ready();\n }, [registry]);\n return (\n <SensitiveFieldsContext.Provider value={registry}>\n {children}\n </SensitiveFieldsContext.Provider>\n );\n};\n\n/**\n * Register a field's sensitivity as declared by its renderer/shared field hook.\n *\n * Registration happens during commit, not render, so abandoned React renders\n * cannot mutate the registry. Layout timing makes new registrations available\n * before paint. Password detection uses the declared input type in\n * useUniformField, so toggling the rendered type to text does not reveal debug\n * values. Once registered, a path is never downgraded within this form instance.\n *\n * @param name - The field path used for form registration\n * @param sensitive - Whether the renderer declares this field sensitive\n */\nexport const useSensitiveField = (name: string, sensitive: boolean) => {\n const registry = useContext(SensitiveFieldsContext);\n useLayoutEffect(() => {\n if (sensitive) {\n registry?.register(name);\n }\n }, [registry, name, sensitive]);\n};\n\n/**\n * Observe sensitivity metadata for rendering diagnostic copies.\n *\n * This subscription contains neither passwords nor RHF's mutable value objects.\n * The debug viewer keeps its existing value subscription and applies these paths\n * when handing values/errors to Json; getValues and onSubmit stay untouched.\n * Callers must honor ready before exposing an initial diagnostic payload.\n */\nexport const useSensitiveDebug = () => {\n const registry = useContext(SensitiveFieldsContext) ?? defaultSensitiveFields;\n // Subscribe only to stable metadata snapshots, not RHF's mutable value objects.\n return useSyncExternalStore(\n registry.subscribe,\n registry.getSnapshot,\n registry.getSnapshot,\n );\n};\n","import type {\n VetoFormattedError,\n VetoInstance,\n VetoTypeAny,\n} from '@fuf-stack/veto';\nimport type { FieldValues } from 'react-hook-form';\n\nimport { useCallback, useMemo, useState } from 'react';\n\nimport { and, veto } from '@fuf-stack/veto';\n\nimport { toValidationFormat } from '../../helpers';\n\n/**\n * Hook that manages client validation schemas state.\n *\n * Provides a centralized way to add/remove dynamic validation schemas\n * that can be combined with base form validation.\n *\n * @returns Object with client validation state and memoized setter function\n */\nexport const useClientValidationManager = () => {\n // Client validation schemas state\n const [clientValidationSchemas, setClientValidationSchemas] = useState<\n Record<string, VetoTypeAny>\n >({});\n\n // Memoized function to set/clear client validation schema\n const setClientValidationSchema = useMemo(() => {\n return (key: string, schema: VetoTypeAny | null) => {\n // update client validation schemas\n setClientValidationSchemas((prev) => {\n // if no schema and no existing client validation schema for this key, do nothing\n if (!prev[key] && !schema) {\n return prev;\n }\n // if no schema, remove the client validation schema for this key\n if (!schema) {\n const { [key]: _removed, ...rest } = prev;\n return rest;\n }\n // if schema, add or update the client validation schema for this key\n return { ...prev, [key]: schema };\n });\n };\n }, []);\n\n return {\n clientValidationSchemas,\n setClientValidationSchema,\n };\n};\n\n/**\n * Hook that creates an extended validation instance combining base Veto validation with dynamic client validation.\n *\n * @param baseValidation - Optional base Veto validation schema\n * @returns Combined validation instance and client schema setter\n */\nexport const useExtendedValidation = (baseValidation?: VetoInstance) => {\n // Setup client validation schemas\n const { clientValidationSchemas, setClientValidationSchema } =\n useClientValidationManager();\n\n // Create a stable dependency array from the client validation schemas\n const clientSchemaValues = useMemo<VetoTypeAny[]>(\n () => {\n const keys = Object.keys(clientValidationSchemas).sort();\n return keys\n .map((key) => {\n return clientValidationSchemas[key];\n })\n .filter((schema): schema is VetoTypeAny => {\n return Boolean(schema);\n });\n },\n // Include the object identity to react to schema instance updates with same shape\n [clientValidationSchemas],\n );\n\n // Memoized extended validation instance\n const extendedValidation = useMemo(\n () => {\n const hasBaseValidation = !!baseValidation;\n const hasClientSchemas = clientSchemaValues.length > 0;\n\n // If no base validation and no client schemas, return undefined\n if (!hasBaseValidation && !hasClientSchemas) {\n return undefined;\n }\n\n // If no client schemas, return base validation\n if (!hasClientSchemas) {\n return baseValidation;\n }\n\n // Combine client validation schemas\n const clientSchemasCombined =\n clientSchemaValues.reduce<VetoTypeAny | null>(\n (combined, clientSchema) => {\n return combined ? and(combined, clientSchema) : clientSchema;\n },\n null,\n );\n\n // return combined validation\n if (baseValidation && clientSchemasCombined) {\n // Put client validation first so dynamic/domain-specific messages\n // are returned before generic base validation errors.\n const baseSchema = baseValidation.schema as VetoTypeAny;\n return veto(and(clientSchemasCombined, baseSchema));\n }\n\n // If we only have client schemas, return them as a veto instance\n if (clientSchemasCombined) {\n return veto(clientSchemasCombined);\n }\n\n // This should not happen due to the conditions above, but just in case\n return baseValidation;\n },\n // Recompute when validation schema instances change\n [baseValidation, clientSchemaValues],\n );\n\n return {\n extendedValidation,\n setClientValidationSchema,\n };\n};\n\n/**\n * Render state for formatted validation errors produced by the resolver.\n *\n * `errors` is the value exposed through Uniform context. `hash` is the stable\n * comparison key used to avoid re-rendering context consumers when validation\n * returns an equivalent error object with a new identity.\n */\ninterface ValidationErrorsState {\n /** Formatted validation errors exposed to Uniform consumers. */\n errors: VetoFormattedError | undefined;\n /** JSON hash of `errors`, used as a cheap equality signal. */\n hash: string | undefined;\n}\n\n/**\n * Creates a React Hook Form resolver from an extended validation instance and\n * stores its latest formatted Veto errors as React state.\n *\n * Keeping the resolver errors in state lets Uniform context consumers re-render\n * when validation output changes, while the hash prevents repeated validations\n * with equivalent errors from causing unnecessary updates.\n *\n * @param extendedValidation - Extended validation instance from useExtendedValidation\n * @returns Resolver function plus the latest validation errors and their hash\n */\nexport const useFormResolver = (extendedValidation?: VetoInstance) => {\n // Keep the latest resolver errors in React state so Uniform context consumers\n // re-render when validation output changes. The paired hash lets us skip the\n // state update when a resolver run returns equivalent errors.\n const [validationErrorsState, setValidationErrorsState] =\n useState<ValidationErrorsState>({\n errors: undefined,\n hash: undefined,\n });\n\n /**\n * Updates resolver error state only when the formatted validation result\n * actually changes. Veto/RHF may create new error objects for equivalent\n * validation output, so the hash is the guard against avoidable context\n * refreshes.\n */\n const updateValidationErrors = useCallback(\n (errors: VetoFormattedError | undefined): void => {\n const nextHash = JSON.stringify(errors);\n\n setValidationErrorsState((current) => {\n if (current.hash === nextHash) {\n return current;\n }\n\n return {\n errors,\n hash: nextHash,\n };\n });\n },\n [],\n );\n\n // Memoized resolver function for React Hook Form\n const resolver = useMemo(() => {\n if (!extendedValidation) {\n return undefined;\n }\n\n return async (values: FieldValues) => {\n const validationValues = toValidationFormat(values) ?? {};\n const result = await extendedValidation.validateAsync(validationValues);\n updateValidationErrors(result.errors ?? undefined);\n\n // Transform veto result to React Hook Form format\n return {\n values: result.data ?? {},\n errors: result.errors ?? {},\n };\n };\n }, [extendedValidation, updateValidationErrors]);\n\n return {\n resolver,\n validationErrors: validationErrorsState.errors,\n validationErrorsHash: validationErrorsState.hash,\n };\n};\n","import type {\n VetoFormattedError,\n VetoInstance,\n VetoTypeAny,\n} from '@fuf-stack/veto';\nimport type { BaseSyntheticEvent, ReactNode } from 'react';\nimport type { FieldValues, Path, SubmitHandler } from 'react-hook-form';\n\nimport React, { useCallback, useMemo, useRef, useState } from 'react';\nimport { FormProvider as HookFormProvider, useForm } from 'react-hook-form';\n\nimport createDebug from 'debug';\n\nimport { useLocalStorage } from '@fuf-stack/pixels';\n\nimport { toFormFormat, toSubmitFormat } from '../../helpers';\nimport { useExtendedValidation, useFormResolver } from './FormResolver';\nimport {\n createSensitiveFields,\n SensitiveFieldsProvider,\n} from './SensitiveFields';\n\nconst debug = createDebug('uniform:FormContext');\n\ntype DebugMode = 'debug' | 'debug-testids' | 'off' | 'disabled';\n\nexport interface DebugModeSettings {\n /** disable form debug completely */\n disable?: boolean;\n /** custom localStorage key to save debug mode state */\n localStorageKey?: string;\n}\n\n/** Listener function that gets called when a form reset is triggered */\nexport type FormResetListener = () => void;\n\n/**\n * Listener function that gets called when a field changes due to user input\n */\nexport type UserChangeListener<TFieldValues extends object = object> = (\n fieldName: Path<TFieldValues>,\n value: unknown,\n) => void;\n\nconst DEBUG_MODE_LOCAL_STORAGE_KEY_DEFAULT = 'uniform:debug-mode';\n\n/**\n * The `UniformContext` provides control over the form's submission behavior and may optionally include\n * a Veto validation schema for form validation.\n *\n * Specifically, this context offers:\n * 1. **Form Submission Control**: The `preventSubmit` function allows components to enable or disable\n * form submissions.\n * 2. **Optional Validation Schema**: The `validation` property may hold a Veto validation schema instance\n * that can be used to validate form fields and handle validation logic.\n * 3. **Client Validation**: The `setClientValidationSchema` function allows setting dynamic client-side\n * validation schemas that complement the base Veto validation.\n * 4. **User Change Tracking**: The `userChange` property provides a pub/sub system for tracking\n * user-initiated field changes (typing, clicking, selecting) - NOT programmatic changes like\n * form.reset() or form.setValue(). Used by the `useWatchUserChange` hook to enable reactive\n * field dependencies.\n * 5. **Form Reset Tracking**: The `formReset` property provides a pub/sub system for tracking\n * programmatic form resets triggered via the wrapped `reset()` from `useFormContext`.\n * Used by hooks like `useWatchFormReset` to run reset-specific normalization logic.\n *\n * This context is useful for components that need to interact with or control the form submission state,\n * or access the validation schema for managing form validation logic.\n *\n * IMPORTANT: Context Singleton Pattern for HMR (Hot Module Replacement)\n * =====================================================================\n *\n * We use a global window variable to ensure only ONE context instance exists across\n * hot module reloads during development. This is critical because:\n *\n * **The Problem:**\n * When using Vite/Storybook with Fast Refresh (HMR), editing this file causes it to\n * be re-evaluated. Each re-evaluation runs `React.createContext()` again, creating a\n * NEW context instance. This leads to \"context instance mismatch\":\n *\n * 1. FormProvider (provider) loads and uses context instance A\n * 2. File is edited, HMR triggers\n * 3. SubmitButton (consumer) hot-reloads and imports context instance B\n * 4. Provider writes to instance A, Consumer reads from instance B\n * 5. Result: Consumer sees default values (triggerSubmit = () => undefined)\n * 6. Clicking submit does nothing because it calls the empty default function\n *\n * **The Solution:**\n * By storing the context in `window.__UNIFORM_CONTEXT__`, we ensure:\n * - First load: Create context and store in window\n * - Subsequent HMRs: Reuse the same context from window\n * - All components always reference the SAME context instance\n * - Provider and consumers can properly communicate\n *\n * **Why This Is Safe:**\n * - Only affects development (production has no HMR)\n * - Context type never changes (same interface)\n * - React handles cleanup on unmount normally\n * - No memory leaks (context is lightweight)\n *\n * Without this pattern, you'd need to restart the dev server after every edit\n * to FormContext.tsx to ensure all components use the same context instance.\n */\n\n// Define the context type\ninterface UniformContextType {\n /** Form debug mode enabled or not */\n debugMode: DebugMode;\n /** settings for form debug mode */\n debugModeSettings?: DebugModeSettings;\n /** Form reset tracking (programmatic reset calls) */\n formReset: {\n /**\n * Subscribe to programmatic form resets.\n * Returns an unsubscribe function.\n */\n subscribe: (listener: FormResetListener) => () => void;\n /**\n * Notify all subscribers about a programmatic form reset.\n * Called from useFormContext when reset() is invoked.\n */\n notify: () => void;\n };\n /** Function to update if the form can currently be submitted */\n preventSubmit: (prevent: boolean) => void;\n /** Setter to enable or disable form debug mode */\n setDebugMode: (debugMode: DebugMode) => void;\n /** Function to trigger form submit programmatically */\n triggerSubmit: (e?: BaseSyntheticEvent) => Promise<void> | void;\n /** User change tracking (user input only, not programmatic changes) */\n userChange: {\n /**\n * Subscribe to user field changes.\n * Returns an unsubscribe function.\n */\n subscribe: (listener: UserChangeListener) => () => void;\n /**\n * Notify all subscribers about a user field change.\n * Called from useController when user interacts with a field.\n */\n notify: (fieldName: string, value: unknown) => void;\n };\n /** Form validation configuration */\n validation: {\n /** Base validation schema instance (without client validation) */\n baseInstance?: VetoInstance;\n /** Veto validation schema instance for form validation */\n instance?: VetoInstance;\n /** Current validation errors in form */\n errors?: VetoFormattedError;\n /** Function to set client validation schema for a specific key */\n setClientValidationSchema: (\n key: string,\n schema: VetoTypeAny | null,\n ) => void;\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nif (!(window as any).__UNIFORM_CONTEXT__) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (window as any).__UNIFORM_CONTEXT__ = React.createContext<UniformContextType>(\n {\n debugMode: 'off',\n formReset: {\n subscribe: () => {\n return () => {\n return undefined;\n };\n },\n notify: () => {\n return undefined;\n },\n },\n preventSubmit: () => {\n return undefined;\n },\n setDebugMode: () => {\n return undefined;\n },\n triggerSubmit: () => {\n return undefined;\n },\n userChange: {\n subscribe: () => {\n return () => {\n return undefined;\n };\n },\n notify: () => {\n return undefined;\n },\n },\n validation: {\n setClientValidationSchema: () => {\n return undefined;\n },\n },\n },\n );\n debug('Creating new UniformContext instance');\n} else {\n debug(\n 'Reusing existing UniformContext instance from window.__UNIFORM_CONTEXT__',\n );\n}\n\n// Export the singleton context instance from window\n// This ensures all imports get the same context, even after HMR\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const UniformContext = (window as any)\n .__UNIFORM_CONTEXT__ as React.Context<UniformContextType>;\n\ndebug('UniformContext exported', {\n contextExists: !!UniformContext,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n windowContextExists: !!(window as any).__UNIFORM_CONTEXT__,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n contextsMatch: UniformContext === (window as any).__UNIFORM_CONTEXT__,\n});\n\n// Define props for the internal FormProvider component\ninterface FormProviderProps {\n /** children form render function */\n children: (childProps: {\n handleSubmit: (e?: BaseSyntheticEvent) => Promise<void>;\n isValid: boolean;\n }) => ReactNode;\n /** settings for form debug mode */\n debugModeSettings?: DebugModeSettings;\n /** initial form values */\n initialValues?: FieldValues;\n /** form submit handler */\n onSubmit: SubmitHandler<FieldValues>;\n /** Veto validation schema instance */\n validation?: VetoInstance;\n /** when the validation should be triggered */\n validationTrigger: 'onChange' | 'onBlur' | 'onSubmit' | 'onTouched' | 'all';\n}\n\n/**\n * FormProvider component provides:\n * - Veto validation schema context\n * - Resolver-backed validation error state\n * - Client validation schema management\n * - Submit handler with automatic data conversion and submission control with preventSubmit\n * - Form Debug Mode state\n * - Form reset pub/sub notifications (`formReset`)\n * - User change pub/sub notifications (`userChange`)\n * - React Hook Form context\n */\nconst FormProvider: React.FC<FormProviderProps> = ({\n children,\n debugModeSettings = undefined,\n initialValues = undefined,\n onSubmit,\n validation: baseValidation = undefined,\n validationTrigger,\n}) => {\n const sensitiveFields = useMemo(() => {\n return createSensitiveFields();\n }, []);\n\n // Form Debug mode state is handled in the form context\n const [debugMode, setDebugMode] = useLocalStorage<DebugMode>(\n debugModeSettings?.localStorageKey ?? DEBUG_MODE_LOCAL_STORAGE_KEY_DEFAULT,\n 'off',\n );\n\n // Create extended validation combining base + client validations\n const { extendedValidation, setClientValidationSchema } =\n useExtendedValidation(baseValidation);\n\n // Create resolver from extended validation + reactive validation error state\n const { resolver, validationErrors, validationErrorsHash } =\n useFormResolver(extendedValidation);\n\n // Initialize react hook form with the resolver\n const methods = useForm({\n defaultValues: initialValues ? toFormFormat(initialValues) : initialValues,\n // set rhf mode\n // see: https://react-hook-form.com/docs/useform#mode\n mode: validationTrigger,\n resolver,\n });\n\n // Get isValid from React Hook Form's formState\n const isValid = methods.formState?.isValid;\n\n // Control if the form can currently be submitted\n const [preventSubmit, setPreventSubmit] = useState(false);\n\n // Form reset listener registry (stored in ref to avoid re-renders)\n const formResetListenersRef = useRef<Set<FormResetListener>>(new Set());\n\n // Subscribe to form reset notifications\n const subscribeFormReset = useCallback(\n (listener: FormResetListener): (() => void) => {\n formResetListenersRef.current.add(listener);\n return () => {\n formResetListenersRef.current.delete(listener);\n };\n },\n [],\n );\n\n // Notify all subscribers about a programmatic form reset\n const notifyFormReset = useCallback((): void => {\n formResetListenersRef.current.forEach((listener) => {\n listener();\n });\n }, []);\n\n // User change listener registry (stored in ref to avoid re-renders)\n const userChangeListenersRef = useRef<Set<UserChangeListener>>(new Set());\n\n // Subscribe to user changes\n const subscribeUserChange = useCallback(\n (listener: UserChangeListener): (() => void) => {\n userChangeListenersRef.current.add(listener);\n // Return cleanup function to unsubscribe\n return () => {\n userChangeListenersRef.current.delete(listener);\n };\n },\n [],\n );\n\n // Notify all subscribers about user change\n const notifyUserChange = useCallback(\n (fieldName: string, value: unknown): void => {\n // Notify all registered listeners\n userChangeListenersRef.current.forEach((listener) => {\n listener(fieldName as Path<object>, value);\n });\n },\n [],\n );\n\n // Create submit handler with automatic data conversion\n // eslint-disable-next-line consistent-return\n const handleSubmit = async (e?: React.BaseSyntheticEvent) => {\n debug('handleSubmit called', {\n preventSubmit,\n formStateIsValid: methods.formState.isValid,\n validationErrors: sensitiveFields.redact(methods.formState.errors),\n validationTrigger,\n formValues: sensitiveFields.redact(methods.getValues()),\n });\n\n // only prevent submit when form state is valid, because otherwise\n // submit will only trigger validation and add errors / focus invalid fields\n if (methods.formState.isValid && preventSubmit) {\n debug('⛔ Form submit PREVENTED', {\n formStateIsValid: methods.formState.isValid,\n preventSubmit,\n });\n console.warn(\n '[FormProvider] form submit was prevented because preventSubmit is true...',\n );\n e?.preventDefault();\n return Promise.resolve();\n }\n\n debug('✓ Form submit ALLOWED', {\n formStateIsValid: methods.formState.isValid,\n preventSubmit,\n reason: !methods.formState.isValid\n ? 'Form is invalid (will trigger validation and show errors)'\n : 'Form is valid and preventSubmit is false',\n });\n\n // Convert form data to submission format:\n // - Unwrap flat array wrappers and convert markers\n // - Remove empty strings, nulls, empty arrays, and empty objects\n const wrappedOnSubmit = (data: FieldValues, event?: BaseSyntheticEvent) => {\n const submitData = toSubmitFormat(data) ?? {};\n debug('onSubmit callback called', {\n submitData: sensitiveFields.redact(submitData),\n });\n return onSubmit(submitData, event);\n };\n\n await methods.handleSubmit(wrappedOnSubmit)(e);\n\n debug('handleSubmit completed');\n };\n\n // Memoize the context value so consumers only re-render when context-relevant\n // state changes, including resolver-backed validation errors.\n const contextValue = useMemo(\n () => {\n return {\n // set debugMode to disabled when debugModeSettings.disable is true\n // otherwise use current debug mode from localStorage\n debugMode: debugModeSettings?.disable ? 'disabled' : debugMode,\n preventSubmit: (prevent: boolean) => {\n debug('preventSubmit called', {\n previousValue: preventSubmit,\n newValue: prevent,\n formStateIsValid: methods.formState.isValid,\n validationErrors: sensitiveFields.redact(methods.formState.errors),\n });\n setPreventSubmit(prevent);\n },\n setClientValidationSchema,\n setDebugMode,\n triggerSubmit: handleSubmit,\n formReset: {\n subscribe: subscribeFormReset,\n notify: notifyFormReset,\n },\n userChange: {\n subscribe: subscribeUserChange,\n notify: notifyUserChange,\n },\n validation: {\n baseInstance: baseValidation,\n instance: extendedValidation,\n errors: validationErrors,\n setClientValidationSchema,\n },\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [debugMode, debugModeSettings?.disable, validationErrorsHash],\n );\n\n return (\n <SensitiveFieldsProvider registry={sensitiveFields}>\n <UniformContext.Provider value={contextValue}>\n {/* Spread all hook form props into HookFormProvider */}\n <HookFormProvider {...methods}>\n {children({ handleSubmit, isValid })}\n </HookFormProvider>\n </UniformContext.Provider>\n </SensitiveFieldsProvider>\n );\n};\n\nexport default FormProvider;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;AAuBjB,MAAa,mBACX,MACA,UACY;CACZ,MAAM,iBAAiB,IAAI,IACzB,MAAM,KAAK,SAAS;EAClB,OAAO,KACJ,QAAQ,cAAc,KAAK,CAAC,CAC5B,MAAM,GAAG,CAAC,CACV,QAAQ,SAAS;GAChB,OAAO,SAAS;EAClB,CAAC,CAAC,CACD,KAAK,GAAG;CACb,CAAC,CACH;CAGA,MAAM,yBAAS,IAAI,QAAyB;CAC5C,MAAM,SAAS,OAAgB,SAA0B;EAGvD,IAAI,eAAe,IAAI,IAAI,GACzB,OAAO;EAET,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B,OAAO;EAET,MAAM,WAAW,OAAO,IAAI,KAAK;EACjC,IAAI,UACF,OAAO;EAET,IAAI,MAAM,QAAQ,KAAK,GAAG;GACxB,MAAM,OAAkB,CAAC;GACzB,OAAO,IAAI,OAAO,IAAI;GACtB,MAAM,SAAS,MAAM,UAAU;IAC7B,KAAK,SAAS,MAAM,MAAM,OAAO,GAAG,KAAK,GAAG,UAAU,OAAO,KAAK,CAAC;GACrE,CAAC;GACD,OAAO,OAAO,KAAK;GACnB,OAAO;EACT;EAEA,MAAM,YAAqB,OAAO,eAAe,KAAK;EACtD,IAAI,cAAc,OAAO,aAAa,cAAc,MAClD,OAAO;EAET,MAAM,OAAgC,CAAC;EACvC,OAAO,IAAI,OAAO,IAAI;EACtB,OAAO,QAAQ,KAAgC,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;GAGzE,OAAO,eAAe,MAAM,KAAK;IA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IACV,WAAW;IACX,QAAQ;GACV;GACA,YAAY;IACV,cAAc;IACd,UAAU;IACV,QAAQ;IACR;GACF;EACF;CACF,GAEA;EAAC;EAAW,mBAAmB;EAAS;CAAoB,CAC9D;CAEA,OACE,oBAAC,yBAAD;EAAyB,UAAU;EACjC,UAAA,oBAAC,eAAe,UAAhB;GAAyB,OAAO;GAE9B,UAAA,oBAACC,cAAD;IAAkB,GAAI;IACnB,UAAA,SAAS;KAAE;KAAc;IAAQ,CAAC;GACnB,CAAA;EACK,CAAA;CACF,CAAA;AAE7B"}
@@ -1 +1 @@
1
- {"version":3,"file":"FormContext-CsFiNvuJ.d.mts","names":[],"sources":["../src/Form/subcomponents/FormContext.tsx"],"mappings":";;;;UAsBiB;;EAEf;;EAEA;;;KAIU;;;;KAKA,mBAAmB,yCAC7B,WAAW,KAAK,eAChB"}
1
+ {"version":3,"file":"FormContext-CsFiNvuJ.d.mts","names":[],"sources":["../src/Form/subcomponents/FormContext.tsx"],"mappings":";;;;UA0BiB;;EAEf;;EAEA;;;KAIU;;;;KAKA,mBAAmB,yCAC7B,WAAW,KAAK,eAChB"}
@@ -632,41 +632,45 @@ declare const inputVariants: ((props?: ({
632
632
  type VariantProps = TVProps<typeof inputVariants>;
633
633
  type ClassName = TVClassName<typeof inputVariants>;
634
634
  interface InputProps extends VariantProps {
635
- /** Custom aria-label for accessibility. If not provided, falls back to field name when no visible label exists */
635
+ /** Overrides the accessible name, otherwise derived from the field name when no visible label exists */
636
636
  ariaLabel?: string;
637
- /** CSS class name */
637
+ /** Applies CSS classes to the input slots */
638
638
  className?: ClassName;
639
- /** shows clear button when input has value */
639
+ /** Shows a clear button when the input has a value */
640
640
  clearable?: boolean;
641
- /** debounce delay in milliseconds for form state updates (default: 300ms) */
641
+ /** Sets the delay in milliseconds before updating form state (default: 300) */
642
642
  debounceDelay?: number;
643
- /** input field is disabled */
643
+ /** Disables the input */
644
644
  disabled?: boolean;
645
- /** added content to the end of the input Field. */
645
+ /** Displays content at the end of the input */
646
646
  endContent?: ReactNode;
647
- /** form field label */
647
+ /** Sets the field label */
648
648
  label?: ReactNode;
649
- /** form field name */
649
+ /** Identifies the field in form state */
650
650
  name: string;
651
- /** callback that is fired when the value is cleared */
651
+ /** Callback invoked when the input value is cleared */
652
652
  onClear?: () => void;
653
- /** form field placeholder */
653
+ /** Sets the placeholder text */
654
654
  placeholder?: string;
655
- /** size of the input */
655
+ /** Redacts the value from Uniform debug output; password inputs are always redacted */
656
+ sensitive?: boolean;
657
+ /** Hides the visibility toggle for password inputs (default: false) */
658
+ hidePasswordToggle?: boolean;
659
+ /** Sets the input size */
656
660
  size?: 'sm' | 'md' | 'lg';
657
- /** content added to the start of the input field */
661
+ /** Displays content at the start of the input */
658
662
  startContent?: ReactNode;
659
- /** HTML data-testid attribute used in e2e tests */
663
+ /** Sets the HTML data-testid attribute for e2e tests */
660
664
  testId?: string;
661
- /** allows disentangled display and form values for a field */
665
+ /** Converts between display and form values */
662
666
  transform?: InputValueTransform<string>;
663
- /** input type */
667
+ /** Sets the input type */
664
668
  type?: 'number' | 'password';
665
669
  }
666
670
  /**
667
671
  * Input component based on [HeroUI Input](https://www.heroui.com//docs/components/input)
668
672
  */
669
- declare const Input: ({ className: _className, clearable, debounceDelay, endContent, name, onClear, placeholder, size, startContent, type, ...uniformFieldProps }: InputProps) => import("react").JSX.Element;
673
+ declare const Input: ({ className: _className, clearable, debounceDelay, endContent, name, onClear, placeholder, hidePasswordToggle, size, startContent, type, ...uniformFieldProps }: InputProps) => import("react").JSX.Element;
670
674
  //#endregion
671
675
  export { type InputProps, Input as default };
672
676
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/Input/Input.tsx"],"mappings":";;;;cAca,iBAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAarB,eAAe,eAAe;KAC9B,YAAY,mBAAmB;UAEnB,mBAAmB;;EAElC;;EAEA,YAAY;;EAEZ;;EAEA;;EAEA;;EAEA,aAAa;;EAEb,QAAQ;;EAER;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,eAAe;;EAEf;;EAEA,YAAY;;EAEZ;;;;;cAMI,UAAS,WAAA,YAAA,WAAA,eAAA,YAAA,MAAA,SAAA,aAAA,oBAAA,MAAA,cAAA,SAAA,qBAaZ,+BAAU,IAAA"}
@@ -1,9 +1,94 @@
1
1
  import { useUniformField } from "../hooks/useUniformField/index.mjs";
2
+ import { useWatchFormReset } from "../hooks/useWatchFormReset/index.mjs";
2
3
  import { useInputValueDebounce } from "../hooks/useInputValueDebounce/index.mjs";
3
- import { tv, variantsToClassNames } from "@fuf-stack/pixel-utils";
4
- import { jsx } from "react/jsx-runtime";
4
+ import { cn, tv, variantsToClassNames } from "@fuf-stack/pixel-utils";
5
+ import { forwardRef, useState } from "react";
6
+ import { jsx, jsxs } from "react/jsx-runtime";
7
+ import { FaEye, FaEyeSlash, FaXmark } from "react-icons/fa6";
5
8
  import { Input } from "@heroui/input";
6
9
  import { NumberInput } from "@heroui/number-input";
10
+ //#region src/Input/InputPassword.tsx
11
+ /** Keeps password presentation separate from form registration and validation. */
12
+ const InputPassword = forwardRef(({ classNames = void 0, clearable, endContent = void 0, isDisabled = false, name, onClear, onKeyDown = void 0, hidePasswordToggle, testId, value, ...inputProps }, ref) => {
13
+ const [isPasswordVisible, setIsPasswordVisible] = useState(false);
14
+ const [previousPasswordField, setPreviousPasswordField] = useState({
15
+ name,
16
+ hidePasswordToggle
17
+ });
18
+ if (previousPasswordField.name !== name || previousPasswordField.hidePasswordToggle !== hidePasswordToggle) {
19
+ setPreviousPasswordField({
20
+ name,
21
+ hidePasswordToggle
22
+ });
23
+ setIsPasswordVisible(false);
24
+ }
25
+ useWatchFormReset({ onReset: () => {
26
+ setIsPasswordVisible(false);
27
+ } });
28
+ const clearValue = () => {
29
+ onClear();
30
+ setIsPasswordVisible(false);
31
+ };
32
+ const passwordEndContent = !hidePasswordToggle ? /* @__PURE__ */ jsxs("span", {
33
+ className: "inline-flex shrink-0 items-center gap-2",
34
+ children: [
35
+ endContent,
36
+ clearable && !!value ? /* @__PURE__ */ jsx("button", {
37
+ "aria-label": "clear input",
38
+ className: cn("rounded-sm p-1 text-default-400 outline-none focus-visible:ring-2 focus-visible:ring-focus", classNames?.clearButton),
39
+ disabled: isDisabled,
40
+ onClick: clearValue,
41
+ onMouseDown: (event) => {
42
+ event.preventDefault();
43
+ },
44
+ type: "button",
45
+ children: /* @__PURE__ */ jsx(FaXmark, { "aria-hidden": "true" })
46
+ }) : null,
47
+ /* @__PURE__ */ jsx("button", {
48
+ "aria-controls": testId,
49
+ "aria-label": isPasswordVisible ? "Hide password" : "Show password",
50
+ "aria-pressed": isPasswordVisible,
51
+ className: "rounded-sm p-1 text-default-400 outline-none focus-visible:ring-2 focus-visible:ring-focus",
52
+ "data-testid": `${testId}_password_toggle`,
53
+ disabled: isDisabled,
54
+ onClick: () => {
55
+ setIsPasswordVisible((visible) => {
56
+ return !visible;
57
+ });
58
+ },
59
+ onMouseDown: (event) => {
60
+ event.preventDefault();
61
+ },
62
+ type: "button",
63
+ children: isPasswordVisible ? /* @__PURE__ */ jsx(FaEyeSlash, { "aria-hidden": "true" }) : /* @__PURE__ */ jsx(FaEye, { "aria-hidden": "true" })
64
+ })
65
+ ]
66
+ }) : endContent;
67
+ const clearableProps = clearable && hidePasswordToggle ? {
68
+ isClearable: true,
69
+ onClear: clearValue
70
+ } : {};
71
+ return /* @__PURE__ */ jsx(Input, {
72
+ ...inputProps,
73
+ ...clearableProps,
74
+ ref,
75
+ classNames,
76
+ endContent: passwordEndContent,
77
+ isDisabled,
78
+ name,
79
+ onKeyDown: !hidePasswordToggle && clearable ? (event) => {
80
+ onKeyDown?.(event);
81
+ if (!event.defaultPrevented && event.key === "Escape" && value && !isDisabled) {
82
+ event.preventDefault();
83
+ clearValue();
84
+ }
85
+ } : onKeyDown,
86
+ type: !hidePasswordToggle && isPasswordVisible ? "text" : "password",
87
+ value
88
+ });
89
+ });
90
+ InputPassword.displayName = "InputPassword";
91
+ //#endregion
7
92
  //#region src/Input/Input.tsx
8
93
  const inputVariants = tv({ slots: {
9
94
  /** wrapper around the whole input */
@@ -18,7 +103,7 @@ const inputVariants = tv({ slots: {
18
103
  /**
19
104
  * Input component based on [HeroUI Input](https://www.heroui.com//docs/components/input)
20
105
  */
21
- const Input$1 = ({ className: _className = void 0, clearable = false, debounceDelay = 300, endContent = void 0, name, onClear = void 0, placeholder = " ", size = void 0, startContent = void 0, type = void 0, ...uniformFieldProps }) => {
106
+ const Input$1 = ({ className: _className = void 0, clearable = false, debounceDelay = 300, endContent = void 0, name, onClear = void 0, placeholder = " ", hidePasswordToggle = false, size = void 0, startContent = void 0, type = void 0, ...uniformFieldProps }) => {
22
107
  const { ariaLabel, disabled, field: { onChange: fieldOnChange, onBlur: fieldOnBlur, value: fieldValue, ref }, errorMessage, invalid, label, required, testId, resetField } = useUniformField({
23
108
  name,
24
109
  type,
@@ -31,14 +116,16 @@ const Input$1 = ({ className: _className = void 0, clearable = false, debounceDe
31
116
  onChange: fieldOnChange,
32
117
  value: fieldValue
33
118
  });
119
+ const clearValue = () => {
120
+ resetField(name, { defaultValue: null });
121
+ onClear?.();
122
+ };
34
123
  const clearableProps = clearable ? {
35
124
  isClearable: true,
36
- onClear: () => {
37
- resetField(name, { defaultValue: null });
38
- if (onClear) onClear();
39
- }
125
+ onClear: clearValue
40
126
  } : {};
41
- const classNames = variantsToClassNames(inputVariants(), _className, "base");
127
+ const variants = inputVariants();
128
+ const classNames = variantsToClassNames(variants, _className, "base");
42
129
  const commonProps = {
43
130
  ref,
44
131
  "aria-label": !placeholder || placeholder.trim() === "" ? ariaLabel : void 0,
@@ -65,13 +152,13 @@ const Input$1 = ({ className: _className = void 0, clearable = false, debounceDe
65
152
  radius: "sm",
66
153
  size,
67
154
  startContent,
68
- variant: "bordered",
69
- ...clearableProps
155
+ variant: "bordered"
70
156
  };
71
157
  if (type === "number") {
72
158
  const numberValue = value !== "" && value != null && !Number.isNaN(Number(value)) ? Number(value) : null;
73
159
  return /* @__PURE__ */ jsx(NumberInput, {
74
160
  ...commonProps,
161
+ ...clearableProps,
75
162
  formatOptions: { useGrouping: false },
76
163
  onChange: (e) => {
77
164
  if (typeof e === "number") onChange({ target: { value: String(e) } });
@@ -80,8 +167,18 @@ const Input$1 = ({ className: _className = void 0, clearable = false, debounceDe
80
167
  value: numberValue
81
168
  });
82
169
  }
170
+ if (type === "password") return /* @__PURE__ */ jsx(InputPassword, {
171
+ ...commonProps,
172
+ clearable,
173
+ hidePasswordToggle,
174
+ onChange,
175
+ onClear: clearValue,
176
+ testId,
177
+ value
178
+ });
83
179
  return /* @__PURE__ */ jsx(Input, {
84
180
  ...commonProps,
181
+ ...clearableProps,
85
182
  onChange,
86
183
  type,
87
184
  value
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["Input","HeroNumberInput","HeroInput","Input"],"sources":["../../src/Input/Input.tsx","../../src/Input/index.ts"],"sourcesContent":["import type { TVClassName, TVProps } from '@fuf-stack/pixel-utils';\nimport type { InputProps as HeroInputProps } from '@heroui/input';\nimport type { ReactNode } from 'react';\nimport type { InputValueTransform } from '../hooks/useInputValueTransform';\n\nimport { Input as HeroInput } from '@heroui/input';\nimport { NumberInput as HeroNumberInput } from '@heroui/number-input';\n\nimport { tv, variantsToClassNames } from '@fuf-stack/pixel-utils';\n\nimport { useInputValueDebounce } from '../hooks/useInputValueDebounce';\nimport { useUniformField } from '../hooks/useUniformField';\n\n// input variants\nexport const inputVariants = tv({\n slots: {\n /** wrapper around the whole input */\n base: '',\n /** clear button */\n clearButton: '',\n /** actual input element */\n input: '',\n /** inner wrapper (HeroUI inputWrapper slot) */\n inputWrapper: 'bg-content1 group-data-[focus=true]:border-focus',\n },\n});\n\ntype VariantProps = TVProps<typeof inputVariants>;\ntype ClassName = TVClassName<typeof inputVariants>;\n\nexport interface InputProps extends VariantProps {\n /** Custom aria-label for accessibility. If not provided, falls back to field name when no visible label exists */\n ariaLabel?: string;\n /** CSS class name */\n className?: ClassName;\n /** shows clear button when input has value */\n clearable?: boolean;\n /** debounce delay in milliseconds for form state updates (default: 300ms) */\n debounceDelay?: number;\n /** input field is disabled */\n disabled?: boolean;\n /** added content to the end of the input Field. */\n endContent?: ReactNode;\n /** form field label */\n label?: ReactNode;\n /** form field name */\n name: string;\n /** callback that is fired when the value is cleared */\n onClear?: () => void;\n /** form field placeholder */\n placeholder?: string;\n /** size of the input */\n size?: 'sm' | 'md' | 'lg';\n /** content added to the start of the input field */\n startContent?: ReactNode;\n /** HTML data-testid attribute used in e2e tests */\n testId?: string;\n /** allows disentangled display and form values for a field */\n transform?: InputValueTransform<string>;\n /** input type */\n type?: 'number' | 'password';\n}\n\n/**\n * Input component based on [HeroUI Input](https://www.heroui.com//docs/components/input)\n */\nconst Input = ({\n className: _className = undefined,\n clearable = false,\n debounceDelay = 300,\n endContent = undefined,\n name,\n onClear = undefined,\n placeholder = ' ',\n size = undefined,\n startContent = undefined,\n type = undefined,\n ...uniformFieldProps\n}: InputProps) => {\n const {\n ariaLabel,\n disabled,\n field: {\n onChange: fieldOnChange,\n onBlur: fieldOnBlur,\n value: fieldValue,\n ref,\n },\n errorMessage,\n invalid,\n label,\n required,\n testId,\n resetField,\n } = useUniformField({ name, type, ...uniformFieldProps });\n\n // Use hook that provides debounced onChange and enhanced blur handling\n const { onChange, onBlur, value } = useInputValueDebounce({\n debounceDelay,\n name,\n onBlur: fieldOnBlur,\n onChange: fieldOnChange,\n value: fieldValue,\n });\n\n // If input is clearable add props for clearing input value\n const clearableProps: Pick<HeroInputProps, 'isClearable' | 'onClear'> =\n clearable\n ? {\n isClearable: true,\n onClear: () => {\n // if field had initial value we do not reset it\n // to that value, but clear it instead\n resetField(name, { defaultValue: null });\n // if onClear cb provided we call it\n if (onClear) {\n onClear();\n }\n },\n }\n : {};\n\n // classNames from slots\n const variants = inputVariants();\n const classNames = variantsToClassNames(variants, _className, 'base');\n\n // Common props for both Input and NumberInput\n const commonProps = {\n ref,\n // Only add aria-label if there's no meaningful placeholder (HeroUI uses placeholder as aria-label)\n 'aria-label':\n !placeholder || placeholder.trim() === '' ? ariaLabel : undefined,\n // disable autocomplete\n autoComplete: 'off',\n classNames: {\n base: classNames.base,\n clearButton: classNames.clearButton,\n // set padding to 0 for error message exit animation\n helperWrapper: 'p-0',\n input: classNames.input,\n inputWrapper: classNames.inputWrapper,\n },\n 'data-testid': testId,\n endContent,\n errorMessage,\n id: testId,\n isDisabled: disabled,\n isInvalid: invalid,\n isRequired: required,\n label,\n labelPlacement: 'outside' as const,\n name,\n onBlur,\n placeholder,\n radius: 'sm' as const,\n size,\n startContent,\n variant: 'bordered' as const,\n ...clearableProps,\n };\n\n // Render NumberInput for number type\n if (type === 'number') {\n // Parse the string value to number - use null for empty/cleared state to keep component controlled\n const numberValue =\n value !== '' && value != null && !Number.isNaN(Number(value))\n ? Number(value)\n : null;\n\n return (\n <HeroNumberInput\n {...commonProps}\n // Disable thousands separator to avoid parsing issues\n formatOptions={{\n useGrouping: false,\n }}\n // NumberInput onChange receives either an event or a number\n onChange={(e: React.ChangeEvent<HTMLInputElement> | number) => {\n if (typeof e === 'number') {\n // Convert number to synthetic event and pass through debounced onChange\n onChange({\n target: { value: String(e) },\n });\n } else {\n // Pass event through debounced onChange\n onChange(e);\n }\n }}\n // @ts-expect-error - HeroUI NumberInput type is not compatible with null,\n // but it needs to be for empty/cleared state to be controlled\n value={numberValue}\n />\n );\n }\n\n // Render regular Input for text/password\n return (\n <HeroInput {...commonProps} onChange={onChange} type={type} value={value} />\n );\n};\n\nexport default Input;\n","import Input from './Input';\n\nexport type { InputProps } from './Input';\n\nexport default Input;\n"],"mappings":";;;;;;;AAcA,MAAa,gBAAgB,GAAG,EAC9B,OAAO;;CAEL,MAAM;;CAEN,aAAa;;CAEb,OAAO;;CAEP,cAAc;AAChB,EACF,CAAC;;;;AAyCD,MAAMA,WAAS,EACb,WAAW,aAAa,KAAA,GACxB,YAAY,OACZ,gBAAgB,KAChB,aAAa,KAAA,GACb,MACA,UAAU,KAAA,GACV,cAAc,KACd,OAAO,KAAA,GACP,eAAe,KAAA,GACf,OAAO,KAAA,GACP,GAAG,wBACa;CAChB,MAAM,EACJ,WACA,UACA,OAAO,EACL,UAAU,eACV,QAAQ,aACR,OAAO,YACP,OAEF,cACA,SACA,OACA,UACA,QACA,eACE,gBAAgB;EAAE;EAAM;EAAM,GAAG;CAAkB,CAAC;CAGxD,MAAM,EAAE,UAAU,QAAQ,UAAU,sBAAsB;EACxD;EACA;EACA,QAAQ;EACR,UAAU;EACV,OAAO;CACT,CAAC;CAGD,MAAM,iBACJ,YACI;EACE,aAAa;EACb,eAAe;GAGb,WAAW,MAAM,EAAE,cAAc,KAAK,CAAC;GAEvC,IAAI,SACF,QAAQ;EAEZ;CACF,IACA,CAAC;CAIP,MAAM,aAAa,qBADF,cAC8B,GAAG,YAAY,MAAM;CAGpE,MAAM,cAAc;EAClB;EAEA,cACE,CAAC,eAAe,YAAY,KAAK,MAAM,KAAK,YAAY,KAAA;EAE1D,cAAc;EACd,YAAY;GACV,MAAM,WAAW;GACjB,aAAa,WAAW;GAExB,eAAe;GACf,OAAO,WAAW;GAClB,cAAc,WAAW;EAC3B;EACA,eAAe;EACf;EACA;EACA,IAAI;EACJ,YAAY;EACZ,WAAW;EACX,YAAY;EACZ;EACA,gBAAgB;EAChB;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA,SAAS;EACT,GAAG;CACL;CAGA,IAAI,SAAS,UAAU;EAErB,MAAM,cACJ,UAAU,MAAM,SAAS,QAAQ,CAAC,OAAO,MAAM,OAAO,KAAK,CAAC,IACxD,OAAO,KAAK,IACZ;EAEN,OACE,oBAACC,aAAD;GACE,GAAI;GAEJ,eAAe,EACb,aAAa,MACf;GAEA,WAAW,MAAoD;IAC7D,IAAI,OAAO,MAAM,UAEf,SAAS,EACP,QAAQ,EAAE,OAAO,OAAO,CAAC,EAAE,EAC7B,CAAC;SAGD,SAAS,CAAC;GAEd;GAGA,OAAO;EACR,CAAA;CAEL;CAGA,OACE,oBAACC,OAAD;EAAW,GAAI;EAAuB;EAAgB;EAAa;CAAQ,CAAA;AAE/E;;;ACnMA,IAAA,gBAAeC"}
1
+ {"version":3,"file":"index.mjs","names":["HeroInput","Input","HeroNumberInput","HeroInput","Input"],"sources":["../../src/Input/InputPassword.tsx","../../src/Input/Input.tsx","../../src/Input/index.ts"],"sourcesContent":["import type { InputProps as HeroInputProps } from '@heroui/input';\n\nimport { forwardRef, useState } from 'react';\nimport { FaEye, FaEyeSlash, FaXmark } from 'react-icons/fa6';\n\nimport { Input as HeroInput } from '@heroui/input';\n\nimport { cn } from '@fuf-stack/pixel-utils';\n\nimport { useWatchFormReset } from '../hooks/useWatchFormReset';\n\ninterface InputPasswordProps extends Omit<\n HeroInputProps,\n 'type' | 'value' | 'name' | 'isClearable' | 'onClear'\n> {\n clearable: boolean;\n name: string;\n onClear: () => void;\n hidePasswordToggle: boolean;\n testId: string;\n value: string;\n}\n\n/** Keeps password presentation separate from form registration and validation. */\nconst InputPassword = forwardRef<HTMLInputElement, InputPasswordProps>(\n (\n {\n classNames = undefined,\n clearable,\n endContent = undefined,\n isDisabled = false,\n name,\n onClear,\n onKeyDown = undefined,\n hidePasswordToggle,\n testId,\n value,\n ...inputProps\n },\n ref,\n ) => {\n const [isPasswordVisible, setIsPasswordVisible] = useState(false);\n\n // Reset visibility before rendering a reused field with new props.\n // Switching away from type=password unmounts this component altogether.\n const [previousPasswordField, setPreviousPasswordField] = useState({\n name,\n hidePasswordToggle,\n });\n if (\n previousPasswordField.name !== name ||\n previousPasswordField.hidePasswordToggle !== hidePasswordToggle\n ) {\n setPreviousPasswordField({ name, hidePasswordToggle });\n setIsPasswordVisible(false);\n }\n useWatchFormReset({\n onReset: () => {\n setIsPasswordVisible(false);\n },\n });\n\n const clearValue = () => {\n onClear();\n setIsPasswordVisible(false);\n };\n\n // HeroUI wraps endContent inside its clear button. Keep clear and reveal as\n // sibling buttons so custom content and the toggle never become nested buttons.\n const passwordEndContent = !hidePasswordToggle ? (\n <span className=\"inline-flex shrink-0 items-center gap-2\">\n {endContent}\n {clearable && !!value ? (\n <button\n aria-label=\"clear input\"\n className={cn(\n 'rounded-sm p-1 text-default-400 outline-none focus-visible:ring-2 focus-visible:ring-focus',\n classNames?.clearButton,\n )}\n disabled={isDisabled}\n onClick={clearValue}\n onMouseDown={(event) => {\n event.preventDefault();\n }}\n type=\"button\"\n >\n <FaXmark aria-hidden=\"true\" />\n </button>\n ) : null}\n <button\n aria-controls={testId}\n aria-label={isPasswordVisible ? 'Hide password' : 'Show password'}\n aria-pressed={isPasswordVisible}\n className=\"rounded-sm p-1 text-default-400 outline-none focus-visible:ring-2 focus-visible:ring-focus\"\n data-testid={`${testId}_password_toggle`}\n disabled={isDisabled}\n onClick={() => {\n setIsPasswordVisible((visible) => {\n return !visible;\n });\n }}\n // Preserve input focus for pointer activation and normal keyboard focus.\n onMouseDown={(event) => {\n event.preventDefault();\n }}\n type=\"button\"\n >\n {isPasswordVisible ? (\n <FaEyeSlash aria-hidden=\"true\" />\n ) : (\n <FaEye aria-hidden=\"true\" />\n )}\n </button>\n </span>\n ) : (\n endContent\n );\n\n const clearableProps: Pick<HeroInputProps, 'isClearable' | 'onClear'> =\n clearable && hidePasswordToggle\n ? { isClearable: true, onClear: clearValue }\n : {};\n\n return (\n <HeroInput\n {...inputProps}\n {...clearableProps}\n ref={ref}\n classNames={classNames}\n endContent={passwordEndContent}\n isDisabled={isDisabled}\n name={name}\n onKeyDown={\n !hidePasswordToggle && clearable\n ? (event) => {\n onKeyDown?.(event);\n if (\n !event.defaultPrevented &&\n event.key === 'Escape' &&\n value &&\n !isDisabled\n ) {\n event.preventDefault();\n clearValue();\n }\n }\n : onKeyDown\n }\n type={!hidePasswordToggle && isPasswordVisible ? 'text' : 'password'}\n value={value}\n />\n );\n },\n);\n\nInputPassword.displayName = 'InputPassword';\n\nexport default InputPassword;\n","import type { TVClassName, TVProps } from '@fuf-stack/pixel-utils';\nimport type { InputProps as HeroInputProps } from '@heroui/input';\nimport type { ReactNode } from 'react';\nimport type { InputValueTransform } from '../hooks/useInputValueTransform';\n\nimport { Input as HeroInput } from '@heroui/input';\nimport { NumberInput as HeroNumberInput } from '@heroui/number-input';\n\nimport { tv, variantsToClassNames } from '@fuf-stack/pixel-utils';\n\nimport { useInputValueDebounce } from '../hooks/useInputValueDebounce';\nimport { useUniformField } from '../hooks/useUniformField';\nimport InputPassword from './InputPassword';\n\n// input variants\nexport const inputVariants = tv({\n slots: {\n /** wrapper around the whole input */\n base: '',\n /** clear button */\n clearButton: '',\n /** actual input element */\n input: '',\n /** inner wrapper (HeroUI inputWrapper slot) */\n inputWrapper: 'bg-content1 group-data-[focus=true]:border-focus',\n },\n});\n\ntype VariantProps = TVProps<typeof inputVariants>;\ntype ClassName = TVClassName<typeof inputVariants>;\n\nexport interface InputProps extends VariantProps {\n /** Overrides the accessible name, otherwise derived from the field name when no visible label exists */\n ariaLabel?: string;\n /** Applies CSS classes to the input slots */\n className?: ClassName;\n /** Shows a clear button when the input has a value */\n clearable?: boolean;\n /** Sets the delay in milliseconds before updating form state (default: 300) */\n debounceDelay?: number;\n /** Disables the input */\n disabled?: boolean;\n /** Displays content at the end of the input */\n endContent?: ReactNode;\n /** Sets the field label */\n label?: ReactNode;\n /** Identifies the field in form state */\n name: string;\n /** Callback invoked when the input value is cleared */\n onClear?: () => void;\n /** Sets the placeholder text */\n placeholder?: string;\n /** Redacts the value from Uniform debug output; password inputs are always redacted */\n sensitive?: boolean;\n /** Hides the visibility toggle for password inputs (default: false) */\n hidePasswordToggle?: boolean;\n /** Sets the input size */\n size?: 'sm' | 'md' | 'lg';\n /** Displays content at the start of the input */\n startContent?: ReactNode;\n /** Sets the HTML data-testid attribute for e2e tests */\n testId?: string;\n /** Converts between display and form values */\n transform?: InputValueTransform<string>;\n /** Sets the input type */\n type?: 'number' | 'password';\n}\n\n/**\n * Input component based on [HeroUI Input](https://www.heroui.com//docs/components/input)\n */\nconst Input = ({\n className: _className = undefined,\n clearable = false,\n debounceDelay = 300,\n endContent = undefined,\n name,\n onClear = undefined,\n placeholder = ' ',\n hidePasswordToggle = false,\n size = undefined,\n startContent = undefined,\n type = undefined,\n ...uniformFieldProps\n}: InputProps) => {\n const {\n ariaLabel,\n disabled,\n field: {\n onChange: fieldOnChange,\n onBlur: fieldOnBlur,\n value: fieldValue,\n ref,\n },\n errorMessage,\n invalid,\n label,\n required,\n testId,\n resetField,\n } = useUniformField({ name, type, ...uniformFieldProps });\n\n // Use hook that provides debounced onChange and enhanced blur handling\n const { onChange, onBlur, value } = useInputValueDebounce({\n debounceDelay,\n name,\n onBlur: fieldOnBlur,\n onChange: fieldOnChange,\n value: fieldValue,\n });\n\n const clearValue = () => {\n // Clear initial values too, rather than restoring the default value.\n resetField(name, { defaultValue: null });\n onClear?.();\n };\n\n const clearableProps: Pick<HeroInputProps, 'isClearable' | 'onClear'> =\n clearable ? { isClearable: true, onClear: clearValue } : {};\n\n const variants = inputVariants();\n const classNames = variantsToClassNames(variants, _className, 'base');\n\n // Common props for both Input and NumberInput\n const commonProps = {\n ref,\n // Only add aria-label if there's no meaningful placeholder (HeroUI uses placeholder as aria-label)\n 'aria-label':\n !placeholder || placeholder.trim() === '' ? ariaLabel : undefined,\n // disable autocomplete\n autoComplete: 'off',\n classNames: {\n base: classNames.base,\n clearButton: classNames.clearButton,\n // set padding to 0 for error message exit animation\n helperWrapper: 'p-0',\n input: classNames.input,\n inputWrapper: classNames.inputWrapper,\n },\n 'data-testid': testId,\n endContent,\n errorMessage,\n id: testId,\n isDisabled: disabled,\n isInvalid: invalid,\n isRequired: required,\n label,\n labelPlacement: 'outside' as const,\n name,\n onBlur,\n placeholder,\n radius: 'sm' as const,\n size,\n startContent,\n variant: 'bordered' as const,\n };\n\n // Render NumberInput for number type\n if (type === 'number') {\n // Parse the string value to number - use null for empty/cleared state to keep component controlled\n const numberValue =\n value !== '' && value != null && !Number.isNaN(Number(value))\n ? Number(value)\n : null;\n\n return (\n <HeroNumberInput\n {...commonProps}\n {...clearableProps}\n // Disable thousands separator to avoid parsing issues\n formatOptions={{\n useGrouping: false,\n }}\n // NumberInput onChange receives either an event or a number\n onChange={(e: React.ChangeEvent<HTMLInputElement> | number) => {\n if (typeof e === 'number') {\n // Convert number to synthetic event and pass through debounced onChange\n onChange({\n target: { value: String(e) },\n });\n } else {\n // Pass event through debounced onChange\n onChange(e);\n }\n }}\n // @ts-expect-error - HeroUI NumberInput type is not compatible with null,\n // but it needs to be for empty/cleared state to be controlled\n value={numberValue}\n />\n );\n }\n\n if (type === 'password') {\n return (\n <InputPassword\n {...commonProps}\n clearable={clearable}\n hidePasswordToggle={hidePasswordToggle}\n onChange={onChange}\n onClear={clearValue}\n testId={testId}\n value={value}\n />\n );\n }\n\n return (\n <HeroInput\n {...commonProps}\n {...clearableProps}\n onChange={onChange}\n type={type}\n value={value}\n />\n );\n};\n\nexport default Input;\n","import Input from './Input';\n\nexport type { InputProps } from './Input';\n\nexport default Input;\n"],"mappings":";;;;;;;;;;;AAwBA,MAAM,gBAAgB,YAElB,EACE,aAAa,KAAA,GACb,WACA,aAAa,KAAA,GACb,aAAa,OACb,MACA,SACA,YAAY,KAAA,GACZ,oBACA,QACA,OACA,GAAG,cAEL,QACG;CACH,MAAM,CAAC,mBAAmB,wBAAwB,SAAS,KAAK;CAIhE,MAAM,CAAC,uBAAuB,4BAA4B,SAAS;EACjE;EACA;CACF,CAAC;CACD,IACE,sBAAsB,SAAS,QAC/B,sBAAsB,uBAAuB,oBAC7C;EACA,yBAAyB;GAAE;GAAM;EAAmB,CAAC;EACrD,qBAAqB,KAAK;CAC5B;CACA,kBAAkB,EAChB,eAAe;EACb,qBAAqB,KAAK;CAC5B,EACF,CAAC;CAED,MAAM,mBAAmB;EACvB,QAAQ;EACR,qBAAqB,KAAK;CAC5B;CAIA,MAAM,qBAAqB,CAAC,qBAC1B,qBAAC,QAAD;EAAM,WAAU;EAAhB,UAAA;GACG;GACA,aAAa,CAAC,CAAC,QACd,oBAAC,UAAD;IACE,cAAW;IACX,WAAW,GACT,8FACA,YAAY,WACd;IACA,UAAU;IACV,SAAS;IACT,cAAc,UAAU;KACtB,MAAM,eAAe;IACvB;IACA,MAAK;IAEL,UAAA,oBAAC,SAAD,EAAS,eAAY,OAAQ,CAAA;GACvB,CAAA,IACN;GACJ,oBAAC,UAAD;IACE,iBAAe;IACf,cAAY,oBAAoB,kBAAkB;IAClD,gBAAc;IACd,WAAU;IACV,eAAa,GAAG,OAAO;IACvB,UAAU;IACV,eAAe;KACb,sBAAsB,YAAY;MAChC,OAAO,CAAC;KACV,CAAC;IACH;IAEA,cAAc,UAAU;KACtB,MAAM,eAAe;IACvB;IACA,MAAK;IAEJ,UAAA,oBACC,oBAAC,YAAD,EAAY,eAAY,OAAQ,CAAA,IAEhC,oBAAC,OAAD,EAAO,eAAY,OAAQ,CAAA;GAEvB,CAAA;EACJ;CAEN,CA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