@formality-ui/react 0.2.2 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +90 -1
- package/dist/index.cjs +143 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -4
- package/dist/index.d.ts +6 -4
- package/dist/index.js +143 -34
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context/ConfigContext.ts","../src/context/FormContext.ts","../src/context/GroupContext.ts","../src/components/FormalityProvider.tsx","../src/utils/makeProxyState.ts","../src/components/Form.tsx","../src/hooks/useInferredInputs.ts","../src/hooks/useConditions.ts","../src/hooks/usePropsEvaluation.ts","../src/hooks/useSubscriptions.ts","../src/components/Field.tsx","../src/components/FieldGroup.tsx","../src/components/UnusedFields.tsx","../src/hooks/useFormState.ts","../src/overlays.ts"],"names":["createContext","useContext","defaultGroupContext","useMemo","jsx","useWatch","evaluateDescriptor","useRef","useEffect","useState","useCallback","Fragment","useRHFFormContext","result"],"mappings":";;;;;;;AAwDA,IAAM,oBAAA,GAA2C;AAAA,EAC/C,QAAQ,EAAC;AAAA,EACT,YAAY,EAAC;AAAA,EACb,SAAS,EAAC;AAAA,EACV,YAAY,EAAC;AAAA,EACb,eAAe,EAAC;AAAA,EAChB,gBAAgB,EAAC;AAAA,EACjB,2BAAA,EAA6B,OAAA;AAAA,EAC7B,mBAAmB;AACrB,CAAA;AAQO,IAAM,aAAA,GACX,cAAkC,oBAAoB;AAExD,aAAA,CAAc,WAAA,GAAc,wBAAA;AAOrB,SAAS,gBAAA,GAAuC;AACrD,EAAA,OAAO,WAAW,aAAa,CAAA;AACjC;ACgEO,IAAM,WAAA,GAAcA,cAAuC,IAAI;AAEtE,WAAA,CAAY,WAAA,GAAc,sBAAA;AAQnB,SAAS,cAAA,GAEoB;AAClC,EAAA,MAAM,OAAA,GAAUC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A,CAAe;AAAA,QAC5B,KAAA;AAAA,QACA,SAAA,EAAW,KAAA;AAAA,QACX,OAAA,EAAS,KAAA;AAAA,QACT,YAAA,EAAc,KAAA;AAAA,QACd,KAAA,EAAO,MAAA;AAAA,QACP,OAAA,EAAS;AAAA,OACV,CAAA;AAAA,IACH,CAAC,CAAA;AAED,IAAA,OAAOA,OAAAA;AAAA,EACT,CAAA,EAAG,CAAC,UAAA,EAAY,aAAa,CAAC,CAAA;AAG9B,EAAA,MAAM,MAAA,GAASV,QAAQ,MAAyB;AAC9C,IAAA,MAAM,IAAA,GAA0B;AAAA,MAC9B,MAAA;AAAA,MACA,QAAQ,EAAC;AAAA;AAAA;AAAA,MAET,OAAA,EAAS,KAAA;AAAA,MACT,SAAA,EAAW,KAAA;AAAA,MACX,OAAA,EAAS,IAAA;AAAA,MACT,YAAA,EAAc,KAAA;AAAA,MACd,QAAQ,EAAC;AAAA,MACT,eAAe,EAAC;AAAA,MAChB,aAAa,EAAC;AAAA,MACd,eAAe;AAAC,KAClB;AAGA,IAAA,MAAA,CAAO,cAAA,CAAe,MAAM,QAAA,EAAU;AAAA,MACpC,GAAA,EAAK,MAAM,gBAAA,EAAkB,MAAA,IAAU,EAAC;AAAA,MACxC,UAAA,EAAY,IAAA;AAAA,MACZ,YAAA,EAAc;AAAA,KACf,CAAA;AAED,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,EAAG,CAAC,MAAA,EAAQ,gBAAA,EAAkB,MAAM,CAAC,CAAA;AAErC,EAAA,OAAO,MAAA;AACT;;;ACRO,SAAS,aACd,MAAA,EACG;AACH,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["// @formality-ui/react - ConfigContext\n// Global configuration context for Formality\n\nimport { createContext, useContext, type ComponentType } from \"react\";\nimport type {\n ValidatorsConfig,\n ErrorMessagesConfig,\n SelectValue,\n} from \"@formality-ui/core\";\nimport type { InputTemplateProps } from \"../types\";\nimport type { ReactInputConfig } from \"../overlays\";\n\n/**\n * ConfigContextValue - Global configuration provided by FormalityProvider\n *\n * Contains all input types, transformers, validators, and global defaults\n * that apply across all forms in the application.\n */\nexport interface ConfigContextValue {\n /** Input type definitions (e.g., textField, switch, autocomplete) */\n inputs: Record<string, ReactInputConfig>;\n\n /** Named formatters for value → display transformation */\n formatters: Record<string, (value: unknown) => unknown>;\n\n /** Named parsers for input → value transformation */\n parsers: Record<string, (value: unknown) => unknown>;\n\n /** Named validators and validator factories */\n validators: ValidatorsConfig;\n\n /** Error message templates by type key */\n errorMessages: ErrorMessagesConfig;\n\n /** Default template component for all inputs */\n defaultInputTemplate?: ComponentType<InputTemplateProps>;\n\n /** Named template components for specific input types */\n inputTemplates: Record<string, ComponentType<InputTemplateProps>>;\n\n /** Default prop name for passSubscriptions (default: 'state') */\n defaultSubscriptionPropName: string;\n\n /** Static default props for all fields */\n defaultFieldProps: Record<string, unknown>;\n\n /** Dynamic default props evaluated per-field */\n selectDefaultFieldProps?: SelectValue;\n}\n\n/**\n * Default configuration context values\n *\n * These are sensible defaults that can be overridden by FormalityProvider.\n * Per PRD 5.1: defaultSubscriptionPropName defaults to 'state'.\n */\nconst defaultConfigContext: ConfigContextValue = {\n inputs: {},\n formatters: {},\n parsers: {},\n validators: {},\n errorMessages: {},\n inputTemplates: {},\n defaultSubscriptionPropName: \"state\",\n defaultFieldProps: {},\n};\n\n/**\n * ConfigContext - React context for global Formality configuration\n *\n * Provides access to input types, transformers, validators, and\n * global defaults to all forms and fields in the application.\n */\nexport const ConfigContext =\n createContext<ConfigContextValue>(defaultConfigContext);\n\nConfigContext.displayName = \"FormalityConfigContext\";\n\n/**\n * useConfigContext - Hook to access global configuration\n *\n * @returns The current ConfigContextValue from the nearest FormalityProvider\n */\nexport function useConfigContext(): ConfigContextValue {\n return useContext(ConfigContext);\n}\n","// @formality-ui/react - FormContext\n// Form-level context for field registration and state management\n\nimport { createContext, useContext } from \"react\";\nimport type { UseFormReturn, FieldValues } from \"react-hook-form\";\nimport type {\n FormFieldsConfig,\n FormConfig,\n FormState,\n InputConfig,\n} from \"@formality-ui/core\";\nimport type { WatcherSetterFn, DebouncedFunction } from \"../types\";\n\n/**\n * FormContextValue - Form-level configuration and operations\n *\n * Provides field registration, subscription management, and access\n * to form state for all fields within a Form component.\n */\nexport interface FormContextValue<\n TFieldValues extends FieldValues = FieldValues,\n> {\n // ========================\n // Configuration\n // ========================\n\n /** Field configurations for this form */\n config: FormFieldsConfig;\n\n /** Form-level configuration (title, groups, input overrides) */\n formConfig: FormConfig;\n\n /** Original record passed to Form (for expression access) */\n record?: Record<string, unknown>;\n\n // ========================\n // Registry Operations\n // ========================\n\n /**\n * Register a field when it mounts\n * @param name - Field name\n */\n registerField: (name: string) => void;\n\n /**\n * Unregister a field when it unmounts\n * @param name - Field name\n */\n unregisterField: (name: string) => void;\n\n // ========================\n // Subscription Operations\n // ========================\n\n /**\n * Add a subscription from subscriber to target field\n * @param target - The field being watched\n * @param subscriber - The field watching\n */\n addSubscription: (target: string, subscriber: string) => void;\n\n /**\n * Remove a subscription from subscriber to target field\n * @param target - The field being watched\n * @param subscriber - The field watching\n */\n removeSubscription: (target: string, subscriber: string) => void;\n\n /**\n * Register a setter for a field's watchers state\n * @param name - Field name\n * @param setter - React state setter for watchers\n */\n registerWatcherSetter: (name: string, setter: WatcherSetterFn) => void;\n\n /**\n * Unregister a watcher setter when field unmounts\n * @param name - Field name\n */\n unregisterWatcherSetter: (name: string) => void;\n\n // ========================\n // Field State Operations\n // ========================\n\n /**\n * Programmatically change a field's value\n * @param name - Field name\n * @param value - New value\n * @param inputConfig - Optional input configuration for this field type\n */\n changeField: (\n name: string,\n value: unknown,\n inputConfig?: InputConfig,\n ) => void;\n\n /**\n * Set a field's validating state\n * @param name - Field name\n * @param isValidating - Whether validation is in progress\n */\n setFieldValidating: (name: string, isValidating: boolean) => void;\n\n // ========================\n // State Access\n // ========================\n\n /**\n * Get the current complete form state\n * Used for expression evaluation and condition checking\n */\n getFormState: () => FormState;\n\n // ========================\n // Submission Operations\n // ========================\n\n /** Optional submit handler passed to Form */\n onSubmit?: (values: Partial<TFieldValues>) => void | Promise<void>;\n\n /** Debounced submit for auto-save forms */\n debouncedSubmit: DebouncedFunction;\n\n /** Immediate submit bypassing debounce */\n submitImmediate: () => void;\n\n // ========================\n // Unused Fields Tracking\n // ========================\n\n /** Fields in config but not rendered (for config-driven forms) */\n unusedFields: string[];\n\n // ========================\n // React Hook Form Integration\n // ========================\n\n /** React Hook Form methods passthrough */\n methods: UseFormReturn<TFieldValues>;\n}\n\n/**\n * FormContext - React context for form-level state and operations\n *\n * Must be provided by a Form component. No default value as\n * fields cannot function without a parent Form.\n */\nexport const FormContext = createContext<FormContextValue | null>(null);\n\nFormContext.displayName = \"FormalityFormContext\";\n\n/**\n * useFormContext - Hook to access form-level context\n *\n * @throws Error if used outside a Form component\n * @returns The FormContextValue from the nearest Form component\n */\nexport function useFormContext<\n TFieldValues extends FieldValues = FieldValues,\n>(): FormContextValue<TFieldValues> {\n const context = useContext(\n FormContext,\n ) as FormContextValue<TFieldValues> | null;\n\n if (!context) {\n throw new Error(\n \"useFormContext must be used within a Form component. \" +\n \"Make sure your component is wrapped in a <Form> component.\",\n );\n }\n\n return context;\n}\n","// @formality-ui/react - GroupContext\n// Group-level context for nested disabled/visible state propagation\n\nimport { createContext, useContext } from \"react\";\nimport type { ConditionDescriptor, GroupConfig } from \"@formality-ui/core\";\n\n/**\n * GroupState - Current computed state for a FieldGroup\n *\n * Contains the resolved disabled/visible states from condition\n * evaluation and the conditions/subscriptions used.\n */\nexport interface GroupState {\n /** Is the group disabled (propagates to all child fields) */\n isDisabled: boolean;\n\n /** Is the group visible (propagates to all child fields) */\n isVisible: boolean;\n\n /** Whether the group has a setValue condition */\n hasSetCondition: boolean;\n\n /** Value to set on all child fields (from group-level set/selectSet) */\n setValue: unknown;\n\n /** Conditions from group configuration */\n conditions: ConditionDescriptor[];\n\n /** Fields this group subscribes to */\n subscriptions: string[];\n}\n\n/**\n * GroupContextValue - Group-level configuration and state\n *\n * Provides inherited disabled/visible state and subscription\n * information to nested fields and groups.\n */\nexport interface GroupContextValue {\n /** Current computed state for the group */\n state: GroupState;\n\n /** Inherited subscriptions from parent groups */\n subscriptions: string[];\n\n /** Field names inferred from group conditions */\n inferredInputs: string[];\n\n /** Group configuration */\n config: GroupConfig;\n}\n\n/**\n * Default group context values\n *\n * When no FieldGroup is present, fields use these defaults:\n * - Not disabled\n * - Visible\n * - No conditions or subscriptions\n */\nconst defaultGroupContext: GroupContextValue = {\n state: {\n isDisabled: false,\n isVisible: true,\n hasSetCondition: false,\n setValue: undefined,\n conditions: [],\n subscriptions: [],\n },\n subscriptions: [],\n inferredInputs: [],\n config: { conditions: [], subscribesTo: [] },\n};\n\n/**\n * GroupContext - React context for group-level state\n *\n * Provides inherited disabled/visible state from parent groups\n * to child fields and nested groups.\n */\nexport const GroupContext =\n createContext<GroupContextValue>(defaultGroupContext);\n\nGroupContext.displayName = \"FormalityGroupContext\";\n\n/**\n * useGroupContext - Hook to access group-level context\n *\n * @returns The GroupContextValue from the nearest FieldGroup or default\n */\nexport function useGroupContext(): GroupContextValue {\n return useContext(GroupContext);\n}\n","// @formality-ui/react - FormalityProvider\n// Global configuration provider for Formality forms\n\nimport { useMemo, type ReactNode, type ComponentType } from \"react\";\nimport type {\n ValidatorsConfig,\n ErrorMessagesConfig,\n SelectValue,\n} from \"@formality-ui/core\";\nimport {\n ConfigContext,\n type ConfigContextValue,\n} from \"../context/ConfigContext\";\nimport type { InputTemplateProps } from \"../types\";\nimport type { ReactInputConfig } from \"../overlays\";\n\n/**\n * FormalityProviderProps - Props for the FormalityProvider component\n *\n * Configures input types, transformers, validators, and global defaults\n * for all forms in the application.\n */\nexport interface FormalityProviderProps {\n /** Child components */\n children: ReactNode;\n\n /**\n * Input type definitions (REQUIRED)\n *\n * Defines how each input type (e.g., textField, switch, autocomplete)\n * behaves across all forms.\n *\n * @example\n * ```tsx\n * inputs={{\n * textField: { component: TextField, defaultValue: '' },\n * switch: { component: Switch, defaultValue: false },\n * }}\n * ```\n *\n * `component` is type-checked as a real React component (a non-component\n * value such as `42` or `\"textField\"` is a compile error). See\n * `ReactInputConfig` for the precise shape.\n */\n inputs: Record<string, ReactInputConfig>;\n\n /**\n * Named formatters for value → display transformation\n *\n * Transform form values before displaying in inputs.\n *\n * @example\n * ```tsx\n * formatters={{\n * currency: (v) => `$${Number(v).toFixed(2)}`,\n * uppercase: (v) => String(v).toUpperCase(),\n * }}\n * ```\n */\n formatters?: Record<string, (value: unknown) => unknown>;\n\n /**\n * Named parsers for input → value transformation\n *\n * Transform user input before storing in form state.\n *\n * @example\n * ```tsx\n * parsers={{\n * number: (v) => Number(v) || 0,\n * trim: (v) => String(v).trim(),\n * }}\n * ```\n */\n parsers?: Record<string, (value: unknown) => unknown>;\n\n /**\n * Named validators and validator factories\n *\n * Define reusable validation logic across forms.\n */\n validators?: ValidatorsConfig;\n\n /**\n * Error message templates by type key\n *\n * Map validation error types to human-readable messages.\n *\n * @example\n * ```tsx\n * errorMessages={{\n * required: 'This field is required',\n * minLength: 'Must be at least {min} characters',\n * }}\n * ```\n */\n errorMessages?: ErrorMessagesConfig;\n\n /**\n * Default template component for all inputs\n *\n * Wraps all inputs for consistent styling, labels, error display.\n */\n defaultInputTemplate?: ComponentType<InputTemplateProps>;\n\n /**\n * Named template components for specific input types\n *\n * Override the default template for specific input types.\n */\n inputTemplates?: Record<string, ComponentType<InputTemplateProps>>;\n\n /**\n * Default prop name for passSubscriptions (default: 'state')\n *\n * When a field has passSubscriptions: true, subscribed field states\n * are passed using this prop name.\n */\n defaultSubscriptionPropName?: string;\n\n /**\n * Static default props for all fields\n *\n * Props applied to every field unless overridden.\n */\n defaultFieldProps?: Record<string, unknown>;\n\n /**\n * Dynamic default props evaluated per-field\n *\n * Expression or function that computes default props.\n */\n selectDefaultFieldProps?: SelectValue;\n}\n\n/**\n * FormalityProvider - Global configuration provider for Formality\n *\n * Wraps your application to provide input types, transformers, validators,\n * and global defaults to all Formality forms.\n *\n * @example\n * ```tsx\n * import { FormalityProvider } from '@formality-ui/react';\n *\n * const inputs = {\n * textField: { component: TextInput, defaultValue: '' },\n * switch: { component: Toggle, defaultValue: false },\n * };\n *\n * function App() {\n * return (\n * <FormalityProvider\n * inputs={inputs}\n * formatters={{ currency: (v) => `$${v}` }}\n * errorMessages={{ required: 'Required' }}\n * >\n * <MyApp />\n * </FormalityProvider>\n * );\n * }\n * ```\n */\nexport function FormalityProvider({\n children,\n inputs,\n formatters = {},\n parsers = {},\n validators = {},\n errorMessages = {},\n defaultInputTemplate,\n inputTemplates = {},\n defaultSubscriptionPropName = \"state\",\n defaultFieldProps = {},\n selectDefaultFieldProps,\n}: FormalityProviderProps): JSX.Element {\n // Memoize context value to prevent unnecessary re-renders\n // in descendant components that consume ConfigContext\n const contextValue = useMemo<ConfigContextValue>(\n () => ({\n inputs,\n formatters,\n parsers,\n validators,\n errorMessages,\n defaultInputTemplate,\n inputTemplates,\n defaultSubscriptionPropName,\n defaultFieldProps,\n selectDefaultFieldProps,\n }),\n [\n inputs,\n formatters,\n parsers,\n validators,\n errorMessages,\n defaultInputTemplate,\n inputTemplates,\n defaultSubscriptionPropName,\n defaultFieldProps,\n selectDefaultFieldProps,\n ],\n );\n\n return (\n <ConfigContext.Provider value={contextValue}>\n {children}\n </ConfigContext.Provider>\n );\n}\n","// @formality-ui/react - makeProxyState\n// Lazy property access utility for React performance optimization\n\n/**\n * Creates a proxy object with lazy property access via Object.defineProperty\n *\n * CRITICAL: This enables React's dependency tracking to only register\n * dependencies on actually accessed properties, not the entire object.\n *\n * Without proxy: accessing fieldState.value creates dependency on entire fieldState\n * With proxy: accessing fieldState.value only creates dependency on value property\n *\n * Performance Impact:\n * - Reduces unnecessary re-renders in condition-heavy forms\n * - Expression evaluation only subscribes to properties actually used\n * - Field states can change without triggering re-renders in unrelated fields\n *\n * Implementation Note:\n * Uses Object.defineProperty (NOT Proxy) because:\n * - Better performance for simple property access\n * - Works with Object.keys() iteration when enumerable: true\n * - Simpler debugging and stack traces\n *\n * @param source - The object to wrap with lazy getters\n * @returns A new object with getter properties that lazily access source\n *\n * @example\n * ```typescript\n * const source = { value: 5, isTouched: false };\n * const proxy = makeProxyState(source);\n *\n * // Properties are accessed lazily\n * console.log(proxy.value); // 5\n *\n * // Changes to source reflect in proxy (lazy access)\n * source.value = 10;\n * console.log(proxy.value); // 10\n *\n * // Object.keys still works\n * console.log(Object.keys(proxy)); // ['value', 'isTouched']\n * ```\n */\nexport function makeProxyState<T extends object>(source: T): T {\n const result = {} as T;\n\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n Object.defineProperty(result, key, {\n get: () => source[key],\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Creates a nested proxy state, recursively wrapping objects\n *\n * Use this for deeply nested state objects where you want\n * lazy access at multiple levels.\n *\n * @param source - The object to wrap with lazy getters (recursively)\n * @returns A new object with recursive getter properties\n */\nexport function makeDeepProxyState<T extends object>(source: T): T {\n const result = {} as T;\n\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n Object.defineProperty(result, key, {\n get: () => {\n const currentValue = source[key];\n if (\n currentValue !== null &&\n typeof currentValue === \"object\" &&\n !Array.isArray(currentValue)\n ) {\n return makeDeepProxyState(currentValue as object);\n }\n return currentValue;\n },\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n return result;\n}\n","// @formality-ui/react - Form Component\n// Core form component with React Hook Form integration\n\nimport {\n useMemo,\n useCallback,\n useRef,\n useState,\n useEffect,\n type ReactNode,\n} from \"react\";\nimport {\n useForm,\n FormProvider,\n type FieldValues,\n type UseFormReturn,\n} from \"react-hook-form\";\nimport { debounce } from \"lodash-es\";\nimport {\n resolveAllInitialValues,\n resolveFormTitle,\n evaluateDescriptor,\n buildFormContext,\n extractValueField,\n transformFieldName,\n} from \"@formality-ui/core\";\nimport type {\n FormFieldsConfig,\n FormConfig,\n FormState,\n InputConfig,\n} from \"@formality-ui/core\";\nimport { FormContext, type FormContextValue } from \"../context/FormContext\";\nimport { GroupContext } from \"../context/GroupContext\";\nimport { useConfigContext } from \"../context/ConfigContext\";\nimport { makeProxyState } from \"../utils/makeProxyState\";\nimport type { WatcherSetterFn, DebouncedFunction } from \"../types\";\nimport type { ReactFormFieldsConfig } from \"../overlays\";\n\n/**\n * Form component props\n */\nexport interface FormProps<TFieldValues extends FieldValues = FieldValues> {\n /** Form content - can be static children or render function */\n children: ReactNode | ((api: FormRenderAPI<TFieldValues>) => ReactNode);\n\n /** Field configurations */\n config: ReactFormFieldsConfig<TFieldValues>;\n\n /** Form-level configuration (title, groups, input overrides) */\n formConfig?: FormConfig;\n\n /** Submit handler */\n onSubmit?: (values: Partial<TFieldValues>) => void | Promise<void>;\n\n /** Initial record data */\n record?: Partial<TFieldValues>;\n\n /** Enable auto-save on field changes */\n autoSave?: boolean;\n\n /**\n * Form-level auto-save debounce, used as the fallback for any field whose\n * `InputConfig.debounce` is unset.\n * - `false` — submit immediately (no debounce timer).\n * - `number` — delay auto-save by this many milliseconds (default: 1000).\n *\n * A field can override its own cadence via `InputConfig.debounce`\n * (`false` for immediate, or a number for a per-field delay).\n */\n debounce?: number | false;\n\n /** Form-level validation */\n validate?: (\n values: Partial<TFieldValues>,\n ) => Record<string, string> | Promise<Record<string, string>>;\n}\n\n/**\n * API passed to render function children\n */\nexport interface FormRenderAPI<TFieldValues extends FieldValues = FieldValues> {\n /** Fields in config but not rendered */\n unusedFields: string[];\n\n /** React Hook Form formState */\n formState: UseFormReturn<TFieldValues>[\"formState\"];\n\n /** React Hook Form methods */\n methods: UseFormReturn<TFieldValues>;\n\n /**\n * Submit handler that runs the full Formality submission pipeline.\n *\n * Use this in place of `methods.handleSubmit` to ensure form-level\n * `validate` and `transformValuesForSubmit` (valueField extraction +\n * getSubmitField rename) are applied before `onSubmit` receives the values.\n * `methods.handleSubmit` remains available as a raw RHF escape hatch but\n * bypasses those transforms.\n */\n handleSubmit: (\n onSubmit: (values: Partial<TFieldValues>) => void | Promise<void>,\n ) => (e?: React.BaseSyntheticEvent) => Promise<void>;\n\n /** Resolved form title (static or evaluated) */\n resolvedTitle?: string;\n}\n\n/**\n * Default group context for fields outside FieldGroup\n */\nconst defaultGroupContext = {\n state: {\n isDisabled: false,\n isVisible: true,\n hasSetCondition: false,\n setValue: undefined,\n conditions: [],\n subscriptions: [],\n },\n subscriptions: [],\n inferredInputs: [],\n config: { conditions: [], subscribesTo: [] },\n};\n\n/**\n * Form component - Core form wrapper with React Hook Form integration\n *\n * Provides:\n * - FormContext for field registration and subscription management\n * - React Hook Form integration with mode: 'onChange'\n * - Auto-save with debounced submission\n * - Config-driven default values\n * - Unused fields tracking for config-driven rendering\n *\n * @example\n * ```tsx\n * <Form\n * config={{\n * name: { type: 'textField', label: 'Name' },\n * email: { type: 'textField', label: 'Email' },\n * }}\n * onSubmit={(values) => console.log(values)}\n * >\n * <Field name=\"name\" />\n * <Field name=\"email\" />\n * <button type=\"submit\">Submit</button>\n * </Form>\n * ```\n */\nexport function Form<TFieldValues extends FieldValues = FieldValues>({\n children,\n config,\n formConfig = {},\n onSubmit,\n record,\n autoSave = false,\n debounce: debounceMs = 1000,\n validate,\n}: FormProps<TFieldValues>): JSX.Element {\n // Get provider configuration\n const providerConfig = useConfigContext();\n\n // Merge input configs (form overrides provider)\n const mergedInputs = useMemo((): Record<string, InputConfig> => {\n const formInputs =\n typeof formConfig.inputs === \"function\"\n ? formConfig.inputs(providerConfig.inputs)\n : (formConfig.inputs ?? {});\n\n // Merge provider inputs with form-level overrides\n const result: Record<string, InputConfig> = { ...providerConfig.inputs };\n for (const [key, override] of Object.entries(formInputs)) {\n if (result[key]) {\n result[key] = { ...result[key], ...override } as InputConfig;\n }\n }\n return result;\n }, [providerConfig.inputs, formConfig.inputs]);\n\n // Calculate default values from config\n const defaultValues = useMemo(() => {\n return resolveAllInitialValues(config, mergedInputs, record ?? {});\n }, [config, mergedInputs, record]);\n\n // Initialize React Hook Form\n const methods = useForm<TFieldValues>({\n mode: \"onChange\",\n defaultValues: defaultValues as any,\n values: record as any,\n });\n\n // === REGISTRIES ===\n\n // Field registration\n const fieldRegistry = useRef(new Set<string>());\n const [registeredFields, setRegisteredFields] = useState<Set<string>>(\n new Set(),\n );\n\n // Subscription management (inverted index: target → subscribers)\n const invertedSubscriptions = useRef(new Map<string, Set<string>>());\n\n // Watcher setters for notifying fields about subscribers\n const watcherSetters = useRef(new Map<string, WatcherSetterFn>());\n\n // Pending updates for fields not yet mounted\n const pendingWatcherUpdates = useRef(new Map<string, Set<string>>());\n\n // Validation state tracking\n const validatingFields = useRef(new Map<string, boolean>());\n\n // Auto-save tracking\n // pendingChanges accumulates field changes while debounce is pending\n const pendingChangedFields = useRef(new Set<string>());\n const pendingAffectedFields = useRef(new Set<string>());\n // executionVersion is incremented when a new auto-save starts, used to abort if new changes come in\n const executionVersionRef = useRef(0);\n\n // Per-field numeric debounce cache: interval (ms) → memoized debounced\n // auto-save fn. Fields that share the same numeric `InputConfig.debounce`\n // coalesce into a single timer (mirroring the single-timer behavior of the\n // Form-level debounce); fields with different numeric debounces each get\n // their own timer and fire on their own cadence.\n const fieldDebouncersRef = useRef(new Map<number, DebouncedFunction>());\n // Ref so `changeField` can reach the latest factory without being rebuilt\n // (and churning its context consumers) on every `executeAutoSave` change.\n const getOrCreateDebouncedRef = useRef<(ms: number) => DebouncedFunction>();\n\n // === REGISTRY OPERATIONS ===\n\n const registerField = useCallback((name: string) => {\n fieldRegistry.current.add(name);\n setRegisteredFields(new Set(fieldRegistry.current));\n }, []);\n\n const unregisterField = useCallback((name: string) => {\n fieldRegistry.current.delete(name);\n setRegisteredFields(new Set(fieldRegistry.current));\n }, []);\n\n // === SUBSCRIPTION OPERATIONS ===\n\n const addSubscription = useCallback((target: string, subscriber: string) => {\n // Update inverted index\n if (!invertedSubscriptions.current.has(target)) {\n invertedSubscriptions.current.set(target, new Set());\n }\n invertedSubscriptions.current.get(target)!.add(subscriber);\n\n // Log subscription addition (development only)\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Formality Subscription] \"${subscriber}\" added to watch \"${target}\"`,\n );\n }\n\n // Notify target field if mounted\n const setter = watcherSetters.current.get(target);\n if (setter) {\n setter((prev) => ({ ...prev, [subscriber]: true }));\n } else {\n // Queue for later\n if (!pendingWatcherUpdates.current.has(target)) {\n pendingWatcherUpdates.current.set(target, new Set());\n }\n pendingWatcherUpdates.current.get(target)!.add(subscriber);\n }\n }, []);\n\n const removeSubscription = useCallback(\n (target: string, subscriber: string) => {\n // Check if subscription exists before removal (for double-cleanup detection)\n const subscribers = invertedSubscriptions.current.get(target);\n const subscriptionExists = subscribers?.has(subscriber) ?? false;\n\n // Perform removal (keep original optional chaining for safety)\n invertedSubscriptions.current.get(target)?.delete(subscriber);\n\n // Log removal or warn about double-cleanup (development only)\n if (process.env.NODE_ENV !== \"production\") {\n if (subscriptionExists) {\n console.warn(\n `[Formality Subscription] \"${subscriber}\" removed from watching \"${target}\"`,\n );\n } else {\n console.warn(\n `[Formality Subscription] WARNING: Double-cleanup attempt - ` +\n `\"${subscriber}\" was not watching \"${target}\"`,\n );\n }\n }\n\n // Update watcher setter\n const setter = watcherSetters.current.get(target);\n if (setter) {\n setter((prev) => {\n const next = { ...prev };\n delete next[subscriber];\n return next;\n });\n }\n },\n [],\n );\n\n const registerWatcherSetter = useCallback(\n (name: string, setter: WatcherSetterFn) => {\n watcherSetters.current.set(name, setter);\n\n // Process pending subscriptions\n const pending = pendingWatcherUpdates.current.get(name);\n if (pending?.size) {\n setter((prev) => {\n const next = { ...prev };\n pending.forEach((sub) => {\n next[sub] = true;\n });\n return next;\n });\n pendingWatcherUpdates.current.delete(name);\n }\n },\n [],\n );\n\n const unregisterWatcherSetter = useCallback((name: string) => {\n watcherSetters.current.delete(name);\n }, []);\n\n // === FIELD STATE OPERATIONS ===\n\n /**\n * Get all fields affected by a change to the given field.\n * This traverses the subscription graph to find all dependents,\n * including transitive dependencies (A -> B -> C).\n */\n const getAffectedFields = useCallback((changedField: string): Set<string> => {\n const affected = new Set<string>();\n const toProcess = [changedField];\n\n while (toProcess.length > 0) {\n const current = toProcess.pop()!;\n const subscribers = invertedSubscriptions.current.get(current);\n if (subscribers) {\n for (const subscriber of subscribers) {\n if (!affected.has(subscriber)) {\n affected.add(subscriber);\n toProcess.push(subscriber); // Check for transitive dependencies\n }\n }\n }\n }\n\n return affected;\n }, []);\n\n const changeField = useCallback(\n (name: string, value: unknown, inputConfig?: InputConfig) => {\n // Auto-save trigger\n if (autoSave) {\n // Accumulate this change\n pendingChangedFields.current.add(name);\n\n // Add affected fields (those that depend on this field via conditions)\n const affected = getAffectedFields(name);\n for (const field of affected) {\n pendingAffectedFields.current.add(field);\n }\n\n // Resolve the auto-save cadence for this field:\n // inputConfig.debounce === false → submit immediately (no timer)\n // inputConfig.debounce === <number> → per-field debounced timer at that ms\n // inputConfig.debounce === undefined → fall back to the Form-level debounce\n // (debouncedSubmitRef already encodes debounceMs, including its false → immediate case)\n const fieldDebounce = inputConfig?.debounce;\n if (fieldDebounce === false) {\n // Immediate submission: bypass debounce entirely (field-level override)\n executeAutoSaveRef.current?.();\n } else if (typeof fieldDebounce === \"number\") {\n // Per-field numeric debounce: schedule at the field's own interval.\n // Previously this branch was dead config — any number fell through to\n // the single Form-level debounce. See autosave Issue 1.\n getOrCreateDebouncedRef.current?.(fieldDebounce)();\n } else {\n // No field-level override → Form-level debounced submission\n debouncedSubmitRef.current?.();\n }\n }\n },\n [autoSave, getAffectedFields],\n );\n\n const setFieldValidating = useCallback(\n (name: string, isValidating: boolean) => {\n validatingFields.current.set(name, isValidating);\n },\n [],\n );\n\n // === STATE ACCESS ===\n\n const getFormState = useCallback((): FormState => {\n const values = methods.getValues();\n const formState = methods.formState;\n\n // Build proxy-wrapped field states\n const fields: Record<string, any> = {};\n Object.keys(config).forEach((name) => {\n const fieldState = methods.getFieldState(name as any, formState);\n fields[name] = makeProxyState({\n value: values[name as keyof typeof values],\n isTouched: fieldState.isTouched,\n isDirty: fieldState.isDirty,\n isValidating: validatingFields.current.get(name) ?? false,\n error: fieldState.error\n ? {\n type: fieldState.error.type,\n message: fieldState.error.message,\n }\n : undefined,\n invalid: fieldState.invalid,\n });\n });\n\n return {\n fields,\n record: record ?? {},\n errors: formState.errors as any,\n defaultValues: defaultValues,\n touchedFields: formState.touchedFields as any,\n dirtyFields: formState.dirtyFields as any,\n isDirty: formState.isDirty,\n isTouched: Object.keys(formState.touchedFields).length > 0,\n isValid: formState.isValid,\n isSubmitting: formState.isSubmitting,\n };\n }, [methods, config, record, defaultValues]);\n\n // === SUBMISSION ===\n\n /**\n * Run the full submission pipeline (validate + transform) on already-collected\n * values, then invoke the supplied submit handler.\n *\n * Used by both auto-save and manual submit. When `overrideOnSubmit` is\n * provided (the manual-submit render-API path), it is called instead of the\n * `<Form onSubmit>` prop so a consumer using `methods.handleSubmit(handler)`\n * receives the transformed values.\n */\n const handleSubmit = useCallback(\n async (\n values: TFieldValues,\n overrideOnSubmit?: (\n values: Partial<TFieldValues>,\n ) => void | Promise<void>,\n ) => {\n // Check if any field is validating\n for (const [, isValidating] of validatingFields.current) {\n if (isValidating) return;\n }\n\n // Run form-level validation\n if (validate) {\n const errors = await validate(values);\n if (Object.keys(errors).length > 0) {\n Object.entries(errors).forEach(([field, message]) => {\n methods.setError(field as any, { message });\n });\n return;\n }\n }\n\n // Transform values for submission\n const submitValues = transformValuesForSubmit(\n values,\n config,\n mergedInputs,\n );\n\n const sink = overrideOnSubmit ?? onSubmit;\n await sink?.(submitValues);\n },\n [validate, methods, onSubmit, config, mergedInputs],\n );\n\n /**\n * Render-API submit handler.\n *\n * Wraps React Hook Form's `methods.handleSubmit` so that the documented\n * submission pipeline (form-level `validate` + `transformValuesForSubmit`)\n * runs on the manual-submit path too — not just auto-save. RHF performs its\n * own field validation first; if it passes, values are routed through\n * `handleSubmit` (validate + transform) before reaching `userOnSubmit`.\n */\n const handleRenderSubmit = useCallback(\n (userOnSubmit: (values: Partial<TFieldValues>) => void | Promise<void>) => {\n return methods.handleSubmit(async (values) => {\n await handleSubmit(values as TFieldValues, userOnSubmit);\n });\n },\n [methods, handleSubmit],\n );\n\n // Debounced submit for auto-save\n const debouncedSubmitRef = useRef<DebouncedFunction>();\n\n // Ref to store executeAutoSave for use in changeField (to avoid initialization order issues)\n const executeAutoSaveRef = useRef<typeof executeAutoSave>();\n\n /**\n * Wait for specific fields to complete their validation.\n * Returns false if the version changed (new changes came in), true otherwise.\n */\n const waitForFieldValidation = useCallback(\n async (fields: string[], version: number): Promise<boolean> => {\n const maxWaitMs = 10000; // 10 second timeout\n const pollIntervalMs = 50;\n const startTime = Date.now();\n\n while (Date.now() - startTime < maxWaitMs) {\n // Check if version changed (new changes came in)\n if (executionVersionRef.current !== version) {\n return false;\n }\n\n // Check if all fields have completed validation\n const allDone = fields.every(\n (field) => !validatingFields.current.get(field),\n );\n if (allDone) {\n return true;\n }\n\n // Wait and check again\n await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));\n }\n\n // Timeout - proceed anyway\n return true;\n },\n [],\n );\n\n /**\n * Execute auto-save: validate only changed/affected fields, wait for completion, then submit.\n * This prevents the issue where handleSubmit() validates ALL fields.\n */\n const executeAutoSave = useCallback(async () => {\n // Capture and increment execution version\n executionVersionRef.current++;\n const executionVersion = executionVersionRef.current;\n\n // Copy and clear pending fields\n const changedFields = new Set(pendingChangedFields.current);\n const affectedFields = new Set(pendingAffectedFields.current);\n pendingChangedFields.current.clear();\n pendingAffectedFields.current.clear();\n\n // If no fields changed, nothing to do\n if (changedFields.size === 0) {\n return;\n }\n\n // Changed fields: already validated by RHF's onChange mode\n // Affected fields: may need validation for cross-field validation\n const fieldsToWaitFor = [...changedFields, ...affectedFields];\n const fieldsToTrigger = [...affectedFields]; // Only affected, not changed\n\n // Wait for any in-flight validations on these fields to complete\n const validationsComplete = await waitForFieldValidation(\n fieldsToWaitFor,\n executionVersion,\n );\n\n // If version changed while waiting, abort (new changes came in)\n if (\n !validationsComplete ||\n executionVersionRef.current !== executionVersion\n ) {\n return;\n }\n\n // Check if changed fields have errors (from onChange validation)\n for (const fieldName of changedFields) {\n const fieldState = methods.getFieldState(fieldName as any);\n if (fieldState.error) {\n // Changed field has validation error, don't submit\n return;\n }\n }\n\n // Only trigger affected fields (changed fields already validated by onChange)\n if (fieldsToTrigger.length > 0) {\n const isValid = await methods.trigger(fieldsToTrigger as any);\n\n // Check version again after async validation\n if (executionVersionRef.current !== executionVersion) {\n return;\n }\n\n if (!isValid) {\n // Validation failed, don't submit\n return;\n }\n\n // Wait for triggered validations to complete\n const postTriggerComplete = await waitForFieldValidation(\n fieldsToTrigger,\n executionVersion,\n );\n\n if (\n !postTriggerComplete ||\n executionVersionRef.current !== executionVersion\n ) {\n return;\n }\n }\n\n // All relevant validations passed.\n //\n // NOTE: we intentionally do NOT bail on whole-form errors here. The checks\n // above already validate exactly the fields this save can touch (changed\n // fields via onChange + affected fields via trigger()). Rejecting on *any*\n // unrelated field's error would silently drop a valid edit — e.g. editing\n // `notes` while an unrelated required `email` is empty — so the user's\n // change would sit unsaved with no feedback. Whole-form validity is still\n // enforced on a full manual submit. See autosave Issue 2.\n const values = methods.getValues();\n await handleSubmit(values as TFieldValues);\n }, [methods, handleSubmit, waitForFieldValidation]);\n\n // Keep the ref in sync with the latest executeAutoSave function\n executeAutoSaveRef.current = executeAutoSave;\n\n /**\n * Get (or lazily create) a debounced auto-save function for a specific\n * interval, used to honor per-field numeric `InputConfig.debounce` values.\n *\n * The cache is keyed by interval so fields sharing the same numeric\n * debounce coalesce into a single timer (mirroring the single-timer\n * behavior of the Form-level debounce); fields with different numeric\n * debounces each get their own timer and fire on their own cadence.\n *\n * This governs *auto-save timing only*. The field value is still committed\n * to React Hook Form on every change (see Field.handleChange); a numeric\n * debounce does NOT throttle value commits / re-renders.\n */\n const getOrCreateDebounced = useCallback(\n (ms: number): DebouncedFunction => {\n const cached = fieldDebouncersRef.current.get(ms);\n if (cached) return cached;\n\n // Forward through executeAutoSaveRef so each cached debounced fn is\n // stable: it always invokes the latest executeAutoSave without rebuilding\n // the timer (and canceling any pending save) when executeAutoSave's\n // identity changes. The cache therefore stays valid for the field's\n // lifetime — no teardown/rebuild needed.\n const debouncedFn = debounce(() => {\n executeAutoSaveRef.current?.();\n }, ms);\n\n // Attach lodash-style methods (matches debouncedSubmit shape)\n const fn = Object.assign(debouncedFn, {\n pending: () => false, // lodash debounce tracks pending internally\n }) as DebouncedFunction;\n\n fieldDebouncersRef.current.set(ms, fn);\n return fn;\n },\n [],\n );\n\n // Keep the factory ref in sync so `changeField` (defined above) always\n // invokes the latest factory. Stable identity (no executeAutoSave dep), so\n // `changeField` and its context consumers are not churned.\n getOrCreateDebouncedRef.current = getOrCreateDebounced;\n\n // Cancel + clear all per-field debouncers on unmount. No rebuild is needed\n // on executeAutoSave changes — the cached fns forward through the ref above.\n useEffect(() => {\n return () => {\n fieldDebouncersRef.current.forEach((fn) => fn.cancel());\n fieldDebouncersRef.current.clear();\n };\n }, [getOrCreateDebounced]);\n\n // Form-level debounced submit, built once per `debounceMs`. It forwards\n // through executeAutoSaveRef so it (a) always invokes the latest\n // executeAutoSave without rebuilding/canceling the timer on every\n // executeAutoSave identity change, and (b) can be assigned during render —\n // making it available on the very first render, consistent with\n // executeAutoSaveRef / getOrCreateDebouncedRef. Previously this was wired\n // up inside an effect, leaving a first-render window where the ref was\n // undefined (the `?.()` no-ops). See autosave Issue 3.\n const debouncedSubmit = useMemo<DebouncedFunction>(() => {\n // When debounce is false, use immediate execution (no debouncing)\n if (debounceMs === false) {\n return Object.assign(\n () => {\n executeAutoSaveRef.current?.();\n },\n {\n cancel: () => {}, // No-op for immediate function\n flush: () => executeAutoSaveRef.current?.(), // Execute immediately on flush\n pending: () => false, // Never pending when immediate\n },\n ) as DebouncedFunction;\n }\n\n // Normal debounce behavior\n const debouncedFn = debounce(() => {\n executeAutoSaveRef.current?.();\n }, debounceMs);\n\n // Attach lodash-style methods\n return Object.assign(debouncedFn, {\n pending: () => false, // lodash debounce handles this internally\n }) as DebouncedFunction;\n }, [debounceMs]);\n\n // Assign during render (not in an effect) so the ref is populated on the\n // first render and never undefined.\n debouncedSubmitRef.current = debouncedSubmit;\n\n // Cancel the lodash timer when the interval changes or on unmount. (For the\n // immediate adapter, cancel() is a no-op.)\n useEffect(() => {\n return () => {\n debouncedSubmit.cancel();\n };\n }, [debouncedSubmit]);\n\n const submitImmediate = useCallback(() => {\n // Flush the Form-level debounced submit: immediate for debounce: false,\n // or fires any pending debounced save right away. The ref is always\n // populated (assigned during render above), so the previous first-render\n // fallback is no longer needed.\n debouncedSubmitRef.current?.flush();\n }, []);\n\n // === UNUSED FIELDS ===\n\n const unusedFields = useMemo(() => {\n const allFields = Object.keys(config);\n return allFields.filter((name) => !registeredFields.has(name));\n }, [config, registeredFields]);\n\n // === RESOLVED TITLE ===\n\n const resolvedTitle = useMemo(() => {\n if (!formConfig.selectTitle && !formConfig.title) {\n return undefined;\n }\n\n // If selectTitle exists, evaluate it\n if (formConfig.selectTitle) {\n const formState = getFormState();\n const context = buildFormContext(\n formState.fields,\n formState.record,\n formState.errors,\n formState.defaultValues,\n formState.touchedFields,\n formState.dirtyFields,\n );\n const evaluated = evaluateDescriptor(formConfig.selectTitle, context);\n return resolveFormTitle(formConfig.title, evaluated);\n }\n\n // Static title\n return resolveFormTitle(formConfig.title);\n }, [formConfig.title, formConfig.selectTitle, getFormState]);\n\n // === CONTEXT VALUE ===\n\n const contextValue = useMemo<FormContextValue<TFieldValues>>(\n () => ({\n config,\n formConfig,\n record,\n registerField,\n unregisterField,\n addSubscription,\n removeSubscription,\n registerWatcherSetter,\n unregisterWatcherSetter,\n changeField,\n setFieldValidating,\n getFormState,\n onSubmit,\n debouncedSubmit,\n submitImmediate,\n unusedFields,\n methods: methods as any,\n }),\n [\n config,\n formConfig,\n record,\n registerField,\n unregisterField,\n addSubscription,\n removeSubscription,\n registerWatcherSetter,\n unregisterWatcherSetter,\n changeField,\n setFieldValidating,\n getFormState,\n onSubmit,\n debouncedSubmit,\n submitImmediate,\n unusedFields,\n methods,\n ],\n );\n\n // === RENDER ===\n\n // CRITICAL: Only access methods.formState when children is a function\n // Accessing formState ANYWHERE creates a subscription to the entire form state\n // This would cause ALL children to re-render on ANY field change\n const isRenderFunction = typeof children === \"function\";\n\n return (\n <FormProvider {...methods}>\n <FormContext.Provider value={contextValue as any}>\n <GroupContext.Provider value={defaultGroupContext}>\n {isRenderFunction\n ? children({\n unusedFields,\n formState: methods.formState,\n methods: methods as any,\n handleSubmit: handleRenderSubmit,\n resolvedTitle,\n })\n : children}\n </GroupContext.Provider>\n </FormContext.Provider>\n </FormProvider>\n );\n}\n\n/**\n * Transform values for submission\n *\n * Applies valueField extraction and field name transformation\n * based on input config settings.\n */\nfunction transformValuesForSubmit<T extends FieldValues>(\n values: T,\n config: FormFieldsConfig,\n inputs: Record<string, InputConfig>,\n): Partial<T> {\n const result: Record<string, unknown> = {};\n\n for (const [name, value] of Object.entries(values)) {\n const fieldConfig = config[name];\n const type = fieldConfig?.type ?? \"textField\";\n const inputConfig = inputs[type];\n\n if (inputConfig) {\n // Get the submit field name (may be transformed)\n const submitName = transformFieldName(name, inputConfig.getSubmitField);\n\n // Extract value from complex object if valueField is specified\n const submitValue = extractValueField(value, inputConfig.valueField);\n\n result[submitName] = submitValue;\n } else {\n result[name] = value;\n }\n }\n\n return result as Partial<T>;\n}\n\nexport type { FormContextValue };\n","// @formality-ui/react - useInferredInputs Hook\n// Infers field dependencies from selectProps and conditions\n\nimport { useMemo } from \"react\";\nimport {\n inferFieldsFromDescriptor,\n inferFieldsFromConditions,\n} from \"@formality-ui/core\";\nimport type { ConditionDescriptor, SelectValue } from \"@formality-ui/core\";\n\ninterface UseInferredInputsOptions {\n /** Dynamic props descriptor to analyze for field references */\n selectProps?: SelectValue;\n\n /** Form-level default field props to analyze for field references */\n formDefaultFieldProps?: SelectValue;\n\n /** Provider-level default field props to analyze for field references */\n providerDefaultFieldProps?: SelectValue;\n\n /** Conditions to analyze for field references */\n conditions?: ConditionDescriptor[];\n\n /** Explicit field subscriptions */\n subscribesTo?: string[];\n}\n\n/**\n * Infers field dependencies from selectProps, conditions, and explicit subscriptions\n *\n * This hook analyzes:\n * - selectProps expressions for field references\n * - condition 'when' fields and 'selectWhen' expressions\n * - explicit subscribesTo declarations\n *\n * Used to automatically determine which fields a Field or FieldGroup\n * should subscribe to for reactive updates.\n *\n * @param options - Sources to analyze for field references\n * @returns Array of unique field names to subscribe to\n *\n * @example\n * ```tsx\n * const subscriptions = useInferredInputs({\n * selectProps: \"client.id\",\n * conditions: [{ when: 'signed', disabled: true }],\n * subscribesTo: ['contact'],\n * });\n * // → ['client', 'signed', 'contact']\n * ```\n */\nexport function useInferredInputs(options: UseInferredInputsOptions): string[] {\n const {\n selectProps,\n formDefaultFieldProps,\n providerDefaultFieldProps,\n conditions,\n subscribesTo,\n } = options;\n\n // Stable content signature.\n //\n // These inputs arrive from config objects that are usually reference-stable,\n // but callers also pass `undefined` (formerly defaulted to a *fresh* `[]` on\n // every call) and sometimes inline arrays. Keying the memo on a serialized\n // signature — instead of the raw array identities — keeps the returned array\n // reference stable across renders when nothing actually changed.\n //\n // Without this, the returned array is a new reference every render, which\n // propagates: `Field.allSubscriptions` memo busts every render, and\n // `useSubscriptions`'s effect (which lists `subscriptions` in its deps) tears\n // down + re-runs on every render — calling `addSubscription`/\n // `removeSubscription`, which `setWatchers` (a setState) inside an effect.\n // That setState-in-effect storm is what surfaces as React's\n // \"Maximum update depth exceeded\".\n const signature = JSON.stringify({\n selectProps,\n formDefaultFieldProps,\n providerDefaultFieldProps,\n conditions,\n subscribesTo,\n });\n\n return useMemo(() => {\n const inferred: string[] = [...(subscribesTo ?? [])];\n\n // Infer from providerDefaultFieldProps expression/descriptor\n if (providerDefaultFieldProps) {\n inferred.push(...inferFieldsFromDescriptor(providerDefaultFieldProps));\n }\n\n // Infer from formDefaultFieldProps expression/descriptor\n if (formDefaultFieldProps) {\n inferred.push(...inferFieldsFromDescriptor(formDefaultFieldProps));\n }\n\n // Infer from selectProps expression/descriptor\n if (selectProps) {\n inferred.push(...inferFieldsFromDescriptor(selectProps));\n }\n\n // Infer from conditions (when fields, selectWhen expressions)\n if (conditions && conditions.length > 0) {\n inferred.push(...inferFieldsFromConditions(conditions));\n }\n\n // Return unique field names\n return [...new Set(inferred)];\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [signature]);\n}\n","// @formality-ui/react - useConditions Hook\n// Evaluates conditions against current field values\n\nimport { useMemo } from \"react\";\nimport { useWatch } from \"react-hook-form\";\nimport {\n evaluateConditions,\n type ConditionResult,\n type FieldStateInput,\n} from \"@formality-ui/core\";\nimport type { ConditionDescriptor, FormFieldsConfig } from \"@formality-ui/core\";\nimport { useFormContext } from \"../context/FormContext\";\nimport { useInferredInputs } from \"./useInferredInputs\";\n\ninterface UseConditionsOptions {\n /** Conditions to evaluate */\n conditions: ConditionDescriptor[];\n\n /** Explicit field subscriptions */\n subscribesTo?: string[];\n\n /** Additional props for expression context */\n props?: Record<string, unknown>;\n\n /** Optional: All field configs for computing disabled states in fieldStates */\n allFieldsConfig?: FormFieldsConfig;\n}\n\n/**\n * Evaluates conditions against current field values\n *\n * This hook:\n * 1. Infers which fields to watch from conditions\n * 2. Subscribes to those fields via useWatch\n * 3. Evaluates conditions whenever watched values change\n *\n * Implements the condition evaluation rules:\n * - disabled: OR logic (any true = disabled)\n * - visible: AND logic (any false = hidden)\n * - setValue: last matching condition wins\n *\n * Uses two-pass evaluation to populate the disabled property in field states:\n * - Pass 1: Build base field states without disabled (prevents circular dependency)\n * - Pass 2: Compute disabled for each field using Pass 1 states\n * - Pass 3: Merge base states with disabled into final field states\n *\n * @param options - Conditions and subscription config\n * @returns Evaluation result with disabled, visible, and setValue states\n *\n * @example\n * ```tsx\n * const result = useConditions({\n * conditions: [\n * { when: 'signed', is: false, disabled: true },\n * { when: 'archived', truthy: true, visible: false },\n * ],\n * });\n * // result.disabled === true when signed is false\n * // result.visible === false when archived is truthy\n * ```\n */\nexport function useConditions(options: UseConditionsOptions): ConditionResult {\n const { conditions, subscribesTo, props, allFieldsConfig } = options;\n const { record, methods } = useFormContext();\n\n // Infer fields to watch from conditions and explicit subscriptions\n const watchFields = useInferredInputs({\n conditions,\n subscribesTo,\n });\n\n // Watch inferred fields (only subscribe if there are fields to watch)\n // CRITICAL: useWatch provides ISOLATED subscriptions - only re-renders when these specific values change\n const watchedValues = useWatch({\n control: methods.control,\n name: watchFields.length > 0 ? (watchFields as any) : [],\n });\n\n // Build field values map from watched values\n const fieldValues = useMemo(() => {\n const values: Record<string, unknown> = {};\n\n if (watchFields.length === 0) {\n return values;\n }\n\n // CRITICAL: useWatch with an array of names ALWAYS returns an array of values,\n // regardless of how many fields are watched. Only useWatch({ name: 'string' })\n // returns a single value.\n if (Array.isArray(watchedValues)) {\n watchFields.forEach((field, i) => {\n values[field] = watchedValues[i];\n });\n } else {\n // Fallback: single field, single value (shouldn't happen with array name)\n values[watchFields[0]] = watchedValues;\n }\n\n return values;\n }, [watchFields, watchedValues]);\n\n // ============================================================================\n // PASS 1: Build base field states WITHOUT disabled property\n // ============================================================================\n // CRITICAL: Use getFieldState() for NON-REACTIVE access to field metadata\n // This prevents subscribing to the entire form state which causes all fields to re-validate\n // Field states are read on-demand when values change, not when ANY field's metadata changes\n //\n // NOTE: This is Pass 1 of two-pass evaluation - disabled is NOT included here\n // to break the circular dependency between conditions and disabled state.\n const baseFieldStates = useMemo(() => {\n const states: Record<string, FieldStateInput> = {};\n\n // Collect all fields to build states for: watched fields + current field\n // Current field is needed for two-pass evaluation when it references other fields' disabled states\n const currentFieldName = props?.name as string | undefined;\n const allFieldsForPass1 = currentFieldName\n ? [...new Set([...watchFields, currentFieldName])]\n : watchFields;\n\n if (allFieldsForPass1.length === 0) {\n return states;\n }\n\n allFieldsForPass1.forEach((fieldName) => {\n // getFieldState() reads current state without creating subscriptions\n const fieldState = methods.getFieldState(fieldName as any);\n states[fieldName] = {\n value: fieldValues[fieldName],\n isTouched: fieldState.isTouched,\n isDirty: fieldState.isDirty,\n error: fieldState.error,\n invalid: fieldState.invalid,\n isValidating: false, // Not easily available per-field\n // ❌ NO disabled property - this is critical for Pass 1 to prevent circular dependency\n };\n });\n\n return states;\n }, [watchFields, fieldValues, methods, props]);\n\n // ============================================================================\n // PASS 2: Compute disabled states for each field\n // ============================================================================\n // Uses baseFieldStates (without disabled) to evaluate conditions\n // This prevents the circular dependency: conditions → disabled → conditions\n //\n // For circular dependencies (e.g., fieldA.isDisabled depends on fieldB.isDisabled),\n // we use iterative evaluation to converge to a stable state:\n // - Start with baseFieldStates (disabled = undefined for all)\n // - Iteratively compute disabled states until stable or max iterations reached\n const disabledStates = useMemo(() => {\n const disabled: Record<string, boolean> = {};\n\n // Collect all fields that need disabled state computation:\n // 1. Watched fields (fields referenced in conditions)\n // 2. Current field (so it can compute its own disabled from conditions)\n // 3. All fields in allFieldsConfig (to ensure we have states for all referenced fields)\n const currentFieldName = props?.name as string | undefined;\n const configFields = allFieldsConfig ? Object.keys(allFieldsConfig) : [];\n const allFieldsForPass2 = [...new Set([...watchFields, ...configFields])];\n if (currentFieldName && !allFieldsForPass2.includes(currentFieldName)) {\n allFieldsForPass2.push(currentFieldName);\n }\n\n if (allFieldsForPass2.length === 0) {\n return disabled;\n }\n\n // Build base states for ALL fields (not just watched fields)\n // This ensures we have states for fields that don't have baseFieldStates yet\n const allBaseStates: Record<string, FieldStateInput> = {};\n for (const fieldName of allFieldsForPass2) {\n if (baseFieldStates[fieldName]) {\n allBaseStates[fieldName] = baseFieldStates[fieldName];\n } else {\n // Field not in baseFieldStates, create default state\n const fieldState = methods.getFieldState(fieldName as any);\n allBaseStates[fieldName] = {\n value: fieldValues[fieldName],\n isTouched: fieldState.isTouched,\n isDirty: fieldState.isDirty,\n error: fieldState.error,\n invalid: fieldState.invalid,\n isValidating: false,\n };\n }\n }\n\n // Initial pass: compute disabled using allBaseStates (no disabled property)\n let currentStates = allBaseStates;\n let hasChanged = true;\n let iteration = 0;\n const maxIterations = 10; // Prevent infinite loops, should converge quickly\n\n while (hasChanged && iteration < maxIterations) {\n hasChanged = false;\n iteration++;\n\n // Compute disabled for all fields using current states\n const newDisabled: Record<string, boolean> = {};\n\n for (const fieldName of allFieldsForPass2) {\n const fieldConfig = allFieldsConfig?.[fieldName];\n const fieldConditions = fieldConfig?.conditions ?? [];\n const configDisabled = fieldConfig?.disabled;\n\n const result = evaluateConditions({\n conditions: fieldConditions,\n fieldValues,\n fieldStates: currentStates,\n record,\n props: { name: fieldName },\n });\n\n // Priority: config > conditions\n // Config-level disabled takes precedence over condition-based disabled\n newDisabled[fieldName] = configDisabled ?? result.disabled ?? false;\n }\n\n // Create new states with updated disabled\n const newStates: Record<string, FieldStateInput> = {};\n for (const fieldName of allFieldsForPass2) {\n const baseState = allBaseStates[fieldName];\n if (baseState) {\n newStates[fieldName] = {\n ...baseState,\n disabled: newDisabled[fieldName],\n };\n }\n }\n\n // Check if disabled states have changed\n for (const fieldName of allFieldsForPass2) {\n const oldDisabled = disabled[fieldName];\n const newDisabledValue = newDisabled[fieldName];\n if (oldDisabled !== newDisabledValue) {\n hasChanged = true;\n disabled[fieldName] = newDisabledValue;\n }\n }\n\n // Use new states for next iteration\n currentStates = newStates;\n }\n\n return disabled;\n }, [\n watchFields,\n allFieldsConfig,\n fieldValues,\n baseFieldStates,\n record,\n props,\n methods,\n ]);\n\n // ============================================================================\n // PASS 3: Merge base states with disabled into final field states\n // ============================================================================\n // This is the final fieldStates object that includes all properties including disabled\n const fieldStates = useMemo(() => {\n // Start with baseFieldStates (watched fields + current field)\n const states: Record<string, FieldStateInput> = { ...baseFieldStates };\n\n // Add disabled states for all fields that have them (from Pass 2)\n // This includes fields from allFieldsConfig that might not be in baseFieldStates\n Object.entries(disabledStates).forEach(([fieldName, disabled]) => {\n if (states[fieldName]) {\n // Field already in baseFieldStates, just add disabled\n states[fieldName] = {\n ...states[fieldName],\n disabled,\n };\n } else {\n // Field not in baseFieldStates, create new state with disabled\n const fieldState = methods.getFieldState(fieldName as any);\n states[fieldName] = {\n value: fieldValues[fieldName],\n isTouched: fieldState.isTouched,\n isDirty: fieldState.isDirty,\n error: fieldState.error,\n invalid: fieldState.invalid,\n isValidating: false,\n disabled,\n };\n }\n });\n\n return states;\n }, [baseFieldStates, disabledStates, fieldValues, methods]);\n\n // Evaluate conditions whenever field values or states change\n return useMemo(() => {\n // Return empty result if no conditions\n if (conditions.length === 0) {\n return {\n disabled: undefined,\n visible: undefined,\n setValue: undefined,\n hasDisabledCondition: false,\n hasVisibleCondition: false,\n hasSetCondition: false,\n };\n }\n\n return evaluateConditions({\n conditions,\n fieldValues,\n fieldStates,\n record,\n props,\n });\n }, [conditions, fieldValues, fieldStates, record, props]);\n}\n","// @formality-ui/react - usePropsEvaluation Hook\n// Evaluates selectProps against current field values\n\nimport { useMemo } from \"react\";\nimport { useWatch } from \"react-hook-form\";\nimport {\n evaluateDescriptor,\n buildFieldContext,\n type FormState,\n} from \"@formality-ui/core\";\nimport type { SelectValue } from \"@formality-ui/core\";\nimport { useFormContext } from \"../context/FormContext\";\nimport { useInferredInputs } from \"./useInferredInputs\";\nimport { makeProxyState } from \"../utils/makeProxyState\";\n\n/**\n * Evaluated props object returned by usePropsEvaluation\n *\n * Result of evaluating SelectValue expressions (selectProps, formDefaultFieldProps,\n * providerDefaultFieldProps) against current form state.\n *\n * The evaluation follows the priority system where higher-priority props override\n * lower-priority ones:\n * 1. Field-level selectProps (highest priority)\n * 2. Form-level formDefaultFieldProps (medium priority)\n * 3. Provider-level providerDefaultFieldProps (lowest priority)\n *\n * @example\n * ```tsx\n * // Expression evaluation\n * const props = usePropsEvaluation({\n * selectProps: { disabled: '!signed' },\n * fieldName: 'contact',\n * });\n * // When signed=false, props = { disabled: true }\n *\n * // Function callback evaluation\n * const props = usePropsEvaluation({\n * selectProps: (formState) => ({\n * variant: formState.fields.type?.value === 'premium' ? 'filled' : 'outlined'\n * }),\n * fieldName: 'variant',\n * });\n * ```\n */\nexport type SelectedProps = Record<string, unknown>;\n\n/**\n * Result of evaluating all three prop sources separately\n *\n * Each layer is evaluated independently so that mergeFieldProps\n * can correctly apply the 8-layer priority order.\n */\nexport interface EvaluatedPropsResult {\n /** Evaluated provider-level selectDefaultFieldProps (layer 7 priority) */\n providerSelectProps: Record<string, unknown>;\n\n /** Evaluated form-level selectDefaultFieldProps (layer 5 priority) */\n formSelectProps: Record<string, unknown>;\n\n /** Evaluated field-level selectProps (layer 2 priority) */\n fieldSelectProps: Record<string, unknown>;\n}\n\nexport interface UsePropsEvaluationOptions {\n /** Dynamic props descriptor to evaluate */\n selectProps?: SelectValue;\n\n /** Dynamic default field props from Form config (higher priority) */\n formDefaultFieldProps?: SelectValue;\n\n /** Dynamic default field props from Provider config (lower priority) */\n providerDefaultFieldProps?: SelectValue;\n\n /** Explicit field subscriptions */\n subscribesTo?: string[];\n\n /** Current field name */\n fieldName: string;\n}\n\n/**\n * Evaluates dynamic props against current field values\n *\n * This hook:\n * 1. Infers which fields to watch from selectProps expressions\n * 2. Subscribes to those fields via useWatch\n * 3. Evaluates selectProps whenever watched values change\n *\n * Handles both expression-based selectProps and function-based selectProps.\n *\n * @param options - Hook options including props to evaluate and subscription config\n * @param {SelectValue} [options.selectProps] - Dynamic props descriptor to evaluate\n * @param {SelectValue} [options.formDefaultFieldProps] - Dynamic default props from Form config (higher priority)\n * @param {SelectValue} [options.providerDefaultFieldProps] - Dynamic default props from Provider config (lower priority)\n * @param {string[]} [options.subscribesTo] - Explicit field subscriptions\n * @param {string} options.fieldName - Current field name\n * @returns Evaluated props object\n *\n * @example\n * ```tsx\n * const props = usePropsEvaluation({\n * selectProps: {\n * options: \"client.id ? clientOptions : allOptions\",\n * disabled: \"!signed\",\n * },\n * fieldName: 'contact',\n * });\n * // props.options and props.disabled are evaluated against current state\n * ```\n */\nexport function usePropsEvaluation(\n options: UsePropsEvaluationOptions,\n): EvaluatedPropsResult {\n const {\n selectProps,\n formDefaultFieldProps,\n providerDefaultFieldProps,\n subscribesTo,\n fieldName,\n } = options;\n const { record, methods } = useFormContext();\n\n // Infer fields to watch from providerDefaultFieldProps, formDefaultFieldProps, selectProps, and explicit subscriptions\n const watchFields = useInferredInputs({\n providerDefaultFieldProps,\n formDefaultFieldProps,\n selectProps,\n subscribesTo,\n });\n\n // Watch inferred fields (only subscribe if there are fields to watch)\n const watchedValues = useWatch({\n control: methods.control,\n name: watchFields.length > 0 ? (watchFields as any) : [],\n });\n\n // Build form state for evaluation (needed for function-based selectProps)\n // CRITICAL: Only build state for watched fields to maintain performance isolation\n const formState = useMemo((): FormState => {\n // Build proxy-wrapped field states ONLY for watched fields\n // This prevents subscribing to the entire form state\n const fields: Record<string, any> = {};\n\n if (watchFields.length > 0) {\n // useWatch returns an array when given an array of field names\n // useWatch({ name: [\"f1\"] }) → [v1]\n // useWatch({ name: [\"f1\", \"f2\"] }) → [v1, v2]\n const values = Array.isArray(watchedValues)\n ? watchFields.reduce(\n (acc, field, i) => {\n acc[field] = watchedValues[i];\n return acc;\n },\n {} as Record<string, unknown>,\n )\n : (watchedValues as Record<string, unknown>);\n\n watchFields.forEach((name) => {\n // Create minimal proxy state with just the value\n // We don't need isTouched/isDirty/error for selectProps evaluation\n fields[name] = makeProxyState({\n value: values[name],\n isTouched: false,\n isDirty: false,\n isValidating: false,\n error: undefined,\n invalid: false,\n });\n });\n }\n\n return {\n fields,\n record: record ?? {},\n errors: {},\n defaultValues: {},\n touchedFields: {},\n dirtyFields: {},\n isDirty: false,\n isTouched: false,\n isValid: true,\n isSubmitting: false,\n };\n // Only depends on watchFields and watchedValues - NOT the entire form state\n }, [watchFields, watchedValues, record]);\n\n // Evaluate props: evaluate ALL three layers separately for mergeFieldProps\n return useMemo(() => {\n // Step 1: Evaluate providerDefaultFieldProps (lowest priority, layer 7)\n let providerResult: Record<string, unknown> = {};\n if (providerDefaultFieldProps) {\n // Handle function providerDefaultFieldProps\n if (typeof providerDefaultFieldProps === \"function\") {\n providerResult =\n (providerDefaultFieldProps(formState, methods) as Record<\n string,\n unknown\n >) ?? {};\n } else {\n // Build evaluation context\n const context = buildFieldContext(formState, fieldName);\n\n // Evaluate descriptor (string expression, object with expressions, or array)\n providerResult =\n (evaluateDescriptor(providerDefaultFieldProps, context) as Record<\n string,\n unknown\n >) ?? {};\n }\n }\n\n // Step 2: Evaluate formDefaultFieldProps (medium priority, layer 5)\n let formResult: Record<string, unknown> = {};\n if (formDefaultFieldProps) {\n // Handle function formDefaultFieldProps\n if (typeof formDefaultFieldProps === \"function\") {\n formResult =\n (formDefaultFieldProps(formState, methods) as Record<\n string,\n unknown\n >) ?? {};\n } else {\n // Build evaluation context\n const context = buildFieldContext(formState, fieldName);\n\n // Evaluate descriptor (string expression, object with expressions, or array)\n formResult =\n (evaluateDescriptor(formDefaultFieldProps, context) as Record<\n string,\n unknown\n >) ?? {};\n }\n }\n\n // Step 3: Evaluate selectProps (highest priority, layer 2)\n let fieldResult: Record<string, unknown> = {};\n if (selectProps) {\n // Handle function selectProps\n if (typeof selectProps === \"function\") {\n fieldResult =\n (selectProps(formState, methods) as Record<string, unknown>) ?? {};\n } else {\n // Build evaluation context\n const context = buildFieldContext(formState, fieldName);\n\n // Evaluate descriptor (string expression, object with expressions, or array)\n fieldResult =\n (evaluateDescriptor(selectProps, context) as Record<\n string,\n unknown\n >) ?? {};\n }\n }\n\n // Step 4: Return all three results for mergeFieldProps to handle priority\n return {\n providerSelectProps: providerResult,\n formSelectProps: formResult,\n fieldSelectProps: fieldResult,\n };\n }, [\n providerDefaultFieldProps,\n formDefaultFieldProps,\n selectProps,\n formState,\n methods,\n fieldName,\n ]);\n}\n","// @formality-ui/react - useSubscriptions Hook\n// Manages field subscriptions in the Form's inverted index\n\nimport { useEffect, useRef } from \"react\";\nimport { useFormContext } from \"../context/FormContext\";\n\n/**\n * Manages field subscriptions\n *\n * This hook registers the current field as a subscriber to the target fields,\n * and cleans up subscriptions when the component unmounts or subscriptions change.\n *\n * Subscriptions are stored in the Form's inverted index (target → subscribers),\n * which allows target fields to know who is watching them (for optimization).\n *\n * @param fieldName - The subscribing field's name\n * @param subscriptions - Array of field names to subscribe to\n *\n * @example\n * ```tsx\n * // Contact field subscribes to client field\n * useSubscriptions('contact', ['client']);\n *\n * // When client changes, its watchers can be notified\n * // This enables features like passSubscriptions\n * ```\n */\nexport function useSubscriptions(\n fieldName: string,\n subscriptions: string[],\n): void {\n const { addSubscription, removeSubscription } = useFormContext();\n\n // PATTERN: Per-effect subscription tracking (similar to executionVersionRef in Form.tsx)\n // Track the current effect run ID\n const runIdRef = useRef<number>(0);\n\n // Store subscriptions added in each effect run\n // Key: run ID, Value: subscriptions array for that run\n const runSubscriptionsRef = useRef<Map<number, string[]>>(new Map());\n\n useEffect(() => {\n // Increment run ID for this effect invocation\n const currentRunId = ++runIdRef.current;\n\n // CRITICAL: Store subscriptions for THIS specific effect run\n // Use [...subscriptions] to create a copy (prevent reference sharing)\n runSubscriptionsRef.current.set(currentRunId, [...subscriptions]);\n\n // Add all subscriptions\n subscriptions.forEach((target) => {\n addSubscription(target, fieldName);\n\n // Log subscription addition (development only)\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Formality Subscription] Run ${currentRunId}: ` +\n `\"${fieldName}\" subscribing to \"${target}\"`,\n );\n }\n });\n\n // Cleanup only removes subscriptions added in THIS run\n return () => {\n // Get subscriptions for THIS specific run (not current subscriptions value)\n const thisRunSubscriptions =\n runSubscriptionsRef.current.get(currentRunId);\n\n if (thisRunSubscriptions) {\n // Log cleanup start (development only)\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Formality Subscription] Run ${currentRunId}: ` +\n `\"${fieldName}\" cleaning up [${thisRunSubscriptions.join(\", \")}]`,\n );\n }\n\n // PATTERN: LIFO cleanup (Last In, First Out)\n // Reverse order for dependent subscriptions\n [...thisRunSubscriptions].reverse().forEach((target) => {\n removeSubscription(target, fieldName);\n });\n\n // CRITICAL: Clean up tracking map to prevent memory leaks\n runSubscriptionsRef.current.delete(currentRunId);\n }\n };\n }, [fieldName, subscriptions, addSubscription, removeSubscription]);\n}\n","// @formality-ui/react - Field Component\n// Core field component with Controller integration\n\nimport {\n useMemo,\n useCallback,\n useEffect,\n useState,\n useRef,\n createElement,\n type ReactNode,\n type Ref,\n} from \"react\";\nimport {\n Controller,\n type ControllerFieldState,\n type UseFormStateReturn,\n type FieldValues,\n} from \"react-hook-form\";\nimport {\n resolveInputConfig,\n mergeFieldProps,\n resolveLabel,\n parse,\n format,\n runValidator,\n resolveErrorMessage,\n} from \"@formality-ui/core\";\nimport type { FieldConfig, InputConfig } from \"@formality-ui/core\";\nimport type { FormalityFieldComponentProps } from \"../overlays\";\nimport { useFormContext } from \"../context/FormContext\";\nimport { useConfigContext } from \"../context/ConfigContext\";\nimport { useGroupContext } from \"../context/GroupContext\";\nimport { useConditions } from \"../hooks/useConditions\";\nimport { usePropsEvaluation } from \"../hooks/usePropsEvaluation\";\nimport { useInferredInputs } from \"../hooks/useInferredInputs\";\nimport { useSubscriptions } from \"../hooks/useSubscriptions\";\nimport type { WatcherSetterFn } from \"../types\";\n\n/**\n * Field component props.\n *\n * `FieldProps` is generic over the field `name`:\n * `FieldProps<TName extends string = string>`. The default `TName = string`\n * means `<Field name={anyString} />` compiles unchanged (no migration) and a\n * bare `FieldProps` is identical to `FieldProps<string>`.\n *\n * To get compile-time checking of the field name, narrow `TName` explicitly —\n * e.g. `FieldProps<\"name\" | \"email\">` or a wrapper that threads a\n * `keyof ClientValues & string`. With a narrowed `TName`, a typo like\n * `name=\"ofice\"` is rejected at compile time instead of silently rendering\n * nothing (the second half of PRD §C.4 / T2.1's \"silent no-op\" fix).\n *\n * Automatic per-form narrowing — where a `<Field>` automatically narrows its\n * `name` against the enclosing `<Form<TFieldValues>>`'s key set — is a planned\n * follow-up (PRD §C.4 T2.1) and is explicitly deferrable.\n *\n * @example\n * ```tsx\n * // Default usage — any string name compiles (unchanged behavior):\n * <Field name=\"email\" />;\n *\n * // Opt-in strict usage — typo names are compile errors:\n * type Names = \"name\" | \"email\";\n * const props: FieldProps<Names> = { name: \"email\" };\n * ```\n */\nexport interface FieldProps<TName extends string = string> {\n /**\n * Field name (must match a key in Form's config).\n *\n * When `FieldProps` is narrowed (e.g. `FieldProps<\"name\" | \"email\">`), the\n * name is checked against `TName` at compile time. With the default\n * (`FieldProps` / `FieldProps<string>`), any string is accepted.\n */\n name: TName;\n\n /** Override the input type from config */\n type?: string;\n\n /** Override disabled state */\n disabled?: boolean;\n\n /** Override hidden state (inverse of visible) */\n hidden?: boolean;\n\n /** Custom render function for advanced use cases */\n children?: ReactNode | ((api: FieldRenderAPI) => ReactNode);\n\n /** Whether to register this field in Form's field registry (default: true) */\n shouldRegister?: boolean;\n\n /** Override input config for this field (e.g., debounce setting) */\n inputConfig?: Partial<InputConfig>;\n\n /** Additional props to pass to the input component */\n [key: string]: unknown;\n}\n\n/**\n * API passed to render function children\n */\nexport interface FieldRenderAPI {\n /** React Hook Form field state */\n fieldState: ControllerFieldState;\n\n /** The rendered input component */\n renderedField: ReactNode;\n\n /** Final merged props passed to input */\n fieldProps: Record<string, unknown>;\n\n /** Map of fields watching this field */\n watchers: Record<string, boolean>;\n\n /** React Hook Form form state */\n formState: UseFormStateReturn<FieldValues>;\n}\n\n/**\n * Field component - Renders a form field with full Formality integration\n *\n * Provides:\n * - React Hook Form Controller integration\n * - Props resolution (8-layer merge)\n * - Condition evaluation (disabled/visible/setValue)\n * - Value transformation (parse/format)\n * - Validation (field + type validators)\n * - Subscription management\n *\n * @example\n * ```tsx\n * // Basic usage\n * <Field name=\"email\" />\n *\n * // Override type\n * <Field name=\"status\" type=\"select\" />\n *\n * // Custom render\n * <Field name=\"name\">\n * {({ renderedField, fieldState }) => (\n * <div className={fieldState.error ? 'has-error' : ''}>\n * {renderedField}\n * </div>\n * )}\n * </Field>\n * ```\n */\nexport function Field<TName extends string = string>({\n name,\n type: typeProp,\n disabled: disabledProp,\n hidden: hiddenProp,\n children,\n shouldRegister = true,\n inputConfig: inputConfigProp,\n ...restProps\n}: FieldProps<TName>): JSX.Element | null {\n const {\n config,\n formConfig,\n methods,\n registerField,\n unregisterField,\n registerWatcherSetter,\n unregisterWatcherSetter,\n changeField,\n setFieldValidating,\n } = useFormContext();\n\n const providerConfig = useConfigContext();\n const groupContext = useGroupContext();\n\n // Get field config\n const fieldConfig: FieldConfig = config[name] ?? {};\n\n // Resolve type\n const type = typeProp ?? fieldConfig.type ?? \"textField\";\n\n // Resolve input config (merge provider + form + prop)\n const inputConfig = useMemo((): InputConfig => {\n const formInputs =\n typeof formConfig.inputs === \"function\"\n ? formConfig.inputs(providerConfig.inputs)\n : (formConfig.inputs ?? {});\n\n // Merge provider inputs with form-level overrides\n const mergedInputs: Record<string, InputConfig> = {\n ...providerConfig.inputs,\n };\n for (const [key, override] of Object.entries(formInputs)) {\n if (mergedInputs[key]) {\n mergedInputs[key] = {\n ...mergedInputs[key],\n ...override,\n } as InputConfig;\n }\n }\n\n const baseInputConfig = resolveInputConfig(type, mergedInputs) ?? {\n component: \"input\",\n defaultValue: \"\",\n };\n\n // Merge with inputConfig prop (prop has highest priority)\n return inputConfigProp\n ? ({ ...baseInputConfig, ...inputConfigProp } as InputConfig)\n : baseInputConfig;\n }, [type, providerConfig.inputs, formConfig.inputs, inputConfigProp]);\n\n // === REGISTRATION ===\n\n useEffect(() => {\n if (shouldRegister) {\n registerField(name);\n return () => unregisterField(name);\n }\n }, [name, shouldRegister, registerField, unregisterField]);\n\n // === WATCHER STATE ===\n\n const [watchers, setWatchers] = useState<Record<string, boolean>>({});\n\n useEffect(() => {\n registerWatcherSetter(name, setWatchers as WatcherSetterFn);\n return () => unregisterWatcherSetter(name);\n }, [name, registerWatcherSetter, unregisterWatcherSetter]);\n\n // === SUBSCRIPTIONS ===\n\n const inferredSubscriptions = useInferredInputs({\n selectProps: fieldConfig.selectProps,\n conditions: fieldConfig.conditions,\n subscribesTo: fieldConfig.subscribesTo,\n });\n\n // Merge with group subscriptions\n const allSubscriptions = useMemo(() => {\n return [\n ...new Set([...inferredSubscriptions, ...groupContext.subscriptions]),\n ];\n }, [inferredSubscriptions, groupContext.subscriptions]);\n\n useSubscriptions(name, allSubscriptions);\n\n // === CONDITIONS ===\n\n const conditionResult = useConditions({\n conditions: fieldConfig.conditions ?? [],\n subscribesTo: fieldConfig.subscribesTo,\n props: { name },\n allFieldsConfig: config, // Pass all field configs for two-pass evaluation of disabled states\n });\n\n // === APPLY SET VALUE FROM CONDITIONS ===\n // When a condition's set/selectSet evaluates, apply the value to the field\n // Priority: field-level conditions > group-level conditions\n // Store methods.setValue in a ref to avoid dependency issues\n const setValueRef = useRef(methods.setValue);\n setValueRef.current = methods.setValue;\n const getValuesRef = useRef(methods.getValues);\n getValuesRef.current = methods.getValues;\n\n // Determine effective setValue: field-level takes priority over group-level\n const effectiveSetValue = useMemo(() => {\n if (conditionResult.hasSetCondition) {\n return { hasCondition: true, value: conditionResult.setValue };\n }\n if (groupContext.state.hasSetCondition) {\n return { hasCondition: true, value: groupContext.state.setValue };\n }\n return { hasCondition: false, value: undefined };\n }, [\n conditionResult.hasSetCondition,\n conditionResult.setValue,\n groupContext.state.hasSetCondition,\n groupContext.state.setValue,\n ]);\n\n useEffect(() => {\n if (\n effectiveSetValue.hasCondition &&\n effectiveSetValue.value !== undefined\n ) {\n const currentValue = getValuesRef.current(name);\n // Only update if the value is actually different to avoid infinite loops\n if (currentValue !== effectiveSetValue.value) {\n // `methods` comes from the un-parameterized `useFormContext()` (→\n // UseFormReturn<FieldValues>), so setValue's name param is\n // FieldPath<FieldValues> === string at runtime. Our generic `name: TName`\n // (extends string) is structurally a string; cast for RHF's deep\n // conditional type. See PRP P1.M1.T1.S2 gotchas.\n setValueRef.current(name as string, effectiveSetValue.value, {\n shouldValidate: true,\n shouldDirty: true,\n shouldTouch: false,\n });\n }\n }\n }, [effectiveSetValue.hasCondition, effectiveSetValue.value, name]);\n\n // === DISABLED/VISIBLE RESOLUTION ===\n\n const isDisabled = useMemo(() => {\n // Resolution order: prop > config > condition > group > false\n if (disabledProp !== undefined) return disabledProp;\n if (fieldConfig.disabled !== undefined) return fieldConfig.disabled;\n if (conditionResult.hasDisabledCondition)\n return conditionResult.disabled ?? false;\n if (groupContext.state.isDisabled) return true;\n return false;\n }, [\n disabledProp,\n fieldConfig.disabled,\n conditionResult,\n groupContext.state.isDisabled,\n ]);\n\n const isVisible = useMemo(() => {\n // Resolution order: prop > config > condition > group > true\n if (hiddenProp !== undefined) return !hiddenProp;\n if (fieldConfig.hidden !== undefined) return !fieldConfig.hidden;\n if (conditionResult.hasVisibleCondition)\n return conditionResult.visible ?? true;\n if (!groupContext.state.isVisible) return false;\n return true;\n }, [\n hiddenProp,\n fieldConfig.hidden,\n conditionResult,\n groupContext.state.isVisible,\n ]);\n\n // === PROPS EVALUATION ===\n\n const { providerSelectProps, formSelectProps, fieldSelectProps } =\n usePropsEvaluation({\n selectProps: fieldConfig.selectProps,\n formDefaultFieldProps: formConfig.selectDefaultFieldProps,\n providerDefaultFieldProps: providerConfig.selectDefaultFieldProps,\n subscribesTo: fieldConfig.subscribesTo,\n fieldName: name,\n });\n\n // Resolve label\n const label = useMemo(() => {\n return resolveLabel(name, fieldConfig, fieldSelectProps, restProps);\n }, [name, fieldConfig, fieldSelectProps, restProps]);\n\n // === VALIDATION ===\n\n const validationRules = useMemo(() => {\n return {\n ...fieldConfig.rules,\n validate: async (value: unknown) => {\n setFieldValidating(name, true);\n\n try {\n // Field-level validator\n if (fieldConfig.validator) {\n const result = await runValidator(\n fieldConfig.validator,\n value,\n methods.getValues(),\n providerConfig.validators,\n );\n if (result !== true && result !== undefined) {\n return resolveErrorMessage(result, providerConfig.errorMessages);\n }\n }\n\n // Type-level validator\n if (inputConfig.validator) {\n const result = await runValidator(\n inputConfig.validator,\n value,\n methods.getValues(),\n providerConfig.validators,\n );\n if (result !== true && result !== undefined) {\n return resolveErrorMessage(result, providerConfig.errorMessages);\n }\n }\n\n return true;\n } finally {\n setFieldValidating(name, false);\n }\n },\n };\n }, [\n fieldConfig.rules,\n fieldConfig.validator,\n inputConfig.validator,\n methods,\n providerConfig.validators,\n providerConfig.errorMessages,\n name,\n setFieldValidating,\n ]);\n\n // === CHANGE HANDLER ===\n\n const handleChange = useCallback(\n (onChange: (value: unknown) => void) => (newValue: unknown) => {\n // Parse value\n const parsedValue = parse(\n newValue,\n inputConfig.parser,\n providerConfig.parsers,\n );\n\n // Update form value\n onChange(parsedValue);\n\n // Notify subscribers\n changeField(name, parsedValue, inputConfig);\n },\n [\n inputConfig.parser,\n providerConfig.parsers,\n changeField,\n name,\n inputConfig,\n ],\n );\n\n // Don't render if not visible\n if (!isVisible) {\n return null;\n }\n\n // === RENDER ===\n\n return (\n <Controller\n control={methods.control}\n name={name}\n rules={validationRules}\n render={({ field, fieldState, formState }) => {\n // Format value for display\n const formattedValue = format(\n field.value,\n inputConfig.formatter,\n providerConfig.formatters,\n );\n\n // Merge props (8 layers)\n const finalProps = mergeFieldProps({\n providerDefaultFieldProps: providerConfig.defaultFieldProps,\n providerSelectDefaultFieldProps: providerSelectProps,\n formDefaultFieldProps: formConfig.defaultFieldProps,\n formSelectDefaultFieldProps: formSelectProps,\n inputProps: inputConfig.props,\n fieldConfigProps: fieldConfig.props,\n selectProps: fieldSelectProps,\n componentProps: restProps,\n coreProps: {\n name,\n label,\n disabled: isDisabled,\n error: fieldState.error?.message,\n [inputConfig.inputFieldProp ?? \"value\"]: formattedValue,\n onChange: handleChange(field.onChange),\n onBlur: field.onBlur,\n forwardRef: field.ref,\n },\n });\n\n // Get component\n const Component =\n inputConfig.component as React.ComponentType<FormalityFieldComponentProps>;\n\n // Host-component fallback (PRD §20.4 narrow exception).\n //\n // When `inputConfig.component` is a string host tag (the degenerate\n // `component: \"input\"` fallback used when an input type is unknown /\n // misconfigured), React only intercepts its SPECIAL `ref` key — NOT the\n // `forwardRef` prop that §20.1/§20.4 deliver for real components. If we\n // spread `finalProps` unchanged onto a host element, RHF's ref callback\n // (delivered as `forwardRef`) is never attached → focus-on-error breaks,\n // and `forwardRef` leaks to the DOM as a spurious `forwardref` attribute.\n //\n // To keep that fallback path functional we translate `forwardRef` back\n // into the special `ref` key (and drop the `forwardRef` prop) ONLY for\n // host-element rendering. Component rendering stays strictly\n // `forwardRef`-exclusive per §20.4 — this branch never runs for real\n // consumer components (which are functions/objects, not strings).\n const isHostComponent = typeof inputConfig.component === \"string\";\n\n // Render through template if present\n const template =\n inputConfig.template ??\n providerConfig.inputTemplates[type] ??\n providerConfig.defaultInputTemplate;\n\n const TemplateComponent = template as\n | React.ComponentType<any>\n | undefined;\n\n let renderedField: React.ReactElement;\n if (TemplateComponent) {\n renderedField = (\n <TemplateComponent\n Field={Component}\n fieldProps={finalProps}\n fieldState={fieldState}\n formState={formState}\n />\n );\n } else if (isHostComponent) {\n // Host-element path: translate `forwardRef` back into React's special\n // `ref` key (see block comment above) so the bare fallback input still\n // wires RHF's ref callback and supports focus-on-error. Cast to a\n // host tag — `isHostComponent` guarantees `inputConfig.component` is a\n // string here, and React's JSX for intrinsic elements accepts `ref`.\n const { forwardRef: hostRef, ...restHostProps } =\n finalProps as Record<string, unknown>;\n renderedField = createElement(inputConfig.component as string, {\n ...restHostProps,\n ref: hostRef as Ref<HTMLElement>,\n });\n } else {\n // Component path: forwardRef-exclusive per PRD §20.4.\n renderedField = <Component {...finalProps} />;\n }\n\n // Render children if function\n if (typeof children === \"function\") {\n const result = children({\n fieldState,\n renderedField,\n fieldProps: finalProps,\n watchers,\n formState,\n });\n // Ensure we return a valid ReactElement\n return <>{result}</>;\n }\n\n return renderedField as React.ReactElement;\n }}\n />\n );\n}\n","// @formality-ui/react - FieldGroup Component\n// Groups fields with shared conditions and state propagation\n\nimport { useMemo, type ReactNode } from \"react\";\nimport type { GroupConfig } from \"@formality-ui/core\";\nimport { useFormContext } from \"../context/FormContext\";\nimport {\n GroupContext,\n useGroupContext,\n type GroupContextValue,\n type GroupState,\n} from \"../context/GroupContext\";\nimport { useConditions } from \"../hooks/useConditions\";\nimport { useInferredInputs } from \"../hooks/useInferredInputs\";\n\n/**\n * FieldGroup component props\n */\nexport interface FieldGroupProps {\n /** Group name (must match a key in FormConfig.groups) */\n name: string;\n\n /** Fields to render within this group */\n children: ReactNode;\n}\n\n/**\n * FieldGroup component - Groups fields with shared conditions\n *\n * Provides:\n * - Group-level condition evaluation (disabled/visible)\n * - State propagation to nested fields:\n * - disabled: OR logic (child || parent)\n * - visible: AND logic (child && parent)\n * - Subscription accumulation from parent groups\n *\n * Groups can be nested, with state merging at each level.\n *\n * @example\n * ```tsx\n * // FormConfig\n * formConfig={{\n * groups: {\n * clientSection: {\n * conditions: [\n * { when: 'hasClient', is: false, visible: false }\n * ]\n * }\n * }\n * }}\n *\n * // Usage\n * <Form config={config} formConfig={formConfig}>\n * <Field name=\"hasClient\" />\n * <FieldGroup name=\"clientSection\">\n * <Field name=\"clientName\" />\n * <Field name=\"clientEmail\" />\n * </FieldGroup>\n * </Form>\n * ```\n */\nexport function FieldGroup({ name, children }: FieldGroupProps): JSX.Element {\n const { formConfig } = useFormContext();\n const parentContext = useGroupContext();\n\n // Get group config\n const groupConfig: GroupConfig = formConfig.groups?.[name] ?? {\n conditions: [],\n subscribesTo: [],\n };\n\n // Warn if group config not found (in development)\n if (process.env.NODE_ENV !== \"production\" && !formConfig.groups?.[name]) {\n console.warn(\n `FieldGroup: No config found for group \"${name}\". ` +\n `Make sure to define it in formConfig.groups.`,\n );\n }\n\n // Infer fields from conditions\n const inferredInputs = useInferredInputs({\n conditions: groupConfig.conditions,\n subscribesTo: groupConfig.subscribesTo,\n });\n\n // Evaluate conditions\n const conditionResult = useConditions({\n conditions: groupConfig.conditions ?? [],\n subscribesTo: groupConfig.subscribesTo,\n });\n\n // Merge with parent context state\n const mergedState = useMemo<GroupState>(() => {\n // Disabled: OR logic (any parent can disable)\n const isDisabled =\n (conditionResult.hasDisabledCondition\n ? (conditionResult.disabled ?? false)\n : false) || parentContext.state.isDisabled;\n\n // Visible: AND logic (any parent can hide)\n const isVisible =\n (conditionResult.hasVisibleCondition\n ? (conditionResult.visible ?? true)\n : true) && parentContext.state.isVisible;\n\n // setValue: This group's setValue takes priority, then parent's\n // (Child fields can still override with their own field-level conditions)\n const hasSetCondition =\n conditionResult.hasSetCondition || parentContext.state.hasSetCondition;\n const setValue = conditionResult.hasSetCondition\n ? conditionResult.setValue\n : parentContext.state.setValue;\n\n // Accumulate conditions and subscriptions\n const conditions = [\n ...parentContext.state.conditions,\n ...(groupConfig.conditions ?? []),\n ];\n\n const subscriptions = [\n ...parentContext.state.subscriptions,\n ...(groupConfig.subscribesTo ?? []),\n ];\n\n return {\n isDisabled,\n isVisible,\n hasSetCondition,\n setValue,\n conditions,\n subscriptions,\n };\n }, [conditionResult, parentContext.state, groupConfig]);\n\n // Build context value\n const contextValue = useMemo<GroupContextValue>(\n () => ({\n state: mergedState,\n subscriptions: mergedState.subscriptions,\n inferredInputs,\n config: groupConfig,\n }),\n [mergedState, inferredInputs, groupConfig],\n );\n\n // CRITICAL: Use span wrapper with display:none instead of returning null\n // This preserves children in DOM for state preservation (PRD Section 5.4, 18.10)\n return (\n <GroupContext.Provider value={contextValue}>\n <span\n style={{ display: mergedState.isVisible ? undefined : \"none\" }}\n data-formality-group={name}\n >\n {children}\n </span>\n </GroupContext.Provider>\n );\n}\n","// @formality-ui/react - UnusedFields Component\n// Renders fields declared in config but not explicitly rendered\n\nimport { type ReactNode, useMemo } from \"react\";\nimport { sortFieldsByOrder } from \"@formality-ui/core\";\nimport { useFormContext } from \"../context/FormContext\";\nimport { Field } from \"./Field\";\n\n/**\n * UnusedFields component props\n */\nexport interface UnusedFieldsProps {\n /** Custom render function for each unused field */\n children?: (field: { name: string; component: ReactNode }) => ReactNode;\n}\n\n/**\n * UnusedFields component - Renders config-driven fields\n *\n * Renders fields that are declared in the Form's config but have not\n * been explicitly rendered using <Field> components. This enables\n * config-driven forms where not all fields need to be declared in JSX.\n *\n * Fields are tracked via the Form's field registry. When a <Field>\n * component mounts, it registers itself. UnusedFields renders all\n * fields that haven't been registered.\n *\n * @example\n * ```tsx\n * // All fields from config rendered automatically\n * <Form config={config}>\n * <UnusedFields />\n * </Form>\n *\n * // Mix explicit and automatic fields\n * <Form config={config}>\n * <Field name=\"name\" /> {/* Explicit with custom props *\\/}\n * <Field name=\"email\" /> {/* Explicit with custom props *\\/}\n * <UnusedFields /> {/* Renders remaining fields *\\/}\n * </Form>\n *\n * // Custom wrapper for unused fields\n * <Form config={config}>\n * <UnusedFields>\n * {({ name, component }) => (\n * <div key={name} className=\"auto-field\">\n * {component}\n * </div>\n * )}\n * </UnusedFields>\n * </Form>\n * ```\n */\nexport function UnusedFields({ children }: UnusedFieldsProps): JSX.Element {\n const { unusedFields, config } = useFormContext();\n\n // Sort unused fields by order property (PRD Section 15)\n const sortedFields = useMemo(() => {\n return sortFieldsByOrder(unusedFields, config);\n }, [unusedFields, config]);\n\n if (children) {\n // Custom render function\n return (\n <>\n {sortedFields.map((name) =>\n children({\n name,\n // CRITICAL: shouldRegister={false} prevents infinite loop (PRD 5.5, 18.9)\n component: <Field key={name} name={name} shouldRegister={false} />,\n }),\n )}\n </>\n );\n }\n\n // Default render\n return (\n <>\n {sortedFields.map((name) => (\n // CRITICAL: shouldRegister={false} prevents infinite loop (PRD 5.5, 18.9)\n <Field key={name} name={name} shouldRegister={false} />\n ))}\n </>\n );\n}\n","// @formality-ui/react - useFormState Hook\n// Custom hook wrapping RHF's useWatch with proxy optimization\n// CRITICAL: This hook is designed for ISOLATED field subscriptions\n\nimport { useMemo } from \"react\";\nimport { useWatch, useFormContext as useRHFFormContext } from \"react-hook-form\";\nimport type { FieldValues } from \"react-hook-form\";\nimport { makeProxyState } from \"../utils/makeProxyState\";\nimport { useFormContext as useFormalityFormContext } from \"../context/FormContext\";\nimport type { CustomFieldState, IsolatedFormState } from \"../types\";\n\n/**\n * Options for useFormState hook\n */\nexport interface UseFormStateOptions {\n /**\n * Specific field name(s) to watch.\n * REQUIRED for performance - you must specify which fields you need.\n * Watching all fields defeats the purpose of isolation.\n */\n name: string | string[];\n}\n\n/**\n * Custom useFormState that provides ISOLATED field subscriptions\n *\n * CRITICAL PERFORMANCE REQUIREMENT:\n * You MUST specify which fields to watch via the `name` option.\n * This hook is designed to prevent the \"subscribe to everything\" anti-pattern.\n *\n * This hook provides:\n * - Proxy-wrapped field states to prevent unnecessary re-renders\n * - Record property access via lazy getter\n * - Integration with Formality's FormContext\n *\n * Performance Benefits:\n * - Only re-renders when specified fields change\n * - Expression evaluation only creates dependencies on used properties\n * - Field states can update independently without cross-field re-renders\n *\n * @example\n * ```tsx\n * function MyField() {\n * // Watch specific fields only\n * const formState = useFormState({ name: ['firstName', 'lastName'] });\n *\n * // Only re-renders when firstName or lastName change\n * const value = formState.fields.firstName?.value;\n *\n * // Access original record for expressions\n * const recordId = formState.record.id;\n * }\n * ```\n */\nexport function useFormState<TFieldValues extends FieldValues = FieldValues>(\n options: UseFormStateOptions,\n): IsolatedFormState {\n // Get RHF context\n const rhfContext = useRHFFormContext<TFieldValues>();\n\n // Get Formality context (may not be available if used outside Form)\n let formalityContext: ReturnType<\n typeof useFormalityFormContext<TFieldValues>\n > | null = null;\n try {\n formalityContext = useFormalityFormContext<TFieldValues>();\n } catch {\n // Used outside Form - formalityContext stays null\n }\n\n // Determine field names to track - MUST be explicitly specified\n const fieldNames = useMemo(() => {\n return Array.isArray(options.name) ? options.name : [options.name];\n }, [options.name]);\n\n // Watch ONLY specified field values via useWatch (isolated subscription)\n const watchedValues = useWatch({\n control: rhfContext.control,\n name: fieldNames as any,\n });\n\n // Build proxy-wrapped field states for watched fields ONLY\n // CRITICAL: We do NOT call getFieldState which would subscribe to form state\n const fields = useMemo(() => {\n const result: Record<string, CustomFieldState> = {};\n\n if (fieldNames.length === 0) {\n return result;\n }\n\n // Handle single field vs multiple fields\n const values =\n fieldNames.length === 1 ? [watchedValues] : (watchedValues as unknown[]);\n\n fieldNames.forEach((name, index) => {\n const value = values[index];\n\n // Create minimal proxy state with just the value\n // We intentionally do NOT access isTouched/isDirty/error from rhfFormState\n // as that would create subscriptions to the entire form state\n result[name] = makeProxyState({\n value,\n isTouched: false,\n isDirty: false,\n isValidating: false,\n error: undefined,\n invalid: false,\n });\n });\n\n return result;\n }, [fieldNames, watchedValues]);\n\n // Create result object with lazy record access\n const result = useMemo((): IsolatedFormState => {\n const base: IsolatedFormState = {\n fields,\n record: {}, // Will be overwritten by defineProperty\n // Provide minimal form-level state that doesn't require subscriptions\n isDirty: false,\n isTouched: false,\n isValid: true,\n isSubmitting: false,\n errors: {},\n touchedFields: {},\n dirtyFields: {},\n defaultValues: {},\n };\n\n // Add record property with lazy access\n Object.defineProperty(base, \"record\", {\n get: () => formalityContext?.record ?? {},\n enumerable: true,\n configurable: true,\n });\n\n return base;\n }, [fields, formalityContext?.record]);\n\n return result;\n}\n","// @formality-ui/react - Type Overlays\n//\n// Core (`@formality-ui/core`) is deliberately framework-agnostic: it cannot\n// import `react` or `react-hook-form`, so any field that is fundamentally a\n// framework construct is typed `unknown` there (InputConfig.component,\n// InputConfig.template, FieldConfig.rules, …). See PRD §1.3.2 / §3.2.\n//\n// This module overlays precise React / react-hook-form types on top of those\n// loose core types. React consumers import these (re-exported from the package\n// entry point) and get full type safety, while core stays reusable by future\n// Vue/Svelte adapters with zero changes.\n\nimport type { ComponentType } from \"react\";\nimport type {\n RegisterOptions,\n FieldValues,\n RefCallBack,\n UseFormStateReturn,\n} from \"react-hook-form\";\nimport type { InputConfig, FieldConfig } from \"@formality-ui/core\";\nimport type { InputTemplateProps, CustomFieldState } from \"./types\";\n\n/**\n * `InputConfig` as seen by React consumers.\n *\n * Narrows core's framework-agnostic `component: unknown` /\n * `template?: unknown` to real React component types. `TValue` is preserved so\n * `defaultValue` / `parser` / `formatter` can share a single value type.\n *\n * @example\n * ```tsx\n * import type { ReactInputConfig } from \"@formality-ui/react\";\n *\n * const textField = {\n * component: TextField,\n * defaultValue: \"\",\n * } satisfies ReactInputConfig<string>;\n * ```\n *\n * Prefer this over the core `InputConfig` type whenever you are writing React\n * code — it will give you a **compile error** if `component` is set to a\n * non-component (e.g. `component: 42` or `component: \"textField\"`).\n */\nexport interface ReactInputConfig<TValue = unknown> extends Omit<\n InputConfig<TValue>,\n \"component\" | \"template\"\n> {\n /** The React component to render for this input type. */\n component: ComponentType<any>;\n\n /** Optional template wrapper (overrides provider/form defaults). */\n template?: ComponentType<InputTemplateProps>;\n}\n\n/**\n * `FieldConfig` as seen by React consumers.\n *\n * Narrows core's framework-agnostic `rules?: Record<string, unknown>` to\n * react-hook-form's `RegisterOptions`, giving autocomplete and checking for\n * `required`, `min`, `max`, `pattern`, `validate`, `valueAsNumber`, `deps`, …\n *\n * The generic `V` defaults to `FieldValues`; pass your form's values type for\n * slightly tighter checking on path-based rules.\n */\nexport interface ReactFieldConfig<\n V extends FieldValues = FieldValues,\n> extends Omit<FieldConfig, \"rules\"> {\n /** react-hook-form register options forwarded to the field's Controller. */\n rules?: RegisterOptions<V>;\n}\n\n/**\n * Map of field name → {@link ReactFieldConfig}. Used by `<Form>`'s `config`\n * prop (via {@link ReactFormFieldsConfig}) so React consumers get RHF-typed\n * `rules` on every field.\n *\n * The keys are narrowed to `Extract<keyof V, string>`. When `V` is left at\n * its default (`FieldValues`) any string key is accepted — byte-for-byte\n * identical to before. When `V` is narrowed to a concrete field-values type\n * (e.g. via `<Form<ClientValues>>`), unknown `config` keys become a\n * **compile error**, catching typos like `ofice` at compile time (PRD §C.4 /\n * T2.1).\n *\n * @example\n * ```tsx\n * import type { ReactFormFieldsConfig } from \"@formality-ui/react\";\n * import type { FieldValues } from \"react-hook-form\";\n *\n * // Default — any string key accepted (non-breaking).\n * const a: ReactFormFieldsConfig<FieldValues> = { anything: { type: \"text\" } };\n *\n * // Narrowed — only known field names accepted.\n * type ClientValues = { name: string; email: string };\n * const b: ReactFormFieldsConfig<ClientValues> = {\n * name: { type: \"text\" },\n * email: { type: \"text\" },\n * };\n *\n * // @ts-expect-error — typo `ofice` is rejected.\n * const c: ReactFormFieldsConfig<ClientValues> = { ofice: { type: \"text\" } };\n * ```\n */\nexport type ReactFormFieldsConfig<V extends FieldValues = FieldValues> = Record<\n Extract<keyof V, string>,\n ReactFieldConfig<V>\n>;\n\n/**\n * Identity helper that lets consumers derive a union of their input-type keys.\n * Opt-in: wrap your provider inputs to get `keyof` checking on `Field` `type`\n * and `FieldConfig.type`.\n *\n * This is a PURE IDENTITY function — it returns `inputs` unchanged with zero\n * runtime effect, so bundlers (tsup/esbuild/rollup) tree-shake it to nothing.\n * It exists purely so consumers can write `type InputType = keyof typeof inputs`.\n *\n * The existing non-generic `Field` and `FieldConfig.type` / `FieldProps.type`\n * (which default to `type?: string`) are UNCHANGED — this helper is purely\n * additive and opt-in. End-to-end wiring of `InputType` into those types is a\n * follow-up (PRD §C.4 T2.2 step 3).\n *\n * @example\n * ```tsx\n * import { defineInputs } from \"@formality-ui/react\";\n *\n * const inputs = defineInputs({\n * textField: { component: TextField, defaultValue: \"\" },\n * switch: { component: Switch, defaultValue: false },\n * });\n * export type InputType = keyof typeof inputs; // \"textField\" | \"switch\"\n * ```\n */\nexport function defineInputs<T extends Record<string, ReactInputConfig>>(\n inputs: T,\n): T {\n return inputs;\n}\n\n/**\n * Props Formality injects onto every field component.\n *\n * `<Field>` renders your input component via React Hook Form's `<Controller>`.\n * At runtime Formality merges a `coreProps` bundle onto the component (name,\n * value, onChange, onBlur, and — as a React-special key — `ref`). The three\n * members below are the **injected-props contract**: `formState` reaches\n * templates and render-prop children; `state` (subscribed field state) and a\n * top-level `forwardRef` key are delivered at runtime by `<Field>` (see\n * \"Runtime delivery\" below).\n *\n * **Destructure before forwarding.** Component authors MUST destructure\n * `state`, `formState`, and `forwardRef` OUT of props before spreading the\n * rest onto the underlying DOM `<input>` — otherwise these non-DOM props leak\n * to the DOM and React warns. Recommended pattern:\n *\n * ```tsx\n * const TextField: ComponentType<FormalityFieldComponentProps<TextFieldProps>> =\n * ({ state, formState, forwardRef, ...domProps }) => (\n * <input ref={forwardRef} {...domProps} />\n * );\n * ```\n *\n * **Wiring `forwardRef` to the inner input.** `forwardRef` is RHF's\n * `RefCallBack` (a function). For a plain `<input>` use `ref={forwardRef}`.\n * For MUI v9 components that no longer accept a top-level `inputRef`, wire it\n * via slots: `slotProps={{ input: { ref: forwardRef } }}` (PRD §5.3.8).\n *\n * **Runtime delivery (important).** `<Field>` delivers RHF's ref as a regular,\n * top-level, enumerable prop named `forwardRef` — no `React.forwardRef` wrap\n * is required for a plain function component that destructures `forwardRef`\n * and wires it to the inner input (`ref={forwardRef}`). Consumers migrating\n * off the old React-special `ref` key: a `React.forwardRef`-wrapped component\n * should consume `props.forwardRef` (PRD §20.4), and under React 19\n * ref-as-prop use `forwardRef` directly. The type ships the intended contract\n * so consumers stop hand-rolling a lossy `WithFormality<P>`.\n *\n * @template P - the field component's own props (e.g. TextFieldProps). Defaults\n * to `unknown` so existing `ComponentType<any>` casts remain valid.\n */\nexport type FormalityFieldComponentProps<P = unknown> = P & {\n /** Subscribed/own field state when `provideState`/`passSubscriptions` is on. */\n state?: CustomFieldState | Record<string, CustomFieldState>;\n\n /** React Hook Form form state threaded from `<Controller>`. */\n formState?: UseFormStateReturn<FieldValues>;\n\n /** RHF ref callback (`RefCallBack`); wire to the inner input (see JSDoc). */\n forwardRef?: RefCallBack;\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/context/ConfigContext.ts","../src/context/FormContext.ts","../src/context/GroupContext.ts","../src/components/FormalityProvider.tsx","../src/utils/makeProxyState.ts","../src/components/Form.tsx","../src/hooks/useInferredInputs.ts","../src/hooks/useConditions.ts","../src/hooks/usePropsEvaluation.ts","../src/hooks/useSubscriptions.ts","../src/components/Field.tsx","../src/components/FieldGroup.tsx","../src/components/UnusedFields.tsx","../src/hooks/useFormState.ts","../src/overlays.ts"],"names":["createContext","useContext","defaultGroupContext","useMemo","jsx","useWatch","evaluateDescriptor","useRef","useEffect","useState","useCallback","Fragment","useRHFFormContext","result"],"mappings":";;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QAAA,EAAU;AAAA,MACpC,GAAA,EAAK,MAAM,gBAAA,EAAkB,MAAA,IAAU,EAAC;AAAA,MACxC,UAAA,EAAY,IAAA;AAAA,MACZ,YAAA,EAAc;AAAA,KACf,CAAA;AAED,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,EAAG,CAAC,MAAA,EAAQ,gBAAA,EAAkB,MAAM,CAAC,CAAA;AAErC,EAAA,OAAO,MAAA;AACT;;;ACRO,SAAS,aACd,MAAA,EACG;AACH,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["// @formality-ui/react - ConfigContext\n// Global configuration context for Formality\n\nimport { createContext, useContext, type ComponentType } from \"react\";\nimport type {\n ValidatorsConfig,\n ErrorMessagesConfig,\n SelectValue,\n} from \"@formality-ui/core\";\nimport type { InputTemplateProps } from \"../types\";\nimport type { ReactInputConfig } from \"../overlays\";\n\n/**\n * ConfigContextValue - Global configuration provided by FormalityProvider\n *\n * Contains all input types, transformers, validators, and global defaults\n * that apply across all forms in the application.\n */\nexport interface ConfigContextValue {\n /** Input type definitions (e.g., textField, switch, autocomplete) */\n inputs: Record<string, ReactInputConfig>;\n\n /** Named formatters for value → display transformation */\n formatters: Record<string, (value: unknown) => unknown>;\n\n /** Named parsers for input → value transformation */\n parsers: Record<string, (value: unknown) => unknown>;\n\n /** Named validators and validator factories */\n validators: ValidatorsConfig;\n\n /** Error message templates by type key */\n errorMessages: ErrorMessagesConfig;\n\n /** Default template component for all inputs */\n defaultInputTemplate?: ComponentType<InputTemplateProps>;\n\n /** Named template components for specific input types */\n inputTemplates: Record<string, ComponentType<InputTemplateProps>>;\n\n /** Default prop name for passSubscriptions (default: 'state') */\n defaultSubscriptionPropName: string;\n\n /** Static default props for all fields */\n defaultFieldProps: Record<string, unknown>;\n\n /** Dynamic default props evaluated per-field */\n selectDefaultFieldProps?: SelectValue;\n}\n\n/**\n * Default configuration context values\n *\n * These are sensible defaults that can be overridden by FormalityProvider.\n * Per PRD 5.1: defaultSubscriptionPropName defaults to 'state'.\n */\nconst defaultConfigContext: ConfigContextValue = {\n inputs: {},\n formatters: {},\n parsers: {},\n validators: {},\n errorMessages: {},\n inputTemplates: {},\n defaultSubscriptionPropName: \"state\",\n defaultFieldProps: {},\n};\n\n/**\n * ConfigContext - React context for global Formality configuration\n *\n * Provides access to input types, transformers, validators, and\n * global defaults to all forms and fields in the application.\n */\nexport const ConfigContext =\n createContext<ConfigContextValue>(defaultConfigContext);\n\nConfigContext.displayName = \"FormalityConfigContext\";\n\n/**\n * useConfigContext - Hook to access global configuration\n *\n * @returns The current ConfigContextValue from the nearest FormalityProvider\n */\nexport function useConfigContext(): ConfigContextValue {\n return useContext(ConfigContext);\n}\n","// @formality-ui/react - FormContext\n// Form-level context for field registration and state management\n\nimport { createContext, useContext } from \"react\";\nimport type { UseFormReturn, FieldValues } from \"react-hook-form\";\nimport type {\n FormFieldsConfig,\n FormConfig,\n FormState,\n InputConfig,\n} from \"@formality-ui/core\";\nimport type { WatcherSetterFn, DebouncedFunction } from \"../types\";\n\n/**\n * FormContextValue - Form-level configuration and operations\n *\n * Provides field registration, subscription management, and access\n * to form state for all fields within a Form component.\n */\nexport interface FormContextValue<\n TFieldValues extends FieldValues = FieldValues,\n> {\n // ========================\n // Configuration\n // ========================\n\n /** Field configurations for this form */\n config: FormFieldsConfig;\n\n /** Form-level configuration (title, groups, input overrides) */\n formConfig: FormConfig;\n\n /** Original record passed to Form (for expression access) */\n record?: Record<string, unknown>;\n\n // ========================\n // Registry Operations\n // ========================\n\n /**\n * Register a field when it mounts\n * @param name - Field name\n */\n registerField: (name: string) => void;\n\n /**\n * Unregister a field when it unmounts\n * @param name - Field name\n */\n unregisterField: (name: string) => void;\n\n // ========================\n // Subscription Operations\n // ========================\n\n /**\n * Add a subscription from subscriber to target field\n * @param target - The field being watched\n * @param subscriber - The field watching\n */\n addSubscription: (target: string, subscriber: string) => void;\n\n /**\n * Remove a subscription from subscriber to target field\n * @param target - The field being watched\n * @param subscriber - The field watching\n */\n removeSubscription: (target: string, subscriber: string) => void;\n\n /**\n * Register a setter for a field's watchers state\n * @param name - Field name\n * @param setter - React state setter for watchers\n */\n registerWatcherSetter: (name: string, setter: WatcherSetterFn) => void;\n\n /**\n * Unregister a watcher setter when field unmounts\n * @param name - Field name\n */\n unregisterWatcherSetter: (name: string) => void;\n\n // ========================\n // Field State Operations\n // ========================\n\n /**\n * Programmatically change a field's value\n * @param name - Field name\n * @param value - New value\n * @param inputConfig - Optional input configuration for this field type\n */\n changeField: (\n name: string,\n value: unknown,\n inputConfig?: InputConfig,\n ) => void;\n\n /**\n * Set a field's validating state\n * @param name - Field name\n * @param isValidating - Whether validation is in progress\n */\n setFieldValidating: (name: string, isValidating: boolean) => void;\n\n // ========================\n // State Access\n // ========================\n\n /**\n * Get the current complete form state\n * Used for expression evaluation and condition checking\n */\n getFormState: () => FormState;\n\n // ========================\n // Submission Operations\n // ========================\n\n /** Optional submit handler passed to Form */\n onSubmit?: (values: Partial<TFieldValues>) => void | Promise<void>;\n\n /** Debounced submit for auto-save forms */\n debouncedSubmit: DebouncedFunction;\n\n /** Immediate submit bypassing debounce */\n submitImmediate: () => void;\n\n // ========================\n // Unused Fields Tracking\n // ========================\n\n /** Fields in config but not rendered (for config-driven forms) */\n unusedFields: string[];\n\n // ========================\n // React Hook Form Integration\n // ========================\n\n /** React Hook Form methods passthrough */\n methods: UseFormReturn<TFieldValues>;\n}\n\n/**\n * FormContext - React context for form-level state and operations\n *\n * Must be provided by a Form component. No default value as\n * fields cannot function without a parent Form.\n */\nexport const FormContext = createContext<FormContextValue | null>(null);\n\nFormContext.displayName = \"FormalityFormContext\";\n\n/**\n * useFormContext - Hook to access form-level context\n *\n * @throws Error if used outside a Form component\n * @returns The FormContextValue from the nearest Form component\n */\nexport function useFormContext<\n TFieldValues extends FieldValues = FieldValues,\n>(): FormContextValue<TFieldValues> {\n const context = useContext(\n FormContext,\n ) as FormContextValue<TFieldValues> | null;\n\n if (!context) {\n throw new Error(\n \"useFormContext must be used within a Form component. \" +\n \"Make sure your component is wrapped in a <Form> component.\",\n );\n }\n\n return context;\n}\n","// @formality-ui/react - GroupContext\n// Group-level context for nested disabled/visible state propagation\n\nimport { createContext, useContext } from \"react\";\nimport type { ConditionDescriptor, GroupConfig } from \"@formality-ui/core\";\n\n/**\n * GroupState - Current computed state for a FieldGroup\n *\n * Contains the resolved disabled/visible states from condition\n * evaluation and the conditions/subscriptions used.\n */\nexport interface GroupState {\n /** Is the group disabled (propagates to all child fields) */\n isDisabled: boolean;\n\n /** Is the group visible (propagates to all child fields) */\n isVisible: boolean;\n\n /** Whether the group has a setValue condition */\n hasSetCondition: boolean;\n\n /** Value to set on all child fields (from group-level set/selectSet) */\n setValue: unknown;\n\n /** Conditions from group configuration */\n conditions: ConditionDescriptor[];\n\n /** Fields this group subscribes to */\n subscriptions: string[];\n}\n\n/**\n * GroupContextValue - Group-level configuration and state\n *\n * Provides inherited disabled/visible state and subscription\n * information to nested fields and groups.\n */\nexport interface GroupContextValue {\n /** Current computed state for the group */\n state: GroupState;\n\n /** Inherited subscriptions from parent groups */\n subscriptions: string[];\n\n /** Field names inferred from group conditions */\n inferredInputs: string[];\n\n /** Group configuration */\n config: GroupConfig;\n}\n\n/**\n * Default group context values\n *\n * When no FieldGroup is present, fields use these defaults:\n * - Not disabled\n * - Visible\n * - No conditions or subscriptions\n */\nconst defaultGroupContext: GroupContextValue = {\n state: {\n isDisabled: false,\n isVisible: true,\n hasSetCondition: false,\n setValue: undefined,\n conditions: [],\n subscriptions: [],\n },\n subscriptions: [],\n inferredInputs: [],\n config: { conditions: [], subscribesTo: [] },\n};\n\n/**\n * GroupContext - React context for group-level state\n *\n * Provides inherited disabled/visible state from parent groups\n * to child fields and nested groups.\n */\nexport const GroupContext =\n createContext<GroupContextValue>(defaultGroupContext);\n\nGroupContext.displayName = \"FormalityGroupContext\";\n\n/**\n * useGroupContext - Hook to access group-level context\n *\n * @returns The GroupContextValue from the nearest FieldGroup or default\n */\nexport function useGroupContext(): GroupContextValue {\n return useContext(GroupContext);\n}\n","// @formality-ui/react - FormalityProvider\n// Global configuration provider for Formality forms\n\nimport { useMemo, type ReactNode, type ComponentType } from \"react\";\nimport type {\n ValidatorsConfig,\n ErrorMessagesConfig,\n SelectValue,\n} from \"@formality-ui/core\";\nimport {\n ConfigContext,\n type ConfigContextValue,\n} from \"../context/ConfigContext\";\nimport type { InputTemplateProps } from \"../types\";\nimport type { ReactInputConfig } from \"../overlays\";\n\n/**\n * FormalityProviderProps - Props for the FormalityProvider component\n *\n * Configures input types, transformers, validators, and global defaults\n * for all forms in the application.\n */\nexport interface FormalityProviderProps {\n /** Child components */\n children: ReactNode;\n\n /**\n * Input type definitions (REQUIRED)\n *\n * Defines how each input type (e.g., textField, switch, autocomplete)\n * behaves across all forms.\n *\n * @example\n * ```tsx\n * inputs={{\n * textField: { component: TextField, defaultValue: '' },\n * switch: { component: Switch, defaultValue: false },\n * }}\n * ```\n *\n * `component` is type-checked as a real React component (a non-component\n * value such as `42` or `\"textField\"` is a compile error). See\n * `ReactInputConfig` for the precise shape.\n */\n inputs: Record<string, ReactInputConfig>;\n\n /**\n * Named formatters for value → display transformation\n *\n * Transform form values before displaying in inputs.\n *\n * @example\n * ```tsx\n * formatters={{\n * currency: (v) => `$${Number(v).toFixed(2)}`,\n * uppercase: (v) => String(v).toUpperCase(),\n * }}\n * ```\n */\n formatters?: Record<string, (value: unknown) => unknown>;\n\n /**\n * Named parsers for input → value transformation\n *\n * Transform user input before storing in form state.\n *\n * @example\n * ```tsx\n * parsers={{\n * number: (v) => Number(v) || 0,\n * trim: (v) => String(v).trim(),\n * }}\n * ```\n */\n parsers?: Record<string, (value: unknown) => unknown>;\n\n /**\n * Named validators and validator factories\n *\n * Define reusable validation logic across forms.\n */\n validators?: ValidatorsConfig;\n\n /**\n * Error message templates by type key\n *\n * Map validation error types to human-readable messages.\n *\n * @example\n * ```tsx\n * errorMessages={{\n * required: 'This field is required',\n * minLength: 'Must be at least {min} characters',\n * }}\n * ```\n */\n errorMessages?: ErrorMessagesConfig;\n\n /**\n * Default template component for all inputs\n *\n * Wraps all inputs for consistent styling, labels, error display.\n */\n defaultInputTemplate?: ComponentType<InputTemplateProps>;\n\n /**\n * Named template components for specific input types\n *\n * Override the default template for specific input types.\n */\n inputTemplates?: Record<string, ComponentType<InputTemplateProps>>;\n\n /**\n * Default prop name for passSubscriptions (default: 'state')\n *\n * When a field has passSubscriptions: true, subscribed field states\n * are passed using this prop name.\n */\n defaultSubscriptionPropName?: string;\n\n /**\n * Static default props for all fields\n *\n * Props applied to every field unless overridden.\n */\n defaultFieldProps?: Record<string, unknown>;\n\n /**\n * Dynamic default props evaluated per-field\n *\n * Expression or function that computes default props.\n */\n selectDefaultFieldProps?: SelectValue;\n}\n\n/**\n * FormalityProvider - Global configuration provider for Formality\n *\n * Wraps your application to provide input types, transformers, validators,\n * and global defaults to all Formality forms.\n *\n * @example\n * ```tsx\n * import { FormalityProvider } from '@formality-ui/react';\n *\n * const inputs = {\n * textField: { component: TextInput, defaultValue: '' },\n * switch: { component: Toggle, defaultValue: false },\n * };\n *\n * function App() {\n * return (\n * <FormalityProvider\n * inputs={inputs}\n * formatters={{ currency: (v) => `$${v}` }}\n * errorMessages={{ required: 'Required' }}\n * >\n * <MyApp />\n * </FormalityProvider>\n * );\n * }\n * ```\n */\nexport function FormalityProvider({\n children,\n inputs,\n formatters = {},\n parsers = {},\n validators = {},\n errorMessages = {},\n defaultInputTemplate,\n inputTemplates = {},\n defaultSubscriptionPropName = \"state\",\n defaultFieldProps = {},\n selectDefaultFieldProps,\n}: FormalityProviderProps): JSX.Element {\n // Memoize context value to prevent unnecessary re-renders\n // in descendant components that consume ConfigContext\n const contextValue = useMemo<ConfigContextValue>(\n () => ({\n inputs,\n formatters,\n parsers,\n validators,\n errorMessages,\n defaultInputTemplate,\n inputTemplates,\n defaultSubscriptionPropName,\n defaultFieldProps,\n selectDefaultFieldProps,\n }),\n [\n inputs,\n formatters,\n parsers,\n validators,\n errorMessages,\n defaultInputTemplate,\n inputTemplates,\n defaultSubscriptionPropName,\n defaultFieldProps,\n selectDefaultFieldProps,\n ],\n );\n\n return (\n <ConfigContext.Provider value={contextValue}>\n {children}\n </ConfigContext.Provider>\n );\n}\n","// @formality-ui/react - makeProxyState\n// Lazy property access utility for React performance optimization\n\n/**\n * Creates a proxy object with lazy property access via Object.defineProperty\n *\n * CRITICAL: This enables React's dependency tracking to only register\n * dependencies on actually accessed properties, not the entire object.\n *\n * Without proxy: accessing fieldState.value creates dependency on entire fieldState\n * With proxy: accessing fieldState.value only creates dependency on value property\n *\n * Performance Impact:\n * - Reduces unnecessary re-renders in condition-heavy forms\n * - Expression evaluation only subscribes to properties actually used\n * - Field states can change without triggering re-renders in unrelated fields\n *\n * Implementation Note:\n * Uses Object.defineProperty (NOT Proxy) because:\n * - Better performance for simple property access\n * - Works with Object.keys() iteration when enumerable: true\n * - Simpler debugging and stack traces\n *\n * @param source - The object to wrap with lazy getters\n * @returns A new object with getter properties that lazily access source\n *\n * @example\n * ```typescript\n * const source = { value: 5, isTouched: false };\n * const proxy = makeProxyState(source);\n *\n * // Properties are accessed lazily\n * console.log(proxy.value); // 5\n *\n * // Changes to source reflect in proxy (lazy access)\n * source.value = 10;\n * console.log(proxy.value); // 10\n *\n * // Object.keys still works\n * console.log(Object.keys(proxy)); // ['value', 'isTouched']\n * ```\n */\nexport function makeProxyState<T extends object>(source: T): T {\n const result = {} as T;\n\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n Object.defineProperty(result, key, {\n get: () => source[key],\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Creates a nested proxy state, recursively wrapping objects\n *\n * Use this for deeply nested state objects where you want\n * lazy access at multiple levels.\n *\n * @param source - The object to wrap with lazy getters (recursively)\n * @returns A new object with recursive getter properties\n */\nexport function makeDeepProxyState<T extends object>(source: T): T {\n const result = {} as T;\n\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n Object.defineProperty(result, key, {\n get: () => {\n const currentValue = source[key];\n if (\n currentValue !== null &&\n typeof currentValue === \"object\" &&\n !Array.isArray(currentValue)\n ) {\n return makeDeepProxyState(currentValue as object);\n }\n return currentValue;\n },\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n return result;\n}\n","// @formality-ui/react - Form Component\n// Core form component with React Hook Form integration\n\nimport {\n useMemo,\n useCallback,\n useRef,\n useState,\n useEffect,\n type ReactNode,\n} from \"react\";\nimport {\n useForm,\n FormProvider,\n type FieldValues,\n type UseFormReturn,\n} from \"react-hook-form\";\nimport { debounce } from \"lodash-es\";\nimport {\n resolveAllInitialValues,\n resolveFormTitle,\n evaluateDescriptor,\n buildFormContext,\n extractValueField,\n transformFieldName,\n} from \"@formality-ui/core\";\nimport type {\n FormFieldsConfig,\n FormConfig,\n FormState,\n InputConfig,\n} from \"@formality-ui/core\";\nimport { FormContext, type FormContextValue } from \"../context/FormContext\";\nimport { GroupContext } from \"../context/GroupContext\";\nimport { useConfigContext } from \"../context/ConfigContext\";\nimport { makeProxyState } from \"../utils/makeProxyState\";\nimport type { WatcherSetterFn, DebouncedFunction } from \"../types\";\nimport type { ReactFormFieldsConfig } from \"../overlays\";\n\n/**\n * Form component props\n */\nexport interface FormProps<TFieldValues extends FieldValues = FieldValues> {\n /** Form content - can be static children or render function */\n children: ReactNode | ((api: FormRenderAPI<TFieldValues>) => ReactNode);\n\n /** Field configurations */\n config: ReactFormFieldsConfig<TFieldValues>;\n\n /** Form-level configuration (title, groups, input overrides) */\n formConfig?: FormConfig;\n\n /** Submit handler */\n onSubmit?: (values: Partial<TFieldValues>) => void | Promise<void>;\n\n /** Initial record data */\n record?: Partial<TFieldValues>;\n\n /** Enable auto-save on field changes */\n autoSave?: boolean;\n\n /**\n * Form-level auto-save debounce, used as the fallback for any field whose\n * `InputConfig.debounce` is unset.\n * - `false` — submit immediately (no debounce timer).\n * - `number` — delay auto-save by this many milliseconds (default: 1000).\n *\n * A field can override its own cadence via `InputConfig.debounce`\n * (`false` for immediate, or a number for a per-field delay).\n */\n debounce?: number | false;\n\n /** Form-level validation */\n validate?: (\n values: Partial<TFieldValues>,\n ) => Record<string, string> | Promise<Record<string, string>>;\n}\n\n/**\n * API passed to render function children\n */\nexport interface FormRenderAPI<TFieldValues extends FieldValues = FieldValues> {\n /** Fields in config but not rendered */\n unusedFields: string[];\n\n /** React Hook Form formState */\n formState: UseFormReturn<TFieldValues>[\"formState\"];\n\n /** React Hook Form methods */\n methods: UseFormReturn<TFieldValues>;\n\n /**\n * Submit handler that runs the full Formality submission pipeline.\n *\n * Use this in place of `methods.handleSubmit` to ensure form-level\n * `validate` and `transformValuesForSubmit` (valueField extraction +\n * getSubmitField rename) are applied before `onSubmit` receives the values.\n * `methods.handleSubmit` remains available as a raw RHF escape hatch but\n * bypasses those transforms.\n */\n handleSubmit: (\n onSubmit: (values: Partial<TFieldValues>) => void | Promise<void>,\n ) => (e?: React.BaseSyntheticEvent) => Promise<void>;\n\n /** Resolved form title (static or evaluated) */\n resolvedTitle?: string;\n}\n\n/**\n * Default group context for fields outside FieldGroup\n */\nconst defaultGroupContext = {\n state: {\n isDisabled: false,\n isVisible: true,\n hasSetCondition: false,\n setValue: undefined,\n conditions: [],\n subscriptions: [],\n },\n subscriptions: [],\n inferredInputs: [],\n config: { conditions: [], subscribesTo: [] },\n};\n\n/**\n * Form component - Core form wrapper with React Hook Form integration\n *\n * Provides:\n * - FormContext for field registration and subscription management\n * - React Hook Form integration with mode: 'onChange'\n * - Auto-save with debounced submission\n * - Config-driven default values\n * - Unused fields tracking for config-driven rendering\n *\n * @example\n * ```tsx\n * <Form\n * config={{\n * name: { type: 'textField', label: 'Name' },\n * email: { type: 'textField', label: 'Email' },\n * }}\n * onSubmit={(values) => console.log(values)}\n * >\n * <Field name=\"name\" />\n * <Field name=\"email\" />\n * <button type=\"submit\">Submit</button>\n * </Form>\n * ```\n */\nexport function Form<TFieldValues extends FieldValues = FieldValues>({\n children,\n config,\n formConfig = {},\n onSubmit,\n record,\n autoSave = false,\n debounce: debounceMs = 1000,\n validate,\n}: FormProps<TFieldValues>): JSX.Element {\n // Get provider configuration\n const providerConfig = useConfigContext();\n\n // Merge input configs (form overrides provider)\n const mergedInputs = useMemo((): Record<string, InputConfig> => {\n const formInputs =\n typeof formConfig.inputs === \"function\"\n ? formConfig.inputs(providerConfig.inputs)\n : (formConfig.inputs ?? {});\n\n // Merge provider inputs with form-level overrides\n const result: Record<string, InputConfig> = { ...providerConfig.inputs };\n for (const [key, override] of Object.entries(formInputs)) {\n if (result[key]) {\n result[key] = { ...result[key], ...override } as InputConfig;\n }\n }\n return result;\n }, [providerConfig.inputs, formConfig.inputs]);\n\n // Calculate default values from config\n const defaultValues = useMemo(() => {\n return resolveAllInitialValues(config, mergedInputs, record ?? {});\n }, [config, mergedInputs, record]);\n\n // Initialize React Hook Form\n const methods = useForm<TFieldValues>({\n mode: \"onChange\",\n defaultValues: defaultValues as any,\n values: record as any,\n });\n\n // === REGISTRIES ===\n\n // Field registration\n const fieldRegistry = useRef(new Set<string>());\n const [registeredFields, setRegisteredFields] = useState<Set<string>>(\n new Set(),\n );\n\n // Subscription management (inverted index: target → subscribers)\n const invertedSubscriptions = useRef(new Map<string, Set<string>>());\n\n // Watcher setters for notifying fields about subscribers\n const watcherSetters = useRef(new Map<string, WatcherSetterFn>());\n\n // Pending updates for fields not yet mounted\n const pendingWatcherUpdates = useRef(new Map<string, Set<string>>());\n\n // Validation state tracking\n const validatingFields = useRef(new Map<string, boolean>());\n\n // Auto-save tracking\n // pendingChanges accumulates field changes while debounce is pending\n const pendingChangedFields = useRef(new Set<string>());\n const pendingAffectedFields = useRef(new Set<string>());\n // executionVersion is incremented when a new auto-save starts, used to abort if new changes come in\n const executionVersionRef = useRef(0);\n\n // Per-field numeric debounce cache: interval (ms) → memoized debounced\n // auto-save fn. Fields that share the same numeric `InputConfig.debounce`\n // coalesce into a single timer (mirroring the single-timer behavior of the\n // Form-level debounce); fields with different numeric debounces each get\n // their own timer and fire on their own cadence.\n const fieldDebouncersRef = useRef(new Map<number, DebouncedFunction>());\n // Ref so `changeField` can reach the latest factory without being rebuilt\n // (and churning its context consumers) on every `executeAutoSave` change.\n const getOrCreateDebouncedRef = useRef<(ms: number) => DebouncedFunction>();\n\n // === REGISTRY OPERATIONS ===\n\n const registerField = useCallback((name: string) => {\n fieldRegistry.current.add(name);\n setRegisteredFields(new Set(fieldRegistry.current));\n }, []);\n\n const unregisterField = useCallback((name: string) => {\n fieldRegistry.current.delete(name);\n setRegisteredFields(new Set(fieldRegistry.current));\n }, []);\n\n // === SUBSCRIPTION OPERATIONS ===\n\n const addSubscription = useCallback((target: string, subscriber: string) => {\n // Update inverted index\n if (!invertedSubscriptions.current.has(target)) {\n invertedSubscriptions.current.set(target, new Set());\n }\n invertedSubscriptions.current.get(target)!.add(subscriber);\n\n // Log subscription addition (development only)\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Formality Subscription] \"${subscriber}\" added to watch \"${target}\"`,\n );\n }\n\n // Notify target field if mounted\n const setter = watcherSetters.current.get(target);\n if (setter) {\n setter((prev) => ({ ...prev, [subscriber]: true }));\n } else {\n // Queue for later\n if (!pendingWatcherUpdates.current.has(target)) {\n pendingWatcherUpdates.current.set(target, new Set());\n }\n pendingWatcherUpdates.current.get(target)!.add(subscriber);\n }\n }, []);\n\n const removeSubscription = useCallback(\n (target: string, subscriber: string) => {\n // Check if subscription exists before removal (for double-cleanup detection)\n const subscribers = invertedSubscriptions.current.get(target);\n const subscriptionExists = subscribers?.has(subscriber) ?? false;\n\n // Perform removal (keep original optional chaining for safety)\n invertedSubscriptions.current.get(target)?.delete(subscriber);\n\n // Log removal or warn about double-cleanup (development only)\n if (process.env.NODE_ENV !== \"production\") {\n if (subscriptionExists) {\n console.warn(\n `[Formality Subscription] \"${subscriber}\" removed from watching \"${target}\"`,\n );\n } else {\n console.warn(\n `[Formality Subscription] WARNING: Double-cleanup attempt - ` +\n `\"${subscriber}\" was not watching \"${target}\"`,\n );\n }\n }\n\n // Update watcher setter\n const setter = watcherSetters.current.get(target);\n if (setter) {\n setter((prev) => {\n const next = { ...prev };\n delete next[subscriber];\n return next;\n });\n }\n },\n [],\n );\n\n const registerWatcherSetter = useCallback(\n (name: string, setter: WatcherSetterFn) => {\n watcherSetters.current.set(name, setter);\n\n // Process pending subscriptions\n const pending = pendingWatcherUpdates.current.get(name);\n if (pending?.size) {\n setter((prev) => {\n const next = { ...prev };\n pending.forEach((sub) => {\n next[sub] = true;\n });\n return next;\n });\n pendingWatcherUpdates.current.delete(name);\n }\n },\n [],\n );\n\n const unregisterWatcherSetter = useCallback((name: string) => {\n watcherSetters.current.delete(name);\n }, []);\n\n // === FIELD STATE OPERATIONS ===\n\n /**\n * Get all fields affected by a change to the given field.\n * This traverses the subscription graph to find all dependents,\n * including transitive dependencies (A -> B -> C).\n */\n const getAffectedFields = useCallback((changedField: string): Set<string> => {\n const affected = new Set<string>();\n const toProcess = [changedField];\n\n while (toProcess.length > 0) {\n const current = toProcess.pop()!;\n const subscribers = invertedSubscriptions.current.get(current);\n if (subscribers) {\n for (const subscriber of subscribers) {\n if (!affected.has(subscriber)) {\n affected.add(subscriber);\n toProcess.push(subscriber); // Check for transitive dependencies\n }\n }\n }\n }\n\n return affected;\n }, []);\n\n const changeField = useCallback(\n (name: string, value: unknown, inputConfig?: InputConfig) => {\n // Auto-save trigger\n if (autoSave) {\n // Accumulate this change\n pendingChangedFields.current.add(name);\n\n // Add affected fields (those that depend on this field via conditions)\n const affected = getAffectedFields(name);\n for (const field of affected) {\n pendingAffectedFields.current.add(field);\n }\n\n // Resolve the auto-save cadence for this field:\n // inputConfig.debounce === false → submit immediately (no timer)\n // inputConfig.debounce === <number> → per-field debounced timer at that ms\n // inputConfig.debounce === undefined → fall back to the Form-level debounce\n // (debouncedSubmitRef already encodes debounceMs, including its false → immediate case)\n const fieldDebounce = inputConfig?.debounce;\n if (fieldDebounce === false) {\n // Immediate submission: bypass debounce entirely (field-level override)\n executeAutoSaveRef.current?.();\n } else if (typeof fieldDebounce === \"number\") {\n // Per-field numeric debounce: schedule at the field's own interval.\n // Previously this branch was dead config — any number fell through to\n // the single Form-level debounce. See autosave Issue 1.\n getOrCreateDebouncedRef.current?.(fieldDebounce)();\n } else {\n // No field-level override → Form-level debounced submission\n debouncedSubmitRef.current?.();\n }\n }\n },\n [autoSave, getAffectedFields],\n );\n\n const setFieldValidating = useCallback(\n (name: string, isValidating: boolean) => {\n validatingFields.current.set(name, isValidating);\n },\n [],\n );\n\n // === STATE ACCESS ===\n\n const getFormState = useCallback((): FormState => {\n const values = methods.getValues();\n const formState = methods.formState;\n\n // Build proxy-wrapped field states\n const fields: Record<string, any> = {};\n Object.keys(config).forEach((name) => {\n const fieldState = methods.getFieldState(name as any, formState);\n fields[name] = makeProxyState({\n value: values[name as keyof typeof values],\n isTouched: fieldState.isTouched,\n isDirty: fieldState.isDirty,\n isValidating: validatingFields.current.get(name) ?? false,\n error: fieldState.error\n ? {\n type: fieldState.error.type,\n message: fieldState.error.message,\n }\n : undefined,\n invalid: fieldState.invalid,\n });\n });\n\n return {\n fields,\n record: record ?? {},\n errors: formState.errors as any,\n defaultValues: defaultValues,\n touchedFields: formState.touchedFields as any,\n dirtyFields: formState.dirtyFields as any,\n isDirty: formState.isDirty,\n isTouched: Object.keys(formState.touchedFields).length > 0,\n isValid: formState.isValid,\n isSubmitting: formState.isSubmitting,\n };\n }, [methods, config, record, defaultValues]);\n\n // === SUBMISSION ===\n\n /**\n * Run the full submission pipeline (validate + transform) on already-collected\n * values, then invoke the supplied submit handler.\n *\n * Used by both auto-save and manual submit. When `overrideOnSubmit` is\n * provided (the manual-submit render-API path), it is called instead of the\n * `<Form onSubmit>` prop so a consumer using `methods.handleSubmit(handler)`\n * receives the transformed values.\n */\n const handleSubmit = useCallback(\n async (\n values: TFieldValues,\n overrideOnSubmit?: (\n values: Partial<TFieldValues>,\n ) => void | Promise<void>,\n ) => {\n // Check if any field is validating\n for (const [, isValidating] of validatingFields.current) {\n if (isValidating) return;\n }\n\n // Run form-level validation\n if (validate) {\n const errors = await validate(values);\n if (Object.keys(errors).length > 0) {\n Object.entries(errors).forEach(([field, message]) => {\n methods.setError(field as any, { message });\n });\n return;\n }\n }\n\n // Transform values for submission\n const submitValues = transformValuesForSubmit(\n values,\n config,\n mergedInputs,\n );\n\n const sink = overrideOnSubmit ?? onSubmit;\n await sink?.(submitValues);\n },\n [validate, methods, onSubmit, config, mergedInputs],\n );\n\n /**\n * Render-API submit handler.\n *\n * Wraps React Hook Form's `methods.handleSubmit` so that the documented\n * submission pipeline (form-level `validate` + `transformValuesForSubmit`)\n * runs on the manual-submit path too — not just auto-save. RHF performs its\n * own field validation first; if it passes, values are routed through\n * `handleSubmit` (validate + transform) before reaching `userOnSubmit`.\n */\n const handleRenderSubmit = useCallback(\n (userOnSubmit: (values: Partial<TFieldValues>) => void | Promise<void>) => {\n return methods.handleSubmit(async (values) => {\n await handleSubmit(values as TFieldValues, userOnSubmit);\n });\n },\n [methods, handleSubmit],\n );\n\n // Debounced submit for auto-save\n const debouncedSubmitRef = useRef<DebouncedFunction>();\n\n // Ref to store executeAutoSave for use in changeField (to avoid initialization order issues)\n const executeAutoSaveRef = useRef<typeof executeAutoSave>();\n\n /**\n * Wait for specific fields to complete their validation.\n * Returns false if the version changed (new changes came in), true otherwise.\n */\n const waitForFieldValidation = useCallback(\n async (fields: string[], version: number): Promise<boolean> => {\n const maxWaitMs = 10000; // 10 second timeout\n const pollIntervalMs = 50;\n const startTime = Date.now();\n\n while (Date.now() - startTime < maxWaitMs) {\n // Check if version changed (new changes came in)\n if (executionVersionRef.current !== version) {\n return false;\n }\n\n // Check if all fields have completed validation\n const allDone = fields.every(\n (field) => !validatingFields.current.get(field),\n );\n if (allDone) {\n return true;\n }\n\n // Wait and check again\n await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));\n }\n\n // Timeout - proceed anyway\n return true;\n },\n [],\n );\n\n /**\n * Execute auto-save: validate only changed/affected fields, wait for completion, then submit.\n * This prevents the issue where handleSubmit() validates ALL fields.\n */\n const executeAutoSave = useCallback(async () => {\n // Capture and increment execution version\n executionVersionRef.current++;\n const executionVersion = executionVersionRef.current;\n\n // Copy and clear pending fields\n const changedFields = new Set(pendingChangedFields.current);\n const affectedFields = new Set(pendingAffectedFields.current);\n pendingChangedFields.current.clear();\n pendingAffectedFields.current.clear();\n\n // If no fields changed, nothing to do\n if (changedFields.size === 0) {\n return;\n }\n\n // Changed fields: already validated by RHF's onChange mode\n // Affected fields: may need validation for cross-field validation\n const fieldsToWaitFor = [...changedFields, ...affectedFields];\n const fieldsToTrigger = [...affectedFields]; // Only affected, not changed\n\n // Wait for any in-flight validations on these fields to complete\n const validationsComplete = await waitForFieldValidation(\n fieldsToWaitFor,\n executionVersion,\n );\n\n // If version changed while waiting, abort (new changes came in)\n if (\n !validationsComplete ||\n executionVersionRef.current !== executionVersion\n ) {\n return;\n }\n\n // Check if changed fields have errors (from onChange validation)\n for (const fieldName of changedFields) {\n const fieldState = methods.getFieldState(fieldName as any);\n if (fieldState.error) {\n // Changed field has validation error, don't submit\n return;\n }\n }\n\n // Only trigger affected fields (changed fields already validated by onChange)\n if (fieldsToTrigger.length > 0) {\n const isValid = await methods.trigger(fieldsToTrigger as any);\n\n // Check version again after async validation\n if (executionVersionRef.current !== executionVersion) {\n return;\n }\n\n if (!isValid) {\n // Validation failed, don't submit\n return;\n }\n\n // Wait for triggered validations to complete\n const postTriggerComplete = await waitForFieldValidation(\n fieldsToTrigger,\n executionVersion,\n );\n\n if (\n !postTriggerComplete ||\n executionVersionRef.current !== executionVersion\n ) {\n return;\n }\n }\n\n // All relevant validations passed.\n //\n // NOTE: we intentionally do NOT bail on whole-form errors here. The checks\n // above already validate exactly the fields this save can touch (changed\n // fields via onChange + affected fields via trigger()). Rejecting on *any*\n // unrelated field's error would silently drop a valid edit — e.g. editing\n // `notes` while an unrelated required `email` is empty — so the user's\n // change would sit unsaved with no feedback. Whole-form validity is still\n // enforced on a full manual submit. See autosave Issue 2.\n const values = methods.getValues();\n await handleSubmit(values as TFieldValues);\n }, [methods, handleSubmit, waitForFieldValidation]);\n\n // Keep the ref in sync with the latest executeAutoSave function\n executeAutoSaveRef.current = executeAutoSave;\n\n /**\n * Get (or lazily create) a debounced auto-save function for a specific\n * interval, used to honor per-field numeric `InputConfig.debounce` values.\n *\n * The cache is keyed by interval so fields sharing the same numeric\n * debounce coalesce into a single timer (mirroring the single-timer\n * behavior of the Form-level debounce); fields with different numeric\n * debounces each get their own timer and fire on their own cadence.\n *\n * This governs *auto-save timing only*. The field value is still committed\n * to React Hook Form on every change (see Field.handleChange); a numeric\n * debounce does NOT throttle value commits / re-renders.\n */\n const getOrCreateDebounced = useCallback((ms: number): DebouncedFunction => {\n const cached = fieldDebouncersRef.current.get(ms);\n if (cached) return cached;\n\n // Forward through executeAutoSaveRef so each cached debounced fn is\n // stable: it always invokes the latest executeAutoSave without rebuilding\n // the timer (and canceling any pending save) when executeAutoSave's\n // identity changes. The cache therefore stays valid for the field's\n // lifetime — no teardown/rebuild needed.\n //\n // Built via wrapDebounced so this per-field timer reports a correct\n // pending() (autosave Issue 3) — the cache therefore also stays\n // pending-accurate for its whole lifetime.\n const fn = wrapDebounced(() => {\n executeAutoSaveRef.current?.();\n }, ms);\n\n fieldDebouncersRef.current.set(ms, fn);\n return fn;\n }, []);\n\n // Keep the factory ref in sync so `changeField` (defined above) always\n // invokes the latest factory. Stable identity (no executeAutoSave dep), so\n // `changeField` and its context consumers are not churned.\n getOrCreateDebouncedRef.current = getOrCreateDebounced;\n\n // Cancel + clear all per-field debouncers on unmount. No rebuild is needed\n // on executeAutoSave changes — the cached fns forward through the ref above.\n useEffect(() => {\n return () => {\n fieldDebouncersRef.current.forEach((fn) => fn.cancel());\n fieldDebouncersRef.current.clear();\n };\n }, [getOrCreateDebounced]);\n\n // Form-level debounced submit, built once per `debounceMs`. It forwards\n // through executeAutoSaveRef so it (a) always invokes the latest\n // executeAutoSave without rebuilding/canceling the timer on every\n // executeAutoSave identity change, and (b) can be assigned during render —\n // making it available on the very first render, consistent with\n // executeAutoSaveRef / getOrCreateDebouncedRef. Previously this was wired\n // up inside an effect, leaving a first-render window where the ref was\n // undefined (the `?.()` no-ops). See autosave Issue 3.\n const debouncedSubmit = useMemo<DebouncedFunction>(() => {\n // When debounce is false, use immediate execution (no debouncing)\n if (debounceMs === false) {\n return Object.assign(\n () => {\n executeAutoSaveRef.current?.();\n },\n {\n cancel: () => {}, // No-op for immediate function\n flush: () => executeAutoSaveRef.current?.(), // Execute immediately on flush\n pending: () => false, // Never pending when immediate\n },\n ) as DebouncedFunction;\n }\n\n // Normal debounce behavior — wrapDebounced gives a correct pending().\n return wrapDebounced(() => {\n executeAutoSaveRef.current?.();\n }, debounceMs);\n }, [debounceMs]);\n\n // Assign during render (not in an effect) so the ref is populated on the\n // first render and never undefined.\n debouncedSubmitRef.current = debouncedSubmit;\n\n // Cancel the lodash timer when the interval changes or on unmount. (For the\n // immediate adapter, cancel() is a no-op.)\n useEffect(() => {\n return () => {\n debouncedSubmit.cancel();\n };\n }, [debouncedSubmit]);\n\n const submitImmediate = useCallback(() => {\n // Flush every pending auto-save immediately — both the per-field numeric\n // debounce timers (autosave Issue 1) and the Form-level debounce.\n //\n // Pending changes accumulate in a single shared set\n // (`pendingChangedFields`), so one `executeAutoSave` captures them all.\n // We therefore (a) detect any pending timer, (b) cancel every idle timer\n // so its trailing callback can't fire a second, version-bumping\n // invocation that would abort this flush (see executionVersionRef in\n // executeAutoSave), and (c) run the save pipeline exactly once.\n const anyPending =\n debouncedSubmitRef.current?.pending() === true ||\n [...fieldDebouncersRef.current.values()].some((fn) => fn.pending());\n if (!anyPending) return; // nothing scheduled — avoid a spurious empty save\n\n // Cancel the idle timers (no-op when not pending, and a no-op for the\n // immediate adapter) so their later callbacks don't race this manual flush.\n debouncedSubmitRef.current?.cancel();\n fieldDebouncersRef.current.forEach((fn) => fn.cancel());\n\n // Drain the shared pending-changes set in a single save. `executeAutoSave`\n // reads the latest values via `methods.getValues()`, so a canceled in-flight\n // save (if any) is superseded without data loss.\n executeAutoSaveRef.current?.();\n }, []);\n\n // === UNUSED FIELDS ===\n\n const unusedFields = useMemo(() => {\n const allFields = Object.keys(config);\n return allFields.filter((name) => !registeredFields.has(name));\n }, [config, registeredFields]);\n\n // === RESOLVED TITLE ===\n\n const resolvedTitle = useMemo(() => {\n if (!formConfig.selectTitle && !formConfig.title) {\n return undefined;\n }\n\n // If selectTitle exists, evaluate it\n if (formConfig.selectTitle) {\n const formState = getFormState();\n const context = buildFormContext(\n formState.fields,\n formState.record,\n formState.errors,\n formState.defaultValues,\n formState.touchedFields,\n formState.dirtyFields,\n );\n const evaluated = evaluateDescriptor(formConfig.selectTitle, context);\n return resolveFormTitle(formConfig.title, evaluated);\n }\n\n // Static title\n return resolveFormTitle(formConfig.title);\n }, [formConfig.title, formConfig.selectTitle, getFormState]);\n\n // === CONTEXT VALUE ===\n\n const contextValue = useMemo<FormContextValue<TFieldValues>>(\n () => ({\n config,\n formConfig,\n record,\n registerField,\n unregisterField,\n addSubscription,\n removeSubscription,\n registerWatcherSetter,\n unregisterWatcherSetter,\n changeField,\n setFieldValidating,\n getFormState,\n onSubmit,\n debouncedSubmit,\n submitImmediate,\n unusedFields,\n methods: methods as any,\n }),\n [\n config,\n formConfig,\n record,\n registerField,\n unregisterField,\n addSubscription,\n removeSubscription,\n registerWatcherSetter,\n unregisterWatcherSetter,\n changeField,\n setFieldValidating,\n getFormState,\n onSubmit,\n debouncedSubmit,\n submitImmediate,\n unusedFields,\n methods,\n ],\n );\n\n // === RENDER ===\n\n // CRITICAL: Only access methods.formState when children is a function\n // Accessing formState ANYWHERE creates a subscription to the entire form state\n // This would cause ALL children to re-render on ANY field change\n const isRenderFunction = typeof children === \"function\";\n\n return (\n <FormProvider {...methods}>\n <FormContext.Provider value={contextValue as any}>\n <GroupContext.Provider value={defaultGroupContext}>\n {isRenderFunction\n ? children({\n unusedFields,\n formState: methods.formState,\n methods: methods as any,\n handleSubmit: handleRenderSubmit,\n resolvedTitle,\n })\n : children}\n </GroupContext.Provider>\n </FormContext.Provider>\n </FormProvider>\n );\n}\n\n/**\n * Wrap a lodash debounced auto-save callback so it satisfies the\n * `DebouncedFunction` contract — including a CORRECT `pending()`.\n *\n * `lodash-es`'s `debounce` returns a function with `cancel` / `flush` but NO\n * `pending()` (the project's earlier comments assumed lodash tracked it\n * internally — it does not). We therefore track the pending state explicitly:\n * - a scheduling call sets it,\n * - the trailing invocation (after `wait`ms), `flush`, and `cancel` clear it.\n *\n * See autosave Issue 3 (`pending()` always returned false).\n */\nfunction wrapDebounced(callback: () => void, ms: number): DebouncedFunction {\n let isPending = false;\n const debounced = debounce(() => {\n isPending = false;\n callback();\n }, ms);\n return Object.assign(\n () => {\n isPending = true;\n debounced();\n },\n {\n cancel: () => {\n isPending = false;\n debounced.cancel();\n },\n flush: () => {\n isPending = false;\n debounced.flush();\n },\n pending: () => isPending,\n },\n ) as DebouncedFunction;\n}\n\n/**\n * Transform values for submission\n *\n * Applies valueField extraction and field name transformation\n * based on input config settings.\n */\nfunction transformValuesForSubmit<T extends FieldValues>(\n values: T,\n config: FormFieldsConfig,\n inputs: Record<string, InputConfig>,\n): Partial<T> {\n const result: Record<string, unknown> = {};\n\n for (const [name, value] of Object.entries(values)) {\n const fieldConfig = config[name];\n const type = fieldConfig?.type ?? \"textField\";\n const inputConfig = inputs[type];\n\n if (inputConfig) {\n // Get the submit field name (may be transformed)\n const submitName = transformFieldName(name, inputConfig.getSubmitField);\n\n // Extract value from complex object if valueField is specified\n const submitValue = extractValueField(value, inputConfig.valueField);\n\n result[submitName] = submitValue;\n } else {\n result[name] = value;\n }\n }\n\n return result as Partial<T>;\n}\n\nexport type { FormContextValue };\n","// @formality-ui/react - useInferredInputs Hook\n// Infers field dependencies from selectProps and conditions\n\nimport { useMemo } from \"react\";\nimport {\n inferFieldsFromDescriptor,\n inferFieldsFromConditions,\n} from \"@formality-ui/core\";\nimport type { ConditionDescriptor, SelectValue } from \"@formality-ui/core\";\n\ninterface UseInferredInputsOptions {\n /** Dynamic props descriptor to analyze for field references */\n selectProps?: SelectValue;\n\n /** Form-level default field props to analyze for field references */\n formDefaultFieldProps?: SelectValue;\n\n /** Provider-level default field props to analyze for field references */\n providerDefaultFieldProps?: SelectValue;\n\n /** Conditions to analyze for field references */\n conditions?: ConditionDescriptor[];\n\n /** Explicit field subscriptions */\n subscribesTo?: string[];\n}\n\n/**\n * Infers field dependencies from selectProps, conditions, and explicit subscriptions\n *\n * This hook analyzes:\n * - selectProps expressions for field references\n * - condition 'when' fields and 'selectWhen' expressions\n * - explicit subscribesTo declarations\n *\n * Used to automatically determine which fields a Field or FieldGroup\n * should subscribe to for reactive updates.\n *\n * @param options - Sources to analyze for field references\n * @returns Array of unique field names to subscribe to\n *\n * @example\n * ```tsx\n * const subscriptions = useInferredInputs({\n * selectProps: \"client.id\",\n * conditions: [{ when: 'signed', disabled: true }],\n * subscribesTo: ['contact'],\n * });\n * // → ['client', 'signed', 'contact']\n * ```\n */\nexport function useInferredInputs(options: UseInferredInputsOptions): string[] {\n const {\n selectProps,\n formDefaultFieldProps,\n providerDefaultFieldProps,\n conditions,\n subscribesTo,\n } = options;\n\n // Stable content signature.\n //\n // These inputs arrive from config objects that are usually reference-stable,\n // but callers also pass `undefined` (formerly defaulted to a *fresh* `[]` on\n // every call) and sometimes inline arrays. Keying the memo on a serialized\n // signature — instead of the raw array identities — keeps the returned array\n // reference stable across renders when nothing actually changed.\n //\n // Without this, the returned array is a new reference every render, which\n // propagates: `Field.allSubscriptions` memo busts every render, and\n // `useSubscriptions`'s effect (which lists `subscriptions` in its deps) tears\n // down + re-runs on every render — calling `addSubscription`/\n // `removeSubscription`, which `setWatchers` (a setState) inside an effect.\n // That setState-in-effect storm is what surfaces as React's\n // \"Maximum update depth exceeded\".\n const signature = JSON.stringify({\n selectProps,\n formDefaultFieldProps,\n providerDefaultFieldProps,\n conditions,\n subscribesTo,\n });\n\n return useMemo(() => {\n const inferred: string[] = [...(subscribesTo ?? [])];\n\n // Infer from providerDefaultFieldProps expression/descriptor\n if (providerDefaultFieldProps) {\n inferred.push(...inferFieldsFromDescriptor(providerDefaultFieldProps));\n }\n\n // Infer from formDefaultFieldProps expression/descriptor\n if (formDefaultFieldProps) {\n inferred.push(...inferFieldsFromDescriptor(formDefaultFieldProps));\n }\n\n // Infer from selectProps expression/descriptor\n if (selectProps) {\n inferred.push(...inferFieldsFromDescriptor(selectProps));\n }\n\n // Infer from conditions (when fields, selectWhen expressions)\n if (conditions && conditions.length > 0) {\n inferred.push(...inferFieldsFromConditions(conditions));\n }\n\n // Return unique field names\n return [...new Set(inferred)];\n }, [signature]);\n}\n","// @formality-ui/react - useConditions Hook\n// Evaluates conditions against current field values\n\nimport { useMemo } from \"react\";\nimport { useWatch } from \"react-hook-form\";\nimport {\n evaluateConditions,\n type ConditionResult,\n type FieldStateInput,\n} from \"@formality-ui/core\";\nimport type { ConditionDescriptor, FormFieldsConfig } from \"@formality-ui/core\";\nimport { useFormContext } from \"../context/FormContext\";\nimport { useInferredInputs } from \"./useInferredInputs\";\n\ninterface UseConditionsOptions {\n /** Conditions to evaluate */\n conditions: ConditionDescriptor[];\n\n /** Explicit field subscriptions */\n subscribesTo?: string[];\n\n /** Additional props for expression context */\n props?: Record<string, unknown>;\n\n /** Optional: All field configs for computing disabled states in fieldStates */\n allFieldsConfig?: FormFieldsConfig;\n}\n\n/**\n * Evaluates conditions against current field values\n *\n * This hook:\n * 1. Infers which fields to watch from conditions\n * 2. Subscribes to those fields via useWatch\n * 3. Evaluates conditions whenever watched values change\n *\n * Implements the condition evaluation rules:\n * - disabled: OR logic (any true = disabled)\n * - visible: AND logic (any false = hidden)\n * - setValue: last matching condition wins\n *\n * Uses two-pass evaluation to populate the disabled property in field states:\n * - Pass 1: Build base field states without disabled (prevents circular dependency)\n * - Pass 2: Compute disabled for each field using Pass 1 states\n * - Pass 3: Merge base states with disabled into final field states\n *\n * @param options - Conditions and subscription config\n * @returns Evaluation result with disabled, visible, and setValue states\n *\n * @example\n * ```tsx\n * const result = useConditions({\n * conditions: [\n * { when: 'signed', is: false, disabled: true },\n * { when: 'archived', truthy: true, visible: false },\n * ],\n * });\n * // result.disabled === true when signed is false\n * // result.visible === false when archived is truthy\n * ```\n */\nexport function useConditions(options: UseConditionsOptions): ConditionResult {\n const { conditions, subscribesTo, props, allFieldsConfig } = options;\n const { record, methods } = useFormContext();\n\n // Infer fields to watch from conditions and explicit subscriptions\n const watchFields = useInferredInputs({\n conditions,\n subscribesTo,\n });\n\n // Watch inferred fields (only subscribe if there are fields to watch)\n // CRITICAL: useWatch provides ISOLATED subscriptions - only re-renders when these specific values change\n const watchedValues = useWatch({\n control: methods.control,\n name: watchFields.length > 0 ? (watchFields as any) : [],\n });\n\n // Build field values map from watched values\n const fieldValues = useMemo(() => {\n const values: Record<string, unknown> = {};\n\n if (watchFields.length === 0) {\n return values;\n }\n\n // CRITICAL: useWatch with an array of names ALWAYS returns an array of values,\n // regardless of how many fields are watched. Only useWatch({ name: 'string' })\n // returns a single value.\n if (Array.isArray(watchedValues)) {\n watchFields.forEach((field, i) => {\n values[field] = watchedValues[i];\n });\n } else {\n // Fallback: single field, single value (shouldn't happen with array name)\n values[watchFields[0]] = watchedValues;\n }\n\n return values;\n }, [watchFields, watchedValues]);\n\n // ============================================================================\n // PASS 1: Build base field states WITHOUT disabled property\n // ============================================================================\n // CRITICAL: Use getFieldState() for NON-REACTIVE access to field metadata\n // This prevents subscribing to the entire form state which causes all fields to re-validate\n // Field states are read on-demand when values change, not when ANY field's metadata changes\n //\n // NOTE: This is Pass 1 of two-pass evaluation - disabled is NOT included here\n // to break the circular dependency between conditions and disabled state.\n const baseFieldStates = useMemo(() => {\n const states: Record<string, FieldStateInput> = {};\n\n // Collect all fields to build states for: watched fields + current field\n // Current field is needed for two-pass evaluation when it references other fields' disabled states\n const currentFieldName = props?.name as string | undefined;\n const allFieldsForPass1 = currentFieldName\n ? [...new Set([...watchFields, currentFieldName])]\n : watchFields;\n\n if (allFieldsForPass1.length === 0) {\n return states;\n }\n\n allFieldsForPass1.forEach((fieldName) => {\n // getFieldState() reads current state without creating subscriptions\n const fieldState = methods.getFieldState(fieldName as any);\n states[fieldName] = {\n value: fieldValues[fieldName],\n isTouched: fieldState.isTouched,\n isDirty: fieldState.isDirty,\n error: fieldState.error,\n invalid: fieldState.invalid,\n isValidating: false, // Not easily available per-field\n // ❌ NO disabled property - this is critical for Pass 1 to prevent circular dependency\n };\n });\n\n return states;\n }, [watchFields, fieldValues, methods, props]);\n\n // ============================================================================\n // PASS 2: Compute disabled states for each field\n // ============================================================================\n // Uses baseFieldStates (without disabled) to evaluate conditions\n // This prevents the circular dependency: conditions → disabled → conditions\n //\n // For circular dependencies (e.g., fieldA.isDisabled depends on fieldB.isDisabled),\n // we use iterative evaluation to converge to a stable state:\n // - Start with baseFieldStates (disabled = undefined for all)\n // - Iteratively compute disabled states until stable or max iterations reached\n const disabledStates = useMemo(() => {\n const disabled: Record<string, boolean> = {};\n\n // Collect all fields that need disabled state computation:\n // 1. Watched fields (fields referenced in conditions)\n // 2. Current field (so it can compute its own disabled from conditions)\n // 3. All fields in allFieldsConfig (to ensure we have states for all referenced fields)\n const currentFieldName = props?.name as string | undefined;\n const configFields = allFieldsConfig ? Object.keys(allFieldsConfig) : [];\n const allFieldsForPass2 = [...new Set([...watchFields, ...configFields])];\n if (currentFieldName && !allFieldsForPass2.includes(currentFieldName)) {\n allFieldsForPass2.push(currentFieldName);\n }\n\n if (allFieldsForPass2.length === 0) {\n return disabled;\n }\n\n // Build base states for ALL fields (not just watched fields)\n // This ensures we have states for fields that don't have baseFieldStates yet\n const allBaseStates: Record<string, FieldStateInput> = {};\n for (const fieldName of allFieldsForPass2) {\n if (baseFieldStates[fieldName]) {\n allBaseStates[fieldName] = baseFieldStates[fieldName];\n } else {\n // Field not in baseFieldStates, create default state\n const fieldState = methods.getFieldState(fieldName as any);\n allBaseStates[fieldName] = {\n value: fieldValues[fieldName],\n isTouched: fieldState.isTouched,\n isDirty: fieldState.isDirty,\n error: fieldState.error,\n invalid: fieldState.invalid,\n isValidating: false,\n };\n }\n }\n\n // Initial pass: compute disabled using allBaseStates (no disabled property)\n let currentStates = allBaseStates;\n let hasChanged = true;\n let iteration = 0;\n const maxIterations = 10; // Prevent infinite loops, should converge quickly\n\n while (hasChanged && iteration < maxIterations) {\n hasChanged = false;\n iteration++;\n\n // Compute disabled for all fields using current states\n const newDisabled: Record<string, boolean> = {};\n\n for (const fieldName of allFieldsForPass2) {\n const fieldConfig = allFieldsConfig?.[fieldName];\n const fieldConditions = fieldConfig?.conditions ?? [];\n const configDisabled = fieldConfig?.disabled;\n\n const result = evaluateConditions({\n conditions: fieldConditions,\n fieldValues,\n fieldStates: currentStates,\n record,\n props: { name: fieldName },\n });\n\n // Priority: config > conditions\n // Config-level disabled takes precedence over condition-based disabled\n newDisabled[fieldName] = configDisabled ?? result.disabled ?? false;\n }\n\n // Create new states with updated disabled\n const newStates: Record<string, FieldStateInput> = {};\n for (const fieldName of allFieldsForPass2) {\n const baseState = allBaseStates[fieldName];\n if (baseState) {\n newStates[fieldName] = {\n ...baseState,\n disabled: newDisabled[fieldName],\n };\n }\n }\n\n // Check if disabled states have changed\n for (const fieldName of allFieldsForPass2) {\n const oldDisabled = disabled[fieldName];\n const newDisabledValue = newDisabled[fieldName];\n if (oldDisabled !== newDisabledValue) {\n hasChanged = true;\n disabled[fieldName] = newDisabledValue;\n }\n }\n\n // Use new states for next iteration\n currentStates = newStates;\n }\n\n return disabled;\n }, [\n watchFields,\n allFieldsConfig,\n fieldValues,\n baseFieldStates,\n record,\n props,\n methods,\n ]);\n\n // ============================================================================\n // PASS 3: Merge base states with disabled into final field states\n // ============================================================================\n // This is the final fieldStates object that includes all properties including disabled\n const fieldStates = useMemo(() => {\n // Start with baseFieldStates (watched fields + current field)\n const states: Record<string, FieldStateInput> = { ...baseFieldStates };\n\n // Add disabled states for all fields that have them (from Pass 2)\n // This includes fields from allFieldsConfig that might not be in baseFieldStates\n Object.entries(disabledStates).forEach(([fieldName, disabled]) => {\n if (states[fieldName]) {\n // Field already in baseFieldStates, just add disabled\n states[fieldName] = {\n ...states[fieldName],\n disabled,\n };\n } else {\n // Field not in baseFieldStates, create new state with disabled\n const fieldState = methods.getFieldState(fieldName as any);\n states[fieldName] = {\n value: fieldValues[fieldName],\n isTouched: fieldState.isTouched,\n isDirty: fieldState.isDirty,\n error: fieldState.error,\n invalid: fieldState.invalid,\n isValidating: false,\n disabled,\n };\n }\n });\n\n return states;\n }, [baseFieldStates, disabledStates, fieldValues, methods]);\n\n // Evaluate conditions whenever field values or states change\n return useMemo(() => {\n // Return empty result if no conditions\n if (conditions.length === 0) {\n return {\n disabled: undefined,\n visible: undefined,\n setValue: undefined,\n hasDisabledCondition: false,\n hasVisibleCondition: false,\n hasSetCondition: false,\n };\n }\n\n return evaluateConditions({\n conditions,\n fieldValues,\n fieldStates,\n record,\n props,\n });\n }, [conditions, fieldValues, fieldStates, record, props]);\n}\n","// @formality-ui/react - usePropsEvaluation Hook\n// Evaluates selectProps against current field values\n\nimport { useMemo } from \"react\";\nimport { useWatch } from \"react-hook-form\";\nimport {\n evaluateDescriptor,\n buildFieldContext,\n type FormState,\n} from \"@formality-ui/core\";\nimport type { SelectValue } from \"@formality-ui/core\";\nimport { useFormContext } from \"../context/FormContext\";\nimport { useInferredInputs } from \"./useInferredInputs\";\nimport { makeProxyState } from \"../utils/makeProxyState\";\n\n/**\n * Evaluated props object returned by usePropsEvaluation\n *\n * Result of evaluating SelectValue expressions (selectProps, formDefaultFieldProps,\n * providerDefaultFieldProps) against current form state.\n *\n * The evaluation follows the priority system where higher-priority props override\n * lower-priority ones:\n * 1. Field-level selectProps (highest priority)\n * 2. Form-level formDefaultFieldProps (medium priority)\n * 3. Provider-level providerDefaultFieldProps (lowest priority)\n *\n * @example\n * ```tsx\n * // Expression evaluation\n * const props = usePropsEvaluation({\n * selectProps: { disabled: '!signed' },\n * fieldName: 'contact',\n * });\n * // When signed=false, props = { disabled: true }\n *\n * // Function callback evaluation\n * const props = usePropsEvaluation({\n * selectProps: (formState) => ({\n * variant: formState.fields.type?.value === 'premium' ? 'filled' : 'outlined'\n * }),\n * fieldName: 'variant',\n * });\n * ```\n */\nexport type SelectedProps = Record<string, unknown>;\n\n/**\n * Result of evaluating all three prop sources separately\n *\n * Each layer is evaluated independently so that mergeFieldProps\n * can correctly apply the 8-layer priority order.\n */\nexport interface EvaluatedPropsResult {\n /** Evaluated provider-level selectDefaultFieldProps (layer 7 priority) */\n providerSelectProps: Record<string, unknown>;\n\n /** Evaluated form-level selectDefaultFieldProps (layer 5 priority) */\n formSelectProps: Record<string, unknown>;\n\n /** Evaluated field-level selectProps (layer 2 priority) */\n fieldSelectProps: Record<string, unknown>;\n}\n\nexport interface UsePropsEvaluationOptions {\n /** Dynamic props descriptor to evaluate */\n selectProps?: SelectValue;\n\n /** Dynamic default field props from Form config (higher priority) */\n formDefaultFieldProps?: SelectValue;\n\n /** Dynamic default field props from Provider config (lower priority) */\n providerDefaultFieldProps?: SelectValue;\n\n /** Explicit field subscriptions */\n subscribesTo?: string[];\n\n /** Current field name */\n fieldName: string;\n}\n\n/**\n * Evaluates dynamic props against current field values\n *\n * This hook:\n * 1. Infers which fields to watch from selectProps expressions\n * 2. Subscribes to those fields via useWatch\n * 3. Evaluates selectProps whenever watched values change\n *\n * Handles both expression-based selectProps and function-based selectProps.\n *\n * @param options - Hook options including props to evaluate and subscription config\n * @param {SelectValue} [options.selectProps] - Dynamic props descriptor to evaluate\n * @param {SelectValue} [options.formDefaultFieldProps] - Dynamic default props from Form config (higher priority)\n * @param {SelectValue} [options.providerDefaultFieldProps] - Dynamic default props from Provider config (lower priority)\n * @param {string[]} [options.subscribesTo] - Explicit field subscriptions\n * @param {string} options.fieldName - Current field name\n * @returns Evaluated props object\n *\n * @example\n * ```tsx\n * const props = usePropsEvaluation({\n * selectProps: {\n * options: \"client.id ? clientOptions : allOptions\",\n * disabled: \"!signed\",\n * },\n * fieldName: 'contact',\n * });\n * // props.options and props.disabled are evaluated against current state\n * ```\n */\nexport function usePropsEvaluation(\n options: UsePropsEvaluationOptions,\n): EvaluatedPropsResult {\n const {\n selectProps,\n formDefaultFieldProps,\n providerDefaultFieldProps,\n subscribesTo,\n fieldName,\n } = options;\n const { record, methods } = useFormContext();\n\n // Infer fields to watch from providerDefaultFieldProps, formDefaultFieldProps, selectProps, and explicit subscriptions\n const watchFields = useInferredInputs({\n providerDefaultFieldProps,\n formDefaultFieldProps,\n selectProps,\n subscribesTo,\n });\n\n // Watch inferred fields (only subscribe if there are fields to watch)\n const watchedValues = useWatch({\n control: methods.control,\n name: watchFields.length > 0 ? (watchFields as any) : [],\n });\n\n // Build form state for evaluation (needed for function-based selectProps)\n // CRITICAL: Only build state for watched fields to maintain performance isolation\n const formState = useMemo((): FormState => {\n // Build proxy-wrapped field states ONLY for watched fields\n // This prevents subscribing to the entire form state\n const fields: Record<string, any> = {};\n\n if (watchFields.length > 0) {\n // useWatch returns an array when given an array of field names\n // useWatch({ name: [\"f1\"] }) → [v1]\n // useWatch({ name: [\"f1\", \"f2\"] }) → [v1, v2]\n const values = Array.isArray(watchedValues)\n ? watchFields.reduce(\n (acc, field, i) => {\n acc[field] = watchedValues[i];\n return acc;\n },\n {} as Record<string, unknown>,\n )\n : (watchedValues as Record<string, unknown>);\n\n watchFields.forEach((name) => {\n // Create minimal proxy state with just the value\n // We don't need isTouched/isDirty/error for selectProps evaluation\n fields[name] = makeProxyState({\n value: values[name],\n isTouched: false,\n isDirty: false,\n isValidating: false,\n error: undefined,\n invalid: false,\n });\n });\n }\n\n return {\n fields,\n record: record ?? {},\n errors: {},\n defaultValues: {},\n touchedFields: {},\n dirtyFields: {},\n isDirty: false,\n isTouched: false,\n isValid: true,\n isSubmitting: false,\n };\n // Only depends on watchFields and watchedValues - NOT the entire form state\n }, [watchFields, watchedValues, record]);\n\n // Evaluate props: evaluate ALL three layers separately for mergeFieldProps\n return useMemo(() => {\n // Step 1: Evaluate providerDefaultFieldProps (lowest priority, layer 7)\n let providerResult: Record<string, unknown> = {};\n if (providerDefaultFieldProps) {\n // Handle function providerDefaultFieldProps\n if (typeof providerDefaultFieldProps === \"function\") {\n providerResult =\n (providerDefaultFieldProps(formState, methods) as Record<\n string,\n unknown\n >) ?? {};\n } else {\n // Build evaluation context\n const context = buildFieldContext(formState, fieldName);\n\n // Evaluate descriptor (string expression, object with expressions, or array)\n providerResult =\n (evaluateDescriptor(providerDefaultFieldProps, context) as Record<\n string,\n unknown\n >) ?? {};\n }\n }\n\n // Step 2: Evaluate formDefaultFieldProps (medium priority, layer 5)\n let formResult: Record<string, unknown> = {};\n if (formDefaultFieldProps) {\n // Handle function formDefaultFieldProps\n if (typeof formDefaultFieldProps === \"function\") {\n formResult =\n (formDefaultFieldProps(formState, methods) as Record<\n string,\n unknown\n >) ?? {};\n } else {\n // Build evaluation context\n const context = buildFieldContext(formState, fieldName);\n\n // Evaluate descriptor (string expression, object with expressions, or array)\n formResult =\n (evaluateDescriptor(formDefaultFieldProps, context) as Record<\n string,\n unknown\n >) ?? {};\n }\n }\n\n // Step 3: Evaluate selectProps (highest priority, layer 2)\n let fieldResult: Record<string, unknown> = {};\n if (selectProps) {\n // Handle function selectProps\n if (typeof selectProps === \"function\") {\n fieldResult =\n (selectProps(formState, methods) as Record<string, unknown>) ?? {};\n } else {\n // Build evaluation context\n const context = buildFieldContext(formState, fieldName);\n\n // Evaluate descriptor (string expression, object with expressions, or array)\n fieldResult =\n (evaluateDescriptor(selectProps, context) as Record<\n string,\n unknown\n >) ?? {};\n }\n }\n\n // Step 4: Return all three results for mergeFieldProps to handle priority\n return {\n providerSelectProps: providerResult,\n formSelectProps: formResult,\n fieldSelectProps: fieldResult,\n };\n }, [\n providerDefaultFieldProps,\n formDefaultFieldProps,\n selectProps,\n formState,\n methods,\n fieldName,\n ]);\n}\n","// @formality-ui/react - useSubscriptions Hook\n// Manages field subscriptions in the Form's inverted index\n\nimport { useEffect, useRef } from \"react\";\nimport { useFormContext } from \"../context/FormContext\";\n\n/**\n * Manages field subscriptions\n *\n * This hook registers the current field as a subscriber to the target fields,\n * and cleans up subscriptions when the component unmounts or subscriptions change.\n *\n * Subscriptions are stored in the Form's inverted index (target → subscribers),\n * which allows target fields to know who is watching them (for optimization).\n *\n * @param fieldName - The subscribing field's name\n * @param subscriptions - Array of field names to subscribe to\n *\n * @example\n * ```tsx\n * // Contact field subscribes to client field\n * useSubscriptions('contact', ['client']);\n *\n * // When client changes, its watchers can be notified\n * // This enables features like passSubscriptions\n * ```\n */\nexport function useSubscriptions(\n fieldName: string,\n subscriptions: string[],\n): void {\n const { addSubscription, removeSubscription } = useFormContext();\n\n // PATTERN: Per-effect subscription tracking (similar to executionVersionRef in Form.tsx)\n // Track the current effect run ID\n const runIdRef = useRef<number>(0);\n\n // Store subscriptions added in each effect run\n // Key: run ID, Value: subscriptions array for that run\n const runSubscriptionsRef = useRef<Map<number, string[]>>(new Map());\n\n useEffect(() => {\n // Increment run ID for this effect invocation\n const currentRunId = ++runIdRef.current;\n\n // CRITICAL: Store subscriptions for THIS specific effect run\n // Use [...subscriptions] to create a copy (prevent reference sharing)\n runSubscriptionsRef.current.set(currentRunId, [...subscriptions]);\n\n // Add all subscriptions\n subscriptions.forEach((target) => {\n addSubscription(target, fieldName);\n\n // Log subscription addition (development only)\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Formality Subscription] Run ${currentRunId}: ` +\n `\"${fieldName}\" subscribing to \"${target}\"`,\n );\n }\n });\n\n // Cleanup only removes subscriptions added in THIS run\n return () => {\n // Get subscriptions for THIS specific run (not current subscriptions value)\n const thisRunSubscriptions =\n runSubscriptionsRef.current.get(currentRunId);\n\n if (thisRunSubscriptions) {\n // Log cleanup start (development only)\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Formality Subscription] Run ${currentRunId}: ` +\n `\"${fieldName}\" cleaning up [${thisRunSubscriptions.join(\", \")}]`,\n );\n }\n\n // PATTERN: LIFO cleanup (Last In, First Out)\n // Reverse order for dependent subscriptions\n [...thisRunSubscriptions].reverse().forEach((target) => {\n removeSubscription(target, fieldName);\n });\n\n // CRITICAL: Clean up tracking map to prevent memory leaks\n runSubscriptionsRef.current.delete(currentRunId);\n }\n };\n }, [fieldName, subscriptions, addSubscription, removeSubscription]);\n}\n","// @formality-ui/react - Field Component\n// Core field component with Controller integration\n\nimport {\n useMemo,\n useCallback,\n useEffect,\n useState,\n useRef,\n createElement,\n type ReactNode,\n type Ref,\n} from \"react\";\nimport {\n Controller,\n useWatch,\n type ControllerFieldState,\n type UseFormStateReturn,\n type FieldValues,\n} from \"react-hook-form\";\nimport {\n resolveInputConfig,\n mergeFieldProps,\n resolveLabel,\n parse,\n format,\n runValidator,\n resolveErrorMessage,\n} from \"@formality-ui/core\";\nimport type { FieldConfig, InputConfig } from \"@formality-ui/core\";\nimport type { FormalityFieldComponentProps } from \"../overlays\";\nimport { useFormContext } from \"../context/FormContext\";\nimport { useConfigContext } from \"../context/ConfigContext\";\nimport { useGroupContext } from \"../context/GroupContext\";\nimport { useConditions } from \"../hooks/useConditions\";\nimport { usePropsEvaluation } from \"../hooks/usePropsEvaluation\";\nimport { useInferredInputs } from \"../hooks/useInferredInputs\";\nimport { useSubscriptions } from \"../hooks/useSubscriptions\";\nimport { makeProxyState } from \"../utils/makeProxyState\";\nimport type { CustomFieldState, WatcherSetterFn } from \"../types\";\n\n/**\n * Field component props.\n *\n * `FieldProps` is generic over the field `name`:\n * `FieldProps<TName extends string = string>`. The default `TName = string`\n * means `<Field name={anyString} />` compiles unchanged (no migration) and a\n * bare `FieldProps` is identical to `FieldProps<string>`.\n *\n * To get compile-time checking of the field name, narrow `TName` explicitly —\n * e.g. `FieldProps<\"name\" | \"email\">` or a wrapper that threads a\n * `keyof ClientValues & string`. With a narrowed `TName`, a typo like\n * `name=\"ofice\"` is rejected at compile time instead of silently rendering\n * nothing (the second half of PRD §C.4 / T2.1's \"silent no-op\" fix).\n *\n * Automatic per-form narrowing — where a `<Field>` automatically narrows its\n * `name` against the enclosing `<Form<TFieldValues>>`'s key set — is a planned\n * follow-up (PRD §C.4 T2.1) and is explicitly deferrable.\n *\n * @example\n * ```tsx\n * // Default usage — any string name compiles (unchanged behavior):\n * <Field name=\"email\" />;\n *\n * // Opt-in strict usage — typo names are compile errors:\n * type Names = \"name\" | \"email\";\n * const props: FieldProps<Names> = { name: \"email\" };\n * ```\n */\nexport interface FieldProps<TName extends string = string> {\n /**\n * Field name (must match a key in Form's config).\n *\n * When `FieldProps` is narrowed (e.g. `FieldProps<\"name\" | \"email\">`), the\n * name is checked against `TName` at compile time. With the default\n * (`FieldProps` / `FieldProps<string>`), any string is accepted.\n */\n name: TName;\n\n /** Override the input type from config */\n type?: string;\n\n /** Override disabled state */\n disabled?: boolean;\n\n /** Override hidden state (inverse of visible) */\n hidden?: boolean;\n\n /** Custom render function for advanced use cases */\n children?: ReactNode | ((api: FieldRenderAPI) => ReactNode);\n\n /** Whether to register this field in Form's field registry (default: true) */\n shouldRegister?: boolean;\n\n /** Override input config for this field (e.g., debounce setting) */\n inputConfig?: Partial<InputConfig>;\n\n /** Additional props to pass to the input component */\n [key: string]: unknown;\n}\n\n/**\n * API passed to render function children\n */\nexport interface FieldRenderAPI {\n /** React Hook Form field state */\n fieldState: ControllerFieldState;\n\n /** The rendered input component */\n renderedField: ReactNode;\n\n /** Final merged props passed to input */\n fieldProps: Record<string, unknown>;\n\n /** Map of fields watching this field */\n watchers: Record<string, boolean>;\n\n /** React Hook Form form state */\n formState: UseFormStateReturn<FieldValues>;\n}\n\n/**\n * Field component - Renders a form field with full Formality integration\n *\n * Provides:\n * - React Hook Form Controller integration\n * - Props resolution (8-layer merge)\n * - Condition evaluation (disabled/visible/setValue)\n * - Value transformation (parse/format)\n * - Validation (field + type validators)\n * - Subscription management\n *\n * @example\n * ```tsx\n * // Basic usage\n * <Field name=\"email\" />\n *\n * // Override type\n * <Field name=\"status\" type=\"select\" />\n *\n * // Custom render\n * <Field name=\"name\">\n * {({ renderedField, fieldState }) => (\n * <div className={fieldState.error ? 'has-error' : ''}>\n * {renderedField}\n * </div>\n * )}\n * </Field>\n * ```\n */\nexport function Field<TName extends string = string>({\n name,\n type: typeProp,\n disabled: disabledProp,\n hidden: hiddenProp,\n children,\n shouldRegister = true,\n inputConfig: inputConfigProp,\n ...restProps\n}: FieldProps<TName>): JSX.Element | null {\n const {\n config,\n formConfig,\n methods,\n registerField,\n unregisterField,\n registerWatcherSetter,\n unregisterWatcherSetter,\n changeField,\n setFieldValidating,\n } = useFormContext();\n\n const providerConfig = useConfigContext();\n const groupContext = useGroupContext();\n\n // Get field config\n const fieldConfig: FieldConfig = config[name] ?? {};\n\n // Resolve type\n const type = typeProp ?? fieldConfig.type ?? \"textField\";\n\n // Resolve input config (merge provider + form + prop)\n const inputConfig = useMemo((): InputConfig => {\n const formInputs =\n typeof formConfig.inputs === \"function\"\n ? formConfig.inputs(providerConfig.inputs)\n : (formConfig.inputs ?? {});\n\n // Merge provider inputs with form-level overrides\n const mergedInputs: Record<string, InputConfig> = {\n ...providerConfig.inputs,\n };\n for (const [key, override] of Object.entries(formInputs)) {\n if (mergedInputs[key]) {\n mergedInputs[key] = {\n ...mergedInputs[key],\n ...override,\n } as InputConfig;\n }\n }\n\n const baseInputConfig = resolveInputConfig(type, mergedInputs) ?? {\n component: \"input\",\n defaultValue: \"\",\n };\n\n // Merge with inputConfig prop (prop has highest priority)\n return inputConfigProp\n ? ({ ...baseInputConfig, ...inputConfigProp } as InputConfig)\n : baseInputConfig;\n }, [type, providerConfig.inputs, formConfig.inputs, inputConfigProp]);\n\n // === REGISTRATION ===\n\n useEffect(() => {\n if (shouldRegister) {\n registerField(name);\n return () => unregisterField(name);\n }\n }, [name, shouldRegister, registerField, unregisterField]);\n\n // === WATCHER STATE ===\n\n const [watchers, setWatchers] = useState<Record<string, boolean>>({});\n\n useEffect(() => {\n registerWatcherSetter(name, setWatchers as WatcherSetterFn);\n return () => unregisterWatcherSetter(name);\n }, [name, registerWatcherSetter, unregisterWatcherSetter]);\n\n // === SUBSCRIPTIONS ===\n\n const inferredSubscriptions = useInferredInputs({\n selectProps: fieldConfig.selectProps,\n conditions: fieldConfig.conditions,\n subscribesTo: fieldConfig.subscribesTo,\n });\n\n // Merge with group subscriptions\n const allSubscriptions = useMemo(() => {\n return [\n ...new Set([...inferredSubscriptions, ...groupContext.subscriptions]),\n ];\n }, [inferredSubscriptions, groupContext.subscriptions]);\n\n useSubscriptions(name, allSubscriptions);\n\n // === CONDITIONS ===\n\n const conditionResult = useConditions({\n conditions: fieldConfig.conditions ?? [],\n subscribesTo: fieldConfig.subscribesTo,\n props: { name },\n allFieldsConfig: config, // Pass all field configs for two-pass evaluation of disabled states\n });\n\n // === APPLY SET VALUE FROM CONDITIONS ===\n // When a condition's set/selectSet evaluates, apply the value to the field\n // Priority: field-level conditions > group-level conditions\n // Store methods.setValue in a ref to avoid dependency issues\n const setValueRef = useRef(methods.setValue);\n setValueRef.current = methods.setValue;\n const getValuesRef = useRef(methods.getValues);\n getValuesRef.current = methods.getValues;\n\n // Determine effective setValue: field-level takes priority over group-level\n const effectiveSetValue = useMemo(() => {\n if (conditionResult.hasSetCondition) {\n return { hasCondition: true, value: conditionResult.setValue };\n }\n if (groupContext.state.hasSetCondition) {\n return { hasCondition: true, value: groupContext.state.setValue };\n }\n return { hasCondition: false, value: undefined };\n }, [\n conditionResult.hasSetCondition,\n conditionResult.setValue,\n groupContext.state.hasSetCondition,\n groupContext.state.setValue,\n ]);\n\n useEffect(() => {\n if (\n effectiveSetValue.hasCondition &&\n effectiveSetValue.value !== undefined\n ) {\n const currentValue = getValuesRef.current(name);\n // Only update if the value is actually different to avoid infinite loops\n if (currentValue !== effectiveSetValue.value) {\n // `methods` comes from the un-parameterized `useFormContext()` (→\n // UseFormReturn<FieldValues>), so setValue's name param is\n // FieldPath<FieldValues> === string at runtime. Our generic `name: TName`\n // (extends string) is structurally a string; cast for RHF's deep\n // conditional type. See PRP P1.M1.T1.S2 gotchas.\n setValueRef.current(name as string, effectiveSetValue.value, {\n shouldValidate: true,\n shouldDirty: true,\n shouldTouch: false,\n });\n }\n }\n }, [effectiveSetValue.hasCondition, effectiveSetValue.value, name]);\n\n // === PROPS EVALUATION ===\n //\n // Evaluated before disabled/visible resolution so that the props-merge\n // layers (selectProps / selectDefaultFieldProps) can contribute `disabled`.\n const { providerSelectProps, formSelectProps, fieldSelectProps } =\n usePropsEvaluation({\n selectProps: fieldConfig.selectProps,\n formDefaultFieldProps: formConfig.selectDefaultFieldProps,\n providerDefaultFieldProps: providerConfig.selectDefaultFieldProps,\n subscribesTo: fieldConfig.subscribesTo,\n fieldName: name,\n });\n\n // === DISABLED/VISIBLE RESOLUTION ===\n //\n // `disabled` is resolved here (rather than flowing solely through the\n // props-merge pipeline) because it participates in the condition system's\n // two-pass evaluation (other fields can match on this field's `isDisabled`).\n // The resolved boolean is emitted as `coreProps.disabled`.\n //\n // To keep the documented props-merge layers (`selectProps`,\n // `selectDefaultFieldProps`, `defaultFieldProps`, `inputConfig.props`,\n // `fieldConfig.props`) able to disable a field — which they could not when\n // an always-emitted boolean `coreProps.disabled` clobbered them — the\n // resolution order consults those layers as a final fallback before\n // defaulting to `false`. The layers are consulted in `mergeFieldProps`\n // priority order (highest first), so a higher-priority layer wins.\n // See PRD §5.3.2 merge pipeline.\n const isDisabled = useMemo(() => {\n // Resolution order: prop > config > condition > group > props-merge > false\n if (disabledProp !== undefined) return disabledProp;\n if (fieldConfig.disabled !== undefined) return fieldConfig.disabled;\n if (conditionResult.hasDisabledCondition)\n return conditionResult.disabled ?? false;\n if (groupContext.state.isDisabled) return true;\n\n // Props-merge layers (evaluated dynamic props + static props), consulted\n // in `mergeFieldProps` priority order (highest first). Each layer may set\n // `disabled` via an evaluated expression (e.g. `selectProps: { disabled:\n // \"!country\" }`) or statically (e.g. `defaultFieldProps: { disabled: true }`).\n const propsLayers = [\n fieldSelectProps, // layer 2: field-level selectProps\n formSelectProps, // layer 5: form-level selectDefaultFieldProps\n providerSelectProps, // layer 7: provider-level selectDefaultFieldProps\n inputConfig.props, // layer 4: input config props\n fieldConfig.props, // layer 3: field config props\n formConfig.defaultFieldProps, // layer 6: form-level defaultFieldProps\n providerConfig.defaultFieldProps, // layer 8: provider-level defaultFieldProps\n ];\n for (const layer of propsLayers) {\n const layerDisabled = layer?.disabled;\n if (layerDisabled !== undefined) return Boolean(layerDisabled);\n }\n\n return false;\n }, [\n disabledProp,\n fieldConfig.disabled,\n fieldConfig.props,\n conditionResult,\n groupContext.state.isDisabled,\n fieldSelectProps,\n formSelectProps,\n providerSelectProps,\n inputConfig.props,\n formConfig.defaultFieldProps,\n providerConfig.defaultFieldProps,\n ]);\n\n const isVisible = useMemo(() => {\n // Resolution order: prop > config > condition > group > true\n if (hiddenProp !== undefined) return !hiddenProp;\n if (fieldConfig.hidden !== undefined) return !fieldConfig.hidden;\n if (conditionResult.hasVisibleCondition)\n return conditionResult.visible ?? true;\n if (!groupContext.state.isVisible) return false;\n return true;\n }, [\n hiddenProp,\n fieldConfig.hidden,\n conditionResult,\n groupContext.state.isVisible,\n ]);\n\n // Resolve label\n const label = useMemo(() => {\n return resolveLabel(name, fieldConfig, fieldSelectProps, restProps);\n }, [name, fieldConfig, fieldSelectProps, restProps]);\n\n // === STATE INJECTION (provideState / passSubscriptions) ===\n //\n // FieldConfig.provideState injects the OWN field's state (value, isTouched,\n // isDirty, invalid, error) under the configured prop name (default 'state').\n // FieldConfig.passSubscriptions injects the SUBSCRIBED fields' states under\n // a prop name (default 'state', override via passSubscriptionsAs). Both are\n // documented in PRD §3.2 / §5.3 / Appendix A and exercised by\n // examples/07-advanced-features.tsx.\n //\n // `provideState` reads from the Controller's fieldState (available in the\n // render callback below); `passSubscriptions` watches the inferred\n // subscriptions here so the component re-renders when they change.\n const passSubscriptionsEnabled = fieldConfig.passSubscriptions === true;\n const provideStateEnabled = fieldConfig.provideState === true;\n\n // Watch subscribed field values for passSubscriptions (only when enabled to\n // avoid unnecessary subscriptions).\n const subscribedWatchNames = useMemo(\n () =>\n passSubscriptionsEnabled && allSubscriptions.length > 0\n ? allSubscriptions\n : [],\n [passSubscriptionsEnabled, allSubscriptions],\n );\n const subscribedValues = useWatch({\n control: methods.control,\n name: subscribedWatchNames.length > 0 ? (subscribedWatchNames as any) : [],\n });\n\n // Build the subscribed-state map (Record<name, CustomFieldState>).\n const subscribedState = useMemo(() => {\n if (!passSubscriptionsEnabled || subscribedWatchNames.length === 0) {\n return undefined;\n }\n const result: Record<string, CustomFieldState> = {};\n const values: unknown[] = Array.isArray(subscribedValues)\n ? subscribedValues\n : [subscribedValues];\n subscribedWatchNames.forEach((fieldName, i) => {\n const fs = methods.getFieldState(fieldName as any);\n result[fieldName] = makeProxyState({\n value: values[i],\n isTouched: fs.isTouched,\n isDirty: fs.isDirty,\n isValidating: fs.isValidating,\n error: fs.error as CustomFieldState[\"error\"],\n invalid: fs.invalid,\n });\n });\n return result;\n }, [\n passSubscriptionsEnabled,\n subscribedWatchNames,\n subscribedValues,\n methods,\n ]);\n\n // === VALIDATION ===\n\n const validationRules = useMemo(() => {\n return {\n ...fieldConfig.rules,\n validate: async (value: unknown) => {\n setFieldValidating(name, true);\n\n try {\n // Field-level validator\n if (fieldConfig.validator) {\n const result = await runValidator(\n fieldConfig.validator,\n value,\n methods.getValues(),\n providerConfig.validators,\n );\n if (result !== true && result !== undefined) {\n return resolveErrorMessage(result, providerConfig.errorMessages);\n }\n }\n\n // Type-level validator\n if (inputConfig.validator) {\n const result = await runValidator(\n inputConfig.validator,\n value,\n methods.getValues(),\n providerConfig.validators,\n );\n if (result !== true && result !== undefined) {\n return resolveErrorMessage(result, providerConfig.errorMessages);\n }\n }\n\n return true;\n } finally {\n setFieldValidating(name, false);\n }\n },\n };\n }, [\n fieldConfig.rules,\n fieldConfig.validator,\n inputConfig.validator,\n methods,\n providerConfig.validators,\n providerConfig.errorMessages,\n name,\n setFieldValidating,\n ]);\n\n // === CHANGE HANDLER ===\n\n const handleChange = useCallback(\n (onChange: (value: unknown) => void) => (newValue: unknown) => {\n // Parse value\n const parsedValue = parse(\n newValue,\n inputConfig.parser,\n providerConfig.parsers,\n );\n\n // Update form value\n onChange(parsedValue);\n\n // Notify subscribers\n changeField(name, parsedValue, inputConfig);\n },\n [\n inputConfig.parser,\n providerConfig.parsers,\n changeField,\n name,\n inputConfig,\n ],\n );\n\n // Don't render if not visible\n if (!isVisible) {\n return null;\n }\n\n // === RENDER ===\n\n return (\n <Controller\n control={methods.control}\n name={name}\n rules={validationRules}\n render={({ field, fieldState, formState }) => {\n // Format value for display\n const formattedValue = format(\n field.value,\n inputConfig.formatter,\n providerConfig.formatters,\n );\n\n // === STATE INJECTION (provideState / passSubscriptions) ===\n //\n // Inject field/subscribed state under the configured prop name. This\n // is delivered through `coreProps` so it reaches the plain-component,\n // template, and render-prop paths uniformly (PRD §3.2 / §5.3).\n //\n // `formState` (PRD §C.4 / T3.1) is delivered to the plain-component\n // path ONLY when the component has opted into Formality state via\n // `provideState` or `passSubscriptions`. This satisfies the\n // FormalityFieldComponentProps contract (where the component author has\n // already agreed to destructure Formality-injected props) while\n // avoiding leaking `formState` onto the DOM for ordinary components\n // that spread props onto a host element. Templates and render-prop\n // children always receive `formState` (below).\n const stateInjection: Record<string, unknown> = {};\n if (provideStateEnabled) {\n stateInjection[providerConfig.defaultSubscriptionPropName] =\n makeProxyState({\n value: field.value,\n isTouched: fieldState.isTouched,\n isDirty: fieldState.isDirty,\n isValidating: fieldState.isValidating,\n error: fieldState.error as CustomFieldState[\"error\"],\n invalid: fieldState.invalid,\n });\n }\n if (passSubscriptionsEnabled && subscribedState) {\n const subsPropName =\n fieldConfig.passSubscriptionsAs ??\n providerConfig.defaultSubscriptionPropName;\n stateInjection[subsPropName] = subscribedState;\n }\n // Issue 6: deliver formState to plain components that have opted into\n // Formality state injection, so the FormalityFieldComponentProps type\n // contract holds for those components (PRD §C.4 / T3.1).\n if (provideStateEnabled || passSubscriptionsEnabled) {\n stateInjection.formState = formState;\n }\n\n // Merge props (8 layers)\n const finalProps = mergeFieldProps({\n providerDefaultFieldProps: providerConfig.defaultFieldProps,\n providerSelectDefaultFieldProps: providerSelectProps,\n formDefaultFieldProps: formConfig.defaultFieldProps,\n formSelectDefaultFieldProps: formSelectProps,\n inputProps: inputConfig.props,\n fieldConfigProps: fieldConfig.props,\n selectProps: fieldSelectProps,\n componentProps: restProps,\n coreProps: {\n name,\n label,\n disabled: isDisabled,\n error: fieldState.error?.message,\n [inputConfig.inputFieldProp ?? \"value\"]: formattedValue,\n onChange: handleChange(field.onChange),\n onBlur: field.onBlur,\n forwardRef: field.ref,\n ...stateInjection,\n },\n });\n\n // Get component\n const Component =\n inputConfig.component as React.ComponentType<FormalityFieldComponentProps>;\n\n // Host-component fallback (PRD §20.4 narrow exception).\n //\n // When `inputConfig.component` is a string host tag (the degenerate\n // `component: \"input\"` fallback used when an input type is unknown /\n // misconfigured), React only intercepts its SPECIAL `ref` key — NOT the\n // `forwardRef` prop that §20.1/§20.4 deliver for real components. If we\n // spread `finalProps` unchanged onto a host element, RHF's ref callback\n // (delivered as `forwardRef`) is never attached → focus-on-error breaks,\n // and `forwardRef` leaks to the DOM as a spurious `forwardref` attribute.\n //\n // To keep that fallback path functional we translate `forwardRef` back\n // into the special `ref` key (and drop the `forwardRef` prop) ONLY for\n // host-element rendering. Component rendering stays strictly\n // `forwardRef`-exclusive per §20.4 — this branch never runs for real\n // consumer components (which are functions/objects, not strings).\n const isHostComponent = typeof inputConfig.component === \"string\";\n\n // Render through template if present\n const template =\n inputConfig.template ??\n providerConfig.inputTemplates[type] ??\n providerConfig.defaultInputTemplate;\n\n const TemplateComponent = template as\n | React.ComponentType<any>\n | undefined;\n\n let renderedField: React.ReactElement;\n if (TemplateComponent) {\n renderedField = (\n <TemplateComponent\n Field={Component}\n fieldProps={finalProps}\n fieldState={fieldState}\n formState={formState}\n />\n );\n } else if (isHostComponent) {\n // Host-element path: translate `forwardRef` back into React's special\n // `ref` key (see block comment above) so the bare fallback input still\n // wires RHF's ref callback and supports focus-on-error. Also strip\n // the Formality-injected non-DOM props (formState, state, and the\n // configured subscriptions prop name) so they don't leak to the DOM\n // as spurious attributes — mirrors the forwardRef handling. Cast to a\n // host tag; `isHostComponent` guarantees `inputConfig.component` is a\n // string here, and React's JSX for intrinsic elements accepts `ref`.\n const subsPropName =\n fieldConfig.passSubscriptionsAs ??\n providerConfig.defaultSubscriptionPropName;\n const strippedHostProps: Record<string, unknown> = {};\n const nonDomKeys = new Set([\n \"forwardRef\",\n \"formState\",\n \"state\",\n subsPropName,\n ]);\n for (const [key, value] of Object.entries(finalProps)) {\n if (!nonDomKeys.has(key)) {\n strippedHostProps[key] = value;\n }\n }\n renderedField = createElement(inputConfig.component as string, {\n ...strippedHostProps,\n ref: (finalProps as Record<string, unknown>)\n .forwardRef as Ref<HTMLElement>,\n });\n } else {\n // Component path: forwardRef-exclusive per PRD §20.4.\n renderedField = <Component {...finalProps} />;\n }\n\n // Render children if function\n if (typeof children === \"function\") {\n const result = children({\n fieldState,\n renderedField,\n fieldProps: finalProps,\n watchers,\n formState,\n });\n // Ensure we return a valid ReactElement\n return <>{result}</>;\n }\n\n return renderedField as React.ReactElement;\n }}\n />\n );\n}\n","// @formality-ui/react - FieldGroup Component\n// Groups fields with shared conditions and state propagation\n\nimport { useMemo, type ReactNode } from \"react\";\nimport type { GroupConfig } from \"@formality-ui/core\";\nimport { useFormContext } from \"../context/FormContext\";\nimport {\n GroupContext,\n useGroupContext,\n type GroupContextValue,\n type GroupState,\n} from \"../context/GroupContext\";\nimport { useConditions } from \"../hooks/useConditions\";\nimport { useInferredInputs } from \"../hooks/useInferredInputs\";\n\n/**\n * FieldGroup component props\n */\nexport interface FieldGroupProps {\n /** Group name (must match a key in FormConfig.groups) */\n name: string;\n\n /** Fields to render within this group */\n children: ReactNode;\n}\n\n/**\n * FieldGroup component - Groups fields with shared conditions\n *\n * Provides:\n * - Group-level condition evaluation (disabled/visible)\n * - State propagation to nested fields:\n * - disabled: OR logic (child || parent)\n * - visible: AND logic (child && parent)\n * - Subscription accumulation from parent groups\n *\n * Groups can be nested, with state merging at each level.\n *\n * @example\n * ```tsx\n * // FormConfig\n * formConfig={{\n * groups: {\n * clientSection: {\n * conditions: [\n * { when: 'hasClient', is: false, visible: false }\n * ]\n * }\n * }\n * }}\n *\n * // Usage\n * <Form config={config} formConfig={formConfig}>\n * <Field name=\"hasClient\" />\n * <FieldGroup name=\"clientSection\">\n * <Field name=\"clientName\" />\n * <Field name=\"clientEmail\" />\n * </FieldGroup>\n * </Form>\n * ```\n */\nexport function FieldGroup({ name, children }: FieldGroupProps): JSX.Element {\n const { formConfig } = useFormContext();\n const parentContext = useGroupContext();\n\n // Get group config\n const groupConfig: GroupConfig = formConfig.groups?.[name] ?? {\n conditions: [],\n subscribesTo: [],\n };\n\n // Warn if group config not found (in development)\n if (process.env.NODE_ENV !== \"production\" && !formConfig.groups?.[name]) {\n console.warn(\n `FieldGroup: No config found for group \"${name}\". ` +\n `Make sure to define it in formConfig.groups.`,\n );\n }\n\n // Infer fields from conditions\n const inferredInputs = useInferredInputs({\n conditions: groupConfig.conditions,\n subscribesTo: groupConfig.subscribesTo,\n });\n\n // Evaluate conditions\n const conditionResult = useConditions({\n conditions: groupConfig.conditions ?? [],\n subscribesTo: groupConfig.subscribesTo,\n });\n\n // Merge with parent context state\n const mergedState = useMemo<GroupState>(() => {\n // Disabled: OR logic (any parent can disable)\n const isDisabled =\n (conditionResult.hasDisabledCondition\n ? (conditionResult.disabled ?? false)\n : false) || parentContext.state.isDisabled;\n\n // Visible: AND logic (any parent can hide)\n const isVisible =\n (conditionResult.hasVisibleCondition\n ? (conditionResult.visible ?? true)\n : true) && parentContext.state.isVisible;\n\n // setValue: This group's setValue takes priority, then parent's\n // (Child fields can still override with their own field-level conditions)\n const hasSetCondition =\n conditionResult.hasSetCondition || parentContext.state.hasSetCondition;\n const setValue = conditionResult.hasSetCondition\n ? conditionResult.setValue\n : parentContext.state.setValue;\n\n // Accumulate conditions and subscriptions\n const conditions = [\n ...parentContext.state.conditions,\n ...(groupConfig.conditions ?? []),\n ];\n\n const subscriptions = [\n ...parentContext.state.subscriptions,\n ...(groupConfig.subscribesTo ?? []),\n ];\n\n return {\n isDisabled,\n isVisible,\n hasSetCondition,\n setValue,\n conditions,\n subscriptions,\n };\n }, [conditionResult, parentContext.state, groupConfig]);\n\n // Build context value\n const contextValue = useMemo<GroupContextValue>(\n () => ({\n state: mergedState,\n subscriptions: mergedState.subscriptions,\n inferredInputs,\n config: groupConfig,\n }),\n [mergedState, inferredInputs, groupConfig],\n );\n\n // CRITICAL: Use span wrapper with display:none instead of returning null\n // This preserves children in DOM for state preservation (PRD Section 5.4, 18.10)\n return (\n <GroupContext.Provider value={contextValue}>\n <span\n style={{ display: mergedState.isVisible ? undefined : \"none\" }}\n data-formality-group={name}\n >\n {children}\n </span>\n </GroupContext.Provider>\n );\n}\n","// @formality-ui/react - UnusedFields Component\n// Renders fields declared in config but not explicitly rendered\n\nimport { type ReactNode, useMemo } from \"react\";\nimport { sortFieldsByOrder } from \"@formality-ui/core\";\nimport { useFormContext } from \"../context/FormContext\";\nimport { Field } from \"./Field\";\n\n/**\n * UnusedFields component props\n */\nexport interface UnusedFieldsProps {\n /** Custom render function for each unused field */\n children?: (field: { name: string; component: ReactNode }) => ReactNode;\n}\n\n/**\n * UnusedFields component - Renders config-driven fields\n *\n * Renders fields that are declared in the Form's config but have not\n * been explicitly rendered using <Field> components. This enables\n * config-driven forms where not all fields need to be declared in JSX.\n *\n * Fields are tracked via the Form's field registry. When a <Field>\n * component mounts, it registers itself. UnusedFields renders all\n * fields that haven't been registered.\n *\n * @example\n * ```tsx\n * // All fields from config rendered automatically\n * <Form config={config}>\n * <UnusedFields />\n * </Form>\n *\n * // Mix explicit and automatic fields\n * <Form config={config}>\n * <Field name=\"name\" /> {/* Explicit with custom props *\\/}\n * <Field name=\"email\" /> {/* Explicit with custom props *\\/}\n * <UnusedFields /> {/* Renders remaining fields *\\/}\n * </Form>\n *\n * // Custom wrapper for unused fields\n * <Form config={config}>\n * <UnusedFields>\n * {({ name, component }) => (\n * <div key={name} className=\"auto-field\">\n * {component}\n * </div>\n * )}\n * </UnusedFields>\n * </Form>\n * ```\n */\nexport function UnusedFields({ children }: UnusedFieldsProps): JSX.Element {\n const { unusedFields, config } = useFormContext();\n\n // Sort unused fields by order property (PRD Section 15)\n const sortedFields = useMemo(() => {\n return sortFieldsByOrder(unusedFields, config);\n }, [unusedFields, config]);\n\n if (children) {\n // Custom render function\n return (\n <>\n {sortedFields.map((name) =>\n children({\n name,\n // CRITICAL: shouldRegister={false} prevents infinite loop (PRD 5.5, 18.9)\n component: <Field key={name} name={name} shouldRegister={false} />,\n }),\n )}\n </>\n );\n }\n\n // Default render\n return (\n <>\n {sortedFields.map((name) => (\n // CRITICAL: shouldRegister={false} prevents infinite loop (PRD 5.5, 18.9)\n <Field key={name} name={name} shouldRegister={false} />\n ))}\n </>\n );\n}\n","// @formality-ui/react - useFormState Hook\n// Custom hook wrapping RHF's useWatch with proxy optimization\n// CRITICAL: This hook is designed for ISOLATED field subscriptions\n\nimport { useMemo } from \"react\";\nimport { useWatch, useFormContext as useRHFFormContext } from \"react-hook-form\";\nimport type { FieldValues } from \"react-hook-form\";\nimport { makeProxyState } from \"../utils/makeProxyState\";\nimport { useFormContext as useFormalityFormContext } from \"../context/FormContext\";\nimport type { CustomFieldState, IsolatedFormState } from \"../types\";\n\n/**\n * Options for useFormState hook\n */\nexport interface UseFormStateOptions {\n /**\n * Specific field name(s) to watch.\n * REQUIRED for performance - you must specify which fields you need.\n * Watching all fields defeats the purpose of isolation.\n */\n name: string | string[];\n}\n\n/**\n * Custom useFormState that provides ISOLATED field subscriptions\n *\n * CRITICAL PERFORMANCE REQUIREMENT:\n * You MUST specify which fields to watch via the `name` option.\n * This hook is designed to prevent the \"subscribe to everything\" anti-pattern.\n *\n * This hook provides:\n * - Proxy-wrapped field states to prevent unnecessary re-renders\n * - Record property access via lazy getter\n * - Integration with Formality's FormContext\n *\n * Performance Benefits:\n * - Only re-renders when specified fields change\n * - Expression evaluation only creates dependencies on used properties\n * - Field states can update independently without cross-field re-renders\n *\n * @example\n * ```tsx\n * function MyField() {\n * // Watch specific fields only\n * const formState = useFormState({ name: ['firstName', 'lastName'] });\n *\n * // Only re-renders when firstName or lastName change\n * const value = formState.fields.firstName?.value;\n *\n * // Access original record for expressions\n * const recordId = formState.record.id;\n * }\n * ```\n */\nexport function useFormState<TFieldValues extends FieldValues = FieldValues>(\n options: UseFormStateOptions,\n): IsolatedFormState {\n // Get RHF context\n const rhfContext = useRHFFormContext<TFieldValues>();\n\n // Get Formality context (may not be available if used outside Form)\n let formalityContext: ReturnType<\n typeof useFormalityFormContext<TFieldValues>\n > | null = null;\n try {\n formalityContext = useFormalityFormContext<TFieldValues>();\n } catch {\n // Used outside Form - formalityContext stays null\n }\n\n // Determine field names to track - MUST be explicitly specified\n const fieldNames = useMemo(() => {\n return Array.isArray(options.name) ? options.name : [options.name];\n }, [options.name]);\n\n // Watch ONLY specified field values via useWatch (isolated subscription)\n const watchedValues = useWatch({\n control: rhfContext.control,\n name: fieldNames as any,\n });\n\n // Build proxy-wrapped field states for watched fields ONLY\n // CRITICAL: We do NOT call getFieldState which would subscribe to form state\n const fields = useMemo(() => {\n const result: Record<string, CustomFieldState> = {};\n\n if (fieldNames.length === 0) {\n return result;\n }\n\n // Handle single field vs multiple fields\n const values =\n fieldNames.length === 1 ? [watchedValues] : (watchedValues as unknown[]);\n\n fieldNames.forEach((name, index) => {\n const value = values[index];\n\n // Create minimal proxy state with just the value\n // We intentionally do NOT access isTouched/isDirty/error from rhfFormState\n // as that would create subscriptions to the entire form state\n result[name] = makeProxyState({\n value,\n isTouched: false,\n isDirty: false,\n isValidating: false,\n error: undefined,\n invalid: false,\n });\n });\n\n return result;\n }, [fieldNames, watchedValues]);\n\n // Create result object with lazy record access\n const result = useMemo((): IsolatedFormState => {\n const base: IsolatedFormState = {\n fields,\n record: {}, // Will be overwritten by defineProperty\n // Provide minimal form-level state that doesn't require subscriptions\n isDirty: false,\n isTouched: false,\n isValid: true,\n isSubmitting: false,\n errors: {},\n touchedFields: {},\n dirtyFields: {},\n defaultValues: {},\n };\n\n // Add record property with lazy access\n Object.defineProperty(base, \"record\", {\n get: () => formalityContext?.record ?? {},\n enumerable: true,\n configurable: true,\n });\n\n return base;\n }, [fields, formalityContext?.record]);\n\n return result;\n}\n","// @formality-ui/react - Type Overlays\n//\n// Core (`@formality-ui/core`) is deliberately framework-agnostic: it cannot\n// import `react` or `react-hook-form`, so any field that is fundamentally a\n// framework construct is typed `unknown` there (InputConfig.component,\n// InputConfig.template, FieldConfig.rules, …). See PRD §1.3.2 / §3.2.\n//\n// This module overlays precise React / react-hook-form types on top of those\n// loose core types. React consumers import these (re-exported from the package\n// entry point) and get full type safety, while core stays reusable by future\n// Vue/Svelte adapters with zero changes.\n\nimport type { ComponentType } from \"react\";\nimport type {\n RegisterOptions,\n FieldValues,\n RefCallBack,\n UseFormStateReturn,\n} from \"react-hook-form\";\nimport type { InputConfig, FieldConfig } from \"@formality-ui/core\";\nimport type { InputTemplateProps, CustomFieldState } from \"./types\";\n\n/**\n * `InputConfig` as seen by React consumers.\n *\n * Narrows core's framework-agnostic `component: unknown` /\n * `template?: unknown` to real React component types. `TValue` is preserved so\n * `defaultValue` / `parser` / `formatter` can share a single value type.\n *\n * @example\n * ```tsx\n * import type { ReactInputConfig } from \"@formality-ui/react\";\n *\n * const textField = {\n * component: TextField,\n * defaultValue: \"\",\n * } satisfies ReactInputConfig<string>;\n * ```\n *\n * Prefer this over the core `InputConfig` type whenever you are writing React\n * code — it will give you a **compile error** if `component` is set to a\n * non-component (e.g. `component: 42` or `component: \"textField\"`).\n */\nexport interface ReactInputConfig<TValue = unknown> extends Omit<\n InputConfig<TValue>,\n \"component\" | \"template\"\n> {\n /** The React component to render for this input type. */\n component: ComponentType<any>;\n\n /** Optional template wrapper (overrides provider/form defaults). */\n template?: ComponentType<InputTemplateProps>;\n}\n\n/**\n * `FieldConfig` as seen by React consumers.\n *\n * Narrows core's framework-agnostic `rules?: Record<string, unknown>` to\n * react-hook-form's `RegisterOptions`, giving autocomplete and checking for\n * `required`, `min`, `max`, `pattern`, `validate`, `valueAsNumber`, `deps`, …\n *\n * The generic `V` defaults to `FieldValues`; pass your form's values type for\n * slightly tighter checking on path-based rules.\n */\nexport interface ReactFieldConfig<\n V extends FieldValues = FieldValues,\n> extends Omit<FieldConfig, \"rules\"> {\n /** react-hook-form register options forwarded to the field's Controller. */\n rules?: RegisterOptions<V>;\n}\n\n/**\n * Map of field name → {@link ReactFieldConfig}. Used by `<Form>`'s `config`\n * prop (via {@link ReactFormFieldsConfig}) so React consumers get RHF-typed\n * `rules` on every field.\n *\n * The keys are narrowed to `Extract<keyof V, string>`. When `V` is left at\n * its default (`FieldValues`) any string key is accepted — byte-for-byte\n * identical to before. When `V` is narrowed to a concrete field-values type\n * (e.g. via `<Form<ClientValues>>`), unknown `config` keys become a\n * **compile error**, catching typos like `ofice` at compile time (PRD §C.4 /\n * T2.1).\n *\n * @example\n * ```tsx\n * import type { ReactFormFieldsConfig } from \"@formality-ui/react\";\n * import type { FieldValues } from \"react-hook-form\";\n *\n * // Default — any string key accepted (non-breaking).\n * const a: ReactFormFieldsConfig<FieldValues> = { anything: { type: \"text\" } };\n *\n * // Narrowed — only known field names accepted.\n * type ClientValues = { name: string; email: string };\n * const b: ReactFormFieldsConfig<ClientValues> = {\n * name: { type: \"text\" },\n * email: { type: \"text\" },\n * };\n *\n * // @ts-expect-error — typo `ofice` is rejected.\n * const c: ReactFormFieldsConfig<ClientValues> = { ofice: { type: \"text\" } };\n * ```\n */\nexport type ReactFormFieldsConfig<V extends FieldValues = FieldValues> = Record<\n Extract<keyof V, string>,\n ReactFieldConfig<V>\n>;\n\n/**\n * Identity helper that lets consumers derive a union of their input-type keys.\n * Opt-in: wrap your provider inputs to get `keyof` checking on `Field` `type`\n * and `FieldConfig.type`.\n *\n * This is a PURE IDENTITY function — it returns `inputs` unchanged with zero\n * runtime effect, so bundlers (tsup/esbuild/rollup) tree-shake it to nothing.\n * It exists purely so consumers can write `type InputType = keyof typeof inputs`.\n *\n * The existing non-generic `Field` and `FieldConfig.type` / `FieldProps.type`\n * (which default to `type?: string`) are UNCHANGED — this helper is purely\n * additive and opt-in. End-to-end wiring of `InputType` into those types is a\n * follow-up (PRD §C.4 T2.2 step 3).\n *\n * @example\n * ```tsx\n * import { defineInputs } from \"@formality-ui/react\";\n *\n * const inputs = defineInputs({\n * textField: { component: TextField, defaultValue: \"\" },\n * switch: { component: Switch, defaultValue: false },\n * });\n * export type InputType = keyof typeof inputs; // \"textField\" | \"switch\"\n * ```\n */\nexport function defineInputs<T extends Record<string, ReactInputConfig>>(\n inputs: T,\n): T {\n return inputs;\n}\n\n/**\n * Props Formality injects onto every field component.\n *\n * `<Field>` renders your input component via React Hook Form's `<Controller>`.\n * At runtime Formality merges a `coreProps` bundle onto the component (name,\n * value, onChange, onBlur, and — as a React-special key — `ref`). The three\n * members below are the **injected-props contract**: `formState` always\n * reaches templates and render-prop children, and reaches plain components\n * that have opted into Formality state via `provideState` /\n * `passSubscriptions`; `state` (subscribed field state) and a top-level\n * `forwardRef` key are delivered at runtime by `<Field>` (see \"Runtime\n * delivery\" below).\n *\n * **Destructure before forwarding.** Component authors MUST destructure\n * `state`, `formState`, and `forwardRef` OUT of props before spreading the\n * rest onto the underlying DOM `<input>` — otherwise these non-DOM props leak\n * to the DOM and React warns. Recommended pattern:\n *\n * ```tsx\n * const TextField: ComponentType<FormalityFieldComponentProps<TextFieldProps>> =\n * ({ state, formState, forwardRef, ...domProps }) => (\n * <input ref={forwardRef} {...domProps} />\n * );\n * ```\n *\n * **Wiring `forwardRef` to the inner input.** `forwardRef` is RHF's\n * `RefCallBack` (a function). For a plain `<input>` use `ref={forwardRef}`.\n * For MUI v9 components that no longer accept a top-level `inputRef`, wire it\n * via slots: `slotProps={{ input: { ref: forwardRef } }}` (PRD §5.3.8).\n *\n * **Runtime delivery (important).** `<Field>` delivers RHF's ref as a regular,\n * top-level, enumerable prop named `forwardRef` — no `React.forwardRef` wrap\n * is required for a plain function component that destructures `forwardRef`\n * and wires it to the inner input (`ref={forwardRef}`). Consumers migrating\n * off the old React-special `ref` key: a `React.forwardRef`-wrapped component\n * should consume `props.forwardRef` (PRD §20.4), and under React 19\n * ref-as-prop use `forwardRef` directly. The type ships the intended contract\n * so consumers stop hand-rolling a lossy `WithFormality<P>`.\n *\n * @template P - the field component's own props (e.g. TextFieldProps). Defaults\n * to `unknown` so existing `ComponentType<any>` casts remain valid.\n */\nexport type FormalityFieldComponentProps<P = unknown> = P & {\n /** Subscribed/own field state when `provideState`/`passSubscriptions` is on. */\n state?: CustomFieldState | Record<string, CustomFieldState>;\n\n /** React Hook Form form state threaded from `<Controller>`. */\n formState?: UseFormStateReturn<FieldValues>;\n\n /** RHF ref callback (`RefCallBack`); wire to the inner input (see JSDoc). */\n forwardRef?: RefCallBack;\n};\n"]}
|