@cervio/plugin-sdk 2.2.0 → 2.3.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.
@@ -0,0 +1,1159 @@
1
+ import { useCallback, useSyncExternalStore, useId, useState, useEffect, useMemo, useRef } from 'react';
2
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
3
+
4
+ // src/forms/react.ts
5
+
6
+ // ../form-core/dist/index.js
7
+ var __defProp = Object.defineProperty;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
10
+ var FormApiError = class extends Error {
11
+ constructor(status, code, message, field) {
12
+ super(message);
13
+ __publicField(this, "status", status);
14
+ __publicField(this, "code", code);
15
+ __publicField(this, "field", field);
16
+ this.name = "FormApiError";
17
+ }
18
+ };
19
+ function createFetchTransport(opts = {}) {
20
+ const base = (opts.baseUrl ?? "").replace(/\/$/, "");
21
+ const doFetch = opts.fetchImpl ?? ((...a) => fetch(...a));
22
+ const e = encodeURIComponent;
23
+ async function call(path, init = {}) {
24
+ const res = await doFetch(`${base}/api/v1${path}`, {
25
+ method: init.method ?? (init.body !== void 0 ? "POST" : "GET"),
26
+ credentials: opts.credentials ?? "include",
27
+ signal: init.signal,
28
+ headers: {
29
+ Accept: "application/json",
30
+ ...init.body !== void 0 ? { "Content-Type": "application/json" } : {},
31
+ ...opts.headers
32
+ },
33
+ ...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {}
34
+ });
35
+ let body = null;
36
+ try {
37
+ body = await res.json();
38
+ } catch {
39
+ }
40
+ if (!res.ok) {
41
+ const b = body ?? {};
42
+ throw new FormApiError(res.status, b.error ?? `http_${res.status}`, b.message ?? b.error ?? res.statusText, b.field);
43
+ }
44
+ return body;
45
+ }
46
+ const UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
47
+ const ids = /* @__PURE__ */ new Map();
48
+ const idOf = (entity) => {
49
+ if (UUID_RE2.test(entity)) return Promise.resolve(entity);
50
+ let p = ids.get(entity);
51
+ if (!p) {
52
+ p = call(`/entities/${e(entity)}`).then((r) => r.entity.id);
53
+ p.catch(() => ids.delete(entity));
54
+ ids.set(entity, p);
55
+ }
56
+ return p;
57
+ };
58
+ const loc = opts.locale ? `&locale=${e(opts.locale)}` : "";
59
+ const formPath = async (entity, form) => `/entities/${e(await idOf(entity))}/forms/${e(form)}`;
60
+ const recordsPath = async (entity) => `/entities/${e(await idOf(entity))}/records`;
61
+ return {
62
+ getSchema: async (entityId, form, signal) => call(`${await formPath(entityId, form)}/write-schema?include=layout${loc}`, { signal }),
63
+ // `layout_state`: hidden blocks and field variants; older hosts ignore it.
64
+ validateDraft: async (entityId, form, data, recordId, signal) => call(`${await formPath(entityId, form)}/validate-draft?include=layout_state${loc}`, {
65
+ body: { data, ...recordId ? { record_id: recordId } : {} },
66
+ signal
67
+ }),
68
+ getRecord: async (entityId, recordId, signal) => {
69
+ const r = await call(`${await recordsPath(entityId)}/${e(recordId)}`, { signal });
70
+ return r.record;
71
+ },
72
+ createRecord: async (entityId, form, data) => call(await recordsPath(entityId), { body: { data, form_name: form } }),
73
+ updateRecord: async (entityId, form, recordId, data, expectedUpdatedAt) => {
74
+ await call(`${await recordsPath(entityId)}/${e(recordId)}`, {
75
+ method: "PATCH",
76
+ body: { data, form_name: form, ...expectedUpdatedAt ? { expected_updated_at: expectedUpdatedAt } : {} }
77
+ });
78
+ },
79
+ fieldOptions: async (entityId, form, field, data) => {
80
+ const path = `${await formPath(entityId, form)}/fields/${e(field)}/options${opts.locale ? `?locale=${e(opts.locale)}` : ""}`;
81
+ return data ? call(path, { body: { data } }) : call(path);
82
+ },
83
+ relationOptions: async (entityId, form, field, q, limit = 20) => call(`${await formPath(entityId, form)}/fields/${e(field)}/relation-options?q=${e(q)}&limit=${limit}`)
84
+ };
85
+ }
86
+ var EMPTY_STATE = {
87
+ status: "loading",
88
+ error: null,
89
+ schema: null,
90
+ layout: null,
91
+ fields: {},
92
+ mode: "create",
93
+ recordId: null,
94
+ updatedAt: null,
95
+ values: {},
96
+ dirty: [],
97
+ touched: [],
98
+ fieldState: {},
99
+ errors: {},
100
+ draftErrors: {},
101
+ validating: false,
102
+ saving: false,
103
+ saveError: null,
104
+ conflict: false,
105
+ submitted: false,
106
+ relationLabels: {},
107
+ hiddenBlocks: [],
108
+ blockedSteps: [],
109
+ fieldDisplay: {}
110
+ };
111
+ function fieldDisplayFor(state, field, nodeId) {
112
+ const own = nodeId ? state.fieldDisplay[nodeId] : void 0;
113
+ if (own?.field === field) return own;
114
+ return Object.values(state.fieldDisplay).find((d) => d.field === field);
115
+ }
116
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
117
+ function asError(e) {
118
+ return e instanceof Error ? e : new Error(String(e));
119
+ }
120
+ function isEmpty(v) {
121
+ return v == null || v === "" || Array.isArray(v) && v.length === 0;
122
+ }
123
+ function sameValue(a, b) {
124
+ if (isEmpty(a) && isEmpty(b)) return true;
125
+ return JSON.stringify(a) === JSON.stringify(b);
126
+ }
127
+ function flatLayout(fields) {
128
+ return {
129
+ version: 1,
130
+ children: [...fields].sort((a, b) => a.order - b.order || a.name.localeCompare(b.name)).map((f) => ({ type: "field", field: f.name }))
131
+ };
132
+ }
133
+ function relationIds(v) {
134
+ if (Array.isArray(v)) return v.filter((x) => typeof x === "string" && UUID_RE.test(x));
135
+ return typeof v === "string" && UUID_RE.test(v) ? [v] : [];
136
+ }
137
+ function createFormController(opts) {
138
+ const { transport, entity, form } = opts;
139
+ const debounceMs = opts.validateDebounceMs ?? 300;
140
+ const requiredMessage = opts.requiredMessage ?? "Campo obbligatorio";
141
+ let state = { ...EMPTY_STATE, mode: opts.recordId ? "edit" : "create", recordId: opts.recordId ?? null };
142
+ let baseline = {};
143
+ const listeners = /* @__PURE__ */ new Set();
144
+ let destroyed = false;
145
+ let timer = null;
146
+ let draftSeq = 0;
147
+ function set(patch) {
148
+ if (destroyed) return;
149
+ state = { ...state, ...patch };
150
+ for (const l of listeners) l(state);
151
+ }
152
+ function shownErrors(draft, touched, submitted) {
153
+ if (submitted) return draft;
154
+ const out = {};
155
+ for (const f of touched) if (draft[f]) out[f] = draft[f];
156
+ return out;
157
+ }
158
+ function writable(name) {
159
+ const f = state.fields[name];
160
+ if (!f) return false;
161
+ const fs = state.fieldState[name];
162
+ return !(fs?.readonly ?? f.readonly) && f.server_filled !== "computed";
163
+ }
164
+ function writableValues() {
165
+ const out = {};
166
+ for (const [k, v] of Object.entries(state.values)) if (writable(k)) out[k] = v;
167
+ return out;
168
+ }
169
+ function applyDraft(r) {
170
+ const values = { ...state.values };
171
+ const resolved = r.resolved_data ?? {};
172
+ for (const [name, kind] of Object.entries(r.server_filled ?? {})) {
173
+ if (!(name in resolved)) continue;
174
+ if (kind === "computed" || kind === "default" && state.mode === "create" && !state.dirty.includes(name) && isEmpty(values[name])) {
175
+ values[name] = resolved[name];
176
+ }
177
+ }
178
+ const draftErrors = {};
179
+ for (const e of r.errors ?? []) if (e.field && !draftErrors[e.field]) draftErrors[e.field] = e.message;
180
+ const fieldState = { ...state.fieldState, ...r.field_state ?? {} };
181
+ for (const [name, f] of Object.entries(state.fields)) {
182
+ const fs = fieldState[name] ?? { visible: true, required: f.required, readonly: f.readonly };
183
+ if (draftErrors[name] || !fs.visible || !fs.required || fs.readonly || f.server_filled) continue;
184
+ if (isEmpty(values[name])) draftErrors[name] = requiredMessage;
185
+ }
186
+ set({
187
+ values,
188
+ fieldState,
189
+ hiddenBlocks: r.hidden_blocks ?? [],
190
+ blockedSteps: r.blocked_steps ?? [],
191
+ fieldDisplay: r.field_display ?? {},
192
+ draftErrors,
193
+ errors: shownErrors(draftErrors, state.touched, state.submitted)
194
+ });
195
+ }
196
+ function runDraft() {
197
+ if (timer) {
198
+ clearTimeout(timer);
199
+ timer = null;
200
+ }
201
+ const my = ++draftSeq;
202
+ set({ validating: true });
203
+ const p = transport.validateDraft(entity, form, writableValues(), state.recordId).then((r) => {
204
+ if (my !== draftSeq || destroyed) return r.ok;
205
+ applyDraft(r);
206
+ set({ validating: timer != null });
207
+ return r.ok;
208
+ }).catch((e) => {
209
+ if (my === draftSeq) set({ validating: false, saveError: asError(e) });
210
+ return false;
211
+ });
212
+ return p;
213
+ }
214
+ function scheduleDraft() {
215
+ if (timer) clearTimeout(timer);
216
+ set({ validating: true });
217
+ timer = setTimeout(() => {
218
+ timer = null;
219
+ void runDraft();
220
+ }, debounceMs);
221
+ }
222
+ async function loadRelationLabels(values) {
223
+ const out = { ...state.relationLabels };
224
+ await Promise.all(
225
+ Object.values(state.fields).filter((f) => f.input?.mode === "relation").map(async (f) => {
226
+ const ids = relationIds(values[f.name]).filter((id) => !out[f.name]?.[id]);
227
+ if (!ids.length) return;
228
+ const found = await Promise.all(
229
+ ids.map((id) => transport.relationOptions(entity, form, f.name, id, 1).then((r) => r.records).catch(() => []))
230
+ );
231
+ out[f.name] = { ...out[f.name] ?? {} };
232
+ for (const r of found.flat()) out[f.name][r.id] = r.label;
233
+ })
234
+ );
235
+ set({ relationLabels: out });
236
+ }
237
+ async function loadRecord() {
238
+ if (!state.recordId) return;
239
+ const rec = await transport.getRecord(entity, state.recordId);
240
+ const values = {};
241
+ for (const name of Object.keys(state.fields)) values[name] = rec.data[name] ?? null;
242
+ baseline = values;
243
+ set({ values, updatedAt: rec.updated_at ?? null, dirty: [], conflict: false, saveError: null });
244
+ await loadRelationLabels(values);
245
+ }
246
+ const ready = (async () => {
247
+ try {
248
+ const schema = await transport.getSchema(entity, form);
249
+ const fields = {};
250
+ const fieldState = {};
251
+ for (const f of schema.fields) {
252
+ fields[f.name] = f;
253
+ fieldState[f.name] = { visible: true, required: f.required, readonly: f.readonly };
254
+ }
255
+ set({ schema, fields, fieldState, layout: schema.layout ?? flatLayout(schema.fields) });
256
+ if (state.recordId) {
257
+ await loadRecord();
258
+ } else {
259
+ const values = {};
260
+ for (const f of schema.fields) values[f.name] = opts.initialValues?.[f.name] ?? null;
261
+ baseline = values;
262
+ set({ values });
263
+ await loadRelationLabels(values);
264
+ }
265
+ await runDraft();
266
+ set({ status: "ready" });
267
+ } catch (e) {
268
+ set({ status: "error", error: asError(e) });
269
+ throw e;
270
+ }
271
+ })();
272
+ ready.catch(() => {
273
+ });
274
+ function setValues(patch) {
275
+ const values = { ...state.values };
276
+ const dirty = new Set(state.dirty);
277
+ for (const [k, v] of Object.entries(patch)) {
278
+ if (!state.fields[k]) continue;
279
+ values[k] = v;
280
+ if (sameValue(v, baseline[k])) dirty.delete(k);
281
+ else dirty.add(k);
282
+ }
283
+ set({ values, dirty: [...dirty], saveError: null });
284
+ scheduleDraft();
285
+ }
286
+ async function save() {
287
+ if (state.saving) return null;
288
+ set({ saving: true, saveError: null, submitted: true });
289
+ try {
290
+ const ok = await runDraft();
291
+ set({ errors: state.draftErrors });
292
+ if (!ok) {
293
+ set({ saving: false });
294
+ return null;
295
+ }
296
+ const names = state.mode === "edit" ? state.dirty : Object.keys(state.fields);
297
+ const data = {};
298
+ for (const n of names) {
299
+ if (!writable(n)) continue;
300
+ if (state.fieldState[n]?.visible === false) continue;
301
+ if (state.mode === "create" && isEmpty(state.values[n])) continue;
302
+ data[n] = state.values[n];
303
+ }
304
+ let id;
305
+ let created = false;
306
+ if (state.mode === "create") {
307
+ id = (await transport.createRecord(entity, form, data)).id;
308
+ created = true;
309
+ set({ mode: "edit", recordId: id });
310
+ } else {
311
+ id = state.recordId;
312
+ if (Object.keys(data).length) {
313
+ if (!state.updatedAt) {
314
+ throw new FormApiError(409, "missing_updated_at", "The record was read without its update time: reload it before saving.");
315
+ }
316
+ await transport.updateRecord(entity, form, id, data, state.updatedAt);
317
+ }
318
+ }
319
+ await loadRecord();
320
+ set({ saving: false, submitted: false, touched: [], errors: {} });
321
+ void runDraft();
322
+ return { id, created };
323
+ } catch (e) {
324
+ const err = asError(e);
325
+ if (err instanceof FormApiError && (err.code === "etag_conflict" || err.code === "missing_updated_at")) {
326
+ set({ saving: false, conflict: true, saveError: err });
327
+ } else if (err instanceof FormApiError && err.field && state.fields[err.field]) {
328
+ const draftErrors = { ...state.draftErrors, [err.field]: err.message };
329
+ set({ saving: false, draftErrors, errors: draftErrors });
330
+ } else {
331
+ set({ saving: false, saveError: err });
332
+ }
333
+ return null;
334
+ }
335
+ }
336
+ return {
337
+ ready,
338
+ getState: () => state,
339
+ subscribe(listener) {
340
+ listeners.add(listener);
341
+ return () => listeners.delete(listener);
342
+ },
343
+ setValue: (field, value) => setValues({ [field]: value }),
344
+ setValues,
345
+ touch(field) {
346
+ if (state.touched.includes(field)) return;
347
+ const touched = [...state.touched, field];
348
+ set({ touched, errors: shownErrors(state.draftErrors, touched, state.submitted) });
349
+ },
350
+ validate: () => runDraft(),
351
+ save,
352
+ reset() {
353
+ set({ values: { ...baseline }, dirty: [], touched: [], submitted: false, errors: {}, saveError: null });
354
+ scheduleDraft();
355
+ },
356
+ async reload() {
357
+ try {
358
+ await loadRecord();
359
+ await runDraft();
360
+ } catch (e) {
361
+ set({ saveError: asError(e) });
362
+ }
363
+ },
364
+ async fieldOptions(field, nodeId) {
365
+ const f = state.fields[field];
366
+ const display = fieldDisplayFor(state, field, nodeId);
367
+ if (display?.options) return display.options;
368
+ const remote = display?.options_source === "remote" || f?.input?.mode === "remote_options";
369
+ if (!remote && f?.input?.options?.length) return f.input.options;
370
+ const r = await transport.fieldOptions(entity, form, field, remote ? state.values : void 0);
371
+ return r.options;
372
+ },
373
+ async relationOptions(field, search, limit) {
374
+ const r = await transport.relationOptions(entity, form, field, search, limit);
375
+ const labels = { ...state.relationLabels[field] ?? {} };
376
+ for (const x of r.records) labels[x.id] = x.label;
377
+ set({ relationLabels: { ...state.relationLabels, [field]: labels } });
378
+ return r.records;
379
+ },
380
+ destroy() {
381
+ destroyed = true;
382
+ if (timer) clearTimeout(timer);
383
+ listeners.clear();
384
+ }
385
+ };
386
+ }
387
+
388
+ // src/context.ts
389
+ function getPluginContext() {
390
+ if (typeof window === "undefined") return null;
391
+ return window.__CERVIO_PLUGIN_CONTEXT__ ?? null;
392
+ }
393
+
394
+ // src/client.ts
395
+ function resolveApiBaseUrl(explicitBaseUrl) {
396
+ const explicit = explicitBaseUrl?.trim();
397
+ if (explicit) return explicit.replace(/\/$/, "");
398
+ const parentOrigin = getPluginContext()?.parentOrigin?.trim();
399
+ if (parentOrigin && parentOrigin !== "null") {
400
+ return parentOrigin.replace(/\/$/, "");
401
+ }
402
+ throw new Error(
403
+ "Unable to resolve the Cervio API base URL. Pass { baseUrl } explicitly, or run inside the Cervio plugin sandbox so window.__CERVIO_PLUGIN_CONTEXT__.parentOrigin is set. Do not fall back to window.location.origin."
404
+ );
405
+ }
406
+
407
+ // src/forms/index.ts
408
+ function createPluginFormController(opts) {
409
+ const { baseUrl, fetchImpl, transport, locale, ...rest } = opts;
410
+ return createFormController({
411
+ ...rest,
412
+ transport: transport ?? createFetchTransport({
413
+ baseUrl: resolveApiBaseUrl(baseUrl),
414
+ fetchImpl,
415
+ // Labels, options and texts in the user's language, like the Cervio form.
416
+ locale: locale ?? getPluginContext()?.locale ?? void 0
417
+ })
418
+ });
419
+ }
420
+ var CERVIO_FORM_CSS = `
421
+ :root{--cf-accent:var(--primary,#2f5fd0);--cf-border:var(--border,#e2e5ea);--cf-input:var(--input,var(--cf-border));--cf-muted:var(--muted,#f3f4f6);--cf-muted-fg:var(--muted-foreground,#6b7280);--cf-bg:var(--background,#fff);--cf-fg:var(--foreground,#111827);--cf-danger:var(--destructive,#dc2626);--cf-warning:var(--warning,#d97706);--cf-success:var(--success,#16a34a);--cf-radius:8px}
422
+ .cf-root{color:var(--cf-fg);font-size:13px;display:flex;flex-direction:column;gap:14px;min-width:0}
423
+ .cf-field{display:flex;flex-direction:column;gap:6px;min-width:0}
424
+ .cf-label{font-size:12.5px;font-weight:500;color:var(--cf-fg);display:flex;gap:4px;align-items:baseline}
425
+ .cf-req{color:var(--cf-danger)}
426
+ .cf-control{width:100%;min-height:36px;border:1px solid var(--cf-input);border-radius:var(--cf-radius);background:var(--cf-bg);color:inherit;padding:6px 10px;font:inherit;box-sizing:border-box}
427
+ textarea.cf-control{min-height:72px;resize:vertical}
428
+ .cf-control:focus-visible,.cf-btn:focus-visible,.cf-tab:focus-visible,.cf-option:focus-visible{outline:2px solid var(--cf-accent);outline-offset:1px}
429
+ .cf-control:disabled,.cf-control[aria-readonly=true]{background:var(--cf-muted);color:var(--cf-muted-fg);cursor:default}
430
+ .cf-field[data-invalid=true] .cf-control{border-color:var(--cf-danger)}
431
+ .cf-error{color:var(--cf-danger);font-size:12px}
432
+ .cf-hint{color:var(--cf-muted-fg);font-size:12px}
433
+ .cf-check{display:inline-flex;gap:8px;align-items:center;min-height:36px;cursor:pointer}
434
+ .cf-check input{accent-color:var(--cf-accent);width:16px;height:16px}
435
+ .cf-readonly{min-height:36px;display:flex;align-items:center;color:var(--cf-fg);padding:0 2px}
436
+ .cf-combo{position:relative}
437
+ .cf-list{position:absolute;z-index:40;top:calc(100% + 4px);left:0;right:0;max-height:240px;overflow:auto;background:var(--popover,var(--cf-bg));color:var(--popover-foreground,var(--cf-fg));border:1px solid var(--cf-border);border-radius:var(--cf-radius);box-shadow:0 8px 24px rgb(0 0 0 / .12);padding:4px;display:grid}
438
+ .cf-option{all:unset;padding:7px 8px;border-radius:6px;cursor:pointer;display:flex;justify-content:space-between;gap:8px}
439
+ .cf-option:hover,.cf-option[data-active=true]{background:var(--cf-muted)}
440
+ .cf-option[aria-selected=true]{font-weight:600}
441
+ .cf-empty{padding:8px;color:var(--cf-muted-fg)}
442
+ .cf-chips{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:6px}
443
+ .cf-chip{display:inline-flex;align-items:center;gap:6px;border-radius:999px;background:var(--cf-muted);padding:2px 4px 2px 10px;font-size:12px}
444
+ .cf-chip button{all:unset;cursor:pointer;width:18px;height:18px;border-radius:50%;text-align:center;line-height:18px;color:var(--cf-muted-fg)}
445
+ .cf-chip button:hover{background:var(--cf-border);color:var(--cf-fg)}
446
+ .cf-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px 16px}
447
+ .cf-grid>.cf-full{grid-column:1 / -1}
448
+ .cf-columns{display:grid;gap:14px 16px}
449
+ .cf-col{display:flex;flex-direction:column;gap:14px;min-width:0}
450
+ @media (max-width:640px){.cf-grid,.cf-columns{grid-template-columns:1fr !important}}
451
+ .cf-group{border:1px solid var(--cf-border);border-radius:10px;padding:14px;display:flex;flex-direction:column;gap:14px}
452
+ .cf-group-title{all:unset;font-weight:600;font-size:13.5px;display:flex;gap:8px;align-items:center}
453
+ button.cf-group-title{cursor:pointer}
454
+ .cf-divider{border:0;border-top:1px solid var(--cf-border);margin:2px 0}
455
+ .cf-text{color:var(--cf-muted-fg);white-space:pre-wrap;line-height:1.5}
456
+ .cf-alert{--cf-tone:var(--cf-accent);border:1px solid color-mix(in srgb,var(--cf-tone) 35%,transparent);background:color-mix(in srgb,var(--cf-tone) 8%,var(--cf-bg));border-radius:var(--cf-radius);padding:10px 12px;display:flex;flex-direction:column;gap:2px;white-space:pre-wrap;line-height:1.5}
457
+ .cf-alert[data-tone=warning]{--cf-tone:var(--cf-warning)}
458
+ .cf-alert[data-tone=error]{--cf-tone:var(--cf-danger)}
459
+ .cf-alert[data-tone=success]{--cf-tone:var(--cf-success)}
460
+ .cf-alert-title{font-weight:600}
461
+ .cf-tabs{display:flex;gap:4px;border-bottom:1px solid var(--cf-border);margin-bottom:4px;flex-wrap:wrap}
462
+ .cf-tab{all:unset;padding:7px 12px;cursor:pointer;color:var(--cf-muted-fg);border-bottom:2px solid transparent;margin-bottom:-1px}
463
+ .cf-tab[aria-selected=true]{color:var(--cf-fg);border-bottom-color:var(--cf-accent);font-weight:600}
464
+ .cf-tab[data-invalid=true]::after{content:" \u2022";color:var(--cf-danger)}
465
+ .cf-actions{display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:flex-end}
466
+ .cf-status{margin-right:auto;color:var(--cf-muted-fg);font-size:12px}
467
+ .cf-btn{height:34px;border:1px solid var(--cf-border);border-radius:var(--cf-radius);background:var(--cf-bg);color:inherit;padding:0 14px;font:inherit;cursor:pointer;display:inline-flex;align-items:center;gap:6px}
468
+ .cf-btn:hover:not(:disabled){background:var(--cf-muted)}
469
+ .cf-btn:disabled{opacity:.55;cursor:default}
470
+ .cf-btn[data-variant=primary]{background:var(--cf-accent);border-color:var(--cf-accent);color:var(--primary-foreground,#fff)}
471
+ .cf-btn[data-variant=primary]:hover:not(:disabled){filter:brightness(1.08)}
472
+ .cf-alert{border:1px solid color-mix(in srgb,var(--cf-danger) 35%,transparent);background:color-mix(in srgb,var(--cf-danger) 8%,transparent);color:var(--cf-fg);border-radius:var(--cf-radius);padding:10px 12px;display:flex;gap:10px;align-items:center;justify-content:space-between;flex-wrap:wrap}
473
+ .cf-summary{margin:0;padding-left:18px;color:var(--cf-danger);font-size:12.5px}
474
+ .cf-block{border:1px dashed var(--cf-border);border-radius:var(--cf-radius);padding:10px 12px;color:var(--cf-muted-fg);font-size:12px}
475
+ `;
476
+ function ensureCervioFormStyles(doc = typeof document === "undefined" ? void 0 : document) {
477
+ if (!doc || doc.querySelector("style[data-cervio-form]")) return;
478
+ const el = doc.createElement("style");
479
+ el.setAttribute("data-cervio-form", "");
480
+ el.textContent = CERVIO_FORM_CSS;
481
+ doc.head.appendChild(el);
482
+ }
483
+ function useFormState(controller) {
484
+ const subscribe = useCallback(
485
+ (cb) => {
486
+ const off = controller.subscribe(cb);
487
+ return () => {
488
+ off();
489
+ };
490
+ },
491
+ [controller]
492
+ );
493
+ return useSyncExternalStore(subscribe, controller.getState, controller.getState);
494
+ }
495
+ function useCervioFormStyles(unstyled) {
496
+ useEffect(() => {
497
+ if (unstyled) return;
498
+ ensureCervioFormStyles();
499
+ }, [unstyled]);
500
+ }
501
+ var it = {
502
+ save: "Salva",
503
+ saving: "Salvataggio\u2026",
504
+ cancel: "Annulla modifiche",
505
+ saved: "Salvato",
506
+ unsaved: (n) => n === 1 ? "1 modifica non salvata" : `${n} modifiche non salvate`,
507
+ checking: "Verifica\u2026",
508
+ search: "Cerca\u2026",
509
+ noResults: "Nessun risultato",
510
+ loading: "Caricamento\u2026",
511
+ choose: "Seleziona\u2026",
512
+ remove: "Rimuovi",
513
+ yes: "S\xEC",
514
+ no: "No",
515
+ conflict: "Qualcuno ha salvato questo record nel frattempo. Ricarica per vedere la versione aggiornata.",
516
+ reload: "Ricarica",
517
+ fixErrors: "Correggi i campi evidenziati:",
518
+ error: "Errore",
519
+ next: "Avanti",
520
+ back: "Indietro",
521
+ stepBlocked: "Non puoi ancora proseguire: controlla i dati di questo passaggio."
522
+ };
523
+ var en = {
524
+ save: "Save",
525
+ saving: "Saving\u2026",
526
+ cancel: "Discard changes",
527
+ saved: "Saved",
528
+ unsaved: (n) => n === 1 ? "1 unsaved change" : `${n} unsaved changes`,
529
+ checking: "Checking\u2026",
530
+ search: "Search\u2026",
531
+ noResults: "No results",
532
+ loading: "Loading\u2026",
533
+ choose: "Choose\u2026",
534
+ remove: "Remove",
535
+ yes: "Yes",
536
+ no: "No",
537
+ conflict: "Someone saved this record in the meantime. Reload to see the latest version.",
538
+ reload: "Reload",
539
+ fixErrors: "Fix the highlighted fields:",
540
+ error: "Error",
541
+ next: "Next",
542
+ back: "Back",
543
+ stepBlocked: "You cannot continue yet: check the data in this step."
544
+ };
545
+ function formLabels(locale, overrides) {
546
+ const base = (locale ?? "it").toLowerCase().startsWith("en") ? en : it;
547
+ return overrides ? { ...base, ...overrides } : base;
548
+ }
549
+ var NUMBER_TYPES = /* @__PURE__ */ new Set(["number", "currency", "integer", "decimal"]);
550
+ function toLocalInput(v) {
551
+ if (typeof v !== "string" || !v) return "";
552
+ const d = new Date(v);
553
+ if (Number.isNaN(d.getTime())) return "";
554
+ const p = (n) => String(n).padStart(2, "0");
555
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`;
556
+ }
557
+ function kindOf(f) {
558
+ const mode = f.input?.mode;
559
+ if (mode === "relation") return f.input.multi_select ? "relation_multi" : "relation";
560
+ if (mode === "fixed_list" || mode === "remote_options") return f.value_shape === "string[]" ? "list_multi" : "list";
561
+ if (mode === "boolean" || f.field_type === "boolean") return "boolean";
562
+ if (f.field_type === "date") return "date";
563
+ if (f.field_type === "datetime") return "datetime";
564
+ if (NUMBER_TYPES.has(f.field_type)) return "number";
565
+ if (f.field_type === "textarea") return "textarea";
566
+ return "text";
567
+ }
568
+ function plain(v) {
569
+ if (v == null) return "";
570
+ if (Array.isArray(v)) return v.map(plain).join(", ");
571
+ if (typeof v === "boolean") return v ? "\u2713" : "";
572
+ return String(v);
573
+ }
574
+ function useOptions(controller, state, f, nodeId) {
575
+ const display = fieldDisplayFor(state, f.name, nodeId);
576
+ const remote = display?.options_source === "remote" || f.input?.mode === "remote_options";
577
+ const fixed = display?.options ?? (!remote && f.input?.options?.length ? f.input.options : null);
578
+ const draftKey = remote ? JSON.stringify(state.values) : "";
579
+ const [loaded, setLoaded] = useState(null);
580
+ useEffect(() => {
581
+ if (fixed) return;
582
+ let live = true;
583
+ controller.fieldOptions(f.name, nodeId).then((o) => live && setLoaded(o)).catch(() => live && setLoaded([]));
584
+ return () => {
585
+ live = false;
586
+ };
587
+ }, [controller, f.name, nodeId, fixed, draftKey]);
588
+ return fixed ?? loaded;
589
+ }
590
+ function ListInput(props) {
591
+ const { ctx, t } = props;
592
+ const opts = useOptions(props.controller, ctx.state, ctx.field, ctx.nodeId);
593
+ const labelOf = (v) => opts?.find((o) => o.value === v)?.label ?? plain(v);
594
+ if (ctx.readonly) {
595
+ const vals = Array.isArray(ctx.value) ? ctx.value : ctx.value == null ? [] : [ctx.value];
596
+ return /* @__PURE__ */ jsx("div", { className: "cf-readonly", children: vals.map(labelOf).join(", ") || "\u2014" });
597
+ }
598
+ if (props.multi) {
599
+ const selected = new Set(Array.isArray(ctx.value) ? ctx.value : []);
600
+ return /* @__PURE__ */ jsx("div", { role: "group", "aria-labelledby": `${ctx.id}-label`, children: (opts ?? []).map((o) => /* @__PURE__ */ jsxs("label", { className: "cf-check", style: { marginRight: 14 }, children: [
601
+ /* @__PURE__ */ jsx(
602
+ "input",
603
+ {
604
+ type: "checkbox",
605
+ checked: selected.has(o.value),
606
+ onChange: (e) => {
607
+ const next = new Set(selected);
608
+ if (e.target.checked) next.add(o.value);
609
+ else next.delete(o.value);
610
+ ctx.setValue([...next]);
611
+ },
612
+ onBlur: ctx.touch
613
+ }
614
+ ),
615
+ o.label
616
+ ] }, o.value)) });
617
+ }
618
+ return /* @__PURE__ */ jsxs(
619
+ "select",
620
+ {
621
+ id: ctx.id,
622
+ className: "cf-control",
623
+ value: ctx.value == null ? "" : String(ctx.value),
624
+ "aria-invalid": ctx.invalid || void 0,
625
+ "aria-required": ctx.required || void 0,
626
+ onChange: (e) => ctx.setValue(e.target.value === "" ? null : e.target.value),
627
+ onBlur: ctx.touch,
628
+ children: [
629
+ /* @__PURE__ */ jsx("option", { value: "", children: opts ? t.choose : t.loading }),
630
+ (opts ?? []).map((o) => /* @__PURE__ */ jsx("option", { value: o.value, children: o.label }, o.value))
631
+ ]
632
+ }
633
+ );
634
+ }
635
+ function RelationInput(props) {
636
+ const { ctx, controller, t, multi } = props;
637
+ const labels = ctx.state.relationLabels[ctx.field.name] ?? {};
638
+ const ids = multi ? Array.isArray(ctx.value) ? ctx.value : [] : ctx.value ? [String(ctx.value)] : [];
639
+ const [open, setOpen] = useState(false);
640
+ const [q, setQ] = useState("");
641
+ const [results, setResults] = useState(null);
642
+ const [active, setActive] = useState(0);
643
+ const wrap = useRef(null);
644
+ const gen = useRef(0);
645
+ useEffect(() => {
646
+ if (!open) return;
647
+ const my = ++gen.current;
648
+ setResults(null);
649
+ const h = setTimeout(() => {
650
+ controller.relationOptions(ctx.field.name, q.trim(), 20).then((r) => my === gen.current && (setResults(r), setActive(0))).catch(() => my === gen.current && setResults([]));
651
+ }, 220);
652
+ return () => clearTimeout(h);
653
+ }, [open, q, controller, ctx.field.name]);
654
+ useEffect(() => {
655
+ if (!open) return;
656
+ const onDown = (e) => {
657
+ if (wrap.current && !wrap.current.contains(e.target)) {
658
+ setOpen(false);
659
+ ctx.touch();
660
+ }
661
+ };
662
+ document.addEventListener("mousedown", onDown);
663
+ return () => document.removeEventListener("mousedown", onDown);
664
+ }, [open, ctx]);
665
+ const pick = (id) => {
666
+ if (multi) ctx.setValue(ids.includes(id) ? ids.filter((x) => x !== id) : [...ids, id]);
667
+ else {
668
+ ctx.setValue(id);
669
+ setOpen(false);
670
+ setQ("");
671
+ }
672
+ };
673
+ if (ctx.readonly) return /* @__PURE__ */ jsx("div", { className: "cf-readonly", children: ids.map((id) => labels[id] ?? "\u2026").join(", ") || "\u2014" });
674
+ const current = !multi && ids[0] ? labels[ids[0]] ?? "\u2026" : "";
675
+ return /* @__PURE__ */ jsxs("div", { className: "cf-combo", ref: wrap, children: [
676
+ multi && ids.length ? /* @__PURE__ */ jsx("div", { className: "cf-chips", children: ids.map((id) => /* @__PURE__ */ jsxs("span", { className: "cf-chip", children: [
677
+ labels[id] ?? "\u2026",
678
+ /* @__PURE__ */ jsx("button", { type: "button", "aria-label": `${t.remove} ${labels[id] ?? ""}`, onClick: () => pick(id), children: "\xD7" })
679
+ ] }, id)) }) : null,
680
+ /* @__PURE__ */ jsx(
681
+ "input",
682
+ {
683
+ id: ctx.id,
684
+ className: "cf-control",
685
+ role: "combobox",
686
+ "aria-expanded": open,
687
+ "aria-controls": `${ctx.id}-list`,
688
+ "aria-invalid": ctx.invalid || void 0,
689
+ "aria-required": ctx.required || void 0,
690
+ autoComplete: "off",
691
+ placeholder: current || t.search,
692
+ value: open ? q : current,
693
+ onFocus: () => setOpen(true),
694
+ onChange: (e) => {
695
+ setQ(e.target.value);
696
+ setOpen(true);
697
+ },
698
+ onKeyDown: (e) => {
699
+ if (e.key === "ArrowDown") {
700
+ e.preventDefault();
701
+ setActive((a) => Math.min((results?.length ?? 1) - 1, a + 1));
702
+ } else if (e.key === "ArrowUp") {
703
+ e.preventDefault();
704
+ setActive((a) => Math.max(0, a - 1));
705
+ } else if (e.key === "Enter" && results?.[active]) {
706
+ e.preventDefault();
707
+ pick(results[active].id);
708
+ } else if (e.key === "Escape") {
709
+ setOpen(false);
710
+ }
711
+ }
712
+ }
713
+ ),
714
+ !multi && ids[0] && !open && !ctx.required ? /* @__PURE__ */ jsx(
715
+ "button",
716
+ {
717
+ type: "button",
718
+ className: "cf-btn",
719
+ style: { position: "absolute", right: 4, top: 4, height: 28, padding: "0 8px", border: 0 },
720
+ "aria-label": t.remove,
721
+ onClick: () => ctx.setValue(null),
722
+ children: "\xD7"
723
+ }
724
+ ) : null,
725
+ open ? /* @__PURE__ */ jsx("div", { className: "cf-list", role: "listbox", id: `${ctx.id}-list`, "aria-multiselectable": multi || void 0, children: results == null ? /* @__PURE__ */ jsx("div", { className: "cf-empty", children: t.loading }) : results.length === 0 ? /* @__PURE__ */ jsx("div", { className: "cf-empty", children: t.noResults }) : results.map((r, i) => /* @__PURE__ */ jsxs(
726
+ "button",
727
+ {
728
+ type: "button",
729
+ role: "option",
730
+ className: "cf-option",
731
+ "aria-selected": ids.includes(r.id),
732
+ "data-active": i === active || void 0,
733
+ onMouseDown: (e) => e.preventDefault(),
734
+ onClick: () => pick(r.id),
735
+ children: [
736
+ r.label,
737
+ ids.includes(r.id) ? /* @__PURE__ */ jsx("span", { "aria-hidden": true, children: "\u2713" }) : null
738
+ ]
739
+ },
740
+ r.id
741
+ )) }) : null
742
+ ] });
743
+ }
744
+ function DefaultInput(props) {
745
+ const { ctx, controller, t } = props;
746
+ const kind = kindOf(ctx.field);
747
+ const common = {
748
+ id: ctx.id,
749
+ className: "cf-control",
750
+ "aria-invalid": ctx.invalid || void 0,
751
+ "aria-required": ctx.required || void 0,
752
+ "aria-readonly": ctx.readonly || void 0,
753
+ readOnly: ctx.readonly,
754
+ onBlur: ctx.touch
755
+ };
756
+ switch (kind) {
757
+ case "relation":
758
+ case "relation_multi":
759
+ return /* @__PURE__ */ jsx(RelationInput, { ctx, controller, t, multi: kind === "relation_multi" });
760
+ case "list":
761
+ case "list_multi":
762
+ return /* @__PURE__ */ jsx(ListInput, { ctx, controller, t, multi: kind === "list_multi" });
763
+ case "boolean":
764
+ return /* @__PURE__ */ jsxs("label", { className: "cf-check", children: [
765
+ /* @__PURE__ */ jsx(
766
+ "input",
767
+ {
768
+ id: ctx.id,
769
+ type: "checkbox",
770
+ checked: ctx.value === true,
771
+ disabled: ctx.readonly,
772
+ onChange: (e) => ctx.setValue(e.target.checked),
773
+ onBlur: ctx.touch
774
+ }
775
+ ),
776
+ ctx.value === true ? t.yes : t.no
777
+ ] });
778
+ case "number":
779
+ return /* @__PURE__ */ jsx(
780
+ "input",
781
+ {
782
+ ...common,
783
+ type: "number",
784
+ step: "any",
785
+ inputMode: "decimal",
786
+ value: typeof ctx.value === "number" || typeof ctx.value === "string" ? String(ctx.value) : "",
787
+ onChange: (e) => ctx.setValue(e.target.value === "" ? null : Number(e.target.value))
788
+ }
789
+ );
790
+ case "date":
791
+ return /* @__PURE__ */ jsx(
792
+ "input",
793
+ {
794
+ ...common,
795
+ type: "date",
796
+ value: typeof ctx.value === "string" ? ctx.value.slice(0, 10) : "",
797
+ onChange: (e) => ctx.setValue(e.target.value || null)
798
+ }
799
+ );
800
+ case "datetime":
801
+ return /* @__PURE__ */ jsx(
802
+ "input",
803
+ {
804
+ ...common,
805
+ type: "datetime-local",
806
+ value: toLocalInput(ctx.value),
807
+ onChange: (e) => ctx.setValue(e.target.value ? new Date(e.target.value).toISOString() : null)
808
+ }
809
+ );
810
+ case "textarea":
811
+ return /* @__PURE__ */ jsx(
812
+ "textarea",
813
+ {
814
+ ...common,
815
+ rows: 3,
816
+ value: typeof ctx.value === "string" ? ctx.value : plain(ctx.value),
817
+ onChange: (e) => ctx.setValue(e.target.value === "" ? null : e.target.value)
818
+ }
819
+ );
820
+ default:
821
+ return /* @__PURE__ */ jsx(
822
+ "input",
823
+ {
824
+ ...common,
825
+ type: "text",
826
+ value: typeof ctx.value === "string" || typeof ctx.value === "number" ? String(ctx.value) : "",
827
+ onChange: (e) => ctx.setValue(e.target.value === "" ? null : e.target.value)
828
+ }
829
+ );
830
+ }
831
+ }
832
+ function Field(props) {
833
+ useCervioFormStyles(props.unstyled);
834
+ const { controller, name } = props;
835
+ const state = useFormState(controller);
836
+ const id = `cf-${useId().replace(/:/g, "")}-${name}`;
837
+ const t = formLabels(props.locale ?? state.schema?.locale, props.labels);
838
+ const field = state.fields[name];
839
+ if (!field) return null;
840
+ const fs = state.fieldState[name] ?? { visible: true, required: field.required, readonly: field.readonly };
841
+ if (!fs.visible && !props.showHidden) return null;
842
+ const error = state.errors[name];
843
+ const ctx = {
844
+ field,
845
+ value: state.values[name],
846
+ setValue: (v) => controller.setValue(name, v),
847
+ touch: () => controller.touch(name),
848
+ readonly: fs.readonly,
849
+ required: fs.required,
850
+ invalid: !!error,
851
+ id,
852
+ state,
853
+ nodeId: props.nodeId
854
+ };
855
+ return /* @__PURE__ */ jsxs(
856
+ "div",
857
+ {
858
+ className: ["cf-field", props.className].filter(Boolean).join(" "),
859
+ style: props.style,
860
+ "data-field": name,
861
+ "data-invalid": error ? "true" : void 0,
862
+ children: [
863
+ props.hideLabel ? null : /* @__PURE__ */ jsxs("label", { className: "cf-label", htmlFor: id, id: `${id}-label`, children: [
864
+ props.label ?? field.label,
865
+ fs.required && !fs.readonly ? /* @__PURE__ */ jsx("span", { className: "cf-req", "aria-hidden": true, children: "*" }) : null
866
+ ] }),
867
+ props.renderInput ? props.renderInput(ctx) : /* @__PURE__ */ jsx(DefaultInput, { ctx, controller, t }),
868
+ error ? /* @__PURE__ */ jsx("div", { className: "cf-error", role: "alert", children: error }) : props.hint ?? field.instructions ? /* @__PURE__ */ jsx("div", { className: "cf-hint", children: props.hint ?? field.instructions }) : null
869
+ ]
870
+ }
871
+ );
872
+ }
873
+ function layoutFields(nodes) {
874
+ const out = [];
875
+ const walk = (n) => {
876
+ switch (n.type) {
877
+ case "field":
878
+ out.push(n.field);
879
+ break;
880
+ case "group":
881
+ n.children.forEach(walk);
882
+ break;
883
+ case "columns":
884
+ n.columns.forEach((c) => c.forEach(walk));
885
+ break;
886
+ case "tabs":
887
+ n.tabs.forEach((t) => t.children.forEach(walk));
888
+ break;
889
+ case "steps":
890
+ n.steps.forEach((s) => s.children.forEach(walk));
891
+ break;
892
+ }
893
+ };
894
+ nodes.forEach(walk);
895
+ return out;
896
+ }
897
+ function shown(ctx, nodes) {
898
+ const only = ctx.props.only;
899
+ if (!only) return true;
900
+ return layoutFields(nodes).some((n) => only.includes(n) && ctx.state.fieldState[n]?.visible !== false);
901
+ }
902
+ function hasError(ctx, nodes) {
903
+ return layoutFields(nodes).some((n) => ctx.state.errors[n]);
904
+ }
905
+ function FieldNode({ ctx, node }) {
906
+ if (ctx.props.only && !ctx.props.only.includes(node.field)) return null;
907
+ const custom = ctx.props.renderField?.(node.field, node);
908
+ if (custom !== void 0) return /* @__PURE__ */ jsx(Fragment, { children: custom });
909
+ return /* @__PURE__ */ jsx(
910
+ Field,
911
+ {
912
+ controller: ctx.controller,
913
+ name: node.field,
914
+ nodeId: node.id,
915
+ hint: node.instructions,
916
+ hideLabel: node.hide_label,
917
+ locale: ctx.props.locale ?? ctx.state.schema?.locale,
918
+ labels: ctx.props.labels,
919
+ unstyled: ctx.props.unstyled
920
+ }
921
+ );
922
+ }
923
+ function Nodes({ ctx, nodes }) {
924
+ return /* @__PURE__ */ jsx("div", { className: "cf-grid", children: nodes.map((n, i) => {
925
+ if (n.type === "field") {
926
+ if (ctx.state.fieldState[n.field]?.visible === false) return null;
927
+ if (ctx.props.only && !ctx.props.only.includes(n.field)) return null;
928
+ const half = n.width === "half" || n.width === 1;
929
+ return /* @__PURE__ */ jsx("div", { className: half ? void 0 : "cf-full", children: /* @__PURE__ */ jsx(FieldNode, { ctx, node: n }) }, `f-${n.field}-${i}`);
930
+ }
931
+ const block = /* @__PURE__ */ jsx(Block, { ctx, node: n }, `b-${i}`);
932
+ return /* @__PURE__ */ jsx("div", { className: "cf-full", children: block }, `b-${i}`);
933
+ }) });
934
+ }
935
+ function Group({ ctx, node }) {
936
+ const [open, setOpen] = useState(node.default_expanded !== false);
937
+ if (!shown(ctx, node.children)) return null;
938
+ const title = node.title ? node.collapsible ? /* @__PURE__ */ jsxs("button", { type: "button", className: "cf-group-title", "aria-expanded": open, onClick: () => setOpen((o) => !o), children: [
939
+ /* @__PURE__ */ jsx("span", { "aria-hidden": true, children: open ? "\u25BE" : "\u25B8" }),
940
+ node.title
941
+ ] }) : /* @__PURE__ */ jsx("div", { className: "cf-group-title", children: node.title }) : null;
942
+ return /* @__PURE__ */ jsxs("section", { className: "cf-group", children: [
943
+ title,
944
+ !node.collapsible || open ? /* @__PURE__ */ jsx(Nodes, { ctx, nodes: node.children }) : null
945
+ ] });
946
+ }
947
+ function Tabs({ ctx, node }) {
948
+ const visible = node.tabs.map((tab, i) => ({ tab, i })).filter(({ tab }) => shown(ctx, tab.children));
949
+ const [current, setCurrent] = useState(0);
950
+ if (!visible.length) return null;
951
+ const active = visible.find((v) => v.i === current) ?? visible[0];
952
+ return /* @__PURE__ */ jsxs("div", { children: [
953
+ /* @__PURE__ */ jsx("div", { className: "cf-tabs", role: "tablist", children: visible.map(({ tab, i }) => /* @__PURE__ */ jsx(
954
+ "button",
955
+ {
956
+ type: "button",
957
+ role: "tab",
958
+ className: "cf-tab",
959
+ "aria-selected": active.i === i,
960
+ "data-invalid": hasError(ctx, tab.children) || void 0,
961
+ onClick: () => setCurrent(i),
962
+ children: tab.label
963
+ },
964
+ i
965
+ )) }),
966
+ /* @__PURE__ */ jsx("div", { role: "tabpanel", children: /* @__PURE__ */ jsx(Nodes, { ctx, nodes: active.tab.children }) })
967
+ ] });
968
+ }
969
+ function Steps({ ctx, node }) {
970
+ const visible = node.steps.filter((s) => !hiddenByCervio(ctx, s.id) && shown(ctx, s.children));
971
+ const [current, setCurrent] = useState(0);
972
+ const [blocked, setBlocked] = useState(null);
973
+ if (!visible.length) return null;
974
+ if (ctx.props.flattenSteps) {
975
+ return /* @__PURE__ */ jsx(Fragment, { children: visible.map((s, i) => /* @__PURE__ */ jsxs("section", { className: "cf-group", children: [
976
+ /* @__PURE__ */ jsx("div", { className: "cf-group-title", children: s.label }),
977
+ /* @__PURE__ */ jsx(Nodes, { ctx, nodes: s.children })
978
+ ] }, i)) });
979
+ }
980
+ const idx = Math.min(current, visible.length - 1);
981
+ const step = visible[idx];
982
+ const next = async () => {
983
+ const names = layoutFields(step.children);
984
+ names.forEach((n) => ctx.controller.touch(n));
985
+ await ctx.controller.validate();
986
+ const after = ctx.controller.getState();
987
+ if (names.some((n) => after.draftErrors[n])) return;
988
+ if (step.advance_rule && step.id && after.blockedSteps.includes(step.id)) {
989
+ setBlocked({ step: step.id, message: step.advance_message || ctx.t.stepBlocked });
990
+ return;
991
+ }
992
+ setCurrent(idx + 1);
993
+ };
994
+ return /* @__PURE__ */ jsxs("div", { className: "cf-root", style: { gap: 12 }, children: [
995
+ /* @__PURE__ */ jsx("div", { className: "cf-tabs", role: "tablist", children: visible.map((s, i) => /* @__PURE__ */ jsxs(
996
+ "button",
997
+ {
998
+ type: "button",
999
+ role: "tab",
1000
+ className: "cf-tab",
1001
+ "aria-selected": i === idx,
1002
+ "data-invalid": hasError(ctx, s.children) || void 0,
1003
+ disabled: i > idx,
1004
+ onClick: () => i <= idx && setCurrent(i),
1005
+ children: [
1006
+ i + 1,
1007
+ ". ",
1008
+ s.label
1009
+ ]
1010
+ },
1011
+ i
1012
+ )) }),
1013
+ /* @__PURE__ */ jsx(Nodes, { ctx, nodes: step.children }),
1014
+ blocked && blocked.step === step.id && ctx.state.blockedSteps.includes(blocked.step) ? /* @__PURE__ */ jsx("div", { className: "cf-alert", "data-tone": "warning", role: "alert", children: blocked.message }) : null,
1015
+ /* @__PURE__ */ jsxs("div", { className: "cf-actions", children: [
1016
+ idx > 0 ? /* @__PURE__ */ jsx("button", { type: "button", className: "cf-btn", onClick: () => setCurrent(idx - 1), children: ctx.t.back }) : null,
1017
+ idx < visible.length - 1 ? /* @__PURE__ */ jsx("button", { type: "button", className: "cf-btn", "data-variant": "primary", onClick: () => void next(), children: ctx.t.next }) : null
1018
+ ] })
1019
+ ] });
1020
+ }
1021
+ function fillValues(ctx, text) {
1022
+ const { values, fields, relationLabels } = ctx.state;
1023
+ const one = (name, v) => {
1024
+ if (v == null || v === "") return "";
1025
+ const choices = fieldDisplayFor(ctx.state, name)?.options ?? fields[name]?.input?.options;
1026
+ const choice = choices?.find((o) => o.value === v);
1027
+ if (choice) return choice.label;
1028
+ return relationLabels[name]?.[String(v)] ?? String(v);
1029
+ };
1030
+ return text.replace(/\{\{\s*([\w-]+)\s*\}\}/g, (_, name) => {
1031
+ const v = values[name];
1032
+ return Array.isArray(v) ? v.map((x) => one(name, x)).filter(Boolean).join(", ") : one(name, v);
1033
+ });
1034
+ }
1035
+ function hiddenByCervio(ctx, id) {
1036
+ return !!id && ctx.state.hiddenBlocks.includes(id);
1037
+ }
1038
+ function Block({ ctx, node }) {
1039
+ if (hiddenByCervio(ctx, node.id)) return null;
1040
+ switch (node.type) {
1041
+ case "group":
1042
+ return /* @__PURE__ */ jsx(Group, { ctx, node });
1043
+ case "columns": {
1044
+ if (!shown(ctx, node.columns.flat())) return null;
1045
+ return /* @__PURE__ */ jsx("div", { className: "cf-columns", style: { gridTemplateColumns: `repeat(${node.columns.length}, minmax(0, 1fr))` }, children: node.columns.map((col, i) => /* @__PURE__ */ jsx("div", { className: "cf-col", children: /* @__PURE__ */ jsx(Nodes, { ctx, nodes: col.map((n) => n.type === "field" ? { ...n, width: "full" } : n) }) }, i)) });
1046
+ }
1047
+ case "tabs":
1048
+ return /* @__PURE__ */ jsx(Tabs, { ctx, node });
1049
+ case "steps":
1050
+ return /* @__PURE__ */ jsx(Steps, { ctx, node });
1051
+ case "divider":
1052
+ return ctx.props.only ? null : /* @__PURE__ */ jsx("hr", { className: "cf-divider" });
1053
+ case "text":
1054
+ return ctx.props.only ? null : /* @__PURE__ */ jsx("p", { className: "cf-text", children: node.content.replace(/\*\*(.+?)\*\*/g, "$1") });
1055
+ case "alert": {
1056
+ if (ctx.props.only) return null;
1057
+ const title = fillValues(ctx, node.title ?? "");
1058
+ const content = fillValues(ctx, node.content);
1059
+ if (!title.trim() && !content.trim()) return null;
1060
+ return /* @__PURE__ */ jsxs("div", { className: "cf-alert", "data-tone": node.tone, role: "note", children: [
1061
+ title ? /* @__PURE__ */ jsx("strong", { className: "cf-alert-title", children: title }) : null,
1062
+ content ? /* @__PURE__ */ jsx("span", { children: content.replace(/\*\*(.+?)\*\*/g, "$1") }) : null
1063
+ ] });
1064
+ }
1065
+ case "block":
1066
+ return null;
1067
+ }
1068
+ }
1069
+ function FormLayout(props) {
1070
+ useCervioFormStyles(props.unstyled);
1071
+ const state = useFormState(props.controller);
1072
+ const t = formLabels(props.locale ?? state.schema?.locale, props.labels);
1073
+ if (!state.layout) return null;
1074
+ const ctx = { controller: props.controller, state, props, t };
1075
+ return /* @__PURE__ */ jsx("div", { className: ["cf-root", props.className].filter(Boolean).join(" "), style: props.style, children: /* @__PURE__ */ jsx(Nodes, { ctx, nodes: state.layout.children }) });
1076
+ }
1077
+ function FormActions(props) {
1078
+ useCervioFormStyles(props.unstyled);
1079
+ const { controller } = props;
1080
+ const s = useFormState(controller);
1081
+ const t = formLabels(props.locale ?? s.schema?.locale, props.labels);
1082
+ const [savedAt, setSavedAt] = useState(null);
1083
+ useEffect(() => {
1084
+ if (s.dirty.length) setSavedAt(null);
1085
+ }, [s.dirty.length]);
1086
+ const errors = s.submitted ? Object.entries(s.errors) : [];
1087
+ const status = s.saving ? t.saving : s.validating && s.dirty.length ? t.checking : s.dirty.length ? t.unsaved(s.dirty.length) : savedAt ? t.saved : "";
1088
+ return /* @__PURE__ */ jsxs("div", { className: ["cf-root", props.className].filter(Boolean).join(" "), style: { gap: 10, ...props.style }, children: [
1089
+ s.conflict ? /* @__PURE__ */ jsxs("div", { className: "cf-alert", role: "alert", children: [
1090
+ /* @__PURE__ */ jsx("span", { children: t.conflict }),
1091
+ /* @__PURE__ */ jsx("button", { type: "button", className: "cf-btn", onClick: () => void controller.reload(), children: t.reload })
1092
+ ] }) : s.saveError ? /* @__PURE__ */ jsx("div", { className: "cf-alert", role: "alert", children: /* @__PURE__ */ jsxs("span", { children: [
1093
+ t.error,
1094
+ ": ",
1095
+ s.saveError.message
1096
+ ] }) }) : null,
1097
+ errors.length ? /* @__PURE__ */ jsxs("div", { role: "alert", children: [
1098
+ /* @__PURE__ */ jsx("div", { className: "cf-error", children: t.fixErrors }),
1099
+ /* @__PURE__ */ jsx("ul", { className: "cf-summary", children: errors.map(([name, msg]) => /* @__PURE__ */ jsxs("li", { children: [
1100
+ s.fields[name]?.label ?? name,
1101
+ ": ",
1102
+ msg
1103
+ ] }, name)) })
1104
+ ] }) : null,
1105
+ /* @__PURE__ */ jsxs("div", { className: "cf-actions", children: [
1106
+ /* @__PURE__ */ jsx("span", { className: "cf-status", "aria-live": "polite", children: status }),
1107
+ props.hideCancel ? null : /* @__PURE__ */ jsx(
1108
+ "button",
1109
+ {
1110
+ type: "button",
1111
+ className: "cf-btn",
1112
+ disabled: !s.dirty.length || s.saving,
1113
+ onClick: () => controller.reset(),
1114
+ children: t.cancel
1115
+ }
1116
+ ),
1117
+ /* @__PURE__ */ jsx(
1118
+ "button",
1119
+ {
1120
+ type: "button",
1121
+ className: "cf-btn",
1122
+ "data-variant": "primary",
1123
+ disabled: s.status !== "ready" || s.saving || s.mode === "edit" && !s.dirty.length,
1124
+ onClick: async () => {
1125
+ const r = await controller.save();
1126
+ if (r) {
1127
+ setSavedAt(Date.now());
1128
+ props.onSaved?.(r);
1129
+ }
1130
+ },
1131
+ children: s.saving ? t.saving : t.save
1132
+ }
1133
+ )
1134
+ ] })
1135
+ ] });
1136
+ }
1137
+
1138
+ // src/forms/react.ts
1139
+ function useCervioForm(opts) {
1140
+ const controller = useMemo(() => createPluginFormController(opts), [opts.entity, opts.form, opts.recordId]);
1141
+ useEffect(() => () => controller.destroy(), [controller]);
1142
+ const state = useSyncExternalStore(controller.subscribe, controller.getState, controller.getState);
1143
+ return {
1144
+ ...state,
1145
+ controller,
1146
+ ready: controller.ready,
1147
+ setValue: controller.setValue,
1148
+ setValues: controller.setValues,
1149
+ touch: controller.touch,
1150
+ validate: controller.validate,
1151
+ save: controller.save,
1152
+ reset: controller.reset,
1153
+ reload: controller.reload,
1154
+ fieldOptions: controller.fieldOptions,
1155
+ relationOptions: controller.relationOptions
1156
+ };
1157
+ }
1158
+
1159
+ export { CERVIO_FORM_CSS, Field, FormActions, FormLayout, ensureCervioFormStyles, formLabels, layoutFields, useCervioForm, useFormState };