@schema-engine/forms-react 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +87 -2
  3. package/dist/chunk-5XCNXEJB.js +19 -0
  4. package/dist/chunk-5XCNXEJB.js.map +7 -0
  5. package/dist/chunk-6RI4LMM6.js +19 -0
  6. package/dist/chunk-6RI4LMM6.js.map +7 -0
  7. package/dist/chunk-7QNWPTT7.js +20 -0
  8. package/dist/chunk-7QNWPTT7.js.map +7 -0
  9. package/dist/chunk-7RUFT6EJ.js +39 -0
  10. package/dist/chunk-7RUFT6EJ.js.map +7 -0
  11. package/dist/chunk-AALIXTCD.js +56 -0
  12. package/dist/chunk-AALIXTCD.js.map +7 -0
  13. package/dist/chunk-CPJMN2IH.js +128 -0
  14. package/dist/chunk-CPJMN2IH.js.map +7 -0
  15. package/dist/chunk-DTJ64NZQ.js +142 -0
  16. package/dist/chunk-DTJ64NZQ.js.map +7 -0
  17. package/dist/chunk-EYDB6NR6.js +9 -0
  18. package/dist/chunk-EYDB6NR6.js.map +7 -0
  19. package/dist/chunk-GH2QO3WC.js +11 -0
  20. package/dist/chunk-GH2QO3WC.js.map +7 -0
  21. package/dist/chunk-H25SUEJE.js +8 -0
  22. package/dist/chunk-H25SUEJE.js.map +7 -0
  23. package/dist/chunk-HT43MPKW.js +0 -0
  24. package/dist/chunk-HT43MPKW.js.map +7 -0
  25. package/dist/chunk-IHX6VMAQ.js +0 -0
  26. package/dist/chunk-IHX6VMAQ.js.map +7 -0
  27. package/dist/chunk-ISDPSORR.js +265 -0
  28. package/dist/chunk-ISDPSORR.js.map +7 -0
  29. package/dist/chunk-IXRV3YCF.js +36 -0
  30. package/dist/chunk-IXRV3YCF.js.map +7 -0
  31. package/dist/chunk-K3LLWGXU.js +30 -0
  32. package/dist/chunk-K3LLWGXU.js.map +7 -0
  33. package/dist/chunk-K66J2V73.js +108 -0
  34. package/dist/chunk-K66J2V73.js.map +7 -0
  35. package/dist/chunk-KG6Q7MNI.js +51 -0
  36. package/dist/chunk-KG6Q7MNI.js.map +7 -0
  37. package/dist/chunk-MBN4WIAC.js +41 -0
  38. package/dist/chunk-MBN4WIAC.js.map +7 -0
  39. package/dist/chunk-NDFV5AQW.js +39 -0
  40. package/dist/chunk-NDFV5AQW.js.map +7 -0
  41. package/dist/chunk-QUZN42PL.js +128 -0
  42. package/dist/chunk-QUZN42PL.js.map +7 -0
  43. package/dist/chunk-SED35QJC.js +78 -0
  44. package/dist/chunk-SED35QJC.js.map +7 -0
  45. package/dist/chunk-ULKJHK3P.js +6 -0
  46. package/dist/chunk-ULKJHK3P.js.map +7 -0
  47. package/dist/chunk-USRF3EEE.js +122 -0
  48. package/dist/chunk-USRF3EEE.js.map +7 -0
  49. package/dist/chunk-WFRWVH4X.js +44 -0
  50. package/dist/chunk-WFRWVH4X.js.map +7 -0
  51. package/dist/chunk-WOTW7A2I.js +7 -0
  52. package/dist/chunk-WOTW7A2I.js.map +7 -0
  53. package/dist/chunk-WRJWSEL7.js +98 -0
  54. package/dist/chunk-WRJWSEL7.js.map +7 -0
  55. package/dist/chunk-XWHP2AGG.js +7 -0
  56. package/dist/chunk-XWHP2AGG.js.map +7 -0
  57. package/dist/chunk-ZWEYALBG.js +25 -0
  58. package/dist/chunk-ZWEYALBG.js.map +7 -0
  59. package/dist/components/form-debugger/form-debugger.css +374 -0
  60. package/dist/components/form-debugger/form-debugger.css.map +7 -0
  61. package/dist/components/form-debugger/form-debugger.d.ts +23 -0
  62. package/dist/components/form-debugger/form-debugger.js +17 -0
  63. package/dist/components/form-debugger/form-debugger.js.map +7 -0
  64. package/dist/components/form-debugger/index.css +374 -0
  65. package/dist/components/form-debugger/index.css.map +7 -0
  66. package/dist/components/form-debugger/index.d.ts +2 -0
  67. package/dist/components/form-debugger/index.js +17 -0
  68. package/dist/components/form-debugger/index.js.map +7 -0
  69. package/dist/components/form-engine-provider.d.ts +7 -0
  70. package/dist/components/form-engine-provider.js +7 -0
  71. package/dist/components/form-engine-provider.js.map +7 -0
  72. package/dist/components/form-provider.d.ts +23 -0
  73. package/dist/components/form-provider.js +13 -0
  74. package/dist/components/form-provider.js.map +7 -0
  75. package/dist/components/index.d.ts +4 -0
  76. package/dist/components/index.js +43 -0
  77. package/dist/components/index.js.map +7 -0
  78. package/dist/components/internals/element-error.d.ts +9 -0
  79. package/dist/components/internals/element-error.js +6 -0
  80. package/dist/components/internals/element-error.js.map +7 -0
  81. package/dist/components/internals/field-renderer.d.ts +26 -0
  82. package/dist/components/internals/field-renderer.js +24 -0
  83. package/dist/components/internals/field-renderer.js.map +7 -0
  84. package/dist/components/internals/form-elements.d.ts +20 -0
  85. package/dist/components/internals/form-elements.js +25 -0
  86. package/dist/components/internals/form-elements.js.map +7 -0
  87. package/dist/components/internals/form-renderer.d.ts +28 -0
  88. package/dist/components/internals/form-renderer.js +31 -0
  89. package/dist/components/internals/form-renderer.js.map +7 -0
  90. package/dist/components/internals/recipe-renderer.d.ts +10 -0
  91. package/dist/components/internals/recipe-renderer.js +17 -0
  92. package/dist/components/internals/recipe-renderer.js.map +7 -0
  93. package/dist/components/provider.d.ts +18 -0
  94. package/dist/components/provider.js +8 -0
  95. package/dist/components/provider.js.map +7 -0
  96. package/dist/contexts/field-constraint-context.d.ts +15 -0
  97. package/dist/contexts/field-constraint-context.js +6 -0
  98. package/dist/contexts/field-constraint-context.js.map +7 -0
  99. package/dist/contexts/index.d.ts +2 -0
  100. package/dist/contexts/index.js +6 -0
  101. package/dist/contexts/index.js.map +7 -0
  102. package/dist/contexts/view-context.d.ts +14 -0
  103. package/dist/contexts/view-context.js +16 -0
  104. package/dist/contexts/view-context.js.map +7 -0
  105. package/dist/global.css +8 -0
  106. package/dist/hooks/field-text.d.ts +6 -0
  107. package/dist/hooks/field-text.js +6 -0
  108. package/dist/hooks/field-text.js.map +7 -0
  109. package/dist/hooks/form-state/context.d.ts +27 -0
  110. package/dist/hooks/form-state/context.js +10 -0
  111. package/dist/hooks/form-state/context.js.map +7 -0
  112. package/dist/hooks/form-state/field-registry.d.ts +60 -0
  113. package/dist/hooks/form-state/field-registry.js +9 -0
  114. package/dist/hooks/form-state/field-registry.js.map +7 -0
  115. package/dist/hooks/form-state/index.d.ts +8 -0
  116. package/dist/hooks/form-state/index.js +27 -0
  117. package/dist/hooks/form-state/index.js.map +7 -0
  118. package/dist/hooks/form-state/native-control.d.ts +39 -0
  119. package/dist/hooks/form-state/native-control.js +17 -0
  120. package/dist/hooks/form-state/native-control.js.map +7 -0
  121. package/dist/hooks/form-state/types.d.ts +191 -0
  122. package/dist/hooks/form-state/types.js +0 -0
  123. package/dist/hooks/form-state/types.js.map +7 -0
  124. package/dist/hooks/form-state/use-field-array.d.ts +12 -0
  125. package/dist/hooks/form-state/use-field-array.js +7 -0
  126. package/dist/hooks/form-state/use-field-array.js.map +7 -0
  127. package/dist/hooks/form-state/use-form-context.d.ts +10 -0
  128. package/dist/hooks/form-state/use-form-context.js +7 -0
  129. package/dist/hooks/form-state/use-form-context.js.map +7 -0
  130. package/dist/hooks/form-state/use-form-field.d.ts +24 -0
  131. package/dist/hooks/form-state/use-form-field.js +11 -0
  132. package/dist/hooks/form-state/use-form-field.js.map +7 -0
  133. package/dist/hooks/form-state/use-watch.d.ts +12 -0
  134. package/dist/hooks/form-state/use-watch.js +7 -0
  135. package/dist/hooks/form-state/use-watch.js.map +7 -0
  136. package/dist/hooks/index.d.ts +7 -0
  137. package/dist/hooks/index.js +78 -0
  138. package/dist/hooks/index.js.map +7 -0
  139. package/dist/hooks/is-element-required.d.ts +5 -0
  140. package/dist/hooks/is-element-required.js +6 -0
  141. package/dist/hooks/is-element-required.js.map +7 -0
  142. package/dist/hooks/use-debounce.d.ts +14 -0
  143. package/dist/hooks/use-debounce.js +8 -0
  144. package/dist/hooks/use-debounce.js.map +7 -0
  145. package/dist/hooks/use-field.d.ts +44 -0
  146. package/dist/hooks/use-field.js +16 -0
  147. package/dist/hooks/use-field.js.map +7 -0
  148. package/dist/hooks/use-form-context.d.ts +63 -0
  149. package/dist/hooks/use-form-context.js +18 -0
  150. package/dist/hooks/use-form-context.js.map +7 -0
  151. package/dist/hooks/use-mobile.d.ts +9 -0
  152. package/dist/hooks/use-mobile.js +6 -0
  153. package/dist/hooks/use-mobile.js.map +7 -0
  154. package/dist/index.d.ts +2 -0
  155. package/dist/index.js +43 -0
  156. package/dist/index.js.map +7 -0
  157. package/dist/lib/logger.d.ts +2 -0
  158. package/dist/lib/object-identity.d.ts +6 -0
  159. package/dist/primitives.d.ts +28 -0
  160. package/dist/primitives.js +37 -0
  161. package/dist/primitives.js.map +7 -0
  162. package/package.json +139 -3
  163. package/skill/SKILL.md +79 -0
  164. package/skill/reference/forms-react-widgets.md +222 -0
  165. package/skill/reference/forms-react.md +92 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/hooks/form-state/use-form-context.ts"],
