@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-present Andrea Zanenghi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # @schema-engine/forms-react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The React renderer for [`@schema-engine/forms`](https://www.npmjs.com/package/@schema-engine/forms). It supplies `FormRenderer`, the hooks that bind your widgets to the engine's form state, and the primitives for view recipes. It ships no element registrations: you write your widgets, or optionally copy ready-made ones from the shadcn registry.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @schema-engine/forms @schema-engine/forms-react @schema-engine/layout react react-dom zod
9
+ ```
10
+
11
+ It needs React 19. Set `"jsx": "react-jsx"` in `tsconfig.json`.
12
+
13
+ ## Example
14
+
15
+ ```tsx
16
+ import * as z from 'zod/mini';
17
+ import { BaseFieldSchema, createFormEngine, defineInput } from '@schema-engine/forms';
18
+ import { FormRenderer } from '@schema-engine/forms-react';
19
+ import { fieldText, useFormField } from '@schema-engine/forms-react/hooks';
20
+
21
+ const TextSchema = z.extend(BaseFieldSchema, { $type: z.literal('text') });
22
+
23
+ function TextField(config: z.output<typeof TextSchema>) {
24
+ const { defaultValue, error, fieldProps, labelProps, errorProps } = useFormField(config);
25
+ return (
26
+ <div>
27
+ <label {...labelProps}>{config.label}</label>
28
+ <input {...fieldProps} defaultValue={fieldText(defaultValue)} />
29
+ {errorProps && <p {...errorProps}>{error}</p>}
30
+ </div>
31
+ );
32
+ }
33
+
34
+ const text = defineInput({
35
+ $type: 'text',
36
+ schema: TextSchema,
37
+ render: TextField,
38
+ value: () => z.string(),
39
+ metadata: { name: 'Text', category: 'input' },
40
+ });
41
+
42
+ const engine = createFormEngine({ elements: [text] });
43
+
44
+ const form = engine.defineForm({
45
+ id: 'contact',
46
+ steps: [
47
+ {
48
+ id: 'details',
49
+ title: 'Your details',
50
+ elements: [
51
+ {
52
+ $type: 'text',
53
+ id: 'name',
54
+ name: 'name',
55
+ label: 'Name',
56
+ rules: [{ $type: 'required', message: 'Enter your name' }],
57
+ },
58
+ ],
59
+ },
60
+ ],
61
+ });
62
+
63
+ export const Contact = () => <FormRenderer engine={engine} config={form} onSubmit={(values) => console.log(values)} />;
64
+ ```
65
+
66
+ ## Entry points
67
+
68
+ | Import | Holds |
69
+ | ----------------------------------------------------- | ----------------------------------------------------------------------------------------- |
70
+ | `@schema-engine/forms-react` | `FormRenderer`, `FormProvider` and `FormEngineProvider` |
71
+ | `@schema-engine/forms-react/hooks` | `useFormField`, `useFormContext`, `useWatch`, `useFieldArray`, the runtime and view hooks |
72
+ | `@schema-engine/forms-react/primitives` | `FormElement`, `FormElements` and `defineRecipe` |
73
+ | `@schema-engine/forms-react/contexts` | The view provider and context types |
74
+ | `@schema-engine/forms-react/components/form-debugger` | `FormDebugger`, a development panel |
75
+
76
+ ## Documentation
77
+
78
+ - [Forms React](https://schema-engine.com/docs/forms-react/overview): what the package supplies.
79
+ - [Installation and quick start](https://schema-engine.com/docs/forms-react/getting-started): your first widget, and the optional shadcn registry.
80
+ - [Writing a widget](https://schema-engine.com/docs/forms-react/widgets): uncontrolled and controlled widgets.
81
+ - [Hooks](https://schema-engine.com/docs/forms-react/hooks) and [View recipes](https://schema-engine.com/docs/forms-react/layouts).
82
+ - [Other React state](https://schema-engine.com/docs/forms-react/other-react-state): mount a form in a panel that holds other state.
83
+ - [API reference](https://schema-engine.com/docs/forms-react/api-reference).
84
+ - [For AI agents](https://schema-engine.com/docs/schema-engine/agent-skill): the package ships its part of the agent skill.
85
+
86
+ ## License
87
+
88
+ MIT
@@ -0,0 +1,19 @@
1
+ // src/components/internals/element-error.tsx
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
+ function ElementError({ title, message, componentType, className, style }) {
4
+ return /* @__PURE__ */ jsx("div", { className: ["se-element-error", className].filter(Boolean).join(" "), style, children: /* @__PURE__ */ jsxs("div", { className: "se-element-error__content", children: [
5
+ /* @__PURE__ */ jsxs("p", { className: "se-element-error__title", children: [
6
+ /* @__PURE__ */ jsx("span", { className: "se-element-error__marker", children: "[error] " }),
7
+ title
8
+ ] }),
9
+ componentType && /* @__PURE__ */ jsxs("p", { className: "se-element-error__type", children: [
10
+ "Component: ",
11
+ componentType
12
+ ] }),
13
+ /* @__PURE__ */ jsx("p", { className: "se-element-error__message", children: message })
14
+ ] }) });
15
+ }
16
+
17
+ export {
18
+ ElementError
19
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/components/internals/element-error.tsx"],
4
+ "sourcesContent": ["import type React from 'react';\n\nexport interface ElementErrorProps {\n\ttitle: string;\n\tmessage: string;\n\tcomponentType?: string;\n\tclassName?: string;\n\tstyle?: React.CSSProperties;\n}\n\nexport function ElementError({ title, message, componentType, className, style }: ElementErrorProps) {\n\treturn (\n\t\t<div className={['se-element-error', className].filter(Boolean).join(' ')} style={style}>\n\t\t\t<div className=\"se-element-error__content\">\n\t\t\t\t<p className=\"se-element-error__title\">\n\t\t\t\t\t<span className=\"se-element-error__marker\">[error] </span>\n\t\t\t\t\t{title}\n\t\t\t\t</p>\n\t\t\t\t{componentType && <p className=\"se-element-error__type\">Component: {componentType}</p>}\n\t\t\t\t<p className=\"se-element-error__message\">{message}</p>\n\t\t\t</div>\n\t\t</div>\n\t);\n}\n"],
5
+ "mappings": ";AAcI,SACC,KADD;AAJG,SAAS,aAAa,EAAE,OAAO,SAAS,eAAe,WAAW,MAAM,GAAsB;AACpG,SACC,oBAAC,SAAI,WAAW,CAAC,oBAAoB,SAAS,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG,GAAG,OAC1E,+BAAC,SAAI,WAAU,6BACd;AAAA,yBAAC,OAAE,WAAU,2BACZ;AAAA,0BAAC,UAAK,WAAU,4BAA2B,sBAAQ;AAAA,MAClD;AAAA,OACF;AAAA,IACC,iBAAiB,qBAAC,OAAE,WAAU,0BAAyB;AAAA;AAAA,MAAY;AAAA,OAAc;AAAA,IAClF,oBAAC,OAAE,WAAU,6BAA6B,mBAAQ;AAAA,KACnD,GACD;AAEF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,19 @@
1
+ import {
2
+ FormEngineContext,
3
+ createFormEngineContextValue
4
+ } from "./chunk-GH2QO3WC.js";
5
+
6
+ // src/components/form-engine-provider.tsx
7
+ import { useMemo } from "react";
8
+ import { jsx } from "react/jsx-runtime";
9
+ function FormEngineProvider({ children, engine }) {
10
+ const value = useMemo(() => createFormEngineContextValue(engine), [engine]);
11
+ if (!engine) {
12
+ throw new Error("FormEngineProvider requires a FormEngine instance. Create one using createFormEngine()");
13
+ }
14
+ return /* @__PURE__ */ jsx(FormEngineContext.Provider, { value, children });
15
+ }
16
+
17
+ export {
18
+ FormEngineProvider
19
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/components/form-engine-provider.tsx"],
4
+ "sourcesContent": ["import { useMemo, type ReactNode } from 'react';\nimport type { EngineOutputMaps, FormEngineRuntime as CoreFormEngine } from '@schema-engine/forms';\nimport { FormEngineContext, createFormEngineContextValue } from './provider';\n\nexport interface FormEngineProviderProps<\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> {\n\tchildren: ReactNode;\n\tengine: CoreFormEngine<TElements, TRecipes, TActions, TOutputs>;\n}\n\nexport function FormEngineProvider<\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>({ children, engine }: FormEngineProviderProps<TElements, TRecipes, TActions, TOutputs>) {\n\tconst value = useMemo(() => createFormEngineContextValue(engine), [engine]);\n\n\tif (!engine) {\n\t\tthrow new Error('FormEngineProvider requires a FormEngine instance. Create one using createFormEngine()');\n\t}\n\n\treturn <FormEngineContext.Provider value={value}>{children}</FormEngineContext.Provider>;\n}\n"],
5
+ "mappings": ";;;;;;AAAA,SAAS,eAA+B;AA0BhC;AAZD,SAAS,mBAKd,EAAE,UAAU,OAAO,GAAqE;AACzF,QAAM,QAAQ,QAAQ,MAAM,6BAA6B,MAAM,GAAG,CAAC,MAAM,CAAC;AAE1E,MAAI,CAAC,QAAQ;AACZ,UAAM,IAAI,MAAM,wFAAwF;AAAA,EACzG;AAEA,SAAO,oBAAC,kBAAkB,UAAlB,EAA2B,OAAe,UAAS;AAC5D;",
6
+ "names": []
7
+ }
@@ -0,0 +1,20 @@
1
+ // src/hooks/use-mobile.ts
2
+ import { useSyncExternalStore } from "react";
3
+ var MOBILE_BREAKPOINT = 768;
4
+ var MOBILE_QUERY = `(max-width: ${MOBILE_BREAKPOINT - 1}px)`;
5
+ function subscribe(onStoreChange) {
6
+ const query = window.matchMedia(MOBILE_QUERY);
7
+ query.addEventListener("change", onStoreChange);
8
+ return () => query.removeEventListener("change", onStoreChange);
9
+ }
10
+ function useIsMobile() {
11
+ return useSyncExternalStore(
12
+ subscribe,
13
+ () => window.matchMedia(MOBILE_QUERY).matches,
14
+ () => false
15
+ );
16
+ }
17
+
18
+ export {
19
+ useIsMobile
20
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/hooks/use-mobile.ts"],
4
+ "sourcesContent": ["import { useSyncExternalStore } from 'react';\n\nconst MOBILE_BREAKPOINT = 768;\nconst MOBILE_QUERY = `(max-width: ${MOBILE_BREAKPOINT - 1}px)`;\n\nfunction subscribe(onStoreChange: () => void) {\n\tconst query = window.matchMedia(MOBILE_QUERY);\n\tquery.addEventListener('change', onStoreChange);\n\treturn () => query.removeEventListener('change', onStoreChange);\n}\n\n/**\n * Whether the viewport is narrower than the mobile breakpoint.\n *\n * @remarks\n * Subscribes to `matchMedia` as an external store, so the first client render\n * already has the real value instead of flashing `false` through an effect.\n * Server and hydration renders report `false`.\n */\nexport function useIsMobile(): boolean {\n\treturn useSyncExternalStore(\n\t\tsubscribe,\n\t\t() => window.matchMedia(MOBILE_QUERY).matches,\n\t\t() => false,\n\t);\n}\n"],
5
+ "mappings": ";AAAA,SAAS,4BAA4B;AAErC,IAAM,oBAAoB;AAC1B,IAAM,eAAe,eAAe,oBAAoB,CAAC;AAEzD,SAAS,UAAU,eAA2B;AAC7C,QAAM,QAAQ,OAAO,WAAW,YAAY;AAC5C,QAAM,iBAAiB,UAAU,aAAa;AAC9C,SAAO,MAAM,MAAM,oBAAoB,UAAU,aAAa;AAC/D;AAUO,SAAS,cAAuB;AACtC,SAAO;AAAA,IACN;AAAA,IACA,MAAM,OAAO,WAAW,YAAY,EAAE;AAAA,IACtC,MAAM;AAAA,EACP;AACD;",
6
+ "names": []
7
+ }
@@ -0,0 +1,39 @@
1
+ // src/hooks/use-debounce.ts
2
+ import { useEffect, useRef, useState } from "react";
3
+ function useDebounce(callback, delay) {
4
+ const timeoutRef = useRef(void 0);
5
+ const callbackRef = useRef(callback);
6
+ useEffect(() => {
7
+ callbackRef.current = callback;
8
+ }, [callback]);
9
+ useEffect(() => {
10
+ return () => {
11
+ if (timeoutRef.current) {
12
+ clearTimeout(timeoutRef.current);
13
+ }
14
+ };
15
+ }, []);
16
+ return (...args) => {
17
+ if (timeoutRef.current) {
18
+ clearTimeout(timeoutRef.current);
19
+ }
20
+ timeoutRef.current = setTimeout(() => {
21
+ callbackRef.current(...args);
22
+ }, delay);
23
+ };
24
+ }
25
+ function useDebouncedValue(value, delay) {
26
+ const [debouncedValue, setDebouncedValue] = useState(value);
27
+ useEffect(() => {
28
+ const timeoutId = setTimeout(() => {
29
+ setDebouncedValue(value);
30
+ }, delay);
31
+ return () => clearTimeout(timeoutId);
32
+ }, [value, delay]);
33
+ return debouncedValue;
34
+ }
35
+
36
+ export {
37
+ useDebounce,
38
+ useDebouncedValue
39
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/hooks/use-debounce.ts"],
4
+ "sourcesContent": ["import { useEffect, useRef, useState } from 'react';\n\n/**\n * A hook that debounces function calls\n * @param callback - The function to debounce\n * @param delay - The delay in milliseconds\n * @returns A debounced version of the callback\n */\nexport function useDebounce<T extends (...args: any[]) => void>(\n\tcallback: T,\n\tdelay: number,\n): (...args: Parameters<T>) => void {\n\tconst timeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n\tconst callbackRef = useRef(callback);\n\n\tuseEffect(() => {\n\t\tcallbackRef.current = callback;\n\t}, [callback]);\n\n\tuseEffect(() => {\n\t\treturn () => {\n\t\t\tif (timeoutRef.current) {\n\t\t\t\tclearTimeout(timeoutRef.current);\n\t\t\t}\n\t\t};\n\t}, []);\n\n\treturn (...args: Parameters<T>) => {\n\t\tif (timeoutRef.current) {\n\t\t\tclearTimeout(timeoutRef.current);\n\t\t}\n\n\t\ttimeoutRef.current = setTimeout(() => {\n\t\t\tcallbackRef.current(...args);\n\t\t}, delay);\n\t};\n}\n\n/**\n * A hook that debounces a value\n * @param value - The value to debounce\n * @param delay - The delay in milliseconds\n * @returns The debounced value\n */\nexport function useDebouncedValue<T>(value: T, delay: number): T {\n\tconst [debouncedValue, setDebouncedValue] = useState(value);\n\n\tuseEffect(() => {\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\tsetDebouncedValue(value);\n\t\t}, delay);\n\n\t\treturn () => clearTimeout(timeoutId);\n\t}, [value, delay]);\n\n\treturn debouncedValue;\n}\n"],
5
+ "mappings": ";AAAA,SAAS,WAAW,QAAQ,gBAAgB;AAQrC,SAAS,YACf,UACA,OACmC;AACnC,QAAM,aAAa,OAAkD,MAAS;AAC9E,QAAM,cAAc,OAAO,QAAQ;AAEnC,YAAU,MAAM;AACf,gBAAY,UAAU;AAAA,EACvB,GAAG,CAAC,QAAQ,CAAC;AAEb,YAAU,MAAM;AACf,WAAO,MAAM;AACZ,UAAI,WAAW,SAAS;AACvB,qBAAa,WAAW,OAAO;AAAA,MAChC;AAAA,IACD;AAAA,EACD,GAAG,CAAC,CAAC;AAEL,SAAO,IAAI,SAAwB;AAClC,QAAI,WAAW,SAAS;AACvB,mBAAa,WAAW,OAAO;AAAA,IAChC;AAEA,eAAW,UAAU,WAAW,MAAM;AACrC,kBAAY,QAAQ,GAAG,IAAI;AAAA,IAC5B,GAAG,KAAK;AAAA,EACT;AACD;AAQO,SAAS,kBAAqB,OAAU,OAAkB;AAChE,QAAM,CAAC,gBAAgB,iBAAiB,IAAI,SAAS,KAAK;AAE1D,YAAU,MAAM;AACf,UAAM,YAAY,WAAW,MAAM;AAClC,wBAAkB,KAAK;AAAA,IACxB,GAAG,KAAK;AAER,WAAO,MAAM,aAAa,SAAS;AAAA,EACpC,GAAG,CAAC,OAAO,KAAK,CAAC;AAEjB,SAAO;AACR;",
6
+ "names": []
7
+ }
@@ -0,0 +1,56 @@
1
+ import {
2
+ useFormStateContext
3
+ } from "./chunk-ZWEYALBG.js";
4
+ import {
5
+ FormEngineContext
6
+ } from "./chunk-GH2QO3WC.js";
7
+
8
+ // src/hooks/use-form-context.ts
9
+ import { useContext, useMemo, useSyncExternalStore } from "react";
10
+ import { GRID_CLASS, getDefaultLayoutTheme, getGridVariables } from "@schema-engine/layout";
11
+ function useFormInstanceActions() {
12
+ const { runtime } = useFormStateContext();
13
+ const { current, navigating, steps } = useSyncExternalStore(
14
+ runtime.subscribe,
15
+ runtime.getSnapshot,
16
+ runtime.getServerSnapshot
17
+ );
18
+ return useMemo(
19
+ () => ({ current, steps, navigating, next: runtime.next, back: runtime.back, goTo: runtime.goTo }),
20
+ [runtime, current, navigating, steps]
21
+ );
22
+ }
23
+ function useFormRuntime() {
24
+ return useFormStateContext().runtime;
25
+ }
26
+ function useFormEngine() {
27
+ const context = useContext(FormEngineContext);
28
+ if (!context) {
29
+ throw new Error("useFormEngine must be used within a FormEngineProvider");
30
+ }
31
+ return context;
32
+ }
33
+ function useOptionalFormEngine() {
34
+ const context = useContext(FormEngineContext);
35
+ return context ? context : null;
36
+ }
37
+ function useLayoutThemeId() {
38
+ return (useOptionalFormEngine()?.engine.getLayout() ?? getDefaultLayoutTheme()).id;
39
+ }
40
+ function useChildGridProps(elements) {
41
+ const layout = useOptionalFormEngine()?.engine.getLayout() ?? getDefaultLayoutTheme();
42
+ return {
43
+ className: `se-form-grid ${GRID_CLASS}`,
44
+ "data-se-theme": layout.id,
45
+ style: getGridVariables(void 0, layout.grid, elements)
46
+ };
47
+ }
48
+
49
+ export {
50
+ useFormInstanceActions,
51
+ useFormRuntime,
52
+ useFormEngine,
53
+ useOptionalFormEngine,
54
+ useLayoutThemeId,
55
+ useChildGridProps
56
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/hooks/use-form-context.ts"],
4
+ "sourcesContent": ["import { useContext, useMemo, useSyncExternalStore } from 'react';\nimport type { FormRuntime, FormStepState, EngineOutputMaps } from '@schema-engine/forms';\nimport { useFormStateContext } from './form-state/context';\nimport { GRID_CLASS, getDefaultLayoutTheme, getGridVariables, type CssVariables } from '@schema-engine/layout';\nimport { FormEngineContext } from '../components/provider';\nimport type { FormEngineContextValue } from '../components/provider';\n\n/**\n * What a component reads of the form's wizard: where it is, and the commands that move it.\n *\n * @remarks\n * The commands are those of the form's runtime and end with an outcome (`'moved'`, `'invalid'`, `'busy'`, ...). `steps` lists every\n * step in order with `skipped`, `visited`, `complete` and `invalid`; a skipped step is passed over by `next` and `back` and refused by `goTo`.\n */\nexport interface FormInstanceContextValue {\n\t/** The id of the current step. */\n\tcurrent: string;\n\tsteps: readonly FormStepState[];\n\t/** A `next`, `back` or `goTo` runs. */\n\tnavigating: boolean;\n\tnext: FormRuntime['next'];\n\tback: FormRuntime['back'];\n\tgoTo: FormRuntime['goTo'];\n}\n\n/**\n * Hook to access the form's wizard state and navigation\n * Must be used within a FormProvider\n */\nexport function useFormInstanceActions(): FormInstanceContextValue {\n\tconst { runtime } = useFormStateContext();\n\tconst { current, navigating, steps } = useSyncExternalStore(\n\t\truntime.subscribe,\n\t\truntime.getSnapshot,\n\t\truntime.getServerSnapshot,\n\t);\n\treturn useMemo(\n\t\t() => ({ current, steps, navigating, next: runtime.next, back: runtime.back, goTo: runtime.goTo }),\n\t\t[runtime, current, navigating, steps],\n\t);\n}\n\n/**\n * The form's runtime: its container, its submission and its wizard, for what takes a form over whole, such as `registerFormAgentTool`.\n *\n * @remarks\n * Must be used within a FormProvider. A new config or engine starts a new runtime, and the provider's children remount with it, so an effect that registers it runs again.\n */\nexport function useFormRuntime(): FormRuntime {\n\treturn useFormStateContext().runtime;\n}\n\n/**\n * Hook to access the form engine context\n * Must be used within a FormEngineProvider\n */\nexport function useFormEngine<\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>(): FormEngineContextValue<TElements, TRecipes, TActions, TOutputs> {\n\tconst context = useContext(FormEngineContext);\n\tif (!context) {\n\t\tthrow new Error('useFormEngine must be used within a FormEngineProvider');\n\t}\n\treturn context as unknown as FormEngineContextValue<TElements, TRecipes, TActions, TOutputs>;\n}\n\nexport function useOptionalFormEngine<\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>(): FormEngineContextValue<TElements, TRecipes, TActions, TOutputs> | null {\n\tconst context = useContext(FormEngineContext);\n\treturn context ? (context as unknown as FormEngineContextValue<TElements, TRecipes, TActions, TOutputs>) : null;\n}\n\n/**\n * Id of the layout theme that owns the field being rendered.\n *\n * @remarks\n * Field hosts set `data-se-theme` to this value so the engine's generated\n * stylesheet matches them and nested grids stay isolated. Single resolver for\n * the React renderer \u2014 the engine context is the only source, with the library\n * default for hosts rendered outside a `FormEngineProvider`.\n */\nexport function useLayoutThemeId(): string {\n\treturn (useOptionalFormEngine()?.engine.getLayout() ?? getDefaultLayoutTheme()).id;\n}\n\n/**\n * Props that make an element's children a grid of their own.\n *\n * @remarks\n * A container (a fieldset, an array row) lays its direct children out in a grid\n * the way a step does: spread the result on the wrapper of its `FormElements`.\n * The grid takes twelve tracks when a child sets `width` or `offset`, and\n * otherwise stays the engine's single column. The theme comes from the engine\n * context, with the library default outside a `FormEngineProvider`.\n */\nexport function useChildGridProps(elements: readonly unknown[]): {\n\tclassName: string;\n\t'data-se-theme': string;\n\tstyle: CssVariables;\n} {\n\tconst layout = useOptionalFormEngine()?.engine.getLayout() ?? getDefaultLayoutTheme();\n\treturn {\n\t\tclassName: `se-form-grid ${GRID_CLASS}`,\n\t\t'data-se-theme': layout.id,\n\t\tstyle: getGridVariables(undefined, layout.grid, elements),\n\t};\n}\n"],
5
+ "mappings": ";;;;;;;;AAAA,SAAS,YAAY,SAAS,4BAA4B;AAG1D,SAAS,YAAY,uBAAuB,wBAA2C;AA0BhF,SAAS,yBAAmD;AAClE,QAAM,EAAE,QAAQ,IAAI,oBAAoB;AACxC,QAAM,EAAE,SAAS,YAAY,MAAM,IAAI;AAAA,IACtC,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,EACT;AACA,SAAO;AAAA,IACN,OAAO,EAAE,SAAS,OAAO,YAAY,MAAM,QAAQ,MAAM,MAAM,QAAQ,MAAM,MAAM,QAAQ,KAAK;AAAA,IAChG,CAAC,SAAS,SAAS,YAAY,KAAK;AAAA,EACrC;AACD;AAQO,SAAS,iBAA8B;AAC7C,SAAO,oBAAoB,EAAE;AAC9B;AAMO,SAAS,gBAKqD;AACpE,QAAM,UAAU,WAAW,iBAAiB;AAC5C,MAAI,CAAC,SAAS;AACb,UAAM,IAAI,MAAM,wDAAwD;AAAA,EACzE;AACA,SAAO;AACR;AAEO,SAAS,wBAK4D;AAC3E,QAAM,UAAU,WAAW,iBAAiB;AAC5C,SAAO,UAAW,UAAyF;AAC5G;AAWO,SAAS,mBAA2B;AAC1C,UAAQ,sBAAsB,GAAG,OAAO,UAAU,KAAK,sBAAsB,GAAG;AACjF;AAYO,SAAS,kBAAkB,UAIhC;AACD,QAAM,SAAS,sBAAsB,GAAG,OAAO,UAAU,KAAK,sBAAsB;AACpF,SAAO;AAAA,IACN,WAAW,gBAAgB,UAAU;AAAA,IACrC,iBAAiB,OAAO;AAAA,IACxB,OAAO,iBAAiB,QAAW,OAAO,MAAM,QAAQ;AAAA,EACzD;AACD;",
6
+ "names": []
7
+ }
@@ -0,0 +1,128 @@
1
+ import {
2
+ fieldText
3
+ } from "./chunk-H25SUEJE.js";
4
+
5
+ // src/hooks/form-state/native-control.ts
6
+ function isNativeControl(element) {
7
+ return element instanceof HTMLInputElement || element instanceof HTMLSelectElement || element instanceof HTMLTextAreaElement;
8
+ }
9
+ var isInput = (control, type) => control instanceof HTMLInputElement && control.type === type;
10
+ var hasValueAttribute = (control) => control.hasAttribute("value");
11
+ var isMultipleSelect = (control) => control instanceof HTMLSelectElement && control.multiple;
12
+ var asList = (value) => Array.isArray(value) ? value.map(String) : [];
13
+ function asNumber(value) {
14
+ if (typeof value === "number") return value;
15
+ return typeof value === "string" && value.trim() !== "" ? Number(value) : Number.NaN;
16
+ }
17
+ var isEmptyFiles = (value) => value === void 0 || value === null || asList(value).length === 0;
18
+ function readControl(control, current) {
19
+ if (isInput(control, "checkbox")) {
20
+ if (!hasValueAttribute(control)) return control.checked;
21
+ const others = asList(current).filter((item) => item !== control.value);
22
+ return control.checked ? [...others, control.value] : others;
23
+ }
24
+ if (isInput(control, "radio")) return control.checked ? control.value : current;
25
+ if (isInput(control, "number")) return Number.isNaN(control.valueAsNumber) ? void 0 : control.valueAsNumber;
26
+ if (isInput(control, "file")) return Array.from(control.files ?? []);
27
+ if (isMultipleSelect(control)) return Array.from(control.selectedOptions, (option) => option.value);
28
+ return control.value;
29
+ }
30
+ function controlMatches(control, value) {
31
+ if (isInput(control, "checkbox")) {
32
+ return control.checked === (hasValueAttribute(control) ? asList(value).includes(control.value) : Boolean(value));
33
+ }
34
+ if (isInput(control, "radio"))
35
+ return control.checked === (fieldText(value) !== "" && control.value === fieldText(value));
36
+ if (isInput(control, "number")) {
37
+ const expected = asNumber(value);
38
+ return Number.isNaN(expected) ? control.value === "" : control.valueAsNumber === expected;
39
+ }
40
+ if (isInput(control, "file")) return !isEmptyFiles(value) || (control.files?.length ?? 0) === 0;
41
+ if (isMultipleSelect(control)) {
42
+ const selected = asList(value);
43
+ return Array.from(control.options).every((option) => option.selected === selected.includes(option.value));
44
+ }
45
+ return control.value === fieldText(value);
46
+ }
47
+ function writeControl(control, value) {
48
+ if (isInput(control, "checkbox")) {
49
+ control.checked = hasValueAttribute(control) ? asList(value).includes(control.value) : Boolean(value);
50
+ } else if (isInput(control, "radio")) {
51
+ control.checked = fieldText(value) !== "" && control.value === fieldText(value);
52
+ } else if (isInput(control, "number")) {
53
+ const expected = asNumber(value);
54
+ control.value = Number.isNaN(expected) ? "" : String(expected);
55
+ } else if (isInput(control, "file")) {
56
+ control.value = "";
57
+ } else if (isMultipleSelect(control)) {
58
+ const selected = asList(value);
59
+ Array.from(control.options).forEach((option) => {
60
+ option.selected = selected.includes(option.value);
61
+ });
62
+ } else {
63
+ control.value = fieldText(value);
64
+ }
65
+ }
66
+ function sameValue(left, right) {
67
+ if (Array.isArray(left) && Array.isArray(right)) {
68
+ return left.length === right.length && left.every((item, index) => Object.is(item, right[index]));
69
+ }
70
+ return Object.is(left, right);
71
+ }
72
+ var FLAGS = [
73
+ "valueMissing",
74
+ "typeMismatch",
75
+ "patternMismatch",
76
+ "tooLong",
77
+ "tooShort",
78
+ "rangeUnderflow",
79
+ "rangeOverflow",
80
+ "stepMismatch",
81
+ "badInput",
82
+ "customError"
83
+ ];
84
+ function flagParams(flag, control) {
85
+ const bound = (input, value) => {
86
+ const numeric = input.type === "number" || input.type === "range";
87
+ return numeric && value !== "" ? Number(value) : value;
88
+ };
89
+ switch (flag) {
90
+ case "tooShort":
91
+ return control instanceof HTMLSelectElement ? void 0 : { minLength: control.minLength };
92
+ case "tooLong":
93
+ return control instanceof HTMLSelectElement ? void 0 : { maxLength: control.maxLength };
94
+ case "rangeUnderflow":
95
+ return control instanceof HTMLInputElement ? { min: bound(control, control.min) } : void 0;
96
+ case "rangeOverflow":
97
+ return control instanceof HTMLInputElement ? { max: bound(control, control.max) } : void 0;
98
+ case "patternMismatch":
99
+ return control instanceof HTMLInputElement ? { pattern: control.pattern } : void 0;
100
+ case "stepMismatch":
101
+ return control instanceof HTMLInputElement ? { step: bound(control, control.step) } : void 0;
102
+ case "typeMismatch":
103
+ return { inputType: control.type };
104
+ default:
105
+ return void 0;
106
+ }
107
+ }
108
+ function readNativeFact(control) {
109
+ if (!control.willValidate) return null;
110
+ const { validity, validationMessage } = control;
111
+ if (validity.valid) return null;
112
+ const flag = FLAGS.find((name) => validity[name]) ?? "customError";
113
+ const params = flagParams(flag, control);
114
+ return {
115
+ type: flag,
116
+ ...params && { params },
117
+ ...validationMessage && { message: validationMessage }
118
+ };
119
+ }
120
+
121
+ export {
122
+ isNativeControl,
123
+ readControl,
124
+ controlMatches,
125
+ writeControl,
126
+ sameValue,
127
+ readNativeFact
128
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/hooks/form-state/native-control.ts"],
4
+ "sourcesContent": ["import type { NativeValidity } from '@schema-engine/forms/state-container';\nimport { fieldText } from '../field-text';\n\n/** The elements the browser validates and holds a value for. */\nexport type NativeControl = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;\n\nexport function isNativeControl(element: HTMLElement): element is NativeControl {\n\treturn (\n\t\telement instanceof HTMLInputElement ||\n\t\telement instanceof HTMLSelectElement ||\n\t\telement instanceof HTMLTextAreaElement\n\t);\n}\n\nconst isInput = (control: NativeControl, type: string): control is HTMLInputElement =>\n\tcontrol instanceof HTMLInputElement && control.type === type;\n\nconst hasValueAttribute = (control: NativeControl): boolean => control.hasAttribute('value');\n\nconst isMultipleSelect = (control: NativeControl): control is HTMLSelectElement =>\n\tcontrol instanceof HTMLSelectElement && control.multiple;\n\nconst asList = (value: unknown): readonly string[] => (Array.isArray(value) ? value.map(String) : []);\n\n/** The number a container value stands for in a number input, or `NaN` when it is empty or not a number. */\nfunction asNumber(value: unknown): number {\n\tif (typeof value === 'number') return value;\n\treturn typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN;\n}\n\nconst isEmptyFiles = (value: unknown): boolean => value === undefined || value === null || asList(value).length === 0;\n\n/**\n * What the control holds, as the container's value for it.\n *\n * @remarks\n * `current` is the container's value for the path, which a choice that does not decide the whole value keeps:\n * a checkbox with a `value` attribute adds or removes its own value in a list, and a radio that is not the\n * checked one leaves the value as it is.\n */\nexport function readControl(control: NativeControl, current: unknown): unknown {\n\tif (isInput(control, 'checkbox')) {\n\t\tif (!hasValueAttribute(control)) return control.checked;\n\t\tconst others = asList(current).filter((item) => item !== control.value);\n\t\treturn control.checked ? [...others, control.value] : others;\n\t}\n\tif (isInput(control, 'radio')) return control.checked ? control.value : current;\n\tif (isInput(control, 'number')) return Number.isNaN(control.valueAsNumber) ? undefined : control.valueAsNumber;\n\tif (isInput(control, 'file')) return Array.from(control.files ?? []);\n\tif (isMultipleSelect(control)) return Array.from(control.selectedOptions, (option) => option.value);\n\treturn control.value;\n}\n\n/**\n * Whether reading the control would already give `value`.\n *\n * @remarks\n * It compares what the control shows with what the container holds and never rewrites text the user is\n * typing: a number input with `badInput` reports an empty value, so it matches an empty container value and\n * keeps its text, and a control that echoes its own change matches too, so the cursor and an IME\n * composition are left alone. A file input can only be cleared, so a value that is not empty matches.\n */\nexport function controlMatches(control: NativeControl, value: unknown): boolean {\n\tif (isInput(control, 'checkbox')) {\n\t\treturn (\n\t\t\tcontrol.checked === (hasValueAttribute(control) ? asList(value).includes(control.value) : Boolean(value))\n\t\t);\n\t}\n\tif (isInput(control, 'radio'))\n\t\treturn control.checked === (fieldText(value) !== '' && control.value === fieldText(value));\n\tif (isInput(control, 'number')) {\n\t\tconst expected = asNumber(value);\n\t\treturn Number.isNaN(expected) ? control.value === '' : control.valueAsNumber === expected;\n\t}\n\tif (isInput(control, 'file')) return !isEmptyFiles(value) || (control.files?.length ?? 0) === 0;\n\tif (isMultipleSelect(control)) {\n\t\tconst selected = asList(value);\n\t\treturn Array.from(control.options).every((option) => option.selected === selected.includes(option.value));\n\t}\n\treturn control.value === fieldText(value);\n}\n\n/** Makes the control show `value`: the counterpart of {@link readControl}, written outside React. */\nexport function writeControl(control: NativeControl, value: unknown): void {\n\tif (isInput(control, 'checkbox')) {\n\t\tcontrol.checked = hasValueAttribute(control) ? asList(value).includes(control.value) : Boolean(value);\n\t} else if (isInput(control, 'radio')) {\n\t\tcontrol.checked = fieldText(value) !== '' && control.value === fieldText(value);\n\t} else if (isInput(control, 'number')) {\n\t\tconst expected = asNumber(value);\n\t\tcontrol.value = Number.isNaN(expected) ? '' : String(expected);\n\t} else if (isInput(control, 'file')) {\n\t\tcontrol.value = '';\n\t} else if (isMultipleSelect(control)) {\n\t\tconst selected = asList(value);\n\t\tArray.from(control.options).forEach((option) => {\n\t\t\toption.selected = selected.includes(option.value);\n\t\t});\n\t} else {\n\t\tcontrol.value = fieldText(value);\n\t}\n}\n\n/** Whether two values read from a control are the same, an array by its items. */\nexport function sameValue(left: unknown, right: unknown): boolean {\n\tif (Array.isArray(left) && Array.isArray(right)) {\n\t\treturn left.length === right.length && left.every((item, index) => Object.is(item, right[index]));\n\t}\n\treturn Object.is(left, right);\n}\n\n/** The `ValidityState` flags a control reports, in the order the first one that is set is the fact. */\nconst FLAGS = [\n\t'valueMissing',\n\t'typeMismatch',\n\t'patternMismatch',\n\t'tooLong',\n\t'tooShort',\n\t'rangeUnderflow',\n\t'rangeOverflow',\n\t'stepMismatch',\n\t'badInput',\n\t'customError',\n] as const;\n\ntype Flag = (typeof FLAGS)[number];\n\n/**\n * The constraint behind a flag that a text needs, from the properties the control carries.\n *\n * @remarks\n * `min`, `max` and `step` are numbers on a number or range input and the attribute's own text on any other type\n * (a date), as they are in `rui-form`.\n */\nfunction flagParams(flag: Flag, control: NativeControl): Readonly<Record<string, unknown>> | undefined {\n\tconst bound = (input: HTMLInputElement, value: string): string | number => {\n\t\tconst numeric = input.type === 'number' || input.type === 'range';\n\t\treturn numeric && value !== '' ? Number(value) : value;\n\t};\n\tswitch (flag) {\n\t\tcase 'tooShort':\n\t\t\treturn control instanceof HTMLSelectElement ? undefined : { minLength: control.minLength };\n\t\tcase 'tooLong':\n\t\t\treturn control instanceof HTMLSelectElement ? undefined : { maxLength: control.maxLength };\n\t\tcase 'rangeUnderflow':\n\t\t\treturn control instanceof HTMLInputElement ? { min: bound(control, control.min) } : undefined;\n\t\tcase 'rangeOverflow':\n\t\t\treturn control instanceof HTMLInputElement ? { max: bound(control, control.max) } : undefined;\n\t\tcase 'patternMismatch':\n\t\t\treturn control instanceof HTMLInputElement ? { pattern: control.pattern } : undefined;\n\t\tcase 'stepMismatch':\n\t\t\treturn control instanceof HTMLInputElement ? { step: bound(control, control.step) } : undefined;\n\t\tcase 'typeMismatch':\n\t\t\treturn { inputType: control.type };\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * What the browser says about the control's value, as the container's native fact, or `null` when it is valid.\n *\n * @remarks\n * The same fact `rui-form` of Radiant UI reports for the same control state, so a form validates alike in both\n * renderers: the first flag set, in the order of {@link FLAGS}, is the `type`, `params` carry the constraint the flag names,\n * and a control that is invalid with no flag set, or whose script called `setCustomValidity`, is a\n * `customError` whose `message` is the script's text. A control the browser does not validate (disabled,\n * read-only, hidden) reports valid. The browser's own message travels only as a fallback, since the form's\n * formatter words the issue. Reads properties and never calls `checkValidity()`, which fires `invalid`.\n */\nexport function readNativeFact(control: NativeControl): NativeValidity | null {\n\tif (!control.willValidate) return null;\n\tconst { validity, validationMessage } = control;\n\tif (validity.valid) return null;\n\tconst flag = FLAGS.find((name) => validity[name]) ?? 'customError';\n\tconst params = flagParams(flag, control);\n\treturn {\n\t\ttype: flag,\n\t\t...(params && { params }),\n\t\t...(validationMessage && { message: validationMessage }),\n\t};\n}\n"],
5
+ "mappings": "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",
6
+ "names": []
7
+ }
@@ -0,0 +1,142 @@
1
+ import {
2
+ isElementRequired
3
+ } from "./chunk-EYDB6NR6.js";
4
+ import {
5
+ logger
6
+ } from "./chunk-XWHP2AGG.js";
7
+ import {
8
+ useOptionalFormEngine
9
+ } from "./chunk-AALIXTCD.js";
10
+ import {
11
+ useContainerSelector,
12
+ useFormStateContext
13
+ } from "./chunk-ZWEYALBG.js";
14
+
15
+ // src/hooks/form-state/use-form-field.ts
16
+ import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
17
+ import { mergeControlProps, createDefaultValidationRegistry } from "@schema-engine/forms";
18
+ import { issueText, selectFieldState, selectValue } from "@schema-engine/forms/state-container";
19
+ import { getGridItemVariables } from "@schema-engine/layout";
20
+ var fallbackValidationRegistry;
21
+ function getFallbackValidationRegistry() {
22
+ fallbackValidationRegistry ??= createDefaultValidationRegistry();
23
+ return fallbackValidationRegistry;
24
+ }
25
+ function useFieldStatus(path) {
26
+ const { formatIssue } = useFormStateContext();
27
+ const { error, warning, invalid, isTouched, isDirty, isValidating } = useContainerSelector(
28
+ (snapshot) => selectFieldState(snapshot, path)
29
+ );
30
+ return {
31
+ error: error && issueText(error, path, formatIssue),
32
+ warning: warning && issueText(warning, path, formatIssue),
33
+ issue: error,
34
+ invalid,
35
+ isTouched,
36
+ isDirty,
37
+ isValidating
38
+ };
39
+ }
40
+ var noValue = () => void 0;
41
+ function useControlledValue(path, controlled) {
42
+ return useContainerSelector(controlled ? (snapshot) => selectValue(snapshot, path) : noValue);
43
+ }
44
+ var subscribeNever = () => () => void 0;
45
+ function useDefaultValue(path) {
46
+ const { container } = useFormStateContext();
47
+ const first = useSyncExternalStore(
48
+ subscribeNever,
49
+ () => selectValue(container.getSnapshot(), path),
50
+ () => selectValue(container.getServerSnapshot(), path)
51
+ );
52
+ return useState(first)[0];
53
+ }
54
+ function useFieldRef(path, controlled, rendered) {
55
+ const { fields } = useFormStateContext();
56
+ return useCallback(
57
+ (element) => element ? fields.register(
58
+ path,
59
+ element,
60
+ controlled ? { mode: "controlled" } : { mode: "uncontrolled", rendered }
61
+ ) : void 0,
62
+ [fields, path, controlled, rendered]
63
+ );
64
+ }
65
+ function useNativeBinding(path, controlled, bound) {
66
+ const { fields } = useFormStateContext();
67
+ useEffect(() => {
68
+ if (bound) fields.reportNative(path);
69
+ });
70
+ useEffect(() => {
71
+ if (!bound || controlled || true) return;
72
+ const { registered, native } = fields.inspect(path);
73
+ if (registered && !native) {
74
+ logger.warn(
75
+ `The field "${path}" is uncontrolled but its ref is not on an input, select or textarea. Use useFormField(config, { controlled: true }) for a component that takes value and onChange.`
76
+ );
77
+ }
78
+ }, [fields, path, controlled, bound]);
79
+ }
80
+ function useFieldRequired(config) {
81
+ const { required: constraintRequired } = useContainerSelector(
82
+ (snapshot) => selectFieldState(snapshot, config?.name ?? "")
83
+ );
84
+ const engineContext = useOptionalFormEngine();
85
+ const registry = useMemo(
86
+ () => engineContext?.engine.getValidationRegistry() ?? getFallbackValidationRegistry(),
87
+ [engineContext]
88
+ );
89
+ return constraintRequired || config !== void 0 && isElementRequired(config, registry);
90
+ }
91
+ function useFormField(target, options) {
92
+ const config = typeof target === "string" ? void 0 : target;
93
+ if (config && !config.name) {
94
+ throw new Error(`Field configuration is missing required "name" property. Config: ${JSON.stringify(config)}`);
95
+ }
96
+ const path = typeof target === "string" ? target : target.name;
97
+ const controlled = options?.controlled === true;
98
+ const { container, fields } = useFormStateContext();
99
+ const status = useFieldStatus(path);
100
+ const required = useFieldRequired(config);
101
+ const value = useControlledValue(path, controlled);
102
+ const defaultValue = useDefaultValue(path);
103
+ useNativeBinding(path, controlled, config !== void 0);
104
+ const ref = useFieldRef(path, controlled, defaultValue);
105
+ const onNativeChange = useCallback(
106
+ (event) => fields.change(path, event.currentTarget),
107
+ [fields, path]
108
+ );
109
+ const onNativeBlur = useCallback(() => fields.blur(path), [fields, path]);
110
+ const onValueChange = useCallback((next) => container.setValue(path, next), [container, path]);
111
+ if (!config) return status;
112
+ const disabled = Boolean(config.disabled);
113
+ const control = mergeControlProps(
114
+ {
115
+ id: config.id,
116
+ name: path,
117
+ required,
118
+ disabled,
119
+ readOnly: config.readonly,
120
+ ref,
121
+ "aria-invalid": status.invalid,
122
+ "aria-describedby": status.error ? `${config.id}-error` : void 0
123
+ },
124
+ config.htmlAttributes
125
+ );
126
+ const element = {
127
+ ...status,
128
+ required,
129
+ disabled,
130
+ labelProps: { htmlFor: config.id },
131
+ errorProps: status.error ? { id: `${config.id}-error`, role: "alert" } : null,
132
+ containerStyles: { ...getGridItemVariables(config.grid), ...config.style }
133
+ };
134
+ if (controlled) {
135
+ return { ...element, value, onChange: onValueChange, onBlur: onNativeBlur, fieldProps: control };
136
+ }
137
+ return { ...element, defaultValue, fieldProps: { ...control, onChange: onNativeChange, onBlur: onNativeBlur } };
138
+ }
139
+
140
+ export {
141
+ useFormField
142
+ };