@nibblearn/editor 0.0.0-stage → 0.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.
package/dist/index.js ADDED
@@ -0,0 +1,1987 @@
1
+ import { createContext, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from "react";
2
+ import { AlertCircle, ArrowDown, ArrowUp, Bold, ChevronDown, Code, Copy, ImagePlus, Italic, Link, List, Plus, Search, Settings, Trash2, X } from "lucide-react";
3
+ import { LiveRegion, ModuleIcon, ModuleRenderer, SafeImage, builtInModuleTypes, defaultRegistry, formatMessage, getLessonJsonSchema, getModuleJsonSchema, humanizeKey, stripMarkup, useAnnounce, useNibblearn, useRootProps, validateLesson, validateModule } from "@nibblearn/react";
4
+ import clsx from "clsx";
5
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
+ import { createEmpty, createExample } from "@nibblearn/core/examples";
7
+ // src/messages.ts
8
+ /** English UI strings of the editor. Override any of them through `NibblearnProvider messages`. */
9
+ var editorMessages = {
10
+ "editor.add": "Add {item}",
11
+ "editor.remove": "Delete",
12
+ "editor.removeItem": "Delete {item} {index}",
13
+ "editor.duplicate": "Duplicate",
14
+ "editor.duplicateItem": "Duplicate {item} {index}",
15
+ "editor.moveUp": "Move up",
16
+ "editor.moveUpItem": "Move {item} {index} up",
17
+ "editor.moveDown": "Move down",
18
+ "editor.moveDownItem": "Move {item} {index} down",
19
+ "editor.expandItem": "Show {item} {index}",
20
+ "editor.collapseItem": "Hide {item} {index}",
21
+ "editor.itemAdded": "{item} added.",
22
+ "editor.itemRemoved": "{item} {index} deleted.",
23
+ "editor.itemMoved": "{item} moved to position {position}.",
24
+ "editor.itemDuplicated": "{item} duplicated.",
25
+ "editor.untitled": "Untitled {item}",
26
+ "editor.optional": "optional",
27
+ "editor.set": "Add",
28
+ "editor.clear": "Clear",
29
+ "editor.variant": "Type",
30
+ "editor.group.content": "Content",
31
+ "editor.group.behavior": "Behaviour",
32
+ "editor.group.feedback": "Feedback",
33
+ "editor.group.appearance": "Appearance",
34
+ "editor.group.advanced": "Advanced",
35
+ "editor.image.src": "Image URL",
36
+ "editor.image.alt": "Alternative text",
37
+ "editor.image.caption": "Caption",
38
+ "editor.image.choose": "Choose image",
39
+ "editor.image.decorative": "Leave empty for a decorative image.",
40
+ "editor.richtext.bold": "Bold",
41
+ "editor.richtext.italic": "Italic",
42
+ "editor.richtext.code": "Code",
43
+ "editor.richtext.link": "Link",
44
+ "editor.richtext.list": "List",
45
+ "editor.richtext.toolbar": "Formatting for {field}",
46
+ "editor.json.invalid": "Not valid JSON.",
47
+ "editor.record.key": "Key",
48
+ "editor.record.value": "Value",
49
+ "editor.record.add": "Add entry",
50
+ "editor.issues.title": "Fix {count} problem(s) before this block can be shown",
51
+ "editor.issues.goTo": "Go to {field}",
52
+ "editor.preview": "Preview",
53
+ "editor.preview.lastValid": "Showing the last valid version while you edit.",
54
+ "editor.form": "Settings",
55
+ "editor.picker.title": "Add a block",
56
+ "editor.picker.search": "Search blocks",
57
+ "editor.picker.example": "With example content",
58
+ "editor.picker.blank": "Blank",
59
+ "editor.picker.start": "Start from",
60
+ "editor.picker.empty": "No blocks match “{query}”.",
61
+ "editor.picker.add": "Add {name}",
62
+ "editor.category.learn": "Learn",
63
+ "editor.category.practice": "Practice",
64
+ "editor.category.explore": "Explore",
65
+ "editor.category.decide": "Decide",
66
+ "editor.category.simulate": "Simulate",
67
+ "editor.category.present": "Present",
68
+ "editor.lesson.modules": "Blocks",
69
+ "editor.lesson.settings": "Lesson settings",
70
+ "editor.lesson.addBlock": "Add block",
71
+ "editor.lesson.empty": "This lesson has no blocks yet.",
72
+ "editor.lesson.select": "Edit {name}",
73
+ "editor.lesson.position": "Block {current} of {total}",
74
+ "editor.lesson.hasIssues": "Has problems",
75
+ "editor.lesson.blockIssues": "In this lesson:"
76
+ };
77
+ /** Translator for editor strings: provider `messages` first, then the English defaults. */
78
+ function useEditorT() {
79
+ const { messages } = useNibblearn();
80
+ return useCallback((key, values) => {
81
+ const own = Object.prototype.hasOwnProperty.call(messages, key) ? messages[key] : void 0;
82
+ const fallback = Object.prototype.hasOwnProperty.call(editorMessages, key) ? editorMessages[key] : key;
83
+ return formatMessage(own ?? fallback, values);
84
+ }, [messages]);
85
+ }
86
+ // src/form/context.ts
87
+ var FormContext = createContext(null);
88
+ function useForm() {
89
+ const ctx = useContext(FormContext);
90
+ if (!ctx) throw new Error("Form fields must be rendered inside ModuleForm");
91
+ return ctx;
92
+ }
93
+ /** DOM id for the control at `path`. */
94
+ var fieldId = (formId, path) => `${formId}-${path.map(String).join("-") || "root"}`;
95
+ /** Key used to match validation issues to fields. */
96
+ var pathKey = (path) => path.map(String).join(".");
97
+ function issueMap(issues) {
98
+ const map = /* @__PURE__ */ new Map();
99
+ for (const issue of issues ?? []) {
100
+ const key = issue.segments ? pathKey(issue.segments) : issue.path.replace(/\[(\d+)\]/g, ".$1");
101
+ map.set(key, [...map.get(key) ?? [], issue.message]);
102
+ }
103
+ return map;
104
+ }
105
+ // src/form/defaults.ts
106
+ /** A new id like `card-3` that is not used by `siblings` (deterministic: a counter, not random). */
107
+ function uniqueId(prefix, taken) {
108
+ const used = new Set(taken);
109
+ const base = prefix.replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "item";
110
+ for (let n = 1; n < 1e5; n++) {
111
+ const id = `${base}-${n}`;
112
+ if (!used.has(id)) return id;
113
+ }
114
+ return `${base}-${used.size + 1}`;
115
+ }
116
+ /**
117
+ * A minimal value for a node: required object fields filled recursively, `minItems` array
118
+ * items, the first enum value, `min` for numbers. Optional fields are left out.
119
+ */
120
+ function defaultFor(node, ctx = {}, depth = 0) {
121
+ if (depth > 20) return void 0;
122
+ if (node.default !== void 0) return structuredClone(node.default);
123
+ switch (node.kind) {
124
+ case "string":
125
+ if (node.ui.widget === "id") return uniqueId(ctx.idPrefix ?? "item", ctx.takenIds ?? []);
126
+ if (node.enum?.length) return node.enum[0];
127
+ return node.minLength ? "New text" : "";
128
+ case "number": {
129
+ const inc = node.step ?? 1;
130
+ const lo = node.min === void 0 ? void 0 : node.min + (node.minExclusive ? inc : 0);
131
+ const hi = node.max === void 0 ? void 0 : node.max - (node.maxExclusive ? inc : 0);
132
+ if (lo !== void 0 && lo > 0) return lo;
133
+ if (hi !== void 0 && hi < 0) return hi;
134
+ return 0;
135
+ }
136
+ case "boolean": return false;
137
+ case "const": return node.value;
138
+ case "object": {
139
+ const out = {};
140
+ for (const f of node.fields) {
141
+ if (!f.required) continue;
142
+ const v = defaultFor(f.node, f.key === "id" ? ctx : { idPrefix: f.key }, depth + 1);
143
+ if (v !== void 0) out[f.key] = v;
144
+ }
145
+ return out;
146
+ }
147
+ case "array": {
148
+ const n = node.minItems ?? 0;
149
+ const items = [];
150
+ const prefix = node.ui.itemName ?? "item";
151
+ for (let i = 0; i < n; i++) {
152
+ const taken = items.map((it) => typeof it === "object" && it && "id" in it ? String(it.id) : "").filter(Boolean);
153
+ items.push(defaultFor(node.item, {
154
+ idPrefix: prefix,
155
+ takenIds: taken
156
+ }, depth + 1));
157
+ }
158
+ return items;
159
+ }
160
+ case "union": {
161
+ const first = node.variants[0];
162
+ return first ? defaultFor(first.node, ctx, depth + 1) : void 0;
163
+ }
164
+ case "record": return {};
165
+ default: return null;
166
+ }
167
+ }
168
+ // src/form/path.ts
169
+ var FORBIDDEN = /* @__PURE__ */ new Set([
170
+ "__proto__",
171
+ "constructor",
172
+ "prototype"
173
+ ]);
174
+ function assertSafe(path) {
175
+ for (const seg of path) if (typeof seg === "string" && FORBIDDEN.has(seg)) throw new TypeError(`unsafe path segment "${seg}"`);
176
+ }
177
+ var isRecord$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
178
+ /** Read the value at `path` (own properties only). */
179
+ function getAt(root, path) {
180
+ let cur = root;
181
+ for (const seg of path) if (typeof seg === "number") {
182
+ if (!Array.isArray(cur)) return void 0;
183
+ cur = cur[seg];
184
+ } else {
185
+ if (!isRecord$1(cur) || !Object.prototype.hasOwnProperty.call(cur, seg)) return void 0;
186
+ cur = cur[seg];
187
+ }
188
+ return cur;
189
+ }
190
+ /**
191
+ * Return a copy of `root` with `value` at `path`; containers along the path are copied, the
192
+ * rest is shared. `undefined` removes an object key.
193
+ */
194
+ function setAt(root, path, value) {
195
+ assertSafe(path);
196
+ const rec = (node, i) => {
197
+ if (i === path.length) return value;
198
+ const seg = path[i];
199
+ if (typeof seg === "number") {
200
+ const arr = Array.isArray(node) ? [...node] : [];
201
+ arr[seg] = rec(arr[seg], i + 1);
202
+ return arr;
203
+ }
204
+ const obj = isRecord$1(node) ? { ...node } : {};
205
+ const next = rec(Object.prototype.hasOwnProperty.call(obj, seg) ? obj[seg] : void 0, i + 1);
206
+ if (next === void 0) delete obj[seg];
207
+ else obj[seg] = next;
208
+ return obj;
209
+ };
210
+ return rec(root, 0);
211
+ }
212
+ /** Remove the array item or object key at `path`. */
213
+ function removeAt(root, path) {
214
+ if (path.length === 0) return root;
215
+ const parentPath = path.slice(0, -1);
216
+ const last = path[path.length - 1];
217
+ const parent = getAt(root, parentPath);
218
+ if (typeof last === "number" && Array.isArray(parent)) return setAt(root, parentPath, parent.filter((_, i) => i !== last));
219
+ return setAt(root, path, void 0);
220
+ }
221
+ /** Insert `value` into the array at `path` before `index` (default: at the end). */
222
+ function insertAt(root, path, value, index) {
223
+ const arr = getAt(root, path);
224
+ const list = Array.isArray(arr) ? [...arr] : [];
225
+ list.splice(index ?? list.length, 0, value);
226
+ return setAt(root, path, list);
227
+ }
228
+ /** Move the array item at `path` from `from` to `to`. */
229
+ function moveItem(root, path, from, to) {
230
+ const arr = getAt(root, path);
231
+ if (!Array.isArray(arr) || from === to || to < 0 || to >= arr.length || from < 0 || from >= arr.length) return root;
232
+ const list = [...arr];
233
+ const [item] = list.splice(from, 1);
234
+ list.splice(to, 0, item);
235
+ return setAt(root, path, list);
236
+ }
237
+ // src/form/fields.tsx
238
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
239
+ /** Label for a field: `field.<type>.<path>` message override, then the schema title. */
240
+ function useLabel(path, node, fallbackKey) {
241
+ const { type } = useForm();
242
+ const t = useEditorT();
243
+ const key = `field.${type}.${path.filter((s) => typeof s === "string").join(".")}`;
244
+ const custom = t(key);
245
+ return custom !== key ? custom : node.title ?? humanizeKey(fallbackKey);
246
+ }
247
+ /** Label, description and error wrapper shared by single-control fields. */
248
+ function FieldFrame({ id, label, description, errors, required, children, inline }) {
249
+ const t = useEditorT();
250
+ return /* @__PURE__ */ jsxs("div", {
251
+ className: clsx("nbe-field", inline && "nbe-field--inline", errors.length > 0 && "nbe-field--invalid"),
252
+ children: [
253
+ /* @__PURE__ */ jsxs("label", {
254
+ className: "nbe-field__label",
255
+ htmlFor: id,
256
+ children: [label, !required && /* @__PURE__ */ jsxs("span", {
257
+ className: "nbe-field__optional",
258
+ children: [
259
+ " (",
260
+ t("editor.optional"),
261
+ ")"
262
+ ]
263
+ })]
264
+ }),
265
+ children,
266
+ description && /* @__PURE__ */ jsx("p", {
267
+ className: "nbe-field__help",
268
+ id: `${id}-help`,
269
+ children: description
270
+ }),
271
+ errors.length > 0 && /* @__PURE__ */ jsx("p", {
272
+ className: "nbe-field__error",
273
+ id: `${id}-error`,
274
+ children: errors.join(" ")
275
+ })
276
+ ]
277
+ });
278
+ }
279
+ var describedBy = (id, description, errors = []) => [description && `${id}-help`, errors.length && `${id}-error`].filter(Boolean).join(" ") || void 0;
280
+ function TextField({ node, path, value, label, required }) {
281
+ const { formId, update, issuesAt } = useForm();
282
+ const id = fieldId(formId, path);
283
+ const errors = issuesAt(path);
284
+ const multiline = node.ui.widget === "textarea";
285
+ const str = typeof value === "string" ? value : "";
286
+ const onChange = (v) => update(path, v === "" && !required ? void 0 : v);
287
+ const common = {
288
+ id,
289
+ className: "nbe-input",
290
+ value: str,
291
+ maxLength: node.kind === "string" ? node.maxLength : void 0,
292
+ "aria-invalid": errors.length > 0 || void 0,
293
+ "aria-describedby": describedBy(id, node.description, errors)
294
+ };
295
+ return /* @__PURE__ */ jsx(FieldFrame, {
296
+ id,
297
+ label,
298
+ description: node.description,
299
+ errors,
300
+ required,
301
+ children: multiline ? /* @__PURE__ */ jsx("textarea", {
302
+ ...common,
303
+ rows: 3,
304
+ onChange: (e) => onChange(e.target.value)
305
+ }) : /* @__PURE__ */ jsx("input", {
306
+ ...common,
307
+ type: "text",
308
+ onChange: (e) => onChange(e.target.value)
309
+ })
310
+ });
311
+ }
312
+ /** Wraps the selection of a textarea in markup, e.g. **bold**. */
313
+ function wrapSelection(el, before, after, placeholder) {
314
+ const { selectionStart: s, selectionEnd: e, value } = el;
315
+ const selected = value.slice(s, e) || placeholder;
316
+ return {
317
+ next: value.slice(0, s) + before + selected + after + value.slice(e),
318
+ start: s + before.length,
319
+ end: s + before.length + selected.length
320
+ };
321
+ }
322
+ function RichTextField({ node, path, value, label, required }) {
323
+ const { formId, update, issuesAt } = useForm();
324
+ const t = useEditorT();
325
+ const id = fieldId(formId, path);
326
+ const errors = issuesAt(path);
327
+ const ref = useRef(null);
328
+ const block = node.ui.widget === "richtext-block";
329
+ const str = typeof value === "string" ? value : "";
330
+ const set = (v) => update(path, v === "" && !required ? void 0 : v);
331
+ const apply = (before, after, placeholder) => {
332
+ const el = ref.current;
333
+ if (!el) return;
334
+ const { next, start, end } = wrapSelection(el, before, after, placeholder);
335
+ set(next);
336
+ requestAnimationFrame(() => {
337
+ el.focus();
338
+ el.setSelectionRange(start, end);
339
+ });
340
+ };
341
+ const tools = [
342
+ [
343
+ t("editor.richtext.bold"),
344
+ /* @__PURE__ */ jsx(Bold, {
345
+ "aria-hidden": true,
346
+ size: 16
347
+ }, "b"),
348
+ "**",
349
+ "**",
350
+ "bold"
351
+ ],
352
+ [
353
+ t("editor.richtext.italic"),
354
+ /* @__PURE__ */ jsx(Italic, {
355
+ "aria-hidden": true,
356
+ size: 16
357
+ }, "i"),
358
+ "*",
359
+ "*",
360
+ "italic"
361
+ ],
362
+ [
363
+ t("editor.richtext.code"),
364
+ /* @__PURE__ */ jsx(Code, {
365
+ "aria-hidden": true,
366
+ size: 16
367
+ }, "c"),
368
+ "`",
369
+ "`",
370
+ "code"
371
+ ],
372
+ [
373
+ t("editor.richtext.link"),
374
+ /* @__PURE__ */ jsx(Link, {
375
+ "aria-hidden": true,
376
+ size: 16
377
+ }, "l"),
378
+ "[",
379
+ "](https://)",
380
+ "link text"
381
+ ],
382
+ ...block ? [[
383
+ t("editor.richtext.list"),
384
+ /* @__PURE__ */ jsx(List, {
385
+ "aria-hidden": true,
386
+ size: 16
387
+ }, "li"),
388
+ "\n- ",
389
+ "",
390
+ "item"
391
+ ]] : []
392
+ ];
393
+ return /* @__PURE__ */ jsxs(FieldFrame, {
394
+ id,
395
+ label,
396
+ description: node.description,
397
+ errors,
398
+ required,
399
+ children: [/* @__PURE__ */ jsx("div", {
400
+ className: "nbe-toolbar",
401
+ role: "toolbar",
402
+ "aria-label": t("editor.richtext.toolbar", { field: label }),
403
+ children: tools.map(([name, icon, before, after, placeholder]) => /* @__PURE__ */ jsxs("button", {
404
+ type: "button",
405
+ className: "nbe-icon-btn",
406
+ onClick: () => apply(before, after, placeholder),
407
+ children: [icon, /* @__PURE__ */ jsx("span", {
408
+ className: "nbe-sr-only",
409
+ children: name
410
+ })]
411
+ }, name))
412
+ }), /* @__PURE__ */ jsx("textarea", {
413
+ ref,
414
+ id,
415
+ className: "nbe-input nbe-input--rich",
416
+ rows: block ? 5 : 2,
417
+ value: str,
418
+ maxLength: node.kind === "string" ? node.maxLength : void 0,
419
+ "aria-invalid": errors.length > 0 || void 0,
420
+ "aria-describedby": describedBy(id, node.description, errors),
421
+ onChange: (e) => set(e.target.value)
422
+ })]
423
+ });
424
+ }
425
+ function NumberField({ node, path, value, label, required }) {
426
+ const { formId, update, issuesAt } = useForm();
427
+ const id = fieldId(formId, path);
428
+ const errors = issuesAt(path);
429
+ const num = typeof value === "number" ? value : "";
430
+ const n = node.kind === "number" ? node : void 0;
431
+ const step = n?.step ?? (n?.integer ? 1 : n && n.max !== void 0 && n.min !== void 0 && n.max - n.min <= 1 ? .01 : "any");
432
+ const [draft, setDraft] = useState(null);
433
+ const set = (raw) => {
434
+ if (raw === "") {
435
+ if (!required) update(path, void 0);
436
+ return;
437
+ }
438
+ const v = Number(raw);
439
+ if (Number.isFinite(v)) update(path, v);
440
+ };
441
+ return /* @__PURE__ */ jsx(FieldFrame, {
442
+ id,
443
+ label,
444
+ description: node.description,
445
+ errors,
446
+ required,
447
+ children: /* @__PURE__ */ jsxs("div", {
448
+ className: "nbe-number",
449
+ children: [node.ui.widget === "slider" && n?.min !== void 0 && n.max !== void 0 && /* @__PURE__ */ jsx("input", {
450
+ type: "range",
451
+ className: "nbe-range",
452
+ min: n.min,
453
+ max: n.max,
454
+ step,
455
+ value: num === "" ? n.min : num,
456
+ tabIndex: -1,
457
+ "aria-hidden": true,
458
+ onChange: (e) => set(e.target.value)
459
+ }), /* @__PURE__ */ jsx("input", {
460
+ id,
461
+ type: "number",
462
+ className: "nbe-input nbe-input--number",
463
+ value: draft ?? num,
464
+ min: n?.min,
465
+ max: n?.max,
466
+ step,
467
+ "aria-invalid": errors.length > 0 || void 0,
468
+ "aria-describedby": describedBy(id, node.description, errors),
469
+ onChange: (e) => {
470
+ setDraft(e.target.value);
471
+ set(e.target.value);
472
+ },
473
+ onBlur: () => setDraft(null)
474
+ })]
475
+ })
476
+ });
477
+ }
478
+ function SwitchField({ node, path, value, label }) {
479
+ const { formId, update, issuesAt } = useForm();
480
+ const id = fieldId(formId, path);
481
+ const errors = issuesAt(path);
482
+ const checked = value === true || value === void 0 && node.default === true;
483
+ return /* @__PURE__ */ jsxs("div", {
484
+ className: "nbe-field nbe-field--switch",
485
+ children: [
486
+ /* @__PURE__ */ jsx("input", {
487
+ id,
488
+ type: "checkbox",
489
+ role: "switch",
490
+ className: "nbe-switch",
491
+ checked,
492
+ "aria-describedby": describedBy(id, node.description, errors),
493
+ onChange: (e) => update(path, e.target.checked)
494
+ }),
495
+ /* @__PURE__ */ jsx("label", {
496
+ htmlFor: id,
497
+ className: "nbe-field__label",
498
+ children: label
499
+ }),
500
+ node.description && /* @__PURE__ */ jsx("p", {
501
+ className: "nbe-field__help",
502
+ id: `${id}-help`,
503
+ children: node.description
504
+ }),
505
+ errors.length > 0 && /* @__PURE__ */ jsx("p", {
506
+ className: "nbe-field__error",
507
+ id: `${id}-error`,
508
+ children: errors.join(" ")
509
+ })
510
+ ]
511
+ });
512
+ }
513
+ function SelectField({ node, path, value, label, required }) {
514
+ const { formId, update, issuesAt } = useForm();
515
+ const id = fieldId(formId, path);
516
+ const errors = issuesAt(path);
517
+ const options = node.kind === "string" ? node.enum ?? [] : [];
518
+ const current = typeof value === "string" ? value : typeof node.default === "string" ? node.default : "";
519
+ return /* @__PURE__ */ jsx(FieldFrame, {
520
+ id,
521
+ label,
522
+ description: node.description,
523
+ errors,
524
+ required,
525
+ children: /* @__PURE__ */ jsxs("select", {
526
+ id,
527
+ className: "nbe-input",
528
+ value: current,
529
+ "aria-invalid": errors.length > 0 || void 0,
530
+ "aria-describedby": describedBy(id, node.description, errors),
531
+ onChange: (e) => update(path, e.target.value === "" ? void 0 : e.target.value),
532
+ children: [!required && /* @__PURE__ */ jsx("option", {
533
+ value: "",
534
+ children: "—"
535
+ }), options.map((o) => /* @__PURE__ */ jsx("option", {
536
+ value: o,
537
+ children: humanizeKey(o)
538
+ }, o))]
539
+ })
540
+ });
541
+ }
542
+ function ColorField({ node, path, value, label, required }) {
543
+ const { formId, update, issuesAt } = useForm();
544
+ const id = fieldId(formId, path);
545
+ const errors = issuesAt(path);
546
+ const str = typeof value === "string" ? value : "";
547
+ const hex = /^#[0-9a-fA-F]{6}$/.test(str) ? str : "#3b5bdb";
548
+ return /* @__PURE__ */ jsx(FieldFrame, {
549
+ id,
550
+ label,
551
+ description: node.description,
552
+ errors,
553
+ required,
554
+ children: /* @__PURE__ */ jsxs("div", {
555
+ className: "nbe-color",
556
+ children: [/* @__PURE__ */ jsx("input", {
557
+ type: "color",
558
+ className: "nbe-color__swatch",
559
+ value: hex,
560
+ "aria-hidden": true,
561
+ tabIndex: -1,
562
+ onChange: (e) => update(path, e.target.value)
563
+ }), /* @__PURE__ */ jsx("input", {
564
+ id,
565
+ type: "text",
566
+ className: "nbe-input",
567
+ value: str,
568
+ placeholder: "#3b5bdb",
569
+ "aria-invalid": errors.length > 0 || void 0,
570
+ "aria-describedby": describedBy(id, node.description, errors),
571
+ onChange: (e) => update(path, e.target.value === "" && !required ? void 0 : e.target.value)
572
+ })]
573
+ })
574
+ });
575
+ }
576
+ function JsonField({ node, path, value, label, required }) {
577
+ const { formId, update, issuesAt } = useForm();
578
+ const t = useEditorT();
579
+ const id = fieldId(formId, path);
580
+ const [text, setText] = useState(() => JSON.stringify(value ?? null, null, 2));
581
+ const [bad, setBad] = useState(false);
582
+ const errors = [...issuesAt(path), ...bad ? [t("editor.json.invalid")] : []];
583
+ return /* @__PURE__ */ jsx(FieldFrame, {
584
+ id,
585
+ label,
586
+ description: node.description,
587
+ errors,
588
+ required,
589
+ children: /* @__PURE__ */ jsx("textarea", {
590
+ id,
591
+ className: "nbe-input nbe-input--code",
592
+ rows: 4,
593
+ value: text,
594
+ "aria-invalid": errors.length > 0 || void 0,
595
+ "aria-describedby": describedBy(id, node.description, errors),
596
+ onChange: (e) => {
597
+ setText(e.target.value);
598
+ try {
599
+ update(path, JSON.parse(e.target.value));
600
+ setBad(false);
601
+ } catch {
602
+ setBad(true);
603
+ }
604
+ }
605
+ })
606
+ });
607
+ }
608
+ function ImageField({ node, path, value, label, required }) {
609
+ const { formId, update, issuesAt, onPickImage } = useForm();
610
+ const t = useEditorT();
611
+ const media = isRecord(value) ? value : void 0;
612
+ const src = typeof media?.src === "string" ? media.src : "";
613
+ const set = (key, v) => update([...path, key], v === "" && key !== "src" && key !== "alt" ? void 0 : v);
614
+ if (!media && !required) return /* @__PURE__ */ jsx(OptionalAdd, {
615
+ label,
616
+ onAdd: () => update(path, {
617
+ src: "",
618
+ alt: ""
619
+ })
620
+ });
621
+ const srcId = fieldId(formId, [...path, "src"]);
622
+ const altId = fieldId(formId, [...path, "alt"]);
623
+ const capId = fieldId(formId, [...path, "caption"]);
624
+ const srcErrors = [...issuesAt(path), ...issuesAt([...path, "src"])];
625
+ return /* @__PURE__ */ jsxs("fieldset", {
626
+ className: "nbe-group nbe-image",
627
+ children: [
628
+ /* @__PURE__ */ jsx("legend", {
629
+ className: "nbe-group__legend",
630
+ children: label
631
+ }),
632
+ node.description && /* @__PURE__ */ jsx("p", {
633
+ className: "nbe-field__help",
634
+ children: node.description
635
+ }),
636
+ /* @__PURE__ */ jsxs("div", {
637
+ className: "nbe-image__body",
638
+ children: [/* @__PURE__ */ jsx("div", {
639
+ className: "nbe-image__preview",
640
+ children: src ? /* @__PURE__ */ jsx(SafeImage, {
641
+ media: {
642
+ src,
643
+ alt: ""
644
+ },
645
+ showCaption: false
646
+ }) : /* @__PURE__ */ jsx("div", {
647
+ className: "nbe-image__empty",
648
+ "aria-hidden": true
649
+ })
650
+ }), /* @__PURE__ */ jsxs("div", {
651
+ className: "nbe-image__fields",
652
+ children: [
653
+ /* @__PURE__ */ jsx(FieldFrame, {
654
+ id: srcId,
655
+ label: t("editor.image.src"),
656
+ errors: srcErrors,
657
+ required: true,
658
+ children: /* @__PURE__ */ jsxs("div", {
659
+ className: "nbe-row",
660
+ children: [/* @__PURE__ */ jsx("input", {
661
+ id: srcId,
662
+ className: "nbe-input",
663
+ value: src,
664
+ "aria-invalid": srcErrors.length > 0 || void 0,
665
+ "aria-describedby": describedBy(srcId, void 0, srcErrors),
666
+ onChange: (e) => set("src", e.target.value)
667
+ }), onPickImage && /* @__PURE__ */ jsxs("button", {
668
+ type: "button",
669
+ className: "nbe-btn",
670
+ onClick: async () => {
671
+ const picked = await onPickImage();
672
+ if (!picked) return;
673
+ update([...path, "src"], picked.src);
674
+ if (picked.alt !== void 0 || typeof media?.alt !== "string") update([...path, "alt"], picked.alt ?? "");
675
+ },
676
+ children: [/* @__PURE__ */ jsx(ImagePlus, {
677
+ "aria-hidden": true,
678
+ size: 16
679
+ }), t("editor.image.choose")]
680
+ })]
681
+ })
682
+ }),
683
+ /* @__PURE__ */ jsx(FieldFrame, {
684
+ id: altId,
685
+ label: t("editor.image.alt"),
686
+ description: t("editor.image.decorative"),
687
+ errors: issuesAt([...path, "alt"]),
688
+ required: false,
689
+ children: /* @__PURE__ */ jsx("input", {
690
+ id: altId,
691
+ className: "nbe-input",
692
+ value: typeof media?.alt === "string" ? media.alt : "",
693
+ "aria-describedby": `${altId}-help`,
694
+ onChange: (e) => set("alt", e.target.value)
695
+ })
696
+ }),
697
+ /* @__PURE__ */ jsx(FieldFrame, {
698
+ id: capId,
699
+ label: t("editor.image.caption"),
700
+ errors: issuesAt([...path, "caption"]),
701
+ required: false,
702
+ children: /* @__PURE__ */ jsx("input", {
703
+ id: capId,
704
+ className: "nbe-input",
705
+ value: typeof media?.caption === "string" ? media.caption : "",
706
+ onChange: (e) => set("caption", e.target.value)
707
+ })
708
+ })
709
+ ]
710
+ })]
711
+ }),
712
+ !required && /* @__PURE__ */ jsxs("button", {
713
+ type: "button",
714
+ className: "nbe-btn nbe-btn--quiet",
715
+ onClick: () => update(path, void 0),
716
+ children: [/* @__PURE__ */ jsx(X, {
717
+ "aria-hidden": true,
718
+ size: 14
719
+ }), t("editor.clear")]
720
+ })
721
+ ]
722
+ });
723
+ }
724
+ function OptionalAdd({ label, onAdd }) {
725
+ const t = useEditorT();
726
+ return /* @__PURE__ */ jsx("div", {
727
+ className: "nbe-field nbe-field--add",
728
+ children: /* @__PURE__ */ jsxs("button", {
729
+ type: "button",
730
+ className: "nbe-btn nbe-btn--dashed",
731
+ onClick: onAdd,
732
+ children: [
733
+ /* @__PURE__ */ jsx(Plus, {
734
+ "aria-hidden": true,
735
+ size: 14
736
+ }),
737
+ t("editor.set"),
738
+ " ",
739
+ label.charAt(0).toLowerCase() + label.slice(1)
740
+ ]
741
+ })
742
+ });
743
+ }
744
+ var GROUP_ORDER = [
745
+ "content",
746
+ "behavior",
747
+ "feedback",
748
+ "appearance",
749
+ "advanced"
750
+ ];
751
+ function ObjectField({ node, path, value, label, required, depth }) {
752
+ const { update } = useForm();
753
+ const t = useEditorT();
754
+ if (node.kind !== "object") return null;
755
+ const obj = isRecord(value) ? value : void 0;
756
+ if (!obj && !required && depth > 0) return /* @__PURE__ */ jsx(OptionalAdd, {
757
+ label,
758
+ onAdd: () => update(path, defaultFor(node))
759
+ });
760
+ const visible = node.fields.filter((f) => f.node.ui.widget !== "hidden" && f.node.kind !== "const");
761
+ const ids = visible.filter((f) => f.node.ui.widget === "id");
762
+ const rest = visible.filter((f) => f.node.ui.widget !== "id");
763
+ const render = (f) => /* @__PURE__ */ jsx(Field, {
764
+ field: f,
765
+ path: [...path, f.key],
766
+ value: obj ? Object.prototype.hasOwnProperty.call(obj, f.key) ? obj[f.key] : void 0 : void 0,
767
+ depth: depth + 1,
768
+ bare: depth === 0 && f.node.kind === "object" && f.node.ui.group !== void 0
769
+ }, f.key);
770
+ if (depth === 0) {
771
+ const byGroup = /* @__PURE__ */ new Map();
772
+ for (const f of rest) {
773
+ const g = f.node.ui.group ?? "content";
774
+ byGroup.set(g, [...byGroup.get(g) ?? [], f]);
775
+ }
776
+ for (const f of ids) byGroup.set("advanced", [...byGroup.get("advanced") ?? [], f]);
777
+ return /* @__PURE__ */ jsx("div", {
778
+ className: "nbe-form__groups",
779
+ children: GROUP_ORDER.filter((g) => byGroup.has(g)).map((g) => g === "content" ? /* @__PURE__ */ jsxs("section", {
780
+ className: "nbe-section",
781
+ "aria-labelledby": `${path.join("-")}-${g}`,
782
+ children: [/* @__PURE__ */ jsx("h3", {
783
+ className: "nbe-section__title",
784
+ id: `${path.join("-")}-${g}`,
785
+ children: t(`editor.group.${g}`)
786
+ }), byGroup.get(g).map(render)]
787
+ }, g) : /* @__PURE__ */ jsxs("details", {
788
+ className: "nbe-section nbe-section--collapsible",
789
+ children: [/* @__PURE__ */ jsxs("summary", {
790
+ className: "nbe-section__title",
791
+ children: [/* @__PURE__ */ jsx(ChevronDown, {
792
+ "aria-hidden": true,
793
+ size: 16,
794
+ className: "nbe-chevron"
795
+ }), t(`editor.group.${g}`)]
796
+ }), byGroup.get(g).map(render)]
797
+ }, g))
798
+ });
799
+ }
800
+ return /* @__PURE__ */ jsxs("fieldset", {
801
+ className: "nbe-group",
802
+ children: [
803
+ /* @__PURE__ */ jsx("legend", {
804
+ className: "nbe-group__legend",
805
+ children: label
806
+ }),
807
+ node.description && /* @__PURE__ */ jsx("p", {
808
+ className: "nbe-field__help",
809
+ children: node.description
810
+ }),
811
+ rest.map(render),
812
+ ids.length > 0 && /* @__PURE__ */ jsxs("details", {
813
+ className: "nbe-advanced",
814
+ children: [/* @__PURE__ */ jsx("summary", { children: t("editor.group.advanced") }), ids.map(render)]
815
+ }),
816
+ !required && obj && /* @__PURE__ */ jsxs("button", {
817
+ type: "button",
818
+ className: "nbe-btn nbe-btn--quiet",
819
+ onClick: () => update(path, void 0),
820
+ children: [/* @__PURE__ */ jsx(X, {
821
+ "aria-hidden": true,
822
+ size: 14
823
+ }), t("editor.clear")]
824
+ })
825
+ ]
826
+ });
827
+ }
828
+ function itemTitle(labelKey, item, fallback) {
829
+ const key = labelKey;
830
+ if (key && isRecord(item) && typeof item[key] === "string" && item[key]) return stripMarkup(item[key]);
831
+ if (typeof item === "string" && item) return stripMarkup(item);
832
+ return fallback;
833
+ }
834
+ function ArrayField({ node, path, value, label, required, depth }) {
835
+ const { formId, update, root, announce, onFocusPath } = useForm();
836
+ const t = useEditorT();
837
+ const list = Array.isArray(value) ? value : [];
838
+ const itemName = node.ui.itemName ?? "item";
839
+ const [expanded, setExpanded] = useState(() => new Set(list.length <= 4 ? list.map((_, i) => i) : [0]));
840
+ const focusAfter = useRef(null);
841
+ const listRef = useRef(null);
842
+ const addRef = useRef(null);
843
+ useEffect(() => {
844
+ const target = focusAfter.current;
845
+ if (!target) return;
846
+ focusAfter.current = null;
847
+ const item = listRef.current?.querySelector(`[data-index="${target.index}"]`);
848
+ const wanted = item?.querySelector(`[data-action="${target.action}"]`);
849
+ ((wanted && !wanted.disabled ? wanted : null) ?? item?.querySelector("button:not(:disabled), input, textarea, select") ?? addRef.current)?.focus();
850
+ });
851
+ if (node.kind !== "array") return null;
852
+ const Item = node.item;
853
+ const min = node.minItems ?? 0;
854
+ const max = node.maxItems ?? Infinity;
855
+ const name = (i) => itemTitle(node.ui.itemLabel, list[i], t("editor.untitled", { item: itemName }));
856
+ const idsInList = () => list.map((it) => isRecord(it) && typeof it.id === "string" ? it.id : "").filter(Boolean);
857
+ const add = () => {
858
+ const created = defaultFor(Item, {
859
+ idPrefix: itemName.replace(/\s+/g, "-"),
860
+ takenIds: idsInList()
861
+ });
862
+ update(path, [...list, created]);
863
+ setExpanded(/* @__PURE__ */ new Set([...expanded, list.length]));
864
+ focusAfter.current = {
865
+ index: list.length,
866
+ action: "toggle"
867
+ };
868
+ announce(t("editor.itemAdded", { item: humanizeKey(itemName) }));
869
+ };
870
+ const remove = (i) => {
871
+ update(path, getAt(removeAt(root, [...path, i]), path));
872
+ focusAfter.current = {
873
+ index: Math.max(0, i - 1),
874
+ action: "toggle"
875
+ };
876
+ announce(t("editor.itemRemoved", {
877
+ item: humanizeKey(itemName),
878
+ index: i + 1
879
+ }));
880
+ };
881
+ const move = (i, to) => {
882
+ update(path, getAt(moveItem(root, path, i, to), path));
883
+ focusAfter.current = {
884
+ index: to,
885
+ action: to < i ? "up" : "down"
886
+ };
887
+ announce(t("editor.itemMoved", {
888
+ item: name(i),
889
+ position: to + 1
890
+ }));
891
+ };
892
+ const duplicate = (i) => {
893
+ const copy = structuredClone(list[i]);
894
+ if (isRecord(copy) && typeof copy.id === "string") copy.id = uniqueId(copy.id.replace(/-\d+$/, ""), idsInList());
895
+ update(path, getAt(insertAt(root, path, copy, i + 1), path));
896
+ setExpanded(/* @__PURE__ */ new Set([...expanded, i + 1]));
897
+ focusAfter.current = {
898
+ index: i + 1,
899
+ action: "toggle"
900
+ };
901
+ announce(t("editor.itemDuplicated", { item: name(i) }));
902
+ };
903
+ const toggle = (i) => {
904
+ const next = new Set(expanded);
905
+ if (next.has(i)) next.delete(i);
906
+ else next.add(i);
907
+ setExpanded(next);
908
+ };
909
+ const scalarItems = Item.kind !== "object" && Item.kind !== "union" && Item.kind !== "array";
910
+ const headingId = `${fieldId(formId, path)}-label`;
911
+ return /* @__PURE__ */ jsxs("section", {
912
+ className: "nbe-array",
913
+ "aria-labelledby": headingId,
914
+ children: [
915
+ /* @__PURE__ */ jsx("div", {
916
+ className: "nbe-array__head",
917
+ children: /* @__PURE__ */ jsxs("h4", {
918
+ className: "nbe-array__title",
919
+ id: headingId,
920
+ children: [
921
+ label,
922
+ " ",
923
+ /* @__PURE__ */ jsx("span", {
924
+ className: "nbe-array__count",
925
+ children: list.length
926
+ }),
927
+ !required && /* @__PURE__ */ jsxs("span", {
928
+ className: "nbe-field__optional",
929
+ children: [
930
+ " (",
931
+ t("editor.optional"),
932
+ ")"
933
+ ]
934
+ })
935
+ ]
936
+ })
937
+ }),
938
+ node.description && /* @__PURE__ */ jsx("p", {
939
+ className: "nbe-field__help",
940
+ children: node.description
941
+ }),
942
+ /* @__PURE__ */ jsx("ol", {
943
+ className: "nbe-array__list",
944
+ ref: listRef,
945
+ children: list.map((item, i) => {
946
+ const itemPath = [...path, i];
947
+ const open = scalarItems || expanded.has(i);
948
+ const n = {
949
+ item: itemName,
950
+ index: i + 1
951
+ };
952
+ return /* @__PURE__ */ jsxs("li", {
953
+ className: "nbe-item",
954
+ "data-index": i,
955
+ onFocusCapture: () => onFocusPath?.(itemPath),
956
+ children: [/* @__PURE__ */ jsxs("div", {
957
+ className: "nbe-item__head",
958
+ children: [
959
+ scalarItems ? /* @__PURE__ */ jsx("span", {
960
+ className: "nbe-item__index",
961
+ "aria-hidden": true,
962
+ children: i + 1
963
+ }) : /* @__PURE__ */ jsxs("button", {
964
+ type: "button",
965
+ className: "nbe-item__toggle",
966
+ "aria-expanded": open,
967
+ "data-action": "toggle",
968
+ onClick: () => toggle(i),
969
+ children: [
970
+ /* @__PURE__ */ jsx(ChevronDown, {
971
+ "aria-hidden": true,
972
+ size: 16,
973
+ className: "nbe-chevron"
974
+ }),
975
+ /* @__PURE__ */ jsxs("span", {
976
+ className: "nbe-item__index",
977
+ children: [i + 1, "."]
978
+ }),
979
+ /* @__PURE__ */ jsx("span", {
980
+ className: "nbe-item__name",
981
+ children: name(i)
982
+ })
983
+ ]
984
+ }),
985
+ scalarItems && /* @__PURE__ */ jsx("div", {
986
+ className: "nbe-item__inline",
987
+ children: /* @__PURE__ */ jsx(Field, {
988
+ field: {
989
+ key: String(i),
990
+ node: {
991
+ ...Item,
992
+ title: `${humanizeKey(itemName)} ${i + 1}`
993
+ },
994
+ required: true
995
+ },
996
+ path: itemPath,
997
+ value: item,
998
+ depth: depth + 1
999
+ })
1000
+ }),
1001
+ /* @__PURE__ */ jsxs("div", {
1002
+ className: "nbe-item__actions",
1003
+ children: [
1004
+ /* @__PURE__ */ jsxs("button", {
1005
+ type: "button",
1006
+ className: "nbe-icon-btn",
1007
+ "data-action": "up",
1008
+ disabled: i === 0,
1009
+ onClick: () => move(i, i - 1),
1010
+ children: [/* @__PURE__ */ jsx(ArrowUp, {
1011
+ "aria-hidden": true,
1012
+ size: 16
1013
+ }), /* @__PURE__ */ jsx("span", {
1014
+ className: "nbe-sr-only",
1015
+ children: t("editor.moveUpItem", n)
1016
+ })]
1017
+ }),
1018
+ /* @__PURE__ */ jsxs("button", {
1019
+ type: "button",
1020
+ className: "nbe-icon-btn",
1021
+ "data-action": "down",
1022
+ disabled: i === list.length - 1,
1023
+ onClick: () => move(i, i + 1),
1024
+ children: [/* @__PURE__ */ jsx(ArrowDown, {
1025
+ "aria-hidden": true,
1026
+ size: 16
1027
+ }), /* @__PURE__ */ jsx("span", {
1028
+ className: "nbe-sr-only",
1029
+ children: t("editor.moveDownItem", n)
1030
+ })]
1031
+ }),
1032
+ /* @__PURE__ */ jsxs("button", {
1033
+ type: "button",
1034
+ className: "nbe-icon-btn",
1035
+ "data-action": "duplicate",
1036
+ disabled: list.length >= max,
1037
+ onClick: () => duplicate(i),
1038
+ children: [/* @__PURE__ */ jsx(Copy, {
1039
+ "aria-hidden": true,
1040
+ size: 16
1041
+ }), /* @__PURE__ */ jsx("span", {
1042
+ className: "nbe-sr-only",
1043
+ children: t("editor.duplicateItem", n)
1044
+ })]
1045
+ }),
1046
+ /* @__PURE__ */ jsxs("button", {
1047
+ type: "button",
1048
+ className: "nbe-icon-btn nbe-icon-btn--danger",
1049
+ "data-action": "remove",
1050
+ disabled: list.length <= min,
1051
+ onClick: () => remove(i),
1052
+ children: [/* @__PURE__ */ jsx(Trash2, {
1053
+ "aria-hidden": true,
1054
+ size: 16
1055
+ }), /* @__PURE__ */ jsx("span", {
1056
+ className: "nbe-sr-only",
1057
+ children: t("editor.removeItem", n)
1058
+ })]
1059
+ })
1060
+ ]
1061
+ })
1062
+ ]
1063
+ }), !scalarItems && open && /* @__PURE__ */ jsx("div", {
1064
+ className: "nbe-item__body",
1065
+ children: /* @__PURE__ */ jsx(Field, {
1066
+ field: {
1067
+ key: String(i),
1068
+ node: Item,
1069
+ required: true
1070
+ },
1071
+ path: itemPath,
1072
+ value: item,
1073
+ depth: depth + 1,
1074
+ bare: true
1075
+ })
1076
+ })]
1077
+ }, i);
1078
+ })
1079
+ }),
1080
+ /* @__PURE__ */ jsxs("button", {
1081
+ ref: addRef,
1082
+ type: "button",
1083
+ className: "nbe-btn nbe-btn--dashed",
1084
+ disabled: list.length >= max,
1085
+ onClick: add,
1086
+ children: [/* @__PURE__ */ jsx(Plus, {
1087
+ "aria-hidden": true,
1088
+ size: 14
1089
+ }), t("editor.add", { item: itemName })]
1090
+ })
1091
+ ]
1092
+ });
1093
+ }
1094
+ function UnionField({ node, path, value, label, required, depth }) {
1095
+ const { formId, update } = useForm();
1096
+ const t = useEditorT();
1097
+ if (node.kind !== "union") return null;
1098
+ const disc = node.discriminator;
1099
+ const current = disc && isRecord(value) ? node.variants.findIndex((v) => v.value === value[disc]) : node.variants.findIndex((v) => v.node.kind === typeof value);
1100
+ const index = current >= 0 ? current : 0;
1101
+ const variant = node.variants[index];
1102
+ const selectId = `${fieldId(formId, path)}-variant`;
1103
+ if (value === void 0 && !required) return /* @__PURE__ */ jsx(OptionalAdd, {
1104
+ label,
1105
+ onAdd: () => update(path, defaultFor(variant.node))
1106
+ });
1107
+ return /* @__PURE__ */ jsxs("fieldset", {
1108
+ className: "nbe-group",
1109
+ children: [
1110
+ /* @__PURE__ */ jsx("legend", {
1111
+ className: "nbe-group__legend",
1112
+ children: label
1113
+ }),
1114
+ /* @__PURE__ */ jsxs("div", {
1115
+ className: "nbe-field",
1116
+ children: [/* @__PURE__ */ jsx("label", {
1117
+ className: "nbe-field__label",
1118
+ htmlFor: selectId,
1119
+ children: t("editor.variant")
1120
+ }), /* @__PURE__ */ jsx("select", {
1121
+ id: selectId,
1122
+ className: "nbe-input",
1123
+ value: index,
1124
+ onChange: (e) => update(path, defaultFor(node.variants[Number(e.target.value)].node)),
1125
+ children: node.variants.map((v, i) => /* @__PURE__ */ jsx("option", {
1126
+ value: i,
1127
+ children: v.value ? humanizeKey(v.value) : v.label
1128
+ }, i))
1129
+ })]
1130
+ }),
1131
+ /* @__PURE__ */ jsx(Field, {
1132
+ field: {
1133
+ key: label,
1134
+ node: variant.node,
1135
+ required: true
1136
+ },
1137
+ path,
1138
+ value,
1139
+ depth: depth + 1,
1140
+ bare: true
1141
+ })
1142
+ ]
1143
+ });
1144
+ }
1145
+ function RecordField({ node, path, value, label, required }) {
1146
+ const { formId, update } = useForm();
1147
+ const t = useEditorT();
1148
+ if (node.kind !== "record") return null;
1149
+ const obj = isRecord(value) ? value : {};
1150
+ const entries = Object.entries(obj);
1151
+ const numeric = node.value.kind === "number";
1152
+ const setEntry = (oldKey, newKey, v) => {
1153
+ const next = {};
1154
+ for (const [k, val] of entries) if (k === oldKey) {
1155
+ if (newKey && ![
1156
+ "__proto__",
1157
+ "constructor",
1158
+ "prototype"
1159
+ ].includes(newKey)) next[newKey] = v;
1160
+ } else next[k] = val;
1161
+ update(path, Object.keys(next).length || required ? next : void 0);
1162
+ };
1163
+ const base = fieldId(formId, path);
1164
+ return /* @__PURE__ */ jsxs("fieldset", {
1165
+ className: "nbe-group",
1166
+ children: [
1167
+ /* @__PURE__ */ jsx("legend", {
1168
+ className: "nbe-group__legend",
1169
+ children: label
1170
+ }),
1171
+ node.description && /* @__PURE__ */ jsx("p", {
1172
+ className: "nbe-field__help",
1173
+ children: node.description
1174
+ }),
1175
+ entries.map(([k, v], i) => /* @__PURE__ */ jsxs("div", {
1176
+ className: "nbe-row nbe-record",
1177
+ children: [
1178
+ /* @__PURE__ */ jsxs("label", {
1179
+ className: "nbe-sr-only",
1180
+ htmlFor: `${base}-k${i}`,
1181
+ children: [
1182
+ t("editor.record.key"),
1183
+ " ",
1184
+ i + 1
1185
+ ]
1186
+ }),
1187
+ /* @__PURE__ */ jsx("input", {
1188
+ id: `${base}-k${i}`,
1189
+ className: "nbe-input",
1190
+ value: k,
1191
+ onChange: (e) => setEntry(k, e.target.value, v)
1192
+ }),
1193
+ /* @__PURE__ */ jsxs("label", {
1194
+ className: "nbe-sr-only",
1195
+ htmlFor: `${base}-v${i}`,
1196
+ children: [
1197
+ t("editor.record.value"),
1198
+ " ",
1199
+ i + 1
1200
+ ]
1201
+ }),
1202
+ /* @__PURE__ */ jsx("input", {
1203
+ id: `${base}-v${i}`,
1204
+ className: "nbe-input",
1205
+ type: numeric ? "number" : "text",
1206
+ value: typeof v === "number" || typeof v === "string" ? v : "",
1207
+ onChange: (e) => setEntry(k, k, numeric ? Number(e.target.value) : e.target.value)
1208
+ }),
1209
+ /* @__PURE__ */ jsxs("button", {
1210
+ type: "button",
1211
+ className: "nbe-icon-btn nbe-icon-btn--danger",
1212
+ onClick: () => setEntry(k, "", void 0),
1213
+ children: [/* @__PURE__ */ jsx(Trash2, {
1214
+ "aria-hidden": true,
1215
+ size: 16
1216
+ }), /* @__PURE__ */ jsxs("span", {
1217
+ className: "nbe-sr-only",
1218
+ children: [
1219
+ t("editor.remove"),
1220
+ " ",
1221
+ k
1222
+ ]
1223
+ })]
1224
+ })
1225
+ ]
1226
+ }, i)),
1227
+ /* @__PURE__ */ jsxs("button", {
1228
+ type: "button",
1229
+ className: "nbe-btn nbe-btn--dashed",
1230
+ onClick: () => update(path, {
1231
+ ...obj,
1232
+ [uniqueId("key", Object.keys(obj))]: numeric ? 0 : ""
1233
+ }),
1234
+ children: [/* @__PURE__ */ jsx(Plus, {
1235
+ "aria-hidden": true,
1236
+ size: 14
1237
+ }), t("editor.record.add")]
1238
+ })
1239
+ ]
1240
+ });
1241
+ }
1242
+ function Field({ field, path, value, depth, bare }) {
1243
+ const { node, key, required } = field;
1244
+ const props = {
1245
+ node,
1246
+ path,
1247
+ value,
1248
+ label: useLabel(path, node, key),
1249
+ required,
1250
+ depth
1251
+ };
1252
+ const w = node.ui.widget;
1253
+ if (w === "hidden" || node.kind === "const") return null;
1254
+ if (w === "image") return /* @__PURE__ */ jsx(ImageField, { ...props });
1255
+ if (w === "json") return /* @__PURE__ */ jsx(JsonField, { ...props });
1256
+ switch (node.kind) {
1257
+ case "string":
1258
+ if (node.enum || w === "select") return /* @__PURE__ */ jsx(SelectField, { ...props });
1259
+ if (w === "color") return /* @__PURE__ */ jsx(ColorField, { ...props });
1260
+ if (w === "richtext" || w === "richtext-block") return /* @__PURE__ */ jsx(RichTextField, { ...props });
1261
+ return /* @__PURE__ */ jsx(TextField, { ...props });
1262
+ case "number": return /* @__PURE__ */ jsx(NumberField, { ...props });
1263
+ case "boolean": return /* @__PURE__ */ jsx(SwitchField, { ...props });
1264
+ case "object": return /* @__PURE__ */ jsxs(Fragment, { children: [bare ? /* @__PURE__ */ jsx(BareObject, { ...props }) : /* @__PURE__ */ jsx(ObjectField, { ...props }), /* @__PURE__ */ jsx(ContainerErrors, { path })] });
1265
+ case "array": return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(ArrayField, { ...props }), /* @__PURE__ */ jsx(ContainerErrors, { path })] });
1266
+ case "union": return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(UnionField, { ...props }), /* @__PURE__ */ jsx(ContainerErrors, { path })] });
1267
+ case "record": return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(RecordField, { ...props }), /* @__PURE__ */ jsx(ContainerErrors, { path })] });
1268
+ default: return /* @__PURE__ */ jsx(JsonField, { ...props });
1269
+ }
1270
+ }
1271
+ /**
1272
+ * Problems reported for a list or group itself (too few items, duplicate ids, cross-field
1273
+ * rules). It carries the field id, so "go to" in the issue summary lands here.
1274
+ */
1275
+ function ContainerErrors({ path }) {
1276
+ const { formId, issuesAt } = useForm();
1277
+ const errors = issuesAt(path);
1278
+ if (errors.length === 0) return null;
1279
+ return /* @__PURE__ */ jsx("p", {
1280
+ className: "nbe-field__error nbe-field__error--group",
1281
+ id: fieldId(formId, path),
1282
+ tabIndex: -1,
1283
+ children: errors.join(" ")
1284
+ });
1285
+ }
1286
+ /** An object's fields without a fieldset (inside an array item or a union variant). */
1287
+ function BareObject({ node, path, value, depth }) {
1288
+ const t = useEditorT();
1289
+ if (node.kind !== "object") return null;
1290
+ const obj = isRecord(value) ? value : {};
1291
+ const visible = node.fields.filter((f) => f.node.ui.widget !== "hidden" && f.node.kind !== "const");
1292
+ const ids = visible.filter((f) => f.node.ui.widget === "id");
1293
+ const rest = visible.filter((f) => f.node.ui.widget !== "id");
1294
+ const render = (f) => /* @__PURE__ */ jsx(Field, {
1295
+ field: f,
1296
+ path: [...path, f.key],
1297
+ value: Object.prototype.hasOwnProperty.call(obj, f.key) ? obj[f.key] : void 0,
1298
+ depth: depth + 1
1299
+ }, f.key);
1300
+ return /* @__PURE__ */ jsxs(Fragment, { children: [rest.map(render), ids.length > 0 && /* @__PURE__ */ jsxs("details", {
1301
+ className: "nbe-advanced",
1302
+ children: [/* @__PURE__ */ jsx("summary", { children: t("editor.group.advanced") }), ids.map(render)]
1303
+ })] });
1304
+ }
1305
+ // src/form/schema.ts
1306
+ var types = (s) => Array.isArray(s.type) ? s.type : s.type ? [s.type] : [];
1307
+ var isNullSchema = (s) => types(s).length === 1 && types(s)[0] === "null";
1308
+ function meta(s, node, extra = {}) {
1309
+ return {
1310
+ ...node,
1311
+ title: s.title,
1312
+ description: s.description,
1313
+ default: s.default,
1314
+ ui: { ...s["x-ui"] ?? {} },
1315
+ ...extra
1316
+ };
1317
+ }
1318
+ /** The property every variant fixes with `const`, if any. */
1319
+ function discriminatorOf(variants) {
1320
+ const first = variants[0]?.properties;
1321
+ if (!first) return void 0;
1322
+ return Object.keys(first).find((k) => variants.every((v) => v.properties?.[k] && v.properties[k].const !== void 0));
1323
+ }
1324
+ /** Normalise a JSON Schema (as produced by `getModuleJsonSchema`) into a form tree. */
1325
+ function toFormNode(schema, depth = 0) {
1326
+ const s = schema;
1327
+ if (depth > 40) return meta(s, { kind: "unknown" });
1328
+ const alternatives = s.oneOf ?? s.anyOf;
1329
+ if (alternatives) {
1330
+ const real = alternatives.filter((a) => !isNullSchema(a));
1331
+ const nullable = real.length < alternatives.length;
1332
+ if (real.length === 1) {
1333
+ const inner = toFormNode({
1334
+ ...real[0],
1335
+ title: s.title ?? real[0].title,
1336
+ description: s.description ?? real[0].description,
1337
+ "x-ui": {
1338
+ ...real[0]["x-ui"] ?? {},
1339
+ ...s["x-ui"] ?? {}
1340
+ }
1341
+ }, depth + 1);
1342
+ return {
1343
+ ...inner,
1344
+ nullable: nullable || inner.nullable,
1345
+ default: s.default ?? inner.default
1346
+ };
1347
+ }
1348
+ const discriminator = discriminatorOf(real);
1349
+ return meta(s, {
1350
+ kind: "union",
1351
+ discriminator,
1352
+ variants: real.map((v, i) => {
1353
+ const value = discriminator ? String(v.properties[discriminator].const) : void 0;
1354
+ return {
1355
+ label: v.title ?? value ?? `Option ${i + 1}`,
1356
+ value,
1357
+ node: toFormNode(v, depth + 1)
1358
+ };
1359
+ })
1360
+ }, { nullable });
1361
+ }
1362
+ if (s.const !== void 0) return meta(s, {
1363
+ kind: "const",
1364
+ value: s.const
1365
+ });
1366
+ const t = types(s).filter((x) => x !== "null");
1367
+ const nullable = types(s).includes("null");
1368
+ if (s.enum && s.enum.every((v) => typeof v === "string")) return meta(s, {
1369
+ kind: "string",
1370
+ enum: s.enum
1371
+ }, { nullable });
1372
+ switch (t[0]) {
1373
+ case "string": return meta(s, {
1374
+ kind: "string",
1375
+ maxLength: s.maxLength,
1376
+ minLength: s.minLength,
1377
+ pattern: s.pattern
1378
+ }, { nullable });
1379
+ case "number":
1380
+ case "integer": {
1381
+ const minExclusive = s.minimum === void 0 && s.exclusiveMinimum !== void 0;
1382
+ const min = minExclusive ? s.exclusiveMinimum : s.minimum;
1383
+ const maxInclusive = s.maximum !== void 0 && s.maximum < Number.MAX_SAFE_INTEGER;
1384
+ const maxExclusive = !maxInclusive && s.exclusiveMaximum !== void 0;
1385
+ const max = maxInclusive ? s.maximum : s.exclusiveMaximum;
1386
+ return meta(s, {
1387
+ kind: "number",
1388
+ integer: t[0] === "integer",
1389
+ min,
1390
+ max,
1391
+ step: s.multipleOf,
1392
+ ...minExclusive ? { minExclusive } : {},
1393
+ ...maxExclusive ? { maxExclusive } : {}
1394
+ }, { nullable });
1395
+ }
1396
+ case "boolean": return meta(s, { kind: "boolean" }, { nullable });
1397
+ case "array": return meta(s, {
1398
+ kind: "array",
1399
+ item: toFormNode(s.items ?? {}, depth + 1),
1400
+ minItems: s.minItems,
1401
+ maxItems: s.maxItems
1402
+ }, { nullable });
1403
+ case "object":
1404
+ if (s.properties) {
1405
+ const required = new Set(s.required ?? []);
1406
+ return meta(s, {
1407
+ kind: "object",
1408
+ fields: Object.entries(s.properties).map(([key, child]) => ({
1409
+ key,
1410
+ node: toFormNode(child, depth + 1),
1411
+ required: required.has(key)
1412
+ }))
1413
+ }, { nullable });
1414
+ }
1415
+ if (s.additionalProperties && typeof s.additionalProperties === "object") return meta(s, {
1416
+ kind: "record",
1417
+ value: toFormNode(s.additionalProperties, depth + 1)
1418
+ }, { nullable });
1419
+ return meta(s, { kind: "unknown" }, { nullable });
1420
+ default: return meta(s, { kind: "unknown" });
1421
+ }
1422
+ }
1423
+ // src/ModuleForm.tsx
1424
+ /**
1425
+ * A form for any registered module, generated from its JSON Schema (field titles, hints and
1426
+ * widgets come from the schema's `x-ui` metadata). Fully controlled.
1427
+ */
1428
+ function ModuleForm({ value, onChange, issues, registry = defaultRegistry, onFocusPath, onPickImage, schema: schemaOverride, className }) {
1429
+ const t = useEditorT();
1430
+ const type = String(value.type ?? "");
1431
+ const schema = useMemo(() => schemaOverride ?? getModuleJsonSchema(type, { registry: registry.schemas }), [
1432
+ schemaOverride,
1433
+ type,
1434
+ registry
1435
+ ]);
1436
+ const root = useMemo(() => schema ? toFormNode(schema) : null, [schema]);
1437
+ const formId = `nbe${useId().replace(/[^a-zA-Z0-9]/g, "")}`;
1438
+ const { message, announce } = useAnnounce();
1439
+ const issueIndex = useMemo(() => issueMap(issues), [issues]);
1440
+ const committed = useRef(value);
1441
+ const pending = useRef(null);
1442
+ useEffect(() => {
1443
+ committed.current = value;
1444
+ });
1445
+ const update = useCallback((path, next) => {
1446
+ const updated = setAt(pending.current ? pending.current.value : committed.current, path, next);
1447
+ if (!pending.current) queueMicrotask(() => pending.current = null);
1448
+ pending.current = { value: updated };
1449
+ onChange(updated);
1450
+ }, [onChange]);
1451
+ const ctx = useMemo(() => ({
1452
+ formId,
1453
+ type,
1454
+ root: value,
1455
+ update,
1456
+ issuesAt: (path) => issueIndex.get(pathKey(path)) ?? [],
1457
+ onFocusPath,
1458
+ onPickImage,
1459
+ announce
1460
+ }), [
1461
+ formId,
1462
+ type,
1463
+ value,
1464
+ update,
1465
+ issueIndex,
1466
+ onFocusPath,
1467
+ onPickImage,
1468
+ announce
1469
+ ]);
1470
+ if (!root) return null;
1471
+ const focusField = (issue) => {
1472
+ const segments = issue.segments ?? [];
1473
+ for (let n = segments.length; n >= 0; n--) {
1474
+ const el = document.getElementById(fieldId(formId, segments.slice(0, n)));
1475
+ if (el) {
1476
+ el.focus();
1477
+ el.scrollIntoView?.({ block: "center" });
1478
+ return;
1479
+ }
1480
+ }
1481
+ };
1482
+ return /* @__PURE__ */ jsx(FormContext.Provider, {
1483
+ value: ctx,
1484
+ children: /* @__PURE__ */ jsxs("div", {
1485
+ className: ["nbe-form", className].filter(Boolean).join(" "),
1486
+ children: [
1487
+ issues && issues.length > 0 && /* @__PURE__ */ jsxs("div", {
1488
+ className: "nbe-issues",
1489
+ role: "group",
1490
+ "aria-labelledby": `${formId}-issues`,
1491
+ children: [/* @__PURE__ */ jsxs("p", {
1492
+ className: "nbe-issues__title",
1493
+ id: `${formId}-issues`,
1494
+ children: [/* @__PURE__ */ jsx(AlertCircle, {
1495
+ "aria-hidden": true,
1496
+ size: 16
1497
+ }), t("editor.issues.title", { count: issues.length })]
1498
+ }), /* @__PURE__ */ jsx("ul", {
1499
+ className: "nbe-issues__list",
1500
+ children: issues.slice(0, 12).map((issue, i) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs("button", {
1501
+ type: "button",
1502
+ className: "nbe-link",
1503
+ onClick: () => focusField(issue),
1504
+ children: [
1505
+ /* @__PURE__ */ jsx("code", { children: issue.path }),
1506
+ ": ",
1507
+ issue.message
1508
+ ]
1509
+ }) }, i))
1510
+ })]
1511
+ }),
1512
+ /* @__PURE__ */ jsx(Field, {
1513
+ field: {
1514
+ key: type,
1515
+ node: root,
1516
+ required: true
1517
+ },
1518
+ path: [],
1519
+ value,
1520
+ depth: 0
1521
+ }),
1522
+ /* @__PURE__ */ jsx(LiveRegion, { message })
1523
+ ]
1524
+ })
1525
+ });
1526
+ }
1527
+ // src/ModuleEditor.tsx
1528
+ /** A module form with a live preview that follows the item being edited. */
1529
+ function ModuleEditor({ layout = "split", onValidityChange, ...form }) {
1530
+ const t = useEditorT();
1531
+ const registry = form.registry ?? defaultRegistry;
1532
+ const result = useMemo(() => validateModule(form.value, { registry: registry.schemas }), [form.value, registry]);
1533
+ const issues = result.success ? [] : result.issues;
1534
+ const [lastValid, setLastValid] = useState(() => result.success ? result.data : null);
1535
+ if (result.success && result.data !== lastValid) setLastValid(result.data);
1536
+ const [focusPath, setFocusPath] = useState(null);
1537
+ useEffect(() => {
1538
+ onValidityChange?.({
1539
+ valid: result.success,
1540
+ issues
1541
+ });
1542
+ }, [result.success, JSON.stringify(issues)]);
1543
+ const preview = lastValid ?? null;
1544
+ const rootProps = useRootProps();
1545
+ return /* @__PURE__ */ jsx("div", {
1546
+ className: "nbe-root nb-theme",
1547
+ ...rootProps,
1548
+ children: /* @__PURE__ */ jsxs("div", {
1549
+ className: `nbe-editor nbe-editor--${layout}`,
1550
+ children: [/* @__PURE__ */ jsx("div", {
1551
+ className: "nbe-editor__form",
1552
+ "aria-label": t("editor.form"),
1553
+ role: "region",
1554
+ children: /* @__PURE__ */ jsx(ModuleForm, {
1555
+ ...form,
1556
+ registry,
1557
+ issues,
1558
+ onFocusPath: setFocusPath
1559
+ })
1560
+ }), layout !== "form" && /* @__PURE__ */ jsxs("div", {
1561
+ className: "nbe-editor__preview",
1562
+ role: "region",
1563
+ "aria-label": t("editor.preview"),
1564
+ children: [!result.success && preview && /* @__PURE__ */ jsx("p", {
1565
+ className: "nbe-note",
1566
+ children: t("editor.preview.lastValid")
1567
+ }), preview && /* @__PURE__ */ jsx(ModuleRenderer, {
1568
+ config: preview,
1569
+ registry,
1570
+ mode: "preview",
1571
+ focus: focusPath ? { path: focusPath } : null
1572
+ })]
1573
+ })]
1574
+ })
1575
+ });
1576
+ }
1577
+ // src/BlockPicker.tsx
1578
+ var CATEGORY_ORDER = [
1579
+ "learn",
1580
+ "practice",
1581
+ "explore",
1582
+ "decide",
1583
+ "simulate",
1584
+ "present"
1585
+ ];
1586
+ var isBuiltIn = (type) => builtInModuleTypes.includes(type);
1587
+ /** A searchable catalogue of block types that creates ready-to-edit configs. */
1588
+ function BlockPicker({ registry = defaultRegistry, onPick, existingIds = [], defaultFrom = "example" }) {
1589
+ const t = useEditorT();
1590
+ const id = useId().replace(/[^a-zA-Z0-9]/g, "");
1591
+ const [query, setQuery] = useState("");
1592
+ const [from, setFrom] = useState(defaultFrom);
1593
+ const groups = useMemo(() => {
1594
+ const q = query.trim().toLowerCase();
1595
+ const defs = registry.list().filter((d) => !q || d.name.toLowerCase().includes(q) || d.description.toLowerCase().includes(q) || d.type.includes(q));
1596
+ return [...CATEGORY_ORDER, ...new Set(defs.map((d) => d.category))].filter((c, i, a) => a.indexOf(c) === i).map((c) => ({
1597
+ category: c,
1598
+ defs: defs.filter((d) => d.category === c)
1599
+ })).filter((g) => g.defs.length);
1600
+ }, [registry, query]);
1601
+ const pick = (type) => {
1602
+ const newId = uniqueId(type, existingIds);
1603
+ onPick(isBuiltIn(type) ? from === "example" ? createExample(type, { id: newId }) : createEmpty(type, { id: newId }) : {
1604
+ id: newId,
1605
+ type
1606
+ }, {
1607
+ type,
1608
+ from
1609
+ });
1610
+ };
1611
+ const rootProps = useRootProps();
1612
+ return /* @__PURE__ */ jsxs("div", {
1613
+ className: "nbe-root nb-theme nbe-picker",
1614
+ ...rootProps,
1615
+ children: [
1616
+ /* @__PURE__ */ jsx("h2", {
1617
+ className: "nbe-picker__title",
1618
+ children: t("editor.picker.title")
1619
+ }),
1620
+ /* @__PURE__ */ jsxs("div", {
1621
+ className: "nbe-picker__controls",
1622
+ children: [/* @__PURE__ */ jsxs("div", {
1623
+ className: "nbe-search",
1624
+ children: [
1625
+ /* @__PURE__ */ jsx(Search, {
1626
+ "aria-hidden": true,
1627
+ size: 16
1628
+ }),
1629
+ /* @__PURE__ */ jsx("label", {
1630
+ className: "nbe-sr-only",
1631
+ htmlFor: `${id}-q`,
1632
+ children: t("editor.picker.search")
1633
+ }),
1634
+ /* @__PURE__ */ jsx("input", {
1635
+ id: `${id}-q`,
1636
+ type: "search",
1637
+ className: "nbe-input",
1638
+ placeholder: t("editor.picker.search"),
1639
+ value: query,
1640
+ onChange: (e) => setQuery(e.target.value)
1641
+ })
1642
+ ]
1643
+ }), /* @__PURE__ */ jsxs("fieldset", {
1644
+ className: "nbe-segmented",
1645
+ children: [/* @__PURE__ */ jsx("legend", {
1646
+ className: "nbe-sr-only",
1647
+ children: t("editor.picker.start")
1648
+ }), ["example", "empty"].map((v) => /* @__PURE__ */ jsxs("label", {
1649
+ className: "nbe-segmented__option",
1650
+ children: [/* @__PURE__ */ jsx("input", {
1651
+ type: "radio",
1652
+ name: `${id}-from`,
1653
+ value: v,
1654
+ checked: from === v,
1655
+ onChange: () => setFrom(v)
1656
+ }), /* @__PURE__ */ jsx("span", { children: t(v === "example" ? "editor.picker.example" : "editor.picker.blank") })]
1657
+ }, v))]
1658
+ })]
1659
+ }),
1660
+ groups.length === 0 && /* @__PURE__ */ jsx("p", {
1661
+ className: "nbe-note",
1662
+ children: t("editor.picker.empty", { query })
1663
+ }),
1664
+ groups.map((g) => /* @__PURE__ */ jsxs("section", {
1665
+ className: "nbe-picker__group",
1666
+ "aria-labelledby": `${id}-${g.category}`,
1667
+ children: [/* @__PURE__ */ jsx("h3", {
1668
+ className: "nbe-picker__category",
1669
+ id: `${id}-${g.category}`,
1670
+ children: t(`editor.category.${g.category}`)
1671
+ }), /* @__PURE__ */ jsx("ul", {
1672
+ className: "nbe-picker__list",
1673
+ children: g.defs.map((d) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs("button", {
1674
+ type: "button",
1675
+ className: "nbe-block",
1676
+ onClick: () => pick(d.type),
1677
+ children: [/* @__PURE__ */ jsx("span", {
1678
+ className: "nbe-block__icon",
1679
+ children: /* @__PURE__ */ jsx(ModuleIcon, {
1680
+ type: d.type,
1681
+ registry,
1682
+ size: 20
1683
+ })
1684
+ }), /* @__PURE__ */ jsxs("span", {
1685
+ className: "nbe-block__text",
1686
+ children: [/* @__PURE__ */ jsx("span", {
1687
+ className: "nbe-block__name",
1688
+ children: d.name
1689
+ }), /* @__PURE__ */ jsx("span", {
1690
+ className: "nbe-block__desc",
1691
+ children: d.description
1692
+ })]
1693
+ })]
1694
+ }) }, d.type))
1695
+ })]
1696
+ }, g.category))
1697
+ ]
1698
+ });
1699
+ }
1700
+ // src/LessonEditor.tsx
1701
+ /** Edit a whole lesson: the list of blocks, each block's settings with preview, and lesson settings. */
1702
+ function LessonEditor({ value, onChange, registry = defaultRegistry, onPickImage }) {
1703
+ const t = useEditorT();
1704
+ const id = useId().replace(/[^a-zA-Z0-9]/g, "");
1705
+ const modules = Array.isArray(value.modules) ? value.modules : [];
1706
+ const [selected, setSelected] = useState(modules.length ? 0 : "add");
1707
+ const index = typeof selected === "number" && modules.length ? Math.min(selected, modules.length - 1) : -1;
1708
+ const current = index >= 0 ? modules[index] : void 0;
1709
+ const settingsSchema = useMemo(() => {
1710
+ const s = getLessonJsonSchema({ registry: registry.schemas });
1711
+ const { modules: _modules, schemaVersion: _version, ...properties } = s.properties;
1712
+ return {
1713
+ ...s,
1714
+ properties,
1715
+ required: (s.required ?? []).filter((k) => k !== "modules" && k !== "schemaVersion")
1716
+ };
1717
+ }, [registry]);
1718
+ const [generation, setGeneration] = useState(0);
1719
+ const [own, setOwn] = useState(null);
1720
+ const [seen, setSeen] = useState(value);
1721
+ if (seen !== value) {
1722
+ setSeen(value);
1723
+ if (value !== own) setGeneration((g) => g + 1);
1724
+ }
1725
+ const latest = useRef({
1726
+ value,
1727
+ generation
1728
+ });
1729
+ useEffect(() => {
1730
+ latest.current = {
1731
+ value,
1732
+ generation
1733
+ };
1734
+ });
1735
+ const emit = (next) => {
1736
+ setOwn(next);
1737
+ onChange(next);
1738
+ };
1739
+ const setModules = (next, structural = false) => {
1740
+ if (structural) setGeneration((g) => g + 1);
1741
+ emit({
1742
+ ...latest.current.value,
1743
+ modules: next
1744
+ });
1745
+ };
1746
+ const ids = modules.map((m) => String(m.id ?? ""));
1747
+ const lessonIssues = useMemo(() => {
1748
+ const r = validateLesson(value, { registry: registry.schemas });
1749
+ return r.success ? [] : r.issues;
1750
+ }, [value, registry]);
1751
+ const blockOf = (i) => i.segments?.[0] === "modules" && typeof i.segments[1] === "number" ? i.segments[1] : -1;
1752
+ const settingsIssues = lessonIssues.filter((i) => blockOf(i) < 0);
1753
+ const hasIssues = (b) => lessonIssues.some((i) => blockOf(i) === b);
1754
+ const ownIssues = current ? validateModule(current, { registry: registry.schemas }) : null;
1755
+ const known = new Set(ownIssues && !ownIssues.success ? ownIssues.issues.map((i) => i.message) : []);
1756
+ const currentExtra = current ? lessonIssues.filter((i) => blockOf(i) === index && !known.has(i.message)) : [];
1757
+ const nameOf = (m) => (typeof m.title === "string" && m.title ? stripMarkup(m.title) : void 0) ?? registry.get(String(m.type))?.name ?? String(m.type);
1758
+ const move = (i, to) => {
1759
+ if (to < 0 || to >= modules.length) return;
1760
+ const next = [...modules];
1761
+ const [m] = next.splice(i, 1);
1762
+ next.splice(to, 0, m);
1763
+ setModules(next, true);
1764
+ setSelected(to);
1765
+ };
1766
+ const duplicate = (i) => {
1767
+ const copy = structuredClone(modules[i]);
1768
+ copy.id = uniqueId(String(copy.id ?? copy.type ?? "block").replace(/-\d+$/, ""), ids);
1769
+ const next = [...modules];
1770
+ next.splice(i + 1, 0, copy);
1771
+ setModules(next, true);
1772
+ setSelected(i + 1);
1773
+ };
1774
+ const remove = (i) => {
1775
+ setModules(modules.filter((_, j) => j !== i), true);
1776
+ setSelected(modules.length > 1 ? Math.max(0, i - 1) : "add");
1777
+ };
1778
+ const rootProps = useRootProps();
1779
+ return /* @__PURE__ */ jsx("div", {
1780
+ className: "nbe-root nb-theme",
1781
+ ...rootProps,
1782
+ children: /* @__PURE__ */ jsxs("div", {
1783
+ className: "nbe-lesson",
1784
+ children: [/* @__PURE__ */ jsxs("nav", {
1785
+ className: "nbe-lesson__nav",
1786
+ "aria-labelledby": `${id}-blocks`,
1787
+ children: [
1788
+ /* @__PURE__ */ jsx("h2", {
1789
+ className: "nbe-lesson__heading",
1790
+ id: `${id}-blocks`,
1791
+ children: t("editor.lesson.modules")
1792
+ }),
1793
+ modules.length === 0 && /* @__PURE__ */ jsx("p", {
1794
+ className: "nbe-note",
1795
+ children: t("editor.lesson.empty")
1796
+ }),
1797
+ /* @__PURE__ */ jsx("ol", {
1798
+ className: "nbe-lesson__list",
1799
+ children: modules.map((m, i) => /* @__PURE__ */ jsxs("li", {
1800
+ className: "nbe-lesson__item",
1801
+ "data-selected": selected === i || void 0,
1802
+ children: [/* @__PURE__ */ jsxs("button", {
1803
+ type: "button",
1804
+ className: "nbe-lesson__select",
1805
+ "aria-current": selected === i ? "true" : void 0,
1806
+ onClick: () => setSelected(i),
1807
+ children: [
1808
+ /* @__PURE__ */ jsx(ModuleIcon, {
1809
+ type: String(m.type),
1810
+ registry,
1811
+ size: 16
1812
+ }),
1813
+ /* @__PURE__ */ jsx("span", {
1814
+ className: "nbe-lesson__name",
1815
+ children: nameOf(m)
1816
+ }),
1817
+ hasIssues(i) && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(AlertCircle, {
1818
+ "aria-hidden": true,
1819
+ size: 14,
1820
+ className: "nbe-lesson__issue"
1821
+ }), /* @__PURE__ */ jsxs("span", {
1822
+ className: "nbe-sr-only",
1823
+ children: [", ", t("editor.lesson.hasIssues")]
1824
+ })] }),
1825
+ /* @__PURE__ */ jsx("span", {
1826
+ className: "nbe-sr-only",
1827
+ children: t("editor.lesson.position", {
1828
+ current: i + 1,
1829
+ total: modules.length
1830
+ })
1831
+ })
1832
+ ]
1833
+ }), /* @__PURE__ */ jsxs("span", {
1834
+ className: "nbe-lesson__actions",
1835
+ children: [
1836
+ /* @__PURE__ */ jsxs("button", {
1837
+ type: "button",
1838
+ className: "nbe-icon-btn",
1839
+ disabled: i === 0,
1840
+ onClick: () => move(i, i - 1),
1841
+ children: [/* @__PURE__ */ jsx(ArrowUp, {
1842
+ "aria-hidden": true,
1843
+ size: 14
1844
+ }), /* @__PURE__ */ jsx("span", {
1845
+ className: "nbe-sr-only",
1846
+ children: t("editor.moveUpItem", {
1847
+ item: nameOf(m),
1848
+ index: ""
1849
+ })
1850
+ })]
1851
+ }),
1852
+ /* @__PURE__ */ jsxs("button", {
1853
+ type: "button",
1854
+ className: "nbe-icon-btn",
1855
+ disabled: i === modules.length - 1,
1856
+ onClick: () => move(i, i + 1),
1857
+ children: [/* @__PURE__ */ jsx(ArrowDown, {
1858
+ "aria-hidden": true,
1859
+ size: 14
1860
+ }), /* @__PURE__ */ jsx("span", {
1861
+ className: "nbe-sr-only",
1862
+ children: t("editor.moveDownItem", {
1863
+ item: nameOf(m),
1864
+ index: ""
1865
+ })
1866
+ })]
1867
+ }),
1868
+ /* @__PURE__ */ jsxs("button", {
1869
+ type: "button",
1870
+ className: "nbe-icon-btn",
1871
+ onClick: () => duplicate(i),
1872
+ children: [/* @__PURE__ */ jsx(Copy, {
1873
+ "aria-hidden": true,
1874
+ size: 14
1875
+ }), /* @__PURE__ */ jsx("span", {
1876
+ className: "nbe-sr-only",
1877
+ children: t("editor.duplicateItem", {
1878
+ item: nameOf(m),
1879
+ index: ""
1880
+ })
1881
+ })]
1882
+ }),
1883
+ /* @__PURE__ */ jsxs("button", {
1884
+ type: "button",
1885
+ className: "nbe-icon-btn nbe-icon-btn--danger",
1886
+ disabled: modules.length <= 1,
1887
+ onClick: () => remove(i),
1888
+ children: [/* @__PURE__ */ jsx(Trash2, {
1889
+ "aria-hidden": true,
1890
+ size: 14
1891
+ }), /* @__PURE__ */ jsx("span", {
1892
+ className: "nbe-sr-only",
1893
+ children: t("editor.removeItem", {
1894
+ item: nameOf(m),
1895
+ index: ""
1896
+ })
1897
+ })]
1898
+ })
1899
+ ]
1900
+ })]
1901
+ }, `${String(m.id)}-${i}`))
1902
+ }),
1903
+ /* @__PURE__ */ jsxs("div", {
1904
+ className: "nbe-lesson__nav-actions",
1905
+ children: [/* @__PURE__ */ jsxs("button", {
1906
+ type: "button",
1907
+ className: "nbe-btn nbe-btn--dashed",
1908
+ "aria-pressed": selected === "add",
1909
+ onClick: () => setSelected("add"),
1910
+ children: [/* @__PURE__ */ jsx(Plus, {
1911
+ "aria-hidden": true,
1912
+ size: 14
1913
+ }), t("editor.lesson.addBlock")]
1914
+ }), /* @__PURE__ */ jsxs("button", {
1915
+ type: "button",
1916
+ className: "nbe-btn",
1917
+ "aria-pressed": selected === "settings",
1918
+ onClick: () => setSelected("settings"),
1919
+ children: [/* @__PURE__ */ jsx(Settings, {
1920
+ "aria-hidden": true,
1921
+ size: 14
1922
+ }), t("editor.lesson.settings")]
1923
+ })]
1924
+ })
1925
+ ]
1926
+ }), /* @__PURE__ */ jsxs("div", {
1927
+ className: "nbe-lesson__main",
1928
+ children: [
1929
+ selected === "settings" && /* @__PURE__ */ jsxs("section", {
1930
+ "aria-labelledby": `${id}-settings`,
1931
+ children: [/* @__PURE__ */ jsx("h2", {
1932
+ className: "nbe-lesson__heading",
1933
+ id: `${id}-settings`,
1934
+ children: t("editor.lesson.settings")
1935
+ }), /* @__PURE__ */ jsx(ModuleForm, {
1936
+ value,
1937
+ onChange: (next) => emit({
1938
+ ...next,
1939
+ modules: latest.current.value.modules,
1940
+ schemaVersion: latest.current.value.schemaVersion ?? 1
1941
+ }),
1942
+ schema: settingsSchema,
1943
+ registry,
1944
+ onPickImage,
1945
+ issues: settingsIssues
1946
+ })]
1947
+ }),
1948
+ selected === "add" && /* @__PURE__ */ jsx(BlockPicker, {
1949
+ registry,
1950
+ existingIds: ids,
1951
+ onPick: (config) => {
1952
+ setModules([...modules, config], true);
1953
+ setSelected(modules.length);
1954
+ }
1955
+ }),
1956
+ current && typeof selected === "number" && currentExtra.length > 0 && /* @__PURE__ */ jsx("div", {
1957
+ className: "nbe-issues",
1958
+ role: "group",
1959
+ "aria-label": t("editor.lesson.blockIssues"),
1960
+ children: /* @__PURE__ */ jsx("ul", {
1961
+ className: "nbe-issues__list",
1962
+ children: currentExtra.map((issue, k) => /* @__PURE__ */ jsxs("li", { children: [
1963
+ /* @__PURE__ */ jsx("code", { children: issue.path }),
1964
+ ": ",
1965
+ issue.message
1966
+ ] }, k))
1967
+ })
1968
+ }),
1969
+ current && typeof selected === "number" && /* @__PURE__ */ jsx(ModuleEditor, {
1970
+ value: current,
1971
+ registry,
1972
+ onPickImage,
1973
+ onChange: (next) => {
1974
+ const at = latest.current;
1975
+ if (at.generation !== generation) return;
1976
+ const list = Array.isArray(at.value.modules) ? at.value.modules : [];
1977
+ setModules(list.map((m, j) => j === index ? next : m));
1978
+ }
1979
+ }, `${generation}:${index}`)
1980
+ ]
1981
+ })]
1982
+ })
1983
+ });
1984
+ }
1985
+ export { BlockPicker, LessonEditor, ModuleEditor, ModuleForm, defaultFor, editorMessages, getAt, insertAt, moveItem, removeAt, setAt, toFormNode, uniqueId, useEditorT };
1986
+
1987
+ //# sourceMappingURL=index.js.map