4
+ "sourcesContent": ["import { useMemo, useSyncExternalStore } from 'react';\nimport {\n\tissueText,\n\ttype FormIssueFormatter,\n\ttype FormStateIssue,\n\ttype FormStateSnapshot,\n\ttype FormSubmissionIssue,\n} from '@schema-engine/forms/state-container';\nimport { useFormStateContext, type FormStateContextValue } from './context';\nimport type { FormContextValue } from './types';\n\ntype FormStateKey = keyof FormContextValue['formState'];\n\ntype Texts = Record<string, { message?: string }>;\n\n/** The text of each error by path, made once for an errors map, since the map keeps its reference until an error changes. */\nfunction createTexts(formatIssue: FormIssueFormatter | undefined) {\n\tconst byErrors = new WeakMap<object, Texts>();\n\treturn (errors: FormStateSnapshot['errors']): Texts => {\n\t\tlet texts = byErrors.get(errors);\n\t\tif (!texts) {\n\t\t\ttexts = Object.fromEntries(\n\t\t\t\tObject.entries(errors).map(([path, error]) => {\n\t\t\t\t\tconst message = issueText(error, path, formatIssue);\n\t\t\t\t\treturn [path, message === undefined ? {} : { message }];\n\t\t\t\t}),\n\t\t\t);\n\t\t\tbyErrors.set(errors, texts);\n\t\t}\n\t\treturn texts;\n\t};\n}\n\n/**\n * Reads a form's state lazily: the keys a component reads are the keys\n * that re-render it.\n *\n * @remarks\n * Reading a key records it, and the store the component subscribes to counts a notification only when a\n * recorded key's value changed. A key read between the render and the subscription is checked when the\n * subscription starts, so no change is missed.\n */\nfunction createTrackedFormState(\n\t{ container, runtime }: Pick<FormStateContextValue, 'container' | 'runtime'>,\n\tformatIssue: FormIssueFormatter | undefined,\n) {\n\tconst seen = new Map<FormStateKey, unknown>();\n\tconst texts = createTexts(formatIssue);\n\tlet version = 0;\n\tconst read = (key: FormStateKey): unknown => {\n\t\tswitch (key) {\n\t\t\tcase 'errors':\n\t\t\t\treturn container.getSnapshot().errors;\n\t\t\tcase 'isValid':\n\t\t\t\treturn container.getSnapshot().isValid;\n\t\t\tcase 'submission':\n\t\t\t\treturn runtime.getSnapshot().submission;\n\t\t}\n\t};\n\tconst track = <T>(key: FormStateKey, value: T): T => {\n\t\tif (!seen.has(key)) seen.set(key, read(key));\n\t\treturn value;\n\t};\n\n\tconst formState: FormContextValue['formState'] = {\n\t\tget errors() {\n\t\t\treturn track('errors', texts(container.getSnapshot().errors));\n\t\t},\n\t\tget isValid() {\n\t\t\treturn track('isValid', container.getSnapshot().isValid);\n\t\t},\n\t\tget submission() {\n\t\t\treturn track('submission', runtime.getSnapshot().submission);\n\t\t},\n\t};\n\n\tconst notify = (listener: () => void) => {\n\t\tlet changed = false;\n\t\tseen.forEach((previous, key) => {\n\t\t\tconst current = read(key);\n\t\t\tif (!Object.is(current, previous)) {\n\t\t\t\tseen.set(key, current);\n\t\t\t\tchanged = true;\n\t\t\t}\n\t\t});\n\t\tif (changed) {\n\t\t\tversion += 1;\n\t\t\tlistener();\n\t\t}\n\t};\n\n\treturn {\n\t\tformState,\n\t\tsubscribe: (listener: () => void) => {\n\t\t\tconst onChange = () => notify(listener);\n\t\t\tconst stopContainer = container.subscribe(onChange);\n\t\t\tconst stopRuntime = runtime.subscribe(onChange);\n\t\t\tonChange();\n\t\t\treturn () => {\n\t\t\t\tstopContainer();\n\t\t\t\tstopRuntime();\n\t\t\t};\n\t\t},\n\t\tgetSnapshot: () => version,\n\t};\n}\n\n/**\n * The commands over the form and its state, read lazily.\n *\n * @remarks\n * `formState` re-renders a component only for the keys it reads: one that reads `submission` does not\n * render while the user types, and reading `isValid` costs nothing, since it reports the errors recorded\n * and never validates. The returned object keeps its identity while the form's formatter does.\n */\nexport function useFormContext(): FormContextValue {\n\tconst { container, formatIssue, fields, runtime } = useFormStateContext();\n\tconst tracked = useMemo(\n\t\t() => createTrackedFormState({ container, runtime }, formatIssue),\n\t\t[container, runtime, formatIssue],\n\t);\n\tuseSyncExternalStore(tracked.subscribe, tracked.getSnapshot, tracked.getSnapshot);\n\n\treturn useMemo(\n\t\t() => ({\n\t\t\tgetValues: () => container.getSnapshot().values,\n\t\t\tsetValue: (name, value) => container.setValue(name, value),\n\t\t\tvalidate: (name) => container.validate(typeof name === 'string' ? [name] : name),\n\t\t\treset: (values) => container.reset(values),\n\t\t\tsetFocus: (name) => fields.focus(name),\n\t\t\tformatIssue: (issue: FormStateIssue | FormSubmissionIssue, { path }) => issueText(issue, path, formatIssue),\n\t\t\tclearSubmission: () => runtime.clearSubmission(),\n\t\t\tformState: tracked.formState,\n\t\t}),\n\t\t[container, fields, runtime, formatIssue, tracked],\n\t);\n}\n"],
5
+ "mappings": ";;;;;AAAA,SAAS,SAAS,4BAA4B;AAC9C;AAAA,EACC;AAAA,OAKM;AASP,SAAS,YAAY,aAA6C;AACjE,QAAM,WAAW,oBAAI,QAAuB;AAC5C,SAAO,CAAC,WAA+C;AACtD,QAAI,QAAQ,SAAS,IAAI,MAAM;AAC/B,QAAI,CAAC,OAAO;AACX,cAAQ,OAAO;AAAA,QACd,OAAO,QAAQ,MAAM,EAAE,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM;AAC7C,gBAAM,UAAU,UAAU,OAAO,MAAM,WAAW;AAClD,iBAAO,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
+ useContainerSelector
9
+ } from "./chunk-ZWEYALBG.js";
10
+ import {
11
+ ElementError
12
+ } from "./chunk-5XCNXEJB.js";
13
+
14
+ // src/components/internals/field-renderer.tsx
15
+ import { applyFieldOverlay, isNormalizedElementConfig } from "@schema-engine/forms";
16
+ import { selectFieldState } from "@schema-engine/forms/state-container";
17
+ import { jsx } from "react/jsx-runtime";
18
+ function FormElement({ config, name, id, instanceId, className, style }) {
19
+ const { engine } = useFormEngine();
20
+ const elementType = config.$type;
21
+ if (!isNormalizedElementConfig(config)) {
22
+ throw new Error(`FormElement config must be normalized before render (${elementType}).`);
23
+ }
24
+ const fieldPath = name ?? config.name;
25
+ const state = useContainerSelector((snapshot) => selectFieldState(snapshot, fieldPath));
26
+ const disabled = "disabled" in config && config.disabled === true || state.disabled;
27
+ if (state.hidden) {
28
+ return null;
29
+ }
30
+ const { $type } = config;
31
+ const elementRegistration = engine.getElement($type);
32
+ if (!elementRegistration) {
33
+ return /* @__PURE__ */ jsx(
34
+ ElementError,
35
+ {
36
+ title: "Component not found",
37
+ message: `The component type "${$type}" is not registered in the form engine.`,
38
+ componentType: $type,
39
+ className,
40
+ style
41
+ }
42
+ );
43
+ }
44
+ const Component = elementRegistration.render;
45
+ const enhancedConfig = applyFieldOverlay({ ...config, disabled }, { name, id, instanceId });
46
+ return /* @__PURE__ */ jsx(FieldHostContext.Provider, { value: { appearance: config.appearance, className: config.className }, children: /* @__PURE__ */ jsx(Component, { ...enhancedConfig }) });
47
+ }
48
+
49
+ export {
50
+ FormElement
51
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/components/internals/field-renderer.tsx"],
4
+ "sourcesContent": ["import type React from 'react';\nimport { useFormEngine } from '@/hooks';\nimport { useContainerSelector } from '@/hooks/form-state/context';\nimport { applyFieldOverlay, type NormalizedElementConfig, isNormalizedElementConfig } from '@schema-engine/forms';\nimport { selectFieldState } from '@schema-engine/forms/state-container';\nimport { FieldHostContext } from '@/contexts/field-constraint-context';\nimport { ElementError } from './element-error';\n\nexport interface FormElementProps {\n\t/**\n\t * Element from a `NormalizedFormConfig` or `engine.validateElement`.\n\t * Authoring JSON is not accepted.\n\t */\n\tconfig: NormalizedElementConfig;\n\t/** Render-time field path. The frozen config is not cloned. */\n\tname?: string;\n\t/** Render-time HTML id. Prefer a stable instance id, not an array index. */\n\tid?: string;\n\t/** Stable array-item identity forwarded to nested containers. */\n\tinstanceId?: string;\n\tclassName?: string;\n\tstyle?: React.CSSProperties;\n}\n\n/**\n * Renders a registered element. Config must already be normalized.\n *\n * @remarks\n * Whether the element is shown or disabled is the container's: `selectFieldState` says it, from the one ordered\n * evaluation of the form's constraints, with the constraints of the containers around the element folded in.\n * A field that takes no part is not rendered.\n */\nexport function FormElement({ config, name, id, instanceId, className, style }: FormElementProps) {\n\tconst { engine } = useFormEngine();\n\tconst elementType = config.$type;\n\tif (!isNormalizedElementConfig(config)) {\n\t\tthrow new Error(`FormElement config must be normalized before render (${elementType}).`);\n\t}\n\tconst fieldPath = name ?? config.name;\n\tconst state = useContainerSelector((snapshot) => selectFieldState(snapshot, fieldPath));\n\tconst disabled = ('disabled' in config && config.disabled === true) || state.disabled;\n\n\tif (state.hidden) {\n\t\treturn null;\n\t}\n\n\tconst { $type } = config;\n\n\tconst elementRegistration = engine.getElement($type);\n\n\tif (!elementRegistration) {\n\t\treturn (\n\t\t\t<ElementError\n\t\t\t\ttitle=\"Component not found\"\n\t\t\t\tmessage={`The component type \"${$type}\" is not registered in the form engine.`}\n\t\t\t\tcomponentType={$type}\n\t\t\t\tclassName={className}\n\t\t\t\tstyle={style}\n\t\t\t/>\n\t\t);\n\t}\n\n\tconst Component = elementRegistration.render as React.ComponentType<Record<string, unknown>>;\n\n\tconst enhancedConfig = applyFieldOverlay({ ...config, disabled }, { name, id, instanceId });\n\n\treturn (\n\t\t<FieldHostContext.Provider value={{ appearance: config.appearance, className: config.className }}>\n\t\t\t<Component {...enhancedConfig} />\n\t\t</FieldHostContext.Provider>\n\t);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;AAGA,SAAS,mBAAiD,iCAAiC;AAC3F,SAAS,wBAAwB;AAgD9B;AApBI,SAAS,YAAY,EAAE,QAAQ,MAAM,IAAI,YAAY,WAAW,MAAM,GAAqB;AACjG,QAAM,EAAE,OAAO,IAAI,cAAc;AACjC,QAAM,cAAc,OAAO;AAC3B,MAAI,CAAC,0BAA0B,MAAM,GAAG;AACvC,UAAM,IAAI,MAAM,wDAAwD,WAAW,IAAI;AAAA,EACxF;AACA,QAAM,YAAY,QAAQ,OAAO;AACjC,QAAM,QAAQ,qBAAqB,CAAC,aAAa,iBAAiB,UAAU,SAAS,CAAC;AACtF,QAAM,WAAY,cAAc,UAAU,OAAO,aAAa,QAAS,MAAM;AAE7E,MAAI,MAAM,QAAQ;AACjB,WAAO;AAAA,EACR;AAEA,QAAM,EAAE,MAAM,IAAI;AAElB,QAAM,sBAAsB,OAAO,WAAW,KAAK;AAEnD,MAAI,CAAC,qBAAqB;AACzB,WACC;AAAA,MAAC;AAAA;AAAA,QACA,OAAM;AAAA,QACN,SAAS,uBAAuB,KAAK;AAAA,QACrC,eAAe;AAAA,QACf;AAAA,QACA;AAAA;AAAA,IACD;AAAA,EAEF;AAEA,QAAM,YAAY,oBAAoB;AAEtC,QAAM,iBAAiB,kBAAkB,EAAE,GAAG,QAAQ,SAAS,GAAG,EAAE,MAAM,IAAI,WAAW,CAAC;AAE1F,SACC,oBAAC,iBAAiB,UAAjB,EAA0B,OAAO,EAAE,YAAY,OAAO,YAAY,WAAW,OAAO,UAAU,GAC9F,8BAAC,aAAW,GAAG,gBAAgB,GAChC;AAEF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,41 @@
1
+ import {
2
+ useContainerSelector,
3
+ useFormStateContext
4
+ } from "./chunk-ZWEYALBG.js";
5
+
6
+ // src/hooks/form-state/use-field-array.ts
7
+ import { useEffect, useMemo, useRef } from "react";
8
+ import { toFieldArrayValue } from "@schema-engine/forms/state-container";
9
+ function useFieldArray(name) {
10
+ const { container, fields } = useFormStateContext();
11
+ const rowIds = useContainerSelector(
12
+ (snapshot) => Object.hasOwn(snapshot.rowIds, name) ? snapshot.rowIds[name] : void 0
13
+ );
14
+ const commands = container.fieldArray(name);
15
+ const value = toFieldArrayValue(rowIds, commands);
16
+ const addedRow = useRef(void 0);
17
+ useEffect(() => {
18
+ if (addedRow.current === void 0) return;
19
+ fields.focusWithin(addedRow.current);
20
+ addedRow.current = void 0;
21
+ }, [rowIds, fields]);
22
+ return useMemo(() => {
23
+ const currentRowIds = () => container.getSnapshot().rowIds[name];
24
+ const adding = (command, firstAdded) => (...args) => {
25
+ const before = currentRowIds();
26
+ const index = firstAdded(...args);
27
+ command(...args);
28
+ if (currentRowIds() !== before) addedRow.current = `${name}.${index}`;
29
+ };
30
+ return {
31
+ ...value,
32
+ append: adding(commands.append, () => currentRowIds()?.length ?? 0),
33
+ prepend: adding(commands.prepend, () => 0),
34
+ insert: adding(commands.insert, (index) => index)
35
+ };
36
+ }, [value, commands, container, name]);
37
+ }
38
+
39
+ export {
40
+ useFieldArray
41
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/hooks/form-state/use-field-array.ts"],
4
+ "sourcesContent": ["import { useEffect, useMemo, useRef } from 'react';\nimport { toFieldArrayValue, type FieldArrayValue } from '@schema-engine/forms/state-container';\nimport { useContainerSelector, useFormStateContext } from './context';\n\n/**\n * The rows of the array at `name` and the commands that change them.\n *\n * @remarks\n * Rows are the container's, so a row keeps its id, errors and touched state through every operation (dirty is\n * the comparison with the defaults, index by index), and a falsy row (`''`, `0`, `false`) is a row. An operation\n * that adds rows (`append`, `prepend`, `insert`) focuses the first control of the first row it added, once that\n * row has rendered; an operation that changes no row focuses nothing. The same object comes back until the rows\n * change.\n */\nexport function useFieldArray(name: string): FieldArrayValue {\n\tconst { container, fields } = useFormStateContext();\n\tconst rowIds = useContainerSelector((snapshot) =>\n\t\tObject.hasOwn(snapshot.rowIds, name) ? snapshot.rowIds[name] : undefined,\n\t);\n\tconst commands = container.fieldArray(name);\n\tconst value = toFieldArrayValue(rowIds, commands);\n\tconst addedRow = useRef<string | undefined>(undefined);\n\n\tuseEffect(() => {\n\t\tif (addedRow.current === undefined) return;\n\t\tfields.focusWithin(addedRow.current);\n\t\taddedRow.current = undefined;\n\t}, [rowIds, fields]);\n\n\treturn useMemo(() => {\n\t\tconst currentRowIds = () => container.getSnapshot().rowIds[name];\n\t\tconst adding =\n\t\t\t<TArgs extends unknown[]>(command: (...args: TArgs) => void, firstAdded: (...args: TArgs) => number) =>\n\t\t\t(...args: TArgs) => {\n\t\t\t\tconst before = currentRowIds();\n\t\t\t\tconst index = firstAdded(...args);\n\t\t\t\tcommand(...args);\n\t\t\t\tif (currentRowIds() !== before) addedRow.current = `${name}.${index}`;\n\t\t\t};\n\t\treturn {\n\t\t\t...value,\n\t\t\tappend: adding(commands.append, () => currentRowIds()?.length ?? 0),\n\t\t\tprepend: adding(commands.prepend, () => 0),\n\t\t\tinsert: adding(commands.insert, (index) => index),\n\t\t};\n\t}, [value, commands, container, name]);\n}\n"],
5
+ "mappings": ";;;;;;AAAA,SAAS,WAAW,SAAS,cAAc;AAC3C,SAAS,yBAA+C;AAajD,SAAS,cAAc,MAA+B;AAC5D,QAAM,EAAE,WAAW,OAAO,IAAI,oBAAoB;AAClD,QAAM,SAAS;AAAA,IAAqB,CAAC,aACpC,OAAO,OAAO,SAAS,QAAQ,IAAI,IAAI,SAAS,OAAO,IAAI,IAAI;AAAA,EAChE;AACA,QAAM,WAAW,UAAU,WAAW,IAAI;AAC1C,QAAM,QAAQ,kBAAkB,QAAQ,QAAQ;AAChD,QAAM,WAAW,OAA2B,MAAS;AAErD,YAAU,MAAM;AACf,QAAI,SAAS,YAAY,OAAW;AACpC,WAAO,YAAY,SAAS,OAAO;AACnC,aAAS,UAAU;AAAA,EACpB,GAAG,CAAC,QAAQ,MAAM,CAAC;AAEnB,SAAO,QAAQ,MAAM;AACpB,UAAM,gBAAgB,MAAM,UAAU,YAAY,EAAE,OAAO,IAAI;AAC/D,UAAM,SACL,CAA0B,SAAmC,eAC7D,IAAI,SAAgB;AACnB,YAAM,SAAS,cAAc;AAC7B,YAAM,QAAQ,WAAW,GAAG,IAAI;AAChC,cAAQ,GAAG,IAAI;AACf,UAAI,cAAc,MAAM,OAAQ,UAAS,UAAU,GAAG,IAAI,IAAI,KAAK;AAAA,IACpE;AACD,WAAO;AAAA,MACN,GAAG;AAAA,MACH,QAAQ,OAAO,SAAS,QAAQ,MAAM,cAAc,GAAG,UAAU,CAAC;AAAA,MAClE,SAAS,OAAO,SAAS,SAAS,MAAM,CAAC;AAAA,MACzC,QAAQ,OAAO,SAAS,QAAQ,CAAC,UAAU,KAAK;AAAA,IACjD;AAAA,EACD,GAAG,CAAC,OAAO,UAAU,WAAW,IAAI,CAAC;AACtC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,39 @@
1
+ import {
2
+ useFormStateContext
3
+ } from "./chunk-ZWEYALBG.js";
4
+
5
+ // src/hooks/form-state/use-watch.ts
6
+ import { useMemo, useSyncExternalStore } from "react";
7
+ import { selectValue } from "@schema-engine/forms/state-container";
8
+ var isPath = (item) => typeof item === "string";
9
+ function parseTarget(key) {
10
+ const parsed = JSON.parse(key);
11
+ if (isPath(parsed)) return parsed;
12
+ return Array.isArray(parsed) && parsed.every(isPath) ? parsed : void 0;
13
+ }
14
+ function createWatchStore(container, target) {
15
+ let last = [];
16
+ const read = (snapshot) => {
17
+ if (target === void 0) return snapshot.values;
18
+ if (isPath(target)) return selectValue(snapshot, target);
19
+ const next = target.map((path) => selectValue(snapshot, path));
20
+ if (next.length === last.length && next.every((value, index) => Object.is(value, last[index]))) return last;
21
+ last = next;
22
+ return next;
23
+ };
24
+ return {
25
+ subscribe: (listener) => container.subscribe(listener),
26
+ getSnapshot: () => read(container.getSnapshot()),
27
+ getServerSnapshot: () => read(container.getServerSnapshot())
28
+ };
29
+ }
30
+ function useWatch(target) {
31
+ const { container } = useFormStateContext();
32
+ const key = JSON.stringify(target ?? null);
33
+ const store = useMemo(() => createWatchStore(container, parseTarget(key)), [container, key]);
34
+ return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
35
+ }
36
+
37
+ export {
38
+ useWatch
39
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/hooks/form-state/use-watch.ts"],
4
+ "sourcesContent": ["import { useMemo, useSyncExternalStore } from 'react';\nimport { selectValue, type FormStateContainer, type FormStateSnapshot } from '@schema-engine/forms/state-container';\nimport { useFormStateContext } from './context';\nimport type { FormValues } from './types';\n\ntype Target = string | readonly string[] | undefined;\n\nconst isPath = (item: unknown): item is string => typeof item === 'string';\n\n/** The target a key stands for: the key is what keeps a store alive while a caller passes a new list of the same paths. */\nfunction parseTarget(key: string): Target {\n\tconst parsed: unknown = JSON.parse(key);\n\tif (isPath(parsed)) return parsed;\n\treturn Array.isArray(parsed) && parsed.every(isPath) ? parsed : undefined;\n}\n\n/**\n * The store of one `useWatch` call: what is watched, as the same object while it did not change.\n *\n * @remarks\n * Kept per call, so two components never share or overwrite a list, and a render never builds a new one for\n * unchanged values, which `useSyncExternalStore` would take for a change.\n */\nfunction createWatchStore(container: FormStateContainer, target: Target) {\n\tlet last: readonly unknown[] = [];\n\tconst read = (snapshot: FormStateSnapshot): unknown => {\n\t\tif (target === undefined) return snapshot.values;\n\t\tif (isPath(target)) return selectValue(snapshot, target);\n\t\tconst next = target.map((path) => selectValue(snapshot, path));\n\t\tif (next.length === last.length && next.every((value, index) => Object.is(value, last[index]))) return last;\n\t\tlast = next;\n\t\treturn next;\n\t};\n\treturn {\n\t\tsubscribe: (listener: () => void) => container.subscribe(listener),\n\t\tgetSnapshot: () => read(container.getSnapshot()),\n\t\tgetServerSnapshot: () => read(container.getServerSnapshot()),\n\t};\n}\n\n/**\n * Watches the form's values and re-renders when what it watches changes.\n *\n * @remarks\n * With no argument it is the whole value tree, the same object while no value changed. With a path it is the\n * value there, `unknown` as the container holds it, which the caller narrows. With a list it is the values at\n * those paths, in the order given, the same array while none changed.\n */\nexport function useWatch(): FormValues;\nexport function useWatch(path: string): unknown;\nexport function useWatch(paths: readonly string[]): readonly unknown[];\nexport function useWatch(target?: string | readonly string[]): unknown {\n\tconst { container } = useFormStateContext();\n\tconst key = JSON.stringify(target ?? null);\n\tconst store = useMemo(() => createWatchStore(container, parseTarget(key)), [container, key]);\n\treturn useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);\n}\n"],
5
+ "mappings": ";;;;;AAAA,SAAS,SAAS,4BAA4B;AAC9C,SAAS,mBAAoE;AAM7E,IAAM,SAAS,CAAC,SAAkC,OAAO,SAAS;AAGlE,SAAS,YAAY,KAAqB;AACzC,QAAM,SAAkB,KAAK,MAAM,GAAG;AACtC,MAAI,OAAO,MAAM,EAAG,QAAO;AAC3B,SAAO,MAAM,QAAQ,MAAM,KAAK,OAAO,MAAM,MAAM,IAAI,SAAS;AACjE;AASA,SAAS,iBAAiB,WAA+B,QAAgB;AACxE,MAAI,OAA2B,CAAC;AAChC,QAAM,OAAO,CAAC,aAAyC;AACtD,QAAI,WAAW,OAAW,QAAO,SAAS;AAC1C,QAAI,OAAO,MAAM,EAAG,QAAO,YAAY,UAAU,MAAM;AACvD,UAAM,OAAO,OAAO,IAAI,CAAC,SAAS,YAAY,UAAU,IAAI,CAAC;AAC7D,QAAI,KAAK,WAAW,KAAK,UAAU,KAAK,MAAM,CAAC,OAAO,UAAU,OAAO,GAAG,OAAO,KAAK,KAAK,CAAC,CAAC,EAAG,QAAO;AACvG,WAAO;AACP,WAAO;AAAA,EACR;AACA,SAAO;AAAA,IACN,WAAW,CAAC,aAAyB,UAAU,UAAU,QAAQ;AAAA,IACjE,aAAa,MAAM,KAAK,UAAU,YAAY,CAAC;AAAA,IAC/C,mBAAmB,MAAM,KAAK,UAAU,kBAAkB,CAAC;AAAA,EAC5D;AACD;AAaO,SAAS,SAAS,QAA8C;AACtE,QAAM,EAAE,UAAU,IAAI,oBAAoB;AAC1C,QAAM,MAAM,KAAK,UAAU,UAAU,IAAI;AACzC,QAAM,QAAQ,QAAQ,MAAM,iBAAiB,WAAW,YAAY,GAAG,CAAC,GAAG,CAAC,WAAW,GAAG,CAAC;AAC3F,SAAO,qBAAqB,MAAM,WAAW,MAAM,aAAa,MAAM,iBAAiB;AACxF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,128 @@
1
+ import {
2
+ RecipeRenderer
3
+ } from "./chunk-SED35QJC.js";
4
+ import {
5
+ FormElements
6
+ } from "./chunk-K3LLWGXU.js";
7
+ import {
8
+ FormEngineProvider
9
+ } from "./chunk-6RI4LMM6.js";
10
+ import {
11
+ FormProvider
12
+ } from "./chunk-WRJWSEL7.js";
13
+ import {
14
+ useFormInstanceActions,
15
+ useOptionalFormEngine
16
+ } from "./chunk-AALIXTCD.js";
17
+
18
+ // src/components/internals/form-renderer.tsx
19
+ import { GRID_CLASS, getAppearanceAttributes, getGridVariables } from "@schema-engine/layout";
20
+ import { useMemo } from "react";
21
+ import {
22
+ isNormalizedFormConfig,
23
+ getRenderableSteps,
24
+ assertFormEngine,
25
+ stepGrid
26
+ } from "@schema-engine/forms";
27
+ import { getViewRecipe } from "@schema-engine/forms/recipes";
28
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
29
+ function LayoutThemeStyle({ themeId, css }) {
30
+ return /* @__PURE__ */ jsx("style", { href: `se-layout-theme-${themeId}`, precedence: "se-layout-theme", "data-se-theme-css": themeId, children: css });
31
+ }
32
+ function StepFields({
33
+ step,
34
+ config,
35
+ layout
36
+ }) {
37
+ return /* @__PURE__ */ jsx(
38
+ "div",
39
+ {
40
+ className: `se-form-step ${step.className ?? ""}`.trim(),
41
+ "data-se-step": step.id,
42
+ style: step.style,
43
+ ...getAppearanceAttributes(step.appearance),
44
+ children: step.elements.length > 0 && /* @__PURE__ */ jsx(
45
+ "div",
46
+ {
47
+ className: `se-form-grid ${GRID_CLASS}`,
48
+ "data-se-theme": layout.id,
49
+ style: getGridVariables(stepGrid(config, step), layout.grid, step.elements),
50
+ children: /* @__PURE__ */ jsx(FormElements, { elements: step.elements })
51
+ }
52
+ )
53
+ }
54
+ );
55
+ }
56
+ function FormElementsRenderer({
57
+ config,
58
+ layout,
59
+ children
60
+ }) {
61
+ const { current } = useFormInstanceActions();
62
+ const engineContext = useOptionalFormEngine();
63
+ const recipe = engineContext ? getViewRecipe(engineContext.engine, config) : void 0;
64
+ const steps = getRenderableSteps(config, current);
65
+ if (steps.length === 0) return null;
66
+ return /* @__PURE__ */ jsx(
67
+ RecipeRenderer,
68
+ {
69
+ config,
70
+ recipe,
71
+ renderFields: () => /* @__PURE__ */ jsx(Fragment, { children: steps.map((step) => /* @__PURE__ */ jsx(StepFields, { step, config, layout }, step.id)) }),
72
+ children
73
+ }
74
+ );
75
+ }
76
+ function FormRendererInner({
77
+ config,
78
+ defaultValues,
79
+ onSubmit,
80
+ onChange,
81
+ onAction,
82
+ onActionResults,
83
+ navigate,
84
+ formatIssue,
85
+ className = "",
86
+ style,
87
+ layout,
88
+ children
89
+ }) {
90
+ return /* @__PURE__ */ jsx(
91
+ FormProvider,
92
+ {
93
+ config,
94
+ defaultValues,
95
+ onSubmit,
96
+ onChange,
97
+ onAction,
98
+ onActionResults,
99
+ navigate,
100
+ formatIssue,
101
+ children: /* @__PURE__ */ jsxs("div", { className: `se-form ${className}`.trim(), style, children: [
102
+ /* @__PURE__ */ jsx(LayoutThemeStyle, { themeId: layout.id, css: layout.css }),
103
+ /* @__PURE__ */ jsx(FormElementsRenderer, { config, layout, children })
104
+ ] })
105
+ }
106
+ );
107
+ }
108
+ function normalize(engine, config) {
109
+ if (isNormalizedFormConfig(config)) return engine.validateForm(config);
110
+ return engine.validateForm(config);
111
+ }
112
+ function FormRenderer({ engine, ...props }) {
113
+ const inheritedEngine = useOptionalFormEngine();
114
+ const resolvedEngine = engine ?? inheritedEngine?.engine;
115
+ const { config, layout } = useMemo(() => {
116
+ assertFormEngine(resolvedEngine, props.config);
117
+ return { config: normalize(resolvedEngine, props.config), layout: resolvedEngine.getLayout() };
118
+ }, [props.config, resolvedEngine]);
119
+ const innerProps = { ...props, config, layout };
120
+ if (!resolvedEngine) {
121
+ return /* @__PURE__ */ jsx(FormRendererInner, { ...innerProps });
122
+ }
123
+ return /* @__PURE__ */ jsx(FormEngineProvider, { engine: resolvedEngine, children: /* @__PURE__ */ jsx(FormRendererInner, { ...innerProps }) });
124
+ }
125
+
126
+ export {
127
+ FormRenderer
128
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/components/internals/form-renderer.tsx"],
4
+ "sourcesContent": ["/**\n * Form grid CSS variables and alignment properties.\n *\n * @remarks\n * Variable emission is shared with the Radiant renderer\n * (`@schema-engine/layout`); the responsive behavior lives in\n * the theme stylesheet the engine generates and the renderer emits inline.\n */\nimport { GRID_CLASS, getAppearanceAttributes, getGridVariables, type LayoutTheme } from '@schema-engine/layout';\nimport type React from 'react';\nimport { useMemo } from 'react';\nimport { FormProvider } from '../form-provider';\nimport type { FormProviderProps } from '../../hooks/form-state/types';\nimport { FormElements } from './form-elements';\nimport { useFormInstanceActions, useOptionalFormEngine } from '@/hooks/use-form-context';\nimport { FormEngineProvider } from '../form-engine-provider';\nimport {\n\ttype EngineOutputMaps,\n\ttype FormEngineRuntime as FormEngine,\n\ttype FormValues,\n\ttype NormalizedFormConfig,\n\tisNormalizedFormConfig,\n\ttype FormConfig,\n\tgetRenderableSteps,\n\tassertFormEngine,\n\tstepGrid,\n} from '@schema-engine/forms';\nimport { getViewRecipe } from '@schema-engine/forms/recipes';\nimport { RecipeRenderer } from './recipe-renderer';\n\nfunction LayoutThemeStyle({ themeId, css }: { themeId: string; css: string }) {\n\treturn (\n\t\t<style href={`se-layout-theme-${themeId}`} precedence=\"se-layout-theme\" data-se-theme-css={themeId}>\n\t\t\t{css}\n\t\t</style>\n\t);\n}\n\nfunction StepFields({\n\tstep,\n\tconfig,\n\tlayout,\n}: {\n\tstep: NormalizedFormConfig['steps'][number];\n\tconfig: NormalizedFormConfig;\n\tlayout: LayoutTheme;\n}) {\n\treturn (\n\t\t<div\n\t\t\tclassName={`se-form-step ${step.className ?? ''}`.trim()}\n\t\t\tdata-se-step={step.id}\n\t\t\tstyle={step.style}\n\t\t\t{...getAppearanceAttributes(step.appearance)}\n\t\t>\n\t\t\t{step.elements.length > 0 && (\n\t\t\t\t<div\n\t\t\t\t\tclassName={`se-form-grid ${GRID_CLASS}`}\n\t\t\t\t\tdata-se-theme={layout.id}\n\t\t\t\t\tstyle={getGridVariables(stepGrid(config, step), layout.grid, step.elements)}\n\t\t\t\t>\n\t\t\t\t\t<FormElements elements={step.elements} />\n\t\t\t\t</div>\n\t\t\t)}\n\t\t</div>\n\t);\n}\n\nfunction FormElementsRenderer<\n\tTElements extends Record<string, unknown>,\n\tTRecipes extends Record<string, unknown>,\n\tTActions extends Record<string, unknown>,\n\tTOutputs extends EngineOutputMaps,\n>({\n\tconfig,\n\tlayout,\n\tchildren,\n}: {\n\tconfig: NormalizedFormConfig<TOutputs['elements'], TOutputs['recipes'], TOutputs['actions']>;\n\tlayout: LayoutTheme;\n\tchildren?: React.ReactNode;\n}) {\n\tconst { current } = useFormInstanceActions();\n\tconst engineContext = useOptionalFormEngine<TElements, TRecipes, TActions, TOutputs>();\n\tconst recipe = engineContext ? getViewRecipe(engineContext.engine, config) : undefined;\n\tconst steps = getRenderableSteps(config, current);\n\n\tif (steps.length === 0) return null;\n\n\treturn (\n\t\t<RecipeRenderer\n\t\t\tconfig={config}\n\t\t\trecipe={recipe}\n\t\t\trenderFields={() => (\n\t\t\t\t<>\n\t\t\t\t\t{steps.map((step) => (\n\t\t\t\t\t\t<StepFields key={step.id} step={step} config={config} layout={layout} />\n\t\t\t\t\t))}\n\t\t\t\t</>\n\t\t\t)}\n\t\t>\n\t\t\t{children}\n\t\t</RecipeRenderer>\n\t);\n}\n\n/**\n * @template TValues - The values the form submits, which the normalized `config` carries: `onSubmit`, `onAction` and\n * `defaultValues` are typed by it. A config passed as authoring input has none, so they are {@link FormValues}.\n */\nexport interface FormRendererProps<\n\tTElements extends Record<string, unknown> = Record<string, unknown>,\n\tTRecipes extends Record<string, unknown> = Record<string, unknown>,\n\tTActions extends Record<string, unknown> = Record<string, unknown>,\n\tTOutputs extends EngineOutputMaps = EngineOutputMaps,\n\tTValues extends FormValues = FormValues,\n> extends Omit<FormProviderProps<TOutputs, TValues>, 'children' | 'config'> {\n\t/**\n\t * The form: the normalized config of `engine.defineForm` or `engine.validateForm`, or an authoring config.\n\t *\n\t * @remarks An authoring config carries no values type, so it is accepted only where `TValues` is {@link FormValues}: a callback typed by other values needs a normalized config that says so.\n\t */\n\tconfig:\n\t\t| NormalizedFormConfig<TOutputs['elements'], TOutputs['recipes'], TOutputs['actions'], TValues>\n\t\t| (FormValues extends TValues ? FormConfig<TElements, TRecipes, TActions> : never);\n\tclassName?: string;\n\tstyle?: React.CSSProperties;\n\tengine?: FormEngine<TElements, TRecipes, TActions, TOutputs>;\n\tchildren?: React.ReactNode;\n}\n\nfunction FormRendererInner<\n\tTElements extends Record<string, unknown>,\n\tTRecipes extends Record<string, unknown>,\n\tTActions extends Record<string, unknown>,\n\tTOutputs extends EngineOutputMaps,\n\tTValues extends FormValues,\n>({\n\tconfig,\n\tdefaultValues,\n\tonSubmit,\n\tonChange,\n\tonAction,\n\tonActionResults,\n\tnavigate,\n\tformatIssue,\n\tclassName = '',\n\tstyle,\n\tlayout,\n\tchildren,\n}: Omit<FormRendererProps<TElements, TRecipes, TActions, TOutputs, TValues>, 'engine' | 'config'> & {\n\tconfig: NormalizedFormConfig<TOutputs['elements'], TOutputs['recipes'], TOutputs['actions'], TValues>;\n\tlayout: LayoutTheme;\n}) {\n\treturn (\n\t\t<FormProvider\n\t\t\tconfig={config}\n\t\t\tdefaultValues={defaultValues}\n\t\t\tonSubmit={onSubmit}\n\t\t\tonChange={onChange}\n\t\t\tonAction={onAction}\n\t\t\tonActionResults={onActionResults}\n\t\t\tnavigate={navigate}\n\t\t\tformatIssue={formatIssue}\n\t\t>\n\t\t\t<div className={`se-form ${className}`.trim()} style={style}>\n\t\t\t\t<LayoutThemeStyle themeId={layout.id} css={layout.css} />\n\t\t\t\t<FormElementsRenderer config={config} layout={layout}>\n\t\t\t\t\t{children}\n\t\t\t\t</FormElementsRenderer>\n\t\t\t</div>\n\t\t</FormProvider>\n\t);\n}\n\n/**\n * The normalized form of a `FormRenderer` config, which keeps the values type of a normalized config.\n *\n * @remarks\n * A normalized config is validated as it is, so it keeps the type it carries. An authoring config carries none, and\n * `FormRendererProps['config']` accepts one only where `TValues` is `FormValues`, so the form it normalizes to is\n * a form of `TValues`; the engine has no signature that says so for a generic `TValues`.\n */\nfunction normalize<\n\tTElements extends Record<string, unknown>,\n\tTRecipes extends Record<string, unknown>,\n\tTActions extends Record<string, unknown>,\n\tTOutputs extends EngineOutputMaps,\n\tTValues extends FormValues,\n>(\n\tengine: FormEngine<TElements, TRecipes, TActions, TOutputs>,\n\tconfig: FormRendererProps<TElements, TRecipes, TActions, TOutputs, TValues>['config'],\n): NormalizedFormConfig<TOutputs['elements'], TOutputs['recipes'], TOutputs['actions'], TValues> {\n\tif (isNormalizedFormConfig(config)) return engine.validateForm(config);\n\treturn engine.validateForm(config) as NormalizedFormConfig<\n\t\tTOutputs['elements'],\n\t\tTOutputs['recipes'],\n\t\tTOutputs['actions'],\n\t\tTValues\n\t>;\n}\n\n/**\n * Renders a form: its fields, its recipe and the provider that runs it.\n *\n * @remarks\n * A normalized config (`engine.defineForm`, or `engine.validateForm` with a `values` schema) types `onSubmit`,\n * `onAction` and `defaultValues` by the values it carries, so a callback needs no annotation and no cast. Validating a\n * normalized config returns it unchanged, so it keeps that type; an authoring config has none and is {@link FormValues}.\n */\nexport function FormRenderer<\n\tTElements extends Record<string, unknown> = Record<string, unknown>,\n\tTRecipes extends Record<string, unknown> = Record<string, unknown>,\n\tTActions extends Record<string, unknown> = Record<string, unknown>,\n\tTOutputs extends EngineOutputMaps = EngineOutputMaps,\n\tTValues extends FormValues = FormValues,\n>({ engine, ...props }: FormRendererProps<TElements, TRecipes, TActions, TOutputs, TValues>) {\n\tconst inheritedEngine = useOptionalFormEngine<TElements, TRecipes, TActions, TOutputs>();\n\tconst resolvedEngine = engine ?? inheritedEngine?.engine;\n\tconst { config, layout } = useMemo(() => {\n\t\tassertFormEngine(resolvedEngine, props.config);\n\t\treturn { config: normalize(resolvedEngine, props.config), layout: resolvedEngine.getLayout() };\n\t}, [props.config, resolvedEngine]);\n\tconst innerProps = { ...props, config, layout };\n\n\tif (!resolvedEngine) {\n\t\treturn <FormRendererInner {...innerProps} />;\n\t}\n\n\treturn (\n\t\t<FormEngineProvider engine={resolvedEngine}>\n\t\t\t<FormRendererInner {...innerProps} />\n\t\t</FormEngineProvider>\n\t);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAQA,SAAS,YAAY,yBAAyB,wBAA0C;AAExF,SAAS,eAAe;AAMxB;AAAA,EAKC;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,SAAS,qBAAqB;AAK5B,SA6DE,UA7DF,KAoIC,YApID;AAFF,SAAS,iBAAiB,EAAE,SAAS,IAAI,GAAqC;AAC7E,SACC,oBAAC,WAAM,MAAM,mBAAmB,OAAO,IAAI,YAAW,mBAAkB,qBAAmB,SACzF,eACF;AAEF;AAEA,SAAS,WAAW;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AACD,GAIG;AACF,SACC;AAAA,IAAC;AAAA;AAAA,MACA,WAAW,gBAAgB,KAAK,aAAa,EAAE,GAAG,KAAK;AAAA,MACvD,gBAAc,KAAK;AAAA,MACnB,OAAO,KAAK;AAAA,MACX,GAAG,wBAAwB,KAAK,UAAU;AAAA,MAE1C,eAAK,SAAS,SAAS,KACvB;AAAA,QAAC;AAAA;AAAA,UACA,WAAW,gBAAgB,UAAU;AAAA,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O,OAAO,aAAa,MAAM;AAMlC;AAUO,SAAS,aAMd,EAAE,QAAQ,GAAG,MAAM,GAAwE;AAC5F,QAAM,kBAAkB,sBAA+D;AACvF,QAAM,iBAAiB,UAAU,iBAAiB;AAClD,QAAM,EAAE,QAAQ,OAAO,IAAI,QAAQ,MAAM;AACxC,qBAAiB,gBAAgB,MAAM,MAAM;AAC7C,WAAO,EAAE,QAAQ,UAAU,gBAAgB,MAAM,MAAM,GAAG,QAAQ,eAAe,UAAU,EAAE;AAAA,EAC9F,GAAG,CAAC,MAAM,QAAQ,cAAc,CAAC;AACjC,QAAM,aAAa,EAAE,GAAG,OAAO,QAAQ,OAAO;AAE9C,MAAI,CAAC,gBAAgB;AACpB,WAAO,oBAAC,qBAAmB,GAAG,YAAY;AAAA,EAC3C;AAEA,SACC,oBAAC,sBAAmB,QAAQ,gBAC3B,8BAAC,qBAAmB,GAAG,YAAY,GACpC;AAEF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,78 @@
1
+ import {
2
+ useFormContext
3
+ } from "./chunk-K66J2V73.js";
4
+ import {
5
+ ViewProvider
6
+ } from "./chunk-IXRV3YCF.js";
7
+ import {
8
+ useFormInstanceActions
9
+ } from "./chunk-AALIXTCD.js";
10
+
11
+ // src/components/internals/recipe-renderer.tsx
12
+ import { useMemo } from "react";
13
+ import { isSubmissionBusy } from "@schema-engine/forms";
14
+ import { buildViewModel, createViewNavigation } from "@schema-engine/forms/recipes";
15
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
16
+ function getRecipeAdapter(registration) {
17
+ const payload = registration.render;
18
+ if (!payload?.slots) {
19
+ throw new Error(`Recipe '${registration.$type}' is missing a React render payload.`);
20
+ }
21
+ return payload;
22
+ }
23
+ function renderSlotBlock(Component) {
24
+ if (!Component) return null;
25
+ return /* @__PURE__ */ jsx(Component, {});
26
+ }
27
+ function RecipeRenderer({ config, recipe, children, renderFields }) {
28
+ const { formState } = useFormContext();
29
+ const { current, steps, next, back, goTo } = useFormInstanceActions();
30
+ const isSubmitting = isSubmissionBusy(formState.submission.status);
31
+ const viewContext = useMemo(
32
+ () => recipe ? buildViewModel({
33
+ config,
34
+ kind: recipe.kind,
35
+ states: steps,
36
+ current,
37
+ navigation: createViewNavigation(steps, current, { next, back, goTo }),
38
+ isSubmitting,
39
+ viewConfig: config.view
40
+ }) : void 0,
41
+ [recipe, config, steps, current, next, back, goTo, isSubmitting]
42
+ );
43
+ const adapter = recipe ? getRecipeAdapter(recipe) : void 0;
44
+ const blocks = useMemo(
45
+ () => adapter && {
46
+ header: renderSlotBlock(adapter.slots.header),
47
+ progress: renderSlotBlock(adapter.slots.progress),
48
+ actions: renderSlotBlock(adapter.slots.actions)
49
+ },
50
+ [adapter]
51
+ );
52
+ if (!adapter || !blocks || !viewContext) {
53
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
54
+ renderFields(),
55
+ children
56
+ ] });
57
+ }
58
+ const { viewConfig } = viewContext;
59
+ const content = /* @__PURE__ */ jsxs(Fragment, { children: [
60
+ renderFields(),
61
+ children
62
+ ] });
63
+ const slots = { ...blocks, content };
64
+ const Shell = adapter.shell;
65
+ if (!Shell) {
66
+ return /* @__PURE__ */ jsxs(ViewProvider, { value: viewContext, children: [
67
+ slots.header,
68
+ slots.progress,
69
+ slots.content,
70
+ slots.actions
71
+ ] });
72
+ }
73
+ return /* @__PURE__ */ jsx(ViewProvider, { value: viewContext, children: /* @__PURE__ */ jsx(Shell, { slots, viewConfig }) });
74
+ }
75
+
76
+ export {
77
+ RecipeRenderer
78
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/components/internals/recipe-renderer.tsx"],
4
+ "sourcesContent": ["import { useMemo } from 'react';\nimport type React from 'react';\nimport { isSubmissionBusy, type FormConfigView, type RecipeRegistration } from '@schema-engine/forms';\nimport { buildViewModel, createViewNavigation } from '@schema-engine/forms/recipes';\nimport { useFormContext } from '@/hooks/form-state';\nimport { useFormInstanceActions } from '@/hooks/use-form-context';\nimport { ViewProvider } from '@/contexts/view-context';\nimport type { ReactRecipeAdapterPayload } from '@/primitives';\n\ntype ReactRecipeRegistration = RecipeRegistration<string, RecipeRegistration['schema'], ReactRecipeAdapterPayload>;\n\nfunction getRecipeAdapter(registration: ReactRecipeRegistration): ReactRecipeAdapterPayload {\n\tconst payload = registration.render;\n\tif (!payload?.slots) {\n\t\tthrow new Error(`Recipe '${registration.$type}' is missing a React render payload.`);\n\t}\n\n\treturn payload;\n}\n\nfunction renderSlotBlock(Component: React.FC | undefined): React.ReactNode {\n\tif (!Component) return null;\n\treturn <Component />;\n}\n\ninterface RecipeRendererProps {\n\tconfig: FormConfigView;\n\trecipe: RecipeRegistration | undefined;\n\tchildren?: React.ReactNode;\n\trenderFields: () => React.ReactNode;\n}\n\nexport function RecipeRenderer({ config, recipe, children, renderFields }: RecipeRendererProps) {\n\tconst { formState } = useFormContext();\n\tconst { current, steps, next, back, goTo } = useFormInstanceActions();\n\tconst isSubmitting = isSubmissionBusy(formState.submission.status);\n\tconst viewContext = useMemo(\n\t\t() =>\n\t\t\trecipe\n\t\t\t\t? buildViewModel({\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tkind: recipe.kind,\n\t\t\t\t\t\tstates: steps,\n\t\t\t\t\t\tcurrent,\n\t\t\t\t\t\tnavigation: createViewNavigation(steps, current, { next, back, goTo }),\n\t\t\t\t\t\tisSubmitting,\n\t\t\t\t\t\tviewConfig: config.view as Record<string, unknown>,\n\t\t\t\t\t})\n\t\t\t\t: undefined,\n\t\t[recipe, config, steps, current, next, back, goTo, isSubmitting],\n\t);\n\tconst adapter = recipe ? getRecipeAdapter(recipe as ReactRecipeRegistration) : undefined;\n\t/** @remarks Slot elements are built once per recipe so React skips a slot whose view context did not change. */\n\tconst blocks = useMemo(\n\t\t() =>\n\t\t\tadapter && {\n\t\t\t\theader: renderSlotBlock(adapter.slots.header),\n\t\t\t\tprogress: renderSlotBlock(adapter.slots.progress),\n\t\t\t\tactions: renderSlotBlock(adapter.slots.actions),\n\t\t\t},\n\t\t[adapter],\n\t);\n\tif (!adapter || !blocks || !viewContext) {\n\t\treturn (\n\t\t\t<>\n\t\t\t\t{renderFields()}\n\t\t\t\t{children}\n\t\t\t</>\n\t\t);\n\t}\n\n\tconst { viewConfig } = viewContext;\n\n\tconst content = (\n\t\t<>\n\t\t\t{renderFields()}\n\t\t\t{children}\n\t\t</>\n\t);\n\n\tconst slots = { ...blocks, content };\n\n\tconst Shell = adapter.shell;\n\tif (!Shell) {\n\t\treturn (\n\t\t\t<ViewProvider value={viewContext}>\n\t\t\t\t{slots.header}\n\t\t\t\t{slots.progress}\n\t\t\t\t{slots.content}\n\t\t\t\t{slots.actions}\n\t\t\t</ViewProvider>\n\t\t);\n\t}\n\n\treturn (\n\t\t<ViewProvider value={viewContext}>\n\t\t\t<Shell slots={slots} viewConfig={viewConfig} />\n\t\t</ViewProvider>\n\t);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;AAAA,SAAS,eAAe;AAExB,SAAS,wBAAsE;AAC/E,SAAS,gBAAgB,4BAA4B;AAmB7C,SA0CL,UA1CK,KA0CL,YA1CK;AAXR,SAAS,iBAAiB,cAAkE;AAC3F,QAAM,UAAU,aAAa;AAC7B,MAAI,CAAC,SAAS,OAAO;AACpB,UAAM,IAAI,MAAM,WAAW,aAAa,KAAK,sCAAsC;AAAA,EACpF;AAEA,SAAO;AACR;AAEA,SAAS,gBAAgB,WAAkD;AAC1E,MAAI,CAAC,UAAW,QAAO;AACvB,SAAO,oBAAC,aAAU;AACnB;AASO,SAAS,eAAe,EAAE,QAAQ,QAAQ,UAAU,aAAa,GAAwB;AAC/F,QAAM,EAAE,UAAU,IAAI,eAAe;AACrC,QAAM,EAAE,SAAS,OAAO,MAAM,MAAM,KAAK,IAAI,uBAAuB;AACpE,QAAM,eAAe,iBAAiB,UAAU,WAAW,MAAM;AACjE,QAAM,cAAc;AAAA,IACnB,MACC,SACG,eAAe;AAAA,MACf;AAAA,MACA,MAAM,OAAO;AAAA,MACb,QAAQ;AAAA,MACR;AAAA,MACA,YAAY,qBAAqB,OAAO,SAAS,EAAE,MAAM,MAAM,KAAK,CAAC;AAAA,MACrE;AAAA,MACA,YAAY,OAAO;AAAA,IACpB,CAAC,IACA;AAAA,IACJ,CAAC,QAAQ,QAAQ,OAAO,SAAS,MAAM,MAAM,MAAM,YAAY;AAAA,EAChE;AACA,QAAM,UAAU,SAAS,iBAAiB,MAAiC,IAAI;AAE/E,QAAM,SAAS;AAAA,IACd,MACC,WAAW;AAAA,MACV,QAAQ,gBAAgB,QAAQ,MAAM,MAAM;AAAA,MAC5C,UAAU,gBAAgB,QAAQ,MAAM,QAAQ;AAAA,MAChD,SAAS,gBAAgB,QAAQ,MAAM,OAAO;AAAA,IAC/C;AAAA,IACD,CAAC,OAAO;AAAA,EACT;AACA,MAAI,CAAC,WAAW,CAAC,UAAU,CAAC,aAAa;AACxC,WACC,iCACE;AAAA,mBAAa;AAAA,MACb;AAAA,OACF;AAAA,EAEF;AAEA,QAAM,EAAE,WAAW,IAAI;AAEvB,QAAM,UACL,iCACE;AAAA,iBAAa;AAAA,IACb;AAAA,KACF;AAGD,QAAM,QAAQ,EAAE,GAAG,QAAQ,QAAQ;AAEnC,QAAM,QAAQ,QAAQ;AACtB,MAAI,CAAC,OAAO;AACX,WACC,qBAAC,gBAAa,OAAO,aACnB;AAAA,YAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,OACR;AAAA,EAEF;AAEA,SACC,oBAAC,gBAAa,OAAO,aACpB,8BAAC,SAAM,OAAc,YAAwB,GAC9C;AAEF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,6 @@
1
+ // src/hooks/form-state/index.ts
2
+ import { FORM_ROOT } from "@schema-engine/forms/state-container";
3
+
4
+ export {
5
+ FORM_ROOT
6
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/hooks/form-state/index.ts"],
4
+ "sourcesContent": ["export type {\n\tFieldArrayValue,\n\tControlledFormField,\n\tFormContextValue,\n\tFormControlProps,\n\tFormField,\n\tFormFieldConfig,\n\tFormFieldOptions,\n\tFormFieldStatus,\n\tNativeControlProps,\n\tFormProviderProps,\n\tFormSubmitHelpers,\n\tFormValues,\n} from './types';\nexport { useFormContext } from './use-form-context';\nexport { useFormField } from './use-form-field';\nexport { useWatch } from './use-watch';\nexport { useFieldArray } from './use-field-array';\nexport type { FormSubmissionState as SubmissionState, SubmissionStatus } from '@schema-engine/forms';\nexport { FORM_ROOT } from '@schema-engine/forms/state-container';\nexport type {\n\tFormIssueFormatter,\n\tFormStateError,\n\tFormStateErrorsInput,\n\tFormStateIssue,\n\tFormSubmissionIssue,\n} from '@schema-engine/forms/state-container';\n"],
5
+ "mappings": ";AAmBA,SAAS,iBAAiB;",
6
+ "names": []
7
+ }
@@ -0,0 +1,122 @@
1
+ import {
2
+ controlMatches,
3
+ isNativeControl,
4
+ readControl,
5
+ readNativeFact,
6
+ sameValue,
7
+ writeControl
8
+ } from "./chunk-CPJMN2IH.js";
9
+ import {
10
+ logger
11
+ } from "./chunk-XWHP2AGG.js";
12
+
13
+ // src/hooks/form-state/field-registry.ts
14
+ import { selectValue } from "@schema-engine/forms/state-container";
15
+ function focusFirstInDocument(elements) {
16
+ elements.filter((element) => element.isConnected).reduce(
17
+ (first, element) => first && !(first.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_PRECEDING) ? first : element,
18
+ void 0
19
+ )?.focus();
20
+ }
21
+ function nativeControls(registrations) {
22
+ return registrations.map(({ element }) => element).filter(isNativeControl);
23
+ }
24
+ function reshapedArrays(before, after) {
25
+ return Object.keys({ ...before, ...after }).filter((array) => before[array] !== after[array]);
26
+ }
27
+ function readFactSafely(control, path) {
28
+ try {
29
+ return readNativeFact(control);
30
+ } catch (error) {
31
+ logger.error(`Could not read the validity of "${path}":`, error);
32
+ return null;
33
+ }
34
+ }
35
+ function createFieldRegistry(container) {
36
+ const controls = /* @__PURE__ */ new Map();
37
+ let unsubscribe;
38
+ let lastRowIds = container.getSnapshot().rowIds;
39
+ const current = (path) => controls.get(path)?.at(-1)?.element;
40
+ const within = (path) => Array.from(controls.keys()).filter((key) => key === path || key.startsWith(`${path}.`)).flatMap((key) => current(key) ?? []);
41
+ const reportNative = (path) => {
42
+ const natives = nativeControls(controls.get(path) ?? []);
43
+ if (natives.length === 0) return;
44
+ const fact = natives.map((control) => readFactSafely(control, path)).find((candidate) => candidate !== null);
45
+ container.reportNative({ [path]: fact ?? null });
46
+ };
47
+ const writeBack = () => {
48
+ const snapshot = container.getSnapshot();
49
+ const reshaped = reshapedArrays(lastRowIds, snapshot.rowIds);
50
+ lastRowIds = snapshot.rowIds;
51
+ for (const [path, registrations] of Array.from(controls)) {
52
+ if (reshaped.some((array) => path.startsWith(`${array}.`))) continue;
53
+ const natives = nativeControls(registrations.filter(({ binding }) => binding.mode === "uncontrolled"));
54
+ const value = selectValue(snapshot, path);
55
+ const stale = natives.filter((control) => !controlMatches(control, value));
56
+ if (stale.length === 0) continue;
57
+ for (const control of stale) writeControl(control, value);
58
+ reportNative(path);
59
+ }
60
+ };
61
+ const settle = (path, control, rendered) => {
62
+ const value = selectValue(container.getSnapshot(), path);
63
+ if (controlMatches(control, value)) return;
64
+ if (controlMatches(control, rendered)) {
65
+ writeControl(control, value);
66
+ return;
67
+ }
68
+ const read = readControl(control, value);
69
+ if (!sameValue(read, value)) container.setValue(path, read);
70
+ };
71
+ return {
72
+ register(path, element, binding) {
73
+ const registration = { element, binding };
74
+ controls.set(path, [...controls.get(path) ?? [], registration]);
75
+ if (!unsubscribe) {
76
+ lastRowIds = container.getSnapshot().rowIds;
77
+ unsubscribe = container.subscribe(writeBack);
78
+ }
79
+ if (binding.mode === "uncontrolled" && isNativeControl(element)) settle(path, element, binding.rendered);
80
+ reportNative(path);
81
+ return () => {
82
+ const remaining = (controls.get(path) ?? []).filter((control) => control !== registration);
83
+ if (remaining.length > 0) controls.set(path, remaining);
84
+ else controls.delete(path);
85
+ if (controls.size === 0) {
86
+ unsubscribe?.();
87
+ unsubscribe = void 0;
88
+ }
89
+ if (!isNativeControl(element)) return;
90
+ if (nativeControls(remaining).length > 0) reportNative(path);
91
+ else container.reportNative({ [path]: null });
92
+ };
93
+ },
94
+ change(path, element) {
95
+ if (!isNativeControl(element)) return;
96
+ container.setValue(path, readControl(element, selectValue(container.getSnapshot(), path)));
97
+ reportNative(path);
98
+ },
99
+ blur(path) {
100
+ reportNative(path);
101
+ container.blur(path);
102
+ },
103
+ reportNative,
104
+ inspect(path) {
105
+ const registrations = controls.get(path) ?? [];
106
+ return { registered: registrations.length > 0, native: nativeControls(registrations).length > 0 };
107
+ },
108
+ focus(path) {
109
+ current(path)?.focus();
110
+ },
111
+ focusFirst(paths) {
112
+ focusFirstInDocument(paths.flatMap(within));
113
+ },
114
+ focusWithin(path) {
115
+ focusFirstInDocument(within(path));
116
+ }
117
+ };
118
+ }
119
+
120
+ export {
121
+ createFieldRegistry
122
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/hooks/form-state/field-registry.ts"],
4
+ "sourcesContent": ["import { selectValue, type FormStateContainer, type FormStateSnapshot } from '@schema-engine/forms/state-container';\nimport { logger } from '@/lib/logger';\nimport {\n\tcontrolMatches,\n\tisNativeControl,\n\treadControl,\n\treadNativeFact,\n\tsameValue,\n\twriteControl,\n\ttype NativeControl,\n} from './native-control';\n\n/**\n * Who owns the value of a control. An uncontrolled control keeps its own value, which the registry reads and\n * writes back, and `rendered` is the value React gave it when the field rendered. A controlled control is\n * rendered by a component from the container's value, and the registry only reads its validity.\n */\nexport type FieldBinding =\n\t{ readonly mode: 'controlled' } | { readonly mode: 'uncontrolled'; readonly rendered: unknown };\n\n/**\n * The controls of a form by field path, which `setFocus` and a failed submit move focus to, and the only\n * module that reads a native control, writes it back and reports what the browser says about it.\n */\nexport interface FieldRegistry {\n\t/**\n\t * Records a control of `path`; returns the function that removes that control.\n\t *\n\t * @remarks\n\t * An uncontrolled native control that differs from the value React rendered it with was changed by the\n\t * user before the form hydrated, so the container takes what it shows. One that still shows what React\n\t * rendered takes the container's value instead, which is newer when the control is a new element of a\n\t * field that has been edited since. Every native control reports its validity on attach and withdraws it\n\t * when it leaves, unless another control of the path remains.\n\t */\n\tregister(path: string, element: HTMLElement, binding: FieldBinding): () => void;\n\t/** Writes what the user did to `element` into the container and reports its validity. */\n\tchange(path: string, element: HTMLElement): void;\n\t/** Reports the validity of the controls of `path`, then marks the path blurred. */\n\tblur(path: string): void;\n\t/** Reports the validity of the native controls of `path`. */\n\treportNative(path: string): void;\n\t/** Whether something is registered for `path`, and whether any of it is an input, select or textarea. */\n\tinspect(path: string): { registered: boolean; native: boolean };\n\tfocus(path: string): void;\n\t/** Focuses the first control, in document order, of the fields at `paths` or below them, so an error on an array reaches its rows. */\n\tfocusFirst(paths: readonly string[]): void;\n\t/** Focuses the first control, in document order, of the field at `path` or below it. */\n\tfocusWithin(path: string): void;\n}\n\ninterface Registration {\n\treadonly element: HTMLElement;\n\treadonly binding: FieldBinding;\n}\n\nfunction focusFirstInDocument(elements: readonly HTMLElement[]): void {\n\telements\n\t\t.filter((element) => element.isConnected)\n\t\t.reduce<HTMLElement | undefined>(\n\t\t\t(first, element) =>\n\t\t\t\tfirst && !(first.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_PRECEDING) ? first : element,\n\t\t\tundefined,\n\t\t)\n\t\t?.focus();\n}\n\nfunction nativeControls(registrations: readonly Registration[]): NativeControl[] {\n\treturn registrations.map(({ element }) => element).filter(isNativeControl);\n}\n\n/** The arrays whose rows were added, removed or moved between two snapshots. */\nfunction reshapedArrays(before: FormStateSnapshot['rowIds'], after: FormStateSnapshot['rowIds']): string[] {\n\treturn Object.keys({ ...before, ...after }).filter((array) => before[array] !== after[array]);\n}\n\n/** The fact of a control, or none when the browser throws while it is read: the others are still reported. */\nfunction readFactSafely(control: NativeControl, path: string) {\n\ttry {\n\t\treturn readNativeFact(control);\n\t} catch (error) {\n\t\tlogger.error(`Could not read the validity of \"${path}\":`, error);\n\t\treturn null;\n\t}\n}\n\n/**\n * @remarks\n * A path can have several controls at once: a radio group or a list of checkboxes shares one path, and a\n * row that is replaced has the old control beside the new one until it unmounts. The latest registered one\n * that is still mounted answers for `focus`.\n *\n * One subscription to the container serves every control. On a change it compares each registered\n * uncontrolled path with what its controls show and writes back only the difference, so a control that\n * echoes the user's own change is never touched: that is what keeps the cursor, an IME composition and the\n * text of a number input with `badInput` where they are. A change that adds, removes or moves the rows of\n * an array is not written back below that array: the rows' controls keep their text and register again\n * under their new paths, where they already agree with the container, and writing the old paths would put\n * one row's text into another's control.\n */\nexport function createFieldRegistry(container: FormStateContainer): FieldRegistry {\n\tconst controls = new Map<string, Registration[]>();\n\tlet unsubscribe: (() => void) | undefined;\n\tlet lastRowIds = container.getSnapshot().rowIds;\n\n\tconst current = (path: string): HTMLElement | undefined => controls.get(path)?.at(-1)?.element;\n\tconst within = (path: string): HTMLElement[] =>\n\t\tArray.from(controls.keys())\n\t\t\t.filter((key) => key === path || key.startsWith(`${path}.`))\n\t\t\t.flatMap((key) => current(key) ?? []);\n\n\tconst reportNative = (path: string): void => {\n\t\tconst natives = nativeControls(controls.get(path) ?? []);\n\t\tif (natives.length === 0) return;\n\t\tconst fact = natives.map((control) => readFactSafely(control, path)).find((candidate) => candidate !== null);\n\t\tcontainer.reportNative({ [path]: fact ?? null });\n\t};\n\n\tconst writeBack = (): void => {\n\t\tconst snapshot = container.getSnapshot();\n\t\tconst reshaped = reshapedArrays(lastRowIds, snapshot.rowIds);\n\t\tlastRowIds = snapshot.rowIds;\n\t\tfor (const [path, registrations] of Array.from(controls)) {\n\t\t\tif (reshaped.some((array) => path.startsWith(`${array}.`))) continue;\n\t\t\tconst natives = nativeControls(registrations.filter(({ binding }) => binding.mode === 'uncontrolled'));\n\t\t\tconst value = selectValue(snapshot, path);\n\t\t\tconst stale = natives.filter((control) => !controlMatches(control, value));\n\t\t\tif (stale.length === 0) continue;\n\t\t\tfor (const control of stale) writeControl(control, value);\n\t\t\treportNative(path);\n\t\t}\n\t};\n\n\tconst settle = (path: string, control: NativeControl, rendered: unknown): void => {\n\t\tconst value = selectValue(container.getSnapshot(), path);\n\t\tif (controlMatches(control, value)) return;\n\t\tif (controlMatches(control, rendered)) {\n\t\t\twriteControl(control, value);\n\t\t\treturn;\n\t\t}\n\t\tconst read = readControl(control, value);\n\t\tif (!sameValue(read, value)) container.setValue(path, read);\n\t};\n\n\treturn {\n\t\tregister(path, element, binding) {\n\t\t\tconst registration: Registration = { element, binding };\n\t\t\tcontrols.set(path, [...(controls.get(path) ?? []), registration]);\n\t\t\tif (!unsubscribe) {\n\t\t\t\tlastRowIds = container.getSnapshot().rowIds;\n\t\t\t\tunsubscribe = container.subscribe(writeBack);\n\t\t\t}\n\t\t\tif (binding.mode === 'uncontrolled' && isNativeControl(element)) settle(path, element, binding.rendered);\n\t\t\treportNative(path);\n\t\t\treturn () => {\n\t\t\t\tconst remaining = (controls.get(path) ?? []).filter((control) => control !== registration);\n\t\t\t\tif (remaining.length > 0) controls.set(path, remaining);\n\t\t\t\telse controls.delete(path);\n\t\t\t\tif (controls.size === 0) {\n\t\t\t\t\tunsubscribe?.();\n\t\t\t\t\tunsubscribe = undefined;\n\t\t\t\t}\n\t\t\t\tif (!isNativeControl(element)) return;\n\t\t\t\tif (nativeControls(remaining).length > 0) reportNative(path);\n\t\t\t\telse container.reportNative({ [path]: null });\n\t\t\t};\n\t\t},\n\t\tchange(path, element) {\n\t\t\tif (!isNativeControl(element)) return;\n\t\t\tcontainer.setValue(path, readControl(element, selectValue(container.getSnapshot(), path)));\n\t\t\treportNative(path);\n\t\t},\n\t\tblur(path) {\n\t\t\treportNative(path);\n\t\t\tcontainer.blur(path);\n\t\t},\n\t\treportNative,\n\t\tinspect(path) {\n\t\t\tconst registrations = controls.get(path) ?? [];\n\t\t\treturn { registered: registrations.length > 0, native: nativeControls(registrations).length > 0 };\n\t\t},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