@contractspec/lib.contracts-runtime-client-react 3.8.5 → 3.8.6

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.
@@ -1,362 +1,2 @@
1
1
  // @bun
2
- var __require = import.meta.require;
3
-
4
- // src/form-render.impl.tsx
5
- import {
6
- buildZodWithRelations,
7
- evalPredicate
8
- } from "@contractspec/lib.contracts-spec/forms";
9
- import { zodResolver } from "@hookform/resolvers/zod";
10
- import React, { useEffect, useMemo, useState } from "react";
11
- import {
12
- Controller,
13
- useFieldArray,
14
- useForm
15
- } from "react-hook-form";
16
- import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
17
- "use client";
18
- function toOptionsArray(src) {
19
- if (!src)
20
- return;
21
- if (Array.isArray(src))
22
- return { kind: "static", options: src };
23
- return src;
24
- }
25
- function getAtPath(values, path) {
26
- if (!path)
27
- return;
28
- const segs = path.replace(/\[(\d+)\]/g, ".$1").split(".").filter(Boolean);
29
- let cur = values;
30
- for (const s of segs) {
31
- if (cur == null)
32
- return;
33
- cur = cur[s];
34
- }
35
- return cur;
36
- }
37
- function makeDepsKey(values, deps) {
38
- if (!deps || deps.length === 0)
39
- return "[]";
40
- try {
41
- return JSON.stringify(deps.map((d) => getAtPath(values, d)));
42
- } catch {
43
- return "[]";
44
- }
45
- }
46
- function useResolvedOptions(values, source, resolvers) {
47
- const [opts, setOpts] = useState([]);
48
- const depKey = useMemo(() => {
49
- if (!source)
50
- return "nil";
51
- if (source.kind === "static")
52
- return JSON.stringify(source.options ?? []);
53
- return makeDepsKey(values, source.deps);
54
- }, [source, values]);
55
- useEffect(() => {
56
- let mounted = true;
57
- const run = async () => {
58
- if (!source)
59
- return setOpts([]);
60
- if (source.kind === "static")
61
- return setOpts([...source.options ?? []]);
62
- const fn = resolvers?.[source.resolverKey];
63
- if (!fn)
64
- return setOpts([]);
65
- const res = await fn(values, source.args);
66
- if (mounted)
67
- setOpts([...res ?? []]);
68
- };
69
- run();
70
- return () => {
71
- mounted = false;
72
- };
73
- }, [
74
- depKey,
75
- source && source.kind === "resolver" ? source.resolverKey : undefined
76
- ]);
77
- return opts;
78
- }
79
- function fieldPath(parent, name, arrayIndex) {
80
- if (!name)
81
- return parent ?? "";
82
- const child = typeof arrayIndex === "number" ? `${name.replace(/^\$index$/, String(arrayIndex))}` : name;
83
- return parent ? `${parent}${typeof arrayIndex === "number" ? `.${arrayIndex}` : ""}.${child}`.replace(/\.+/g, ".") : child;
84
- }
85
- function createFormRenderer(base) {
86
- const conf = base;
87
- const { driver } = conf;
88
- function InternalForm(props) {
89
- const { spec, options, merged } = props;
90
- const baseZod = useMemo(() => buildZodWithRelations(spec), [spec]);
91
- const form = useForm({
92
- ...merged.formOptions,
93
- resolver: zodResolver(baseZod),
94
- defaultValues: options?.defaultValues
95
- });
96
- const values = form.watch();
97
- const renderOne = (f, parent, arrayIndex) => {
98
- const DriverField = driver.Field;
99
- const DriverLabel = driver.FieldLabel;
100
- const DriverDesc = driver.FieldDescription;
101
- const DriverError = driver.FieldError;
102
- const name = fieldPath(parent, f.name, arrayIndex);
103
- const visible = evalPredicate(values, f.visibleWhen);
104
- const enabled = evalPredicate(values, f.enabledWhen);
105
- const invalid = Boolean(form.getFieldState(name)?.invalid);
106
- if (!visible)
107
- return null;
108
- const id = name?.replace(/\./g, "-");
109
- const commonWrapProps = {
110
- "data-invalid": invalid,
111
- hidden: !visible,
112
- disabled: !enabled
113
- };
114
- const labelNode = f.labelI18n ? /* @__PURE__ */ jsxDEV(DriverLabel, {
115
- htmlFor: id,
116
- children: f.labelI18n
117
- }, undefined, false, undefined, this) : null;
118
- const descNode = f.descriptionI18n ? /* @__PURE__ */ jsxDEV(DriverDesc, {
119
- children: f.descriptionI18n
120
- }, undefined, false, undefined, this) : null;
121
- if (f.kind === "group") {
122
- const children = f.fields.map((c, i) => /* @__PURE__ */ jsxDEV(React.Fragment, {
123
- children: renderOne(c, name, arrayIndex)
124
- }, `${name}-${i}`, false, undefined, this));
125
- return /* @__PURE__ */ jsxDEV(DriverField, {
126
- ...commonWrapProps,
127
- children: [
128
- labelNode,
129
- children,
130
- descNode
131
- ]
132
- }, undefined, true, undefined, this);
133
- }
134
- if (f.kind === "array") {
135
- return renderArray(f, parent);
136
- }
137
- return /* @__PURE__ */ jsxDEV(Controller, {
138
- name,
139
- control: form.control,
140
- render: ({ field, fieldState }) => {
141
- const err = fieldState.error ? [fieldState.error] : [];
142
- const ariaInvalid = fieldState.invalid || undefined;
143
- if (f.kind === "text") {
144
- const textField = f;
145
- const Input = driver.Input;
146
- return /* @__PURE__ */ jsxDEV(DriverField, {
147
- ...commonWrapProps,
148
- children: [
149
- labelNode,
150
- /* @__PURE__ */ jsxDEV(Input, {
151
- id,
152
- "aria-invalid": ariaInvalid,
153
- placeholder: f.placeholderI18n,
154
- autoComplete: textField.autoComplete,
155
- inputMode: textField.inputMode,
156
- maxLength: textField.maxLength,
157
- minLength: textField.minLength,
158
- disabled: !enabled,
159
- ...field,
160
- ...f.uiProps
161
- }, undefined, false, undefined, this),
162
- descNode,
163
- fieldState.invalid ? /* @__PURE__ */ jsxDEV(DriverError, {
164
- errors: err
165
- }, undefined, false, undefined, this) : null
166
- ]
167
- }, undefined, true, undefined, this);
168
- }
169
- if (f.kind === "textarea") {
170
- const textareaField = f;
171
- const Textarea = driver.Textarea;
172
- return /* @__PURE__ */ jsxDEV(DriverField, {
173
- ...commonWrapProps,
174
- children: [
175
- labelNode,
176
- /* @__PURE__ */ jsxDEV(Textarea, {
177
- id,
178
- "aria-invalid": ariaInvalid,
179
- placeholder: f.placeholderI18n,
180
- rows: textareaField.rows,
181
- maxLength: textareaField.maxLength,
182
- disabled: !enabled,
183
- ...field,
184
- ...f.uiProps
185
- }, undefined, false, undefined, this),
186
- descNode,
187
- fieldState.invalid ? /* @__PURE__ */ jsxDEV(DriverError, {
188
- errors: err
189
- }, undefined, false, undefined, this) : null
190
- ]
191
- }, undefined, true, undefined, this);
192
- }
193
- if (f.kind === "select") {
194
- const selectField = f;
195
- const Select = driver.Select;
196
- const src = toOptionsArray(selectField.options);
197
- const opts = useResolvedOptions(values, src, merged.resolvers);
198
- return /* @__PURE__ */ jsxDEV(DriverField, {
199
- ...commonWrapProps,
200
- children: [
201
- labelNode,
202
- /* @__PURE__ */ jsxDEV(Select, {
203
- id,
204
- name,
205
- "aria-invalid": ariaInvalid,
206
- disabled: !enabled,
207
- value: field.value,
208
- onChange: (v) => field.onChange(v),
209
- options: opts,
210
- ...f.uiProps
211
- }, undefined, false, undefined, this),
212
- descNode,
213
- fieldState.invalid ? /* @__PURE__ */ jsxDEV(DriverError, {
214
- errors: err
215
- }, undefined, false, undefined, this) : null
216
- ]
217
- }, undefined, true, undefined, this);
218
- }
219
- if (f.kind === "checkbox") {
220
- const Checkbox = driver.Checkbox;
221
- return /* @__PURE__ */ jsxDEV(DriverField, {
222
- ...commonWrapProps,
223
- children: [
224
- labelNode,
225
- /* @__PURE__ */ jsxDEV(Checkbox, {
226
- id,
227
- name,
228
- disabled: !enabled,
229
- checked: !!field.value,
230
- onCheckedChange: (v) => field.onChange(v),
231
- ...f.uiProps
232
- }, undefined, false, undefined, this),
233
- descNode,
234
- fieldState.invalid ? /* @__PURE__ */ jsxDEV(DriverError, {
235
- errors: err
236
- }, undefined, false, undefined, this) : null
237
- ]
238
- }, undefined, true, undefined, this);
239
- }
240
- if (f.kind === "radio") {
241
- const radioField = f;
242
- const RadioGroup = driver.RadioGroup;
243
- const src = toOptionsArray(radioField.options);
244
- const opts = useResolvedOptions(values, src, merged.resolvers);
245
- return /* @__PURE__ */ jsxDEV(DriverField, {
246
- ...commonWrapProps,
247
- children: [
248
- labelNode,
249
- /* @__PURE__ */ jsxDEV(RadioGroup, {
250
- id,
251
- name,
252
- disabled: !enabled,
253
- value: field.value,
254
- onValueChange: (v) => field.onChange(v),
255
- options: opts,
256
- ...f.uiProps
257
- }, undefined, false, undefined, this),
258
- descNode,
259
- fieldState.invalid ? /* @__PURE__ */ jsxDEV(DriverError, {
260
- errors: err
261
- }, undefined, false, undefined, this) : null
262
- ]
263
- }, undefined, true, undefined, this);
264
- }
265
- if (f.kind === "switch") {
266
- const Switch = driver.Switch;
267
- return /* @__PURE__ */ jsxDEV(DriverField, {
268
- ...commonWrapProps,
269
- children: [
270
- labelNode,
271
- /* @__PURE__ */ jsxDEV(Switch, {
272
- id,
273
- name,
274
- disabled: !enabled,
275
- checked: !!field.value,
276
- onCheckedChange: (v) => field.onChange(v),
277
- ...f.uiProps
278
- }, undefined, false, undefined, this),
279
- descNode,
280
- fieldState.invalid ? /* @__PURE__ */ jsxDEV(DriverError, {
281
- errors: err
282
- }, undefined, false, undefined, this) : null
283
- ]
284
- }, undefined, true, undefined, this);
285
- }
286
- return /* @__PURE__ */ jsxDEV(Fragment, {}, undefined, false, undefined, this);
287
- }
288
- }, name, false, undefined, this);
289
- };
290
- const renderArray = (f, parent) => {
291
- const name = fieldPath(parent, f.name);
292
- const { fields, append, remove } = useFieldArray({
293
- control: form.control,
294
- name
295
- });
296
- const canAdd = f.max == null || fields.length < f.max;
297
- const canRemove = (idx) => (f.min == null ? fields.length > 0 : fields.length > f.min) && idx >= 0;
298
- const Button2 = driver.Button;
299
- const Label = driver.FieldLabel;
300
- return /* @__PURE__ */ jsxDEV("div", {
301
- children: [
302
- f.labelI18n ? /* @__PURE__ */ jsxDEV(Label, {
303
- children: f.labelI18n
304
- }, undefined, false, undefined, this) : null,
305
- fields.map((row, idx) => /* @__PURE__ */ jsxDEV("div", {
306
- children: [
307
- renderOne(f.of, name, idx),
308
- canRemove(idx) ? /* @__PURE__ */ jsxDEV(Button2, {
309
- type: "button",
310
- variant: "ghost",
311
- size: "sm",
312
- onClick: () => remove(idx),
313
- children: "Remove"
314
- }, undefined, false, undefined, this) : null
315
- ]
316
- }, row.id ?? idx, true, undefined, this)),
317
- canAdd ? /* @__PURE__ */ jsxDEV(Button2, {
318
- type: "button",
319
- variant: "outline",
320
- size: "sm",
321
- onClick: () => append({}),
322
- children: "Add"
323
- }, undefined, false, undefined, this) : null
324
- ]
325
- }, name, true, undefined, this);
326
- };
327
- const onSubmit = async (data) => {
328
- const actionKey = spec.actions?.[0]?.key ?? "submit";
329
- if (merged.onSubmitOverride) {
330
- return merged.onSubmitOverride(data, actionKey);
331
- }
332
- };
333
- const Button = driver.Button;
334
- return /* @__PURE__ */ jsxDEV("form", {
335
- onSubmit: form.handleSubmit(onSubmit),
336
- children: [
337
- (spec.fields || []).map((f, i) => /* @__PURE__ */ jsxDEV(React.Fragment, {
338
- children: renderOne(f)
339
- }, i, false, undefined, this)),
340
- spec.actions && spec.actions.length ? /* @__PURE__ */ jsxDEV("div", {
341
- children: spec.actions.map((a) => /* @__PURE__ */ jsxDEV(Button, {
342
- type: "submit",
343
- children: a.labelI18n
344
- }, a.key, false, undefined, this))
345
- }, undefined, false, undefined, this) : null
346
- ]
347
- }, undefined, true, undefined, this);
348
- }
349
- return {
350
- render: (spec, options) => /* @__PURE__ */ jsxDEV(InternalForm, {
351
- spec,
352
- options,
353
- merged: {
354
- ...conf,
355
- ...options?.overrides ?? {}
356
- }
357
- }, undefined, false, undefined, this)
358
- };
359
- }
360
- export {
361
- createFormRenderer
362
- };
2
+ var Qq=import.meta.require;import{buildZodWithRelations as o,evalPredicate as u}from"@contractspec/lib.contracts-spec/forms";import{zodResolver as i}from"@hookform/resolvers/zod";import x,{useEffect as a,useMemo as n,useState as d}from"react";import{Controller as s,useFieldArray as r,useForm as e}from"react-hook-form";import{jsx as Q,jsxs as M,Fragment as Jq}from"react/jsx-runtime";function v(U){if(!U)return;if(Array.isArray(U))return{kind:"static",options:U};return U}function qq(U,H){if(!H)return;let J=H.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean),T=U;for(let L of J){if(T==null)return;T=T[L]}return T}function Hq(U,H){if(!H||H.length===0)return"[]";try{return JSON.stringify(H.map((J)=>qq(U,J)))}catch{return"[]"}}function p(U,H,J){let[T,L]=d([]),X=n(()=>{if(!H)return"nil";if(H.kind==="static")return JSON.stringify(H.options??[]);return Hq(U,H.deps)},[H,U]);return a(()=>{let N=!0;return(async()=>{if(!H)return L([]);if(H.kind==="static")return L([...H.options??[]]);let h=J?.[H.resolverKey];if(!h)return L([]);let k=await h(U,H.args);if(N)L([...k??[]])})(),()=>{N=!1}},[X,H&&H.kind==="resolver"?H.resolverKey:void 0]),T}function c(U,H,J){if(!H)return U??"";let T=typeof J==="number"?`${H.replace(/^\$index$/,String(J))}`:H;return U?`${U}${typeof J==="number"?`.${J}`:""}.${T}`.replace(/\.+/g,"."):T}function $q(U){let H=U,{driver:J}=H;function T(L){let{spec:X,options:N,merged:R}=L,h=n(()=>o(X),[X]),k=e({...R.formOptions,resolver:i(h),defaultValues:N?.defaultValues}),D=k.watch(),I=(q,w,W)=>{let{Field:Y,FieldLabel:y,FieldDescription:F,FieldError:B}=J,_=c(w,q.name,W),O=u(D,q.visibleWhen),Z=u(D,q.enabledWhen),P=Boolean(k.getFieldState(_)?.invalid);if(!O)return null;let $=_?.replace(/\./g,"-"),A={"data-invalid":P,hidden:!O,disabled:!Z},E=q.labelI18n?Q(y,{htmlFor:$,children:q.labelI18n}):null,g=q.descriptionI18n?Q(F,{children:q.descriptionI18n}):null;if(q.kind==="group"){let G=q.fields.map((z,K)=>Q(x.Fragment,{children:I(z,_,W)},`${_}-${K}`));return M(Y,{...A,children:[E,G,g]})}if(q.kind==="array")return l(q,w);return Q(s,{name:_,control:k.control,render:({field:G,fieldState:z})=>{let K=z.error?[z.error]:[],S=z.invalid||void 0;if(q.kind==="text"){let V=q,C=J.Input;return M(Y,{...A,children:[E,Q(C,{id:$,"aria-invalid":S,placeholder:q.placeholderI18n,autoComplete:V.autoComplete,inputMode:V.inputMode,maxLength:V.maxLength,minLength:V.minLength,disabled:!Z,...G,...q.uiProps}),g,z.invalid?Q(B,{errors:K}):null]})}if(q.kind==="textarea"){let V=q,C=J.Textarea;return M(Y,{...A,children:[E,Q(C,{id:$,"aria-invalid":S,placeholder:q.placeholderI18n,rows:V.rows,maxLength:V.maxLength,disabled:!Z,...G,...q.uiProps}),g,z.invalid?Q(B,{errors:K}):null]})}if(q.kind==="select"){let V=q,C=J.Select,b=v(V.options),j=p(D,b,R.resolvers);return M(Y,{...A,children:[E,Q(C,{id:$,name:_,"aria-invalid":S,disabled:!Z,value:G.value,onChange:(m)=>G.onChange(m),options:j,...q.uiProps}),g,z.invalid?Q(B,{errors:K}):null]})}if(q.kind==="checkbox"){let V=J.Checkbox;return M(Y,{...A,children:[E,Q(V,{id:$,name:_,disabled:!Z,checked:!!G.value,onCheckedChange:(C)=>G.onChange(C),...q.uiProps}),g,z.invalid?Q(B,{errors:K}):null]})}if(q.kind==="radio"){let V=q,C=J.RadioGroup,b=v(V.options),j=p(D,b,R.resolvers);return M(Y,{...A,children:[E,Q(C,{id:$,name:_,disabled:!Z,value:G.value,onValueChange:(m)=>G.onChange(m),options:j,...q.uiProps}),g,z.invalid?Q(B,{errors:K}):null]})}if(q.kind==="switch"){let V=J.Switch;return M(Y,{...A,children:[E,Q(V,{id:$,name:_,disabled:!Z,checked:!!G.value,onCheckedChange:(C)=>G.onChange(C),...q.uiProps}),g,z.invalid?Q(B,{errors:K}):null]})}return Q(Jq,{})}},_)},l=(q,w)=>{let W=c(w,q.name),{fields:Y,append:y,remove:F}=r({control:k.control,name:W}),B=q.max==null||Y.length<q.max,_=(P)=>(q.min==null?Y.length>0:Y.length>q.min)&&P>=0,O=J.Button,Z=J.FieldLabel;return M("div",{children:[q.labelI18n?Q(Z,{children:q.labelI18n}):null,Y.map((P,$)=>M("div",{children:[I(q.of,W,$),_($)?Q(O,{type:"button",variant:"ghost",size:"sm",onClick:()=>F($),children:"Remove"}):null]},P.id??$)),B?Q(O,{type:"button",variant:"outline",size:"sm",onClick:()=>y({}),children:"Add"}):null]},W)},t=async(q)=>{let w=X.actions?.[0]?.key??"submit";if(R.onSubmitOverride)return R.onSubmitOverride(q,w)},f=J.Button;return M("form",{onSubmit:k.handleSubmit(t),children:[(X.fields||[]).map((q,w)=>Q(x.Fragment,{children:I(q)},w)),X.actions&&X.actions.length?Q("div",{children:X.actions.map((q)=>Q(f,{type:"submit",children:q.labelI18n},q.key))}):null]})}return{render:(L,X)=>Q(T,{spec:L,options:X,merged:{...H,...X?.overrides??{}}})}}export{$q as createFormRenderer};