foldkit-builder 0.0.0-stage → 0.1.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.mjs ADDED
@@ -0,0 +1,1711 @@
1
+ import { Effect, Option, Result, Schema } from "effect";
2
+ import { Bundle } from "foldkit-bundle";
3
+ import { Block, Catalog, Composition, NodeId, fieldsOf, spaced } from "foldkit-composition";
4
+ import { Renderer, fieldName, fieldOf } from "foldkit-composition/foldkit";
5
+ import { Form, Input, fillWords } from "foldkit-form";
6
+ import { Entity, Words } from "foldkit-entity";
7
+ import { Metadata } from "foldkit-metadata";
8
+ import { copyText, readText } from "foldkit-primitives/dom";
9
+ import { LiveAnnounce, TreeNavigation } from "foldkit-primitives/interaction";
10
+ import { History, HistoryModel } from "foldkit-primitives/state";
11
+ import * as Command from "foldkit/command";
12
+ import { inertHtml } from "foldkit/html";
13
+ import { defineMessageUnion } from "foldkit/message";
14
+ import * as Submodel from "foldkit/submodel";
15
+ //#region src/settings.ts
16
+ /**
17
+ * A node's values as `foldkit-form` forms: a Block's props, and the input of
18
+ * each action an event runs. The inspector edits a node through them. The
19
+ * Document owns the values; a form holds only what a field shows, including
20
+ * text that does not decode yet (a number typed as "1."), and each change
21
+ * that decodes becomes one Operation.
22
+ */
23
+ const controlsKey = Metadata.key("foldkit-builder/controls", {
24
+ merge: (records) => [Object.assign({}, ...records)],
25
+ summarize: (record) => Object.entries(record).map(([key, control]) => `${key}: ${control.kind}`).join(", ")
26
+ });
27
+ /**
28
+ * Block metadata: the control the inspector draws a prop with, where its
29
+ * Schema alone does not say, as
30
+ * `Heading.pipe(Block.annotate(Builder.controls({ text: Input.multiline() })))`.
31
+ * `Input.hidden()` leaves a prop out of the inspector.
32
+ */
33
+ const controls = (given) => controlsKey.of(given);
34
+ /** A prop's words: its Schema's `title`, else its key spaced, and its description. */
35
+ const wordsOf = (key, schema) => {
36
+ const { title, description } = Words.of(schema);
37
+ return {
38
+ label: Option.getOrElse(title, () => spaced(key)),
39
+ description
40
+ };
41
+ };
42
+ /** A form over `fields`, named `name`, with the controls `hints` asks for. */
43
+ const make = (name, fields, hints) => {
44
+ const resolve = (key, schema) => hints[key] ?? Input.resolve(Entity.unmapped, schema);
45
+ const editable = Object.entries(fields).filter(([key, schema]) => resolve(key, Schema.toEncoded(schema)) !== void 0);
46
+ const decoders = Object.fromEntries(editable.map(([key, schema]) => [key, Schema.decodeUnknownResult(schema)]));
47
+ const Props = Schema.Struct(Object.fromEntries(editable.map(([key, schema]) => [key, Schema.toEncoded(schema).check(Schema.makeFilter((value) => Result.match(decoders[key](value), {
48
+ onSuccess: () => void 0,
49
+ onFailure: (error) => error.message
50
+ })))])));
51
+ const labels = Object.fromEntries(editable.map(([key, schema]) => {
52
+ const { label, description } = wordsOf(key, schema);
53
+ return [key, Form.label(label, Option.getOrUndefined(description))];
54
+ }));
55
+ const entity = Entity.define(name, Props).pipe(Entity.annotateMembers(labels));
56
+ const form = Form.make(name, Entity.input(entity, Props), { inputs: hints });
57
+ if (form.bundle.subscriptions !== void 0 || form.bundle.resources !== void 0) throw new Error(`Builder: "${name}" has a control with Subscriptions or Resources (an Input.bundle), which the inspector cannot run; give it a control that needs neither`);
58
+ const encodeModel = Schema.encodeSync(form.bundle.Model);
59
+ const decodeModel = Schema.decodeUnknownResult(form.bundle.Model);
60
+ const encodeMessage = Schema.encodeSync(form.bundle.Message);
61
+ const decodeMessage = Schema.decodeUnknownResult(form.bundle.Message, { onExcessProperty: "error" });
62
+ return {
63
+ form,
64
+ /** Every key the form's Schema names, edited or shown. */
65
+ keys: Object.keys(fields),
66
+ /** The props the form does not edit, labelled as its fields are, and as stored: shown, not changed. */
67
+ shown: (stored) => Object.entries(fields).filter(([key]) => !Object.hasOwn(decoders, key)).map(([key, schema]) => ({
68
+ key,
69
+ label: wordsOf(key, schema).label,
70
+ value: stored[key]
71
+ })),
72
+ /**
73
+ * `model` with the fields `keep` spares filled from a node's stored props.
74
+ * A stored prop that does not decode is shown as it is, with its error.
75
+ */
76
+ fill: (model, stored, keep = () => false) => {
77
+ const keys = Object.keys(decoders).filter((key) => !keep(key));
78
+ const filled = form.fill(model, Object.fromEntries(keys.map((key) => [key, stored[key]]))).model;
79
+ return keys.filter((key) => stored[key] !== void 0 && Result.isFailure(decoders[key](stored[key]))).reduce((next, key) => form.bundle.update(next, form.Message.Blurred({ key }), void 0).model, filled);
80
+ },
81
+ /** The form's Model as the Builder's Model holds it: JSON. */
82
+ encode: (model) => encodeModel(model),
83
+ /** A held form Model read back; none if it no longer fits, which a refill then replaces. */
84
+ decode: (held) => Result.getSuccess(decodeModel(held)),
85
+ encodeMessage: (message) => encodeMessage(message),
86
+ decodeMessage: (held) => Result.getSuccess(decodeMessage(held)),
87
+ /**
88
+ * A Message of the Bundle behind `key`'s control (an `Input.bundle`), as the
89
+ * form's own. Built from runtime fields, the form's type names no such key,
90
+ * so it is checked here: a key not edited by one throws.
91
+ */
92
+ control: (key, message) => form.control(key).send(message),
93
+ /**
94
+ * What a new value starts from, as the Document stores it: each field's
95
+ * empty value where it decodes (`''`, `null`, `false`), else a number's
96
+ * zero or a select's first choice; a field with neither is left out. It is
97
+ * not checked: a zero a number's check refuses, or a field left out, makes
98
+ * a value the Document refuses when it is set.
99
+ */
100
+ seed: () => {
101
+ const empty = form.partial(form.initial);
102
+ return Object.fromEntries(editable.flatMap(([key, schema]) => {
103
+ if (Object.hasOwn(empty, key)) return [[key, empty[key]]];
104
+ const control = resolve(key, Schema.toEncoded(schema));
105
+ if (control !== void 0 && Input.Number.is(control)) return [[key, 0]];
106
+ const [first] = control !== void 0 && Input.Select.is(control) ? control.data.options : [];
107
+ return first === void 0 ? [] : [[key, first]];
108
+ }));
109
+ },
110
+ /** A value from the form, as the Document stores it; none for a prop the form does not edit. */
111
+ stored: (key, value) => Object.hasOwn(decoders, key) ? Option.some(value) : Option.none()
112
+ };
113
+ };
114
+ const made = /* @__PURE__ */ new WeakMap();
115
+ /** A Block's props as a form, made at the first use and kept: one per Block. */
116
+ const settingsOf = (block) => {
117
+ const known = made.get(block);
118
+ if (known !== void 0) return known;
119
+ const settings = make(`${block.name}Settings`, fieldsOf(block.Props), controlsKey.get(block.metadata)[0] ?? {});
120
+ made.set(block, settings);
121
+ return settings;
122
+ };
123
+ const inputs = /* @__PURE__ */ new WeakMap();
124
+ /**
125
+ * The input an event of a Block runs an action with, as a form, made at the
126
+ * first use and kept. One per Block, event and action, so two events of one
127
+ * node that run the same action draw their fields under ids of their own.
128
+ */
129
+ const inputOf = (block, event, action) => {
130
+ const name = `${block.name}-${event}-${action.name}`;
131
+ const known = inputs.get(action) ?? /* @__PURE__ */ new Map();
132
+ inputs.set(action, known);
133
+ const held = known.get(name);
134
+ if (held !== void 0) return held;
135
+ const settings = make(name, fieldsOf(action.input), {});
136
+ known.set(name, settings);
137
+ return settings;
138
+ };
139
+ /** The control a prop is drawn with: the Block's hint, else what its Schema says. */
140
+ const controlOf = (block, key, schema) => controlsKey.get(block.metadata)[0]?.[key] ?? Input.resolve(Entity.unmapped, schema);
141
+ //#endregion
142
+ //#region src/words.ts
143
+ const editWords = Object.freeze({
144
+ at: ", {position} of {count} in {container}",
145
+ thePage: "the page",
146
+ inRegion: "{label} {region}",
147
+ moved: "Moved {label}{at}",
148
+ added: "Added {label}{at}",
149
+ duplicated: "Duplicated {label}{at}",
150
+ removed: "Removed {label}",
151
+ editedPage: "Edited the page",
152
+ undone: "Undone",
153
+ redone: "Redone",
154
+ notMoved: "Not moved",
155
+ notAdded: "Not added",
156
+ copied: "Copied {label}",
157
+ cut: "Cut {label}",
158
+ nothingCopied: "Nothing has been copied",
159
+ notAPage: "The clipboard holds no part of a page",
160
+ noStartingProps: "\"{block}\" has no starting props, so it cannot be inserted",
161
+ startingPropsFail: "\"{block}\"'s starting props do not encode",
162
+ notANode: "\"{id}\" is not a node",
163
+ unknownPattern: "the Catalog has no pattern \"{name}\"",
164
+ noPlace: "There is no place on this page for a {label}",
165
+ copyChanged: "\"{id}\" changed while its copy was being made; copy it again",
166
+ refusal: "{message}",
167
+ moveUp: "Move up",
168
+ moveDown: "Move down",
169
+ moveOut: "Move out",
170
+ moveIn: "Move in",
171
+ duplicate: "Duplicate",
172
+ copy: "Copy",
173
+ cutCommand: "Cut",
174
+ delete: "Delete",
175
+ undo: "Undo",
176
+ redo: "Redo",
177
+ paste: "Paste",
178
+ editText: "Edit its text",
179
+ deselect: "Select nothing"
180
+ });
181
+ //#endregion
182
+ //#region src/index.ts
183
+ /**
184
+ * `foldkit-builder`: the page builder's state, as an ordinary Bundle.
185
+ *
186
+ * The Builder edits a `foldkit-composition` Document by Operations. Its Model
187
+ * holds the page as an undo history (`foldkit-primitives/state`) whose present
188
+ * is the Document, with the editor's state beside it (what is selected, the
189
+ * open panel, the viewport), so an edit and the undo step that records it are
190
+ * one value, changed in one transition. The Catalog and the Renderer are
191
+ * vocabulary, not state: the Builder closes over them where it is made, and
192
+ * they never enter the Model or a placement's args.
193
+ *
194
+ * Placed as a form key's control (`builder.input`), the Document is that key's
195
+ * value: the form validates it, submits it, and a CMS autosaves it, while a
196
+ * selection or an open panel is not an edit. Placed alone, with
197
+ * `Bundle.withChild`, its parent owns the Model instead.
198
+ */
199
+ const Panel = Schema.Literals([
200
+ "insert",
201
+ "layers",
202
+ "properties"
203
+ ]);
204
+ const Viewport = Schema.Literals([
205
+ "wide",
206
+ "medium",
207
+ "narrow"
208
+ ]);
209
+ /** The layers panel's keyboard focus and which rows are open: a tree that starts open. */
210
+ const Layers = Bundle.declare(TreeNavigation.bundle, "layers");
211
+ const layersArgs = { openByDefault: true };
212
+ /** What the editor says to assistive technology: a move, an insert, a refusal. */
213
+ const Announcer = Bundle.declare(LiveAnnounce.bundle, "announcer");
214
+ const announcerArgs = {
215
+ debounceMs: 150,
216
+ clearAfterMs: 5e3
217
+ };
218
+ /** Where over a node a drop lands: before it, inside it, or after it. */
219
+ const DropZone = Schema.Literals([
220
+ "before",
221
+ "inside",
222
+ "after"
223
+ ]);
224
+ /** What a drag carries: a node on the page, or a new node of a Block, from the palette. */
225
+ const DragSource = Schema.Union([Schema.TaggedStruct("Existing", { id: NodeId }), Schema.TaggedStruct("New", { block: Schema.String })]);
226
+ /** A drag under way: what is dragged, what it is over, and where it would go. */
227
+ const Drag = Schema.Struct({
228
+ source: DragSource,
229
+ /**
230
+ * The node it is over and the zone of it; none while it is over nothing, or
231
+ * over the page's own space, which `at` then tells apart.
232
+ */
233
+ over: Schema.OptionFromNullOr(Schema.Struct({
234
+ id: NodeId,
235
+ zone: DropZone,
236
+ /** The empty Region of the node it is over, which a drop goes into. */
237
+ region: Schema.OptionFromNullOr(Schema.String)
238
+ })),
239
+ /**
240
+ * Where a drop now puts it; none where a drop there would be refused.
241
+ * `over.zone` is where it lands: `inside` a node that takes nothing is `after`.
242
+ */
243
+ at: Schema.OptionFromNullOr(Composition.Position)
244
+ });
245
+ /** A value of the page's context, as the editor previews it. */
246
+ const ContextValue = Schema.Union([
247
+ Schema.String,
248
+ Schema.Number,
249
+ Schema.Boolean,
250
+ Schema.Null
251
+ ]);
252
+ const Model = Schema.Struct({
253
+ ...Layers.fields,
254
+ ...Announcer.fields,
255
+ /** The page and its undo steps: `page.present` is the Document being edited. */
256
+ page: HistoryModel(Composition.Document),
257
+ /** The node the inspector and the node actions work on. */
258
+ selected: Schema.OptionFromNullOr(NodeId),
259
+ /** The node under the pointer on the canvas or in the layers. */
260
+ hovered: Schema.OptionFromNullOr(NodeId),
261
+ panel: Panel,
262
+ viewport: Viewport,
263
+ /** Why the last edit was refused, until the next one goes through. */
264
+ refused: Schema.OptionFromNullOr(Schema.Struct({
265
+ code: Schema.String,
266
+ message: Schema.String
267
+ })),
268
+ /** A pointer drag under way. */
269
+ drag: Schema.OptionFromNullOr(Drag),
270
+ /**
271
+ * The context the page is drawn for in the editor, by the Catalog's context
272
+ * keys: what an author previews it as. A node whose `when` fails here is
273
+ * drawn marked, not left out.
274
+ */
275
+ preview: Schema.Record(Schema.String, ContextValue),
276
+ /**
277
+ * What the inspector's fields hold for the node they show: each form's Model
278
+ * encoded to JSON, by the form's key (`props`, or `on:<event>:<action>`), so
279
+ * text that does not decode yet stays here, not in the page. None until a
280
+ * field is changed, and after the selection moves; a form it does not hold is
281
+ * filled from the node. Stored only when some, so a Builder saved before
282
+ * there was one still reads.
283
+ */
284
+ inspector: Schema.OptionFromOptionalNullOr(Schema.Struct({
285
+ id: NodeId,
286
+ forms: Schema.Record(Schema.String, Schema.Json)
287
+ })),
288
+ /**
289
+ * The last node copied or cut, and all it holds: what a paste inserts when
290
+ * the system clipboard cannot be read. Kept across pages, so a copy on one
291
+ * pastes on another.
292
+ */
293
+ clipboard: Schema.OptionFromOptionalNullOr(Composition.Tree),
294
+ /**
295
+ * The text prop being edited in place on the canvas; its text when editing
296
+ * began, which the canvas keeps the field at; and whether anything has been
297
+ * typed, since only then does ending it write. Stored only when some.
298
+ */
299
+ editing: Schema.OptionFromOptionalNullOr(Schema.Struct({
300
+ id: NodeId,
301
+ key: Schema.String,
302
+ initial: Schema.String,
303
+ typed: Schema.Boolean
304
+ }))
305
+ });
306
+ /** An edit that creates nodes and waits for their new ids. */
307
+ const Request = Schema.Union([
308
+ Schema.TaggedStruct("Insert", {
309
+ block: Schema.String,
310
+ at: Composition.Position
311
+ }),
312
+ Schema.TaggedStruct("Duplicate", {
313
+ id: NodeId,
314
+ at: Composition.Position
315
+ }),
316
+ Schema.TaggedStruct("Paste", {
317
+ tree: Composition.Tree,
318
+ at: Composition.Position
319
+ }),
320
+ Schema.TaggedStruct("Pattern", {
321
+ pattern: Schema.String,
322
+ at: Composition.Position
323
+ })
324
+ ]);
325
+ /**
326
+ * A copied node as the system clipboard holds it: JSON, tagged, so text that
327
+ * is not part of a page is not pasted as one.
328
+ */
329
+ const Clip = Schema.fromJsonString(Schema.Struct({
330
+ format: Schema.Literal("foldkit-composition"),
331
+ tree: Composition.Tree
332
+ }));
333
+ const clipText = (tree) => Schema.encodeSync(Clip)({
334
+ format: "foldkit-composition",
335
+ tree
336
+ });
337
+ const clipOf = Schema.decodeUnknownResult(Clip, { onExcessProperty: "error" });
338
+ const Message = defineMessageUnion({
339
+ ...Layers.cases,
340
+ ...Announcer.cases,
341
+ Selected: { id: NodeId },
342
+ /** Nothing is selected. */
343
+ Deselected: {},
344
+ Hovered: { id: NodeId },
345
+ /** The pointer left every node. */
346
+ Unhovered: {},
347
+ /** An Operation, from a button, a key, a drag, or an agent. */
348
+ Applied: { op: Composition.Operation },
349
+ /** A new node of a Block, with the Block's starting props, once an id is minted. */
350
+ InsertAsked: {
351
+ block: Schema.String,
352
+ at: Composition.Position
353
+ },
354
+ /** A copy of a node and everything it holds, once ids are minted. */
355
+ DuplicateAsked: {
356
+ id: NodeId,
357
+ at: Composition.Position
358
+ },
359
+ /** One of the Catalog's patterns, once ids are minted for its nodes. */
360
+ PatternAsked: {
361
+ pattern: Schema.String,
362
+ at: Composition.Position
363
+ },
364
+ /** The selected node and all it holds, copied. */
365
+ CopyAsked: { id: NodeId },
366
+ /** The selected node and all it holds, copied and removed. */
367
+ CutAsked: { id: NodeId },
368
+ /** A paste: the system clipboard is read, and what it holds goes in by the selection. */
369
+ PasteAsked: {},
370
+ /** What the system clipboard held for a paste; none when it could not be read. */
371
+ ClipboardRead: { text: Schema.OptionFromNullOr(Schema.String) },
372
+ /**
373
+ * Text on the page is asked to be edited in place: a double-click on it, or
374
+ * Enter on its node. Each of these names the field as the canvas marks it
375
+ * (`data-composition-field`), which is checked here.
376
+ */
377
+ EditingAsked: { field: Schema.String },
378
+ /** What the field being edited holds now. */
379
+ FieldTyped: {
380
+ field: Schema.String,
381
+ text: Schema.String
382
+ },
383
+ /** Editing ended with the text kept: Enter, or leaving the field. */
384
+ EditingCommitted: {
385
+ field: Schema.String,
386
+ text: Schema.String
387
+ },
388
+ /** Editing ended with the text put back as it began: Escape. */
389
+ EditingCancelled: { field: Schema.String },
390
+ /** The ids a request waited for. */
391
+ Minted: {
392
+ ids: Schema.Array(NodeId),
393
+ request: Request
394
+ },
395
+ Undid: {},
396
+ Redid: {},
397
+ PanelChosen: { panel: Panel },
398
+ ViewportChosen: { viewport: Viewport },
399
+ /** A pointer drag of a node began: it is selected, and nothing moves until the drop. */
400
+ DragStarted: { source: DragSource },
401
+ /** The dragged node is over another, in a zone of it. */
402
+ DraggedOver: {
403
+ id: NodeId,
404
+ zone: DropZone
405
+ },
406
+ /** The dragged node is over a node's empty Region, by name: a drop goes into it. */
407
+ DraggedOverRegion: {
408
+ id: NodeId,
409
+ region: Schema.String
410
+ },
411
+ /** The dragged node is over nothing. */
412
+ DraggedOff: {},
413
+ /**
414
+ * A palette tile is over the page but over none of its nodes, as an empty
415
+ * page or the space below the last node: it goes last where the page takes it.
416
+ */
417
+ DraggedOverPage: {},
418
+ /** The drag ended where it is: the node moves there, when it may. */
419
+ DragDropped: {},
420
+ DragCancelled: {},
421
+ /** The author previews the page with one context key set. */
422
+ PreviewChosen: {
423
+ key: Schema.String,
424
+ value: ContextValue
425
+ },
426
+ /** The author previews the page with one context key unset. */
427
+ PreviewCleared: { key: Schema.String },
428
+ /**
429
+ * A Message of one of a node's forms (`Inspecting`), encoded to JSON. One for
430
+ * a node no longer selected, or a form it no longer draws, such as a form's
431
+ * Command answering late, is ignored.
432
+ */
433
+ Inspected: {
434
+ id: NodeId,
435
+ form: Schema.String,
436
+ message: Schema.Json
437
+ }
438
+ });
439
+ const Parent = Bundle.parent({
440
+ Model,
441
+ Message
442
+ });
443
+ /** The layers' tree and the announcer, placed in the Builder's own Model. */
444
+ const placements = Parent.assemble(Parent.at(Layers, { args: layersArgs }), Parent.at(Announcer, { args: announcerArgs }));
445
+ /** Props as a Document stores them, read from what a Block's Schema encoded. */
446
+ const storedProps = Schema.decodeUnknownResult(Composition.Node.fields.props);
447
+ /**
448
+ * Where a new node of `block` goes, given what is selected: inside it, after
449
+ * it, or last, among the roots or, for a Block that is no root, in the last
450
+ * Region on the page with room that accepts it. None where it fits nowhere.
451
+ */
452
+ const placeFor = (catalog, document, selected, blockName) => {
453
+ const block = Catalog.block(catalog, blockName);
454
+ if (block === void 0) return Option.none();
455
+ const fits = (accepted) => block.provides.some((content) => accepted.includes(content));
456
+ /** Last in the first of a node's Regions with room that accepts the Block. */
457
+ const inside = (id) => {
458
+ const node = document.nodes[id];
459
+ const owner = node === void 0 ? void 0 : Catalog.block(catalog, node.block);
460
+ if (node !== void 0 && owner !== void 0) for (const [name, region] of Object.entries(owner.regions)) {
461
+ const children = node.regions[name] ?? [];
462
+ if (fits(region.accepts) && children.length < region.max) return Option.some(Composition.region(id, name, children.length));
463
+ }
464
+ return Option.none();
465
+ };
466
+ if (Option.isSome(selected)) {
467
+ const within = inside(selected.value);
468
+ if (Option.isSome(within)) return within;
469
+ }
470
+ const place = Option.isSome(selected) ? Composition.index(document).get(selected.value) : void 0;
471
+ if (place !== void 0 && place.parent !== void 0 && place.region !== void 0) {
472
+ const parent = document.nodes[place.parent];
473
+ const region = (parent === void 0 ? void 0 : Catalog.block(catalog, parent.block))?.regions[place.region];
474
+ const siblings = parent?.regions[place.region] ?? [];
475
+ if (region !== void 0 && fits(region.accepts) && siblings.length < region.max) return Option.some(Composition.region(place.parent, place.region, place.index + 1));
476
+ }
477
+ if (fits(catalog.roots)) return Option.some(Composition.root(place !== void 0 && place.parent === void 0 ? place.index + 1 : document.roots.length));
478
+ const order = [];
479
+ const visit = (id) => {
480
+ order.push(id);
481
+ for (const ids of Object.values(document.nodes[id]?.regions ?? {})) ids.forEach(visit);
482
+ };
483
+ document.roots.forEach(visit);
484
+ for (const id of order.reverse()) {
485
+ const last = inside(id);
486
+ if (Option.isSome(last)) return last;
487
+ }
488
+ return Option.none();
489
+ };
490
+ /** Whether a place has room for one more node: a root always, a Region below its most. */
491
+ const hasRoom = (catalog, document, at) => {
492
+ if (at._tag === "Root") return true;
493
+ const holder = document.nodes[at.parent];
494
+ const region = holder === void 0 ? void 0 : Catalog.block(catalog, holder.block)?.regions[at.region];
495
+ return region !== void 0 && (holder?.regions[at.region] ?? []).length < region.max;
496
+ };
497
+ /** The Operation that moves a node `delta` places among its siblings; none at an end. */
498
+ const moveBy = (document, id, delta) => {
499
+ const place = Composition.index(document).get(id);
500
+ if (place === void 0) return Option.none();
501
+ const to = place.index + delta;
502
+ const siblings = place.parent === void 0 ? document.roots : document.nodes[place.parent]?.regions[place.region ?? ""] ?? [];
503
+ if (to < 0 || to >= siblings.length) return Option.none();
504
+ return Option.some(Composition.Op.move(id, place.parent === void 0 ? Composition.root(to) : Composition.region(place.parent, place.region ?? "", to)));
505
+ };
506
+ /** The first of a holder's Regions that accepts a Block, by name: where "inside it" goes. */
507
+ const regionTaking = (catalog, holder, block) => {
508
+ const owner = Catalog.block(catalog, holder);
509
+ const taken = Catalog.block(catalog, block);
510
+ return Option.map(Option.fromUndefinedOr(Object.entries(owner?.regions ?? {}).find(([, candidate]) => (taken?.provides ?? []).some((content) => candidate.accepts.includes(content)))), ([name]) => name);
511
+ };
512
+ /**
513
+ * Where something dragged over `target`, in `zone`, lands beside or inside
514
+ * that one node: before or after it among its siblings, or last in the first
515
+ * of its Regions that accepts it, with the zone it landed in. `inside` a node
516
+ * that takes it nowhere lands after it. None when the page would refuse it
517
+ * there, such as a node into itself: each place is tried, a move for a node
518
+ * and an insert for a new one. `stays` where it would land on its own place.
519
+ */
520
+ const landingBy = (catalog, document, dragged, target, zone, region) => {
521
+ const place = Composition.index(document).get(target);
522
+ if (Option.contains(dragged.id, target) || place === void 0) return Option.none();
523
+ const without = (ids) => ids.filter((id) => !Option.contains(dragged.id, id));
524
+ const beside = (offset) => {
525
+ const siblings = place.parent === void 0 ? document.roots : document.nodes[place.parent]?.regions[place.region ?? ""] ?? [];
526
+ const at = without(siblings).indexOf(target) + offset;
527
+ return Option.some(place.parent === void 0 ? Composition.root(at) : Composition.region(place.parent, place.region ?? "", at));
528
+ };
529
+ const inside = () => {
530
+ const holder = document.nodes[target];
531
+ if (holder === void 0) return Option.none();
532
+ const named = Option.orElse(region, () => regionTaking(catalog, holder.block, dragged.block));
533
+ return Option.map(named, (regionName) => Composition.region(target, regionName, without(holder.regions[regionName] ?? []).length));
534
+ };
535
+ const current = Option.flatMap(dragged.id, (id) => Option.fromUndefinedOr(Composition.index(document).get(id))).pipe(Option.getOrUndefined);
536
+ const stays = (at) => current !== void 0 && at.index === current.index && (at._tag === "Root" ? current.parent === void 0 : at.parent === current.parent && at.region === current.region);
537
+ const candidates = zone === "before" ? [{
538
+ at: beside(0),
539
+ zone
540
+ }] : zone === "after" ? [{
541
+ at: beside(1),
542
+ zone
543
+ }] : [{
544
+ at: inside(),
545
+ zone
546
+ }, {
547
+ at: beside(1),
548
+ zone: "after"
549
+ }];
550
+ for (const candidate of candidates) {
551
+ if (Option.isNone(candidate.at)) continue;
552
+ const at = candidate.at.value;
553
+ if (stays(at)) return "stays";
554
+ if (Result.isSuccess(Composition.apply(catalog, document, dragged.to(at)))) return Option.some({
555
+ at,
556
+ zone: candidate.zone
557
+ });
558
+ }
559
+ return Option.none();
560
+ };
561
+ /** The Document being edited. */
562
+ const documentOf = (model) => model.page.present;
563
+ /**
564
+ * The undo group an Operation joins: consecutive edits of one prop of one node
565
+ * are one step, so typing a heading undoes as a whole. Everything else stands
566
+ * alone, which `History.push` takes as a `null` group.
567
+ */
568
+ const groupOf = (op) => op._tag === "SetProp" ? `SetProp:${op.id}:${op.prop}` : null;
569
+ /** The position right after a node, among its siblings. */
570
+ const after = (document, id) => {
571
+ const place = Composition.index(document).get(id);
572
+ if (place === void 0) return Option.none();
573
+ return Option.some(place.parent === void 0 ? Composition.root(place.index + 1) : Composition.region(place.parent, place.region ?? "", place.index + 1));
574
+ };
575
+ /** The Operation that moves a node out of its parent, to just after it; none at the top. */
576
+ const outdent = (document, id) => {
577
+ const parent = Composition.index(document).get(id)?.parent;
578
+ if (parent === void 0) return Option.none();
579
+ return Option.map(after(document, parent), (to) => Composition.Op.move(id, to));
580
+ };
581
+ /**
582
+ * The Operation that moves a node into the sibling above it, last in the first
583
+ * of its Regions that accepts it; none when there is none. Whether it fits is
584
+ * `apply`'s to check; this only picks the Region.
585
+ */
586
+ const indent = (catalog, document, id) => {
587
+ const place = Composition.index(document).get(id);
588
+ const node = document.nodes[id];
589
+ if (place === void 0 || node === void 0 || place.index === 0) return Option.none();
590
+ const above = (place.parent === void 0 ? document.roots : document.nodes[place.parent]?.regions[place.region ?? ""] ?? [])[place.index - 1];
591
+ const target = above === void 0 ? void 0 : document.nodes[above];
592
+ if (above === void 0 || target === void 0) return Option.none();
593
+ return Option.map(regionTaking(catalog, target.block, node.block), (regionName) => Composition.Op.move(id, Composition.region(above, regionName, (target.regions[regionName] ?? []).length)));
594
+ };
595
+ /** The node a pattern's use makes its root; none for a pattern the Catalog lacks. */
596
+ const patternRoot = (catalog, op) => Option.flatMap(Catalog.pattern(catalog, op.pattern), (pattern) => Option.fromUndefinedOr(op.ids[pattern.tree.root]));
597
+ /** A Block's label, the Catalog's word; one the Catalog lacks by its stored name. */
598
+ const blockLabel = (catalog, block) => Catalog.block(catalog, block)?.words.label ?? block;
599
+ /** What an applied edit says to assistive technology; none for a prop change. */
600
+ const describeEdit = (catalog, words, before, after, op) => {
601
+ const labelOf = (document, id) => Option.match(Option.fromUndefinedOr(document.nodes[id]), {
602
+ onNone: () => id,
603
+ onSome: (node) => blockLabel(catalog, node.block)
604
+ });
605
+ const where = (id) => {
606
+ const place = Composition.index(after).get(id);
607
+ if (place === void 0) return "";
608
+ const siblings = place.parent === void 0 ? after.roots.length : after.nodes[place.parent]?.regions[place.region ?? ""]?.length ?? 0;
609
+ const container = place.parent === void 0 ? words.thePage : fillWords(words.inRegion, {
610
+ label: labelOf(after, place.parent),
611
+ region: place.region ?? ""
612
+ });
613
+ return fillWords(words.at, {
614
+ position: place.index + 1,
615
+ count: siblings,
616
+ container
617
+ });
618
+ };
619
+ const said = (template, id) => fillWords(template, {
620
+ label: labelOf(after, id),
621
+ at: where(id)
622
+ });
623
+ switch (op._tag) {
624
+ case "Move": return Option.some(said(words.moved, op.id));
625
+ case "Insert": return Option.some(said(words.added, op.id));
626
+ case "InsertTree": return Option.some(said(words.added, op.tree.root));
627
+ case "Duplicate": return Option.map(Option.fromUndefinedOr(op.ids[op.id]), (copy) => said(words.duplicated, copy));
628
+ case "UsePattern": return Option.map(patternRoot(catalog, op), (root) => said(words.added, root));
629
+ case "Remove": return Option.some(fillWords(words.removed, { label: labelOf(before, op.id) }));
630
+ case "Batch": return op.ops.length === 0 ? Option.none() : Option.some(words.editedPage);
631
+ case "SetProp":
632
+ case "UnsetProp":
633
+ case "SetWhen":
634
+ case "SetAppearance":
635
+ case "SetAction": return Option.none();
636
+ }
637
+ };
638
+ /** The selection, kept only while the Document still holds it. */
639
+ const keptIn = (document, selected) => Option.filter(selected, (id) => document.nodes[id] !== void 0);
640
+ /** The Model showing another Document: what a fill, a reset or a restored revision does. */
641
+ const replace = (model, document) => ({
642
+ ...model,
643
+ page: History.start(document),
644
+ selected: keptIn(document, model.selected),
645
+ hovered: Option.none(),
646
+ refused: Option.none(),
647
+ drag: Option.none(),
648
+ inspector: Option.none(),
649
+ editing: Option.none()
650
+ });
651
+ /** The Model with nothing in flight, as a stored draft is shown again: no hover, no drag, no undo, no refusal. */
652
+ const settle = (model) => ({
653
+ ...model,
654
+ hovered: Option.none(),
655
+ refused: Option.none(),
656
+ drag: Option.none(),
657
+ editing: Option.none(),
658
+ page: History.clear(model.page)
659
+ });
660
+ /** The undo group of one editing session: its steps are one, and ending it cancelled takes them back. */
661
+ const editingGroup = (editing) => `Editing:${fieldName(editing.id, editing.key)}`;
662
+ /**
663
+ * Where something dragged over `target`, in `zone`, lands: by `target`, else
664
+ * by the nearest node holding it where it fits, before it for `before` and
665
+ * after it otherwise, so a Section dropped on the last Heading of a Section
666
+ * lands after that Section. It climbs no further than a node being dragged.
667
+ * With the node it landed by.
668
+ */
669
+ const landing = (catalog, document, dragged, target, zone, region = Option.none()) => {
670
+ const places = Composition.index(document);
671
+ for (let by = target, at = zone, into = region; by !== void 0 && !Option.contains(dragged.id, by); by = places.get(by)?.parent, at = zone === "before" ? "before" : "after", into = Option.none()) {
672
+ const landed = landingBy(catalog, document, dragged, by, at, into);
673
+ if (landed === "stays") return Option.none();
674
+ if (Option.isSome(landed)) return Option.some({
675
+ ...landed.value,
676
+ by,
677
+ region: landed.value.zone === "inside" ? into : Option.none()
678
+ });
679
+ }
680
+ return Option.none();
681
+ };
682
+ /** The node an Operation that creates nodes creates first, to select it. */
683
+ const created = (catalog, op) => op._tag === "Insert" ? Option.some(op.id) : op._tag === "InsertTree" ? Option.some(op.tree.root) : op._tag === "Duplicate" ? Option.fromUndefinedOr(op.ids[op.id]) : op._tag === "UsePattern" ? patternRoot(catalog, op) : Option.none();
684
+ /** Whether a key press is `spec`. A letter is matched as either case. */
685
+ const pressed = (spec, key, modifiers) => spec.key.toLowerCase() === key.toLowerCase() && (spec.mod ?? false) === (modifiers.ctrlKey || modifiers.metaKey) && (spec.alt ?? false) === modifiers.altKey && (spec.shift === void 0 || spec.shift === modifiers.shiftKey);
686
+ const Builder = {
687
+ /**
688
+ * Block metadata: the control the inspector draws a prop with, where its
689
+ * Schema alone does not say, as
690
+ * `Heading.pipe(Block.annotate(Builder.controls({ text: Input.multiline() })))`.
691
+ * `Input.hidden()` leaves a prop out of the inspector.
692
+ */
693
+ controls,
694
+ /**
695
+ * A Builder for a Catalog: its Bundle, the form control that places it as a
696
+ * key, and the helpers a view uses. `starters` gives the props a new node of
697
+ * each Block starts with; the insert panel offers exactly those Blocks.
698
+ */
699
+ make: (name, config) => {
700
+ const { catalog, renderer } = config;
701
+ const words = {
702
+ ...editWords,
703
+ ...config.words
704
+ };
705
+ const starters = config.starters;
706
+ for (const block of catalog.blocks) settingsOf(block);
707
+ const capacity = config.capacity ?? 200;
708
+ const initial = placements.initial({
709
+ page: History.start(Composition.empty()),
710
+ selected: Option.none(),
711
+ hovered: Option.none(),
712
+ panel: "insert",
713
+ viewport: "wide",
714
+ refused: Option.none(),
715
+ drag: Option.none(),
716
+ preview: { ...config.preview },
717
+ inspector: Option.none(),
718
+ clipboard: Option.none(),
719
+ editing: Option.none()
720
+ }).model;
721
+ /** Says `text` to assistive technology, once the Builder's transition is done. */
722
+ const announce = (text, politeness = "polite") => [{
723
+ name: `${name}.announce`,
724
+ effect: Effect.succeed(LiveAnnounce.say(Announcer)(text, politeness))
725
+ }];
726
+ const refuse = (model, refusal) => ({
727
+ model: {
728
+ ...model,
729
+ refused: Option.some(refusal)
730
+ },
731
+ commands: announce(refusal.message, "assertive")
732
+ });
733
+ const applyOp = (model, op, group = groupOf(op)) => {
734
+ const result = Composition.apply(catalog, documentOf(model), op);
735
+ if (Result.isFailure(result)) return refuse(model, {
736
+ ...result.failure,
737
+ message: fillWords(words.refusal, {
738
+ code: result.failure.code,
739
+ message: result.failure.message
740
+ })
741
+ });
742
+ const { document, removed } = result.success;
743
+ const kept = Option.filter(model.selected, (id) => !removed.includes(id));
744
+ return {
745
+ model: {
746
+ ...model,
747
+ page: History.push(model.page, document, {
748
+ capacity,
749
+ group
750
+ }),
751
+ selected: Option.orElse(created(catalog, op), () => kept),
752
+ refused: Option.none()
753
+ },
754
+ ...Option.match(describeEdit(catalog, words, documentOf(model), document, op), {
755
+ onNone: () => ({}),
756
+ onSome: (said) => ({ commands: announce(said) })
757
+ })
758
+ };
759
+ };
760
+ /** A Block's starting props, encoded as the Document stores them; none for a Block with none. */
761
+ const startingProps = (name) => {
762
+ const block = Catalog.block(catalog, name);
763
+ if (block === void 0) return Option.none();
764
+ return Result.getSuccess(Result.flatMap(Block.encode(block, starters[name]), storedProps));
765
+ };
766
+ /**
767
+ * Where a palette tile dropped on the page's own space goes: last where the
768
+ * page takes its Block, as a press with nothing selected puts it. None for
769
+ * a node on the page, which is moved only onto another.
770
+ */
771
+ const onPage = (document, source) => source._tag === "New" ? placeFor(catalog, document, Option.none(), source.block) : Option.none();
772
+ /** What a drag carries, as `landing` weighs it; none for a node gone or a Block not offered. */
773
+ const draggedOf = (document, source) => {
774
+ if (source._tag === "Existing") {
775
+ const node = document.nodes[source.id];
776
+ return node === void 0 ? Option.none() : Option.some({
777
+ block: node.block,
778
+ id: Option.some(source.id),
779
+ to: (at) => Composition.Op.move(source.id, at)
780
+ });
781
+ }
782
+ let unused = "dragged";
783
+ while (document.nodes[NodeId.make(unused)] !== void 0) unused = `${unused}-`;
784
+ const trial = NodeId.make(unused);
785
+ return Option.map(startingProps(source.block), (props) => ({
786
+ block: source.block,
787
+ id: Option.none(),
788
+ to: (at) => Composition.Op.insert({
789
+ id: trial,
790
+ block: source.block,
791
+ props,
792
+ at
793
+ })
794
+ }));
795
+ };
796
+ /**
797
+ * The drag, over `id` in `zone` (or its empty `region`), marked where it
798
+ * lands: a drop inside a node that takes nothing is after it, and one its
799
+ * holder takes instead is marked on the holder.
800
+ */
801
+ const draggedOver = (model, id, zone, region) => {
802
+ if (Option.isNone(model.drag)) return { model };
803
+ const drag = model.drag.value;
804
+ const landed = Option.flatMap(draggedOf(documentOf(model), drag.source), (dragged) => landing(catalog, documentOf(model), dragged, id, zone, region));
805
+ return { model: {
806
+ ...model,
807
+ drag: Option.some({
808
+ ...drag,
809
+ over: Option.some(Option.match(landed, {
810
+ onNone: () => ({
811
+ id,
812
+ zone,
813
+ region
814
+ }),
815
+ onSome: ({ by, zone, region }) => ({
816
+ id: by,
817
+ zone,
818
+ region
819
+ })
820
+ })),
821
+ at: Option.map(landed, ({ at }) => at)
822
+ })
823
+ } };
824
+ };
825
+ /** Puts a node's tree on the system clipboard, then says `said`, whether it could or not. */
826
+ const copy = (tree, said) => [{
827
+ name: `${name}.copy`,
828
+ effect: Effect.as(copyText(clipText(tree)).effect, LiveAnnounce.say(Announcer)(said, "polite"))
829
+ }];
830
+ /** The edit under way of the field a canvas Message names; none for any other. */
831
+ const editingOf = (model, field) => Option.flatMap(fieldOf(field), (named) => Option.filter(model.editing, (editing) => editing.id === named.id && editing.key === named.key));
832
+ /** What is said when a drag ends with nothing done. */
833
+ const unmoved = (source) => source._tag === "Existing" ? words.notMoved : words.notAdded;
834
+ /** Asks for `count` new ids; the request goes through once they arrive. */
835
+ const mint = (count, request) => [{
836
+ name: `${name}.mint`,
837
+ effect: Effect.map(Composition.newIds(count), (ids) => Message.Minted({
838
+ ids,
839
+ request
840
+ }))
841
+ }];
842
+ /** A stored value that is a record of JSON, as props and an action's input are; else empty. */
843
+ const recordOf = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
844
+ /**
845
+ * A node's forms, each with the stored values it fills from and the
846
+ * Operations that write its changed values back and take away those
847
+ * cleared.
848
+ */
849
+ const formsOf = (id, node, block) => {
850
+ const props = {
851
+ key: "props",
852
+ settings: settingsOf(block),
853
+ stored: recordOf(node.props),
854
+ write: (changed, cleared) => [...Object.entries(changed).map(([key, value]) => Composition.Op.setProp(id, key, value)), ...cleared.map((key) => Composition.Op.unsetProp(id, key))]
855
+ };
856
+ const refs = recordOf(node.actions);
857
+ return {
858
+ props,
859
+ on: block.events.flatMap((event) => {
860
+ const ref = recordOf(refs[event]);
861
+ const action = catalog.actions.find((each) => each.name === ref["action"]);
862
+ if (action === void 0) return [];
863
+ const input = recordOf(ref["input"]);
864
+ const settings = inputOf(block, event, action);
865
+ return [{
866
+ event,
867
+ key: `on:${event}:${action.name}`,
868
+ settings,
869
+ stored: input,
870
+ write: (changed, cleared) => [Composition.Op.setAction(id, event, {
871
+ action: action.name,
872
+ input: Object.fromEntries(Object.entries({
873
+ ...input,
874
+ ...changed
875
+ }).filter(([key]) => settings.keys.includes(key) && !cleared.includes(key)))
876
+ })]
877
+ }];
878
+ })
879
+ };
880
+ };
881
+ /**
882
+ * The selected node's forms and their Models: the Model the inspector
883
+ * holds for each, else one filled from the node. None when nothing is
884
+ * selected or its Block is not in the Catalog.
885
+ */
886
+ const inspecting = (model) => Option.flatMap(model.selected, (id) => {
887
+ const node = documentOf(model).nodes[id];
888
+ const block = node === void 0 ? void 0 : Catalog.block(catalog, node.block);
889
+ if (node === void 0 || block === void 0) return Option.none();
890
+ const held = Option.match(Option.filter(model.inspector, (inspector) => inspector.id === id), {
891
+ onNone: () => ({}),
892
+ onSome: (inspector) => inspector.forms
893
+ });
894
+ const drawn = (form) => ({
895
+ key: form.key,
896
+ settings: form.settings,
897
+ model: Option.getOrElse(Option.flatMap(Option.fromUndefinedOr(held[form.key]), form.settings.decode), () => form.settings.fill(form.settings.form.initial, form.stored))
898
+ });
899
+ const { props, on } = formsOf(id, node, block);
900
+ return Option.some({
901
+ id,
902
+ block,
903
+ props: drawn(props),
904
+ on: Object.fromEntries(on.map((form) => [form.event, drawn(form)]))
905
+ });
906
+ });
907
+ /** A form's Model refilled from what the node stores, but for a field that does not decode. */
908
+ const refill = (settings, model, stored) => settings.fill(model, stored, (key) => settings.form.field(model, key)._tag === "Invalid");
909
+ /**
910
+ * A Message of one of the selected node's forms: the form takes it, and
911
+ * each value it changed, and that the node does not already hold, is
912
+ * written back: a prop by one `setProp` each, an action's input by one
913
+ * `setAction`; a value cleared that the node held is taken away. A field
914
+ * that does not decode writes nothing and shows its error; a value the
915
+ * node refuses is said, and the form shows what the node holds again.
916
+ */
917
+ const inspect = (model, message) => {
918
+ const target = Option.filter(inspecting(model), (each) => each.id === message.id);
919
+ const node = documentOf(model).nodes[message.id];
920
+ if (Option.isNone(target) || node === void 0) return { model };
921
+ const { id, block, props, on } = target.value;
922
+ const forms = formsOf(id, node, block);
923
+ const known = [{
924
+ ...forms.props,
925
+ model: props.model
926
+ }, ...forms.on.flatMap((form) => {
927
+ const drawn = on[form.event];
928
+ return drawn === void 0 ? [] : [{
929
+ ...form,
930
+ model: drawn.model
931
+ }];
932
+ })].find((form) => form.key === message.form);
933
+ if (known === void 0) return { model };
934
+ const { settings, stored, write } = known;
935
+ return Option.match(settings.decodeMessage(message.message), {
936
+ onNone: () => ({ model }),
937
+ onSome: (formMessage) => {
938
+ const next = settings.form.bundle.update(known.model, formMessage, void 0);
939
+ const text = (value) => JSON.stringify(value);
940
+ const before = settings.form.partial(known.model);
941
+ const after = settings.form.partial(next.model);
942
+ const changed = Object.fromEntries(Object.entries(after).flatMap(([key, value]) => Object.hasOwn(before, key) && text(before[key]) === text(value) ? [] : Option.match(settings.stored(key, value), {
943
+ onNone: () => [],
944
+ onSome: (json) => text(json) === text(stored[key]) ? [] : [[key, json]]
945
+ })));
946
+ const cleared = Object.keys(before).filter((key) => !Object.hasOwn(after, key) && settings.form.field(next.model, key)._tag !== "Invalid");
947
+ const held = Option.match(model.inspector, {
948
+ onNone: () => ({}),
949
+ onSome: (inspector) => inspector.id === id ? inspector.forms : {}
950
+ });
951
+ let result = { model: {
952
+ ...model,
953
+ inspector: Option.some({
954
+ id,
955
+ forms: {
956
+ ...held,
957
+ [known.key]: settings.encode(next.model)
958
+ }
959
+ })
960
+ } };
961
+ const commands = [...Command.mapMessages(next.commands, (sent) => Message.Inspected({
962
+ id,
963
+ form: known.key,
964
+ message: settings.encodeMessage(sent)
965
+ }))];
966
+ let refused = false;
967
+ if (Object.keys(changed).length > 0 || cleared.length > 0) for (const op of write(changed, cleared)) {
968
+ result = applyOp(result.model, op);
969
+ refused ||= Option.isSome(result.model.refused);
970
+ commands.push(...result.commands ?? []);
971
+ }
972
+ if (!refused) return {
973
+ model: result.model,
974
+ commands
975
+ };
976
+ const now = formsOf(id, documentOf(result.model).nodes[id] ?? node, block);
977
+ const holds = [now.props, ...now.on].find((form) => form.key === known.key);
978
+ return {
979
+ model: {
980
+ ...result.model,
981
+ inspector: Option.some({
982
+ id,
983
+ forms: {
984
+ ...held,
985
+ [known.key]: settings.encode(refill(settings, next.model, holds?.stored ?? stored))
986
+ }
987
+ })
988
+ },
989
+ commands
990
+ };
991
+ }
992
+ });
993
+ };
994
+ /**
995
+ * The inspector after a transition not its own: dropped when the selection
996
+ * moved; when the page changed by another way (an undo, the canvas, an
997
+ * agent), each form it holds is refilled from the node, except a field the
998
+ * author is typing into that does not decode, and a form the node no
999
+ * longer draws is let go.
1000
+ */
1001
+ const reconciled = (before, after) => {
1002
+ if (Option.isNone(after.inspector)) return after;
1003
+ const { id, forms: held } = after.inspector.value;
1004
+ if (!Option.contains(after.selected, id)) return {
1005
+ ...after,
1006
+ inspector: Option.none()
1007
+ };
1008
+ if (documentOf(after) === documentOf(before)) return after;
1009
+ const node = documentOf(after).nodes[id];
1010
+ const block = node === void 0 ? void 0 : Catalog.block(catalog, node.block);
1011
+ if (node === void 0 || block === void 0) return {
1012
+ ...after,
1013
+ inspector: Option.none()
1014
+ };
1015
+ const { props, on } = formsOf(id, node, block);
1016
+ const refilled = [props, ...on].flatMap((form) => Option.match(Option.flatMap(Option.fromUndefinedOr(held[form.key]), form.settings.decode), {
1017
+ onNone: () => [],
1018
+ onSome: (model) => [[form.key, form.settings.encode(refill(form.settings, model, form.stored))]]
1019
+ }));
1020
+ return {
1021
+ ...after,
1022
+ inspector: refilled.length === 0 ? Option.none() : Option.some({
1023
+ id,
1024
+ forms: Object.fromEntries(refilled)
1025
+ })
1026
+ };
1027
+ };
1028
+ const own = (model, message) => {
1029
+ switch (message._tag) {
1030
+ case "Selected": return documentOf(model).nodes[message.id] === void 0 ? { model: {
1031
+ ...model,
1032
+ selected: Option.none()
1033
+ } } : { model: {
1034
+ ...model,
1035
+ selected: Option.some(message.id),
1036
+ panel: "properties"
1037
+ } };
1038
+ case "Deselected": return { model: {
1039
+ ...model,
1040
+ selected: Option.none()
1041
+ } };
1042
+ case "Hovered": return { model: {
1043
+ ...model,
1044
+ hovered: Option.some(message.id)
1045
+ } };
1046
+ case "Unhovered": return { model: {
1047
+ ...model,
1048
+ hovered: Option.none()
1049
+ } };
1050
+ case "Applied": return applyOp(model, message.op);
1051
+ case "InsertAsked": return !Object.hasOwn(starters, message.block) ? refuse(model, {
1052
+ code: "composition:unknown-block",
1053
+ message: fillWords(words.noStartingProps, { block: message.block })
1054
+ }) : {
1055
+ model,
1056
+ commands: mint(1, {
1057
+ _tag: "Insert",
1058
+ block: message.block,
1059
+ at: message.at
1060
+ })
1061
+ };
1062
+ case "DuplicateAsked": {
1063
+ if (documentOf(model).nodes[message.id] === void 0) return refuse(model, {
1064
+ code: "composition:missing-node",
1065
+ message: fillWords(words.notANode, { id: message.id })
1066
+ });
1067
+ const count = Object.keys(Composition.takeTree(documentOf(model), message.id).nodes).length;
1068
+ return {
1069
+ model,
1070
+ commands: mint(count, {
1071
+ _tag: "Duplicate",
1072
+ id: message.id,
1073
+ at: message.at
1074
+ })
1075
+ };
1076
+ }
1077
+ case "CopyAsked":
1078
+ case "CutAsked": {
1079
+ const node = documentOf(model).nodes[message.id];
1080
+ if (node === void 0) return refuse(model, {
1081
+ code: "composition:missing-node",
1082
+ message: fillWords(words.notANode, { id: message.id })
1083
+ });
1084
+ const tree = Composition.takeTree(documentOf(model), message.id);
1085
+ const copied = {
1086
+ ...model,
1087
+ clipboard: Option.some(tree)
1088
+ };
1089
+ if (message._tag === "CopyAsked") return {
1090
+ model: copied,
1091
+ commands: copy(tree, fillWords(words.copied, { label: blockLabel(catalog, node.block) }))
1092
+ };
1093
+ const cut = applyOp(copied, Composition.Op.remove(message.id));
1094
+ return cut.model.page === model.page ? {
1095
+ ...cut,
1096
+ model: {
1097
+ ...cut.model,
1098
+ clipboard: model.clipboard
1099
+ }
1100
+ } : {
1101
+ model: cut.model,
1102
+ commands: copy(tree, fillWords(words.cut, { label: blockLabel(catalog, node.block) }))
1103
+ };
1104
+ }
1105
+ case "PasteAsked": return {
1106
+ model,
1107
+ commands: [{
1108
+ name: `${name}.paste`,
1109
+ effect: Effect.map(readText().effect, (read) => Message.ClipboardRead({ text: read._tag === "Read" ? Option.some(read.text) : Option.none() }))
1110
+ }]
1111
+ };
1112
+ case "ClipboardRead": {
1113
+ const tree = Option.match(message.text, {
1114
+ onNone: () => model.clipboard,
1115
+ onSome: (text) => Option.map(Result.getSuccess(clipOf(text)), ({ tree }) => tree)
1116
+ });
1117
+ if (Option.isNone(tree)) return refuse(model, {
1118
+ code: "builder:nothing-to-paste",
1119
+ message: Option.isSome(message.text) ? words.notAPage : words.nothingCopied
1120
+ });
1121
+ const wrong = Composition.treeRefusal(catalog, tree.value);
1122
+ if (Option.isSome(wrong)) return refuse(model, {
1123
+ ...wrong.value,
1124
+ message: fillWords(words.refusal, {
1125
+ code: wrong.value.code,
1126
+ message: wrong.value.message
1127
+ })
1128
+ });
1129
+ const block = tree.value.nodes[tree.value.root]?.block ?? "";
1130
+ const place = placeFor(catalog, documentOf(model), model.selected, block);
1131
+ if (Option.isNone(place)) return refuse(model, {
1132
+ code: "builder:no-place",
1133
+ message: fillWords(words.noPlace, { label: blockLabel(catalog, block) })
1134
+ });
1135
+ const at = place.value;
1136
+ return {
1137
+ model,
1138
+ commands: mint(Object.keys(tree.value.nodes).length, {
1139
+ _tag: "Paste",
1140
+ tree: tree.value,
1141
+ at
1142
+ })
1143
+ };
1144
+ }
1145
+ case "PatternAsked": return Option.match(Catalog.pattern(catalog, message.pattern), {
1146
+ onNone: () => refuse(model, {
1147
+ code: "composition:unknown-pattern",
1148
+ message: fillWords(words.unknownPattern, { name: message.pattern })
1149
+ }),
1150
+ onSome: (pattern) => ({
1151
+ model,
1152
+ commands: mint(Object.keys(pattern.tree.nodes).length, {
1153
+ _tag: "Pattern",
1154
+ pattern: message.pattern,
1155
+ at: message.at
1156
+ })
1157
+ })
1158
+ });
1159
+ case "EditingAsked":
1160
+ if (Option.isSome(editingOf(model, message.field))) return { model };
1161
+ return Option.match(fieldOf(message.field), {
1162
+ onNone: () => ({ model }),
1163
+ onSome: ({ id, key }) => {
1164
+ const stored = documentOf(model).nodes[id]?.props[key];
1165
+ if (typeof stored !== "string" || !Renderer.fields(renderer, documentOf(model), id).includes(key)) return { model };
1166
+ return { model: {
1167
+ ...model,
1168
+ editing: Option.some({
1169
+ id,
1170
+ key,
1171
+ initial: stored,
1172
+ typed: false
1173
+ }),
1174
+ selected: Option.some(id),
1175
+ page: History.close(model.page)
1176
+ } };
1177
+ }
1178
+ });
1179
+ case "FieldTyped": return Option.match(editingOf(model, message.field), {
1180
+ onNone: () => ({ model }),
1181
+ onSome: (editing) => applyOp({
1182
+ ...model,
1183
+ editing: Option.some({
1184
+ ...editing,
1185
+ typed: true
1186
+ })
1187
+ }, Composition.Op.setProp(editing.id, editing.key, message.text), editingGroup(editing))
1188
+ });
1189
+ case "EditingCommitted":
1190
+ case "EditingCancelled": return Option.match(editingOf(model, message.field), {
1191
+ onNone: () => ({ model }),
1192
+ onSome: (editing) => {
1193
+ const kept = message._tag === "EditingCommitted" ? message.text : editing.initial;
1194
+ if (!editing.typed && kept === editing.initial) return { model: {
1195
+ ...model,
1196
+ editing: Option.none()
1197
+ } };
1198
+ const group = editingGroup(editing);
1199
+ const page = kept === editing.initial ? History.revert(model.page, group) : model.page;
1200
+ const ended = {
1201
+ ...model,
1202
+ page,
1203
+ editing: Option.none()
1204
+ };
1205
+ return documentOf(ended).nodes[editing.id]?.props[editing.key] === kept ? { model: ended } : applyOp(ended, Composition.Op.setProp(editing.id, editing.key, kept), group);
1206
+ }
1207
+ });
1208
+ case "Minted": {
1209
+ const { request, ids } = message;
1210
+ switch (request._tag) {
1211
+ case "Insert": {
1212
+ const props = startingProps(request.block);
1213
+ if (ids[0] === void 0 || Option.isNone(props)) return refuse(model, {
1214
+ code: "composition:invalid-props",
1215
+ message: fillWords(words.startingPropsFail, { block: request.block })
1216
+ });
1217
+ return applyOp(model, Composition.Op.insert({
1218
+ id: ids[0],
1219
+ block: request.block,
1220
+ props: props.value,
1221
+ at: request.at
1222
+ }));
1223
+ }
1224
+ case "Pattern": {
1225
+ const held = Option.match(Catalog.pattern(catalog, request.pattern), {
1226
+ onNone: () => [],
1227
+ onSome: (pattern) => Object.keys(pattern.tree.nodes)
1228
+ });
1229
+ return applyOp(model, Composition.Op.usePattern({
1230
+ pattern: request.pattern,
1231
+ ids: Object.fromEntries(held.map((id, at) => [id, ids[at]])),
1232
+ at: request.at
1233
+ }));
1234
+ }
1235
+ case "Paste": {
1236
+ const renamed = Composition.rekey(request.tree, Object.fromEntries(Object.keys(request.tree.nodes).map((id, at) => [id, ids[at]])));
1237
+ return applyOp(model, Composition.Op.insertTree({
1238
+ tree: renamed,
1239
+ at: request.at
1240
+ }));
1241
+ }
1242
+ case "Duplicate": {
1243
+ if (documentOf(model).nodes[request.id] === void 0) return refuse(model, {
1244
+ code: "composition:missing-node",
1245
+ message: fillWords(words.notANode, { id: request.id })
1246
+ });
1247
+ const held = Object.keys(Composition.takeTree(documentOf(model), request.id).nodes);
1248
+ if (held.length !== ids.length) return refuse(model, {
1249
+ code: "composition:malformed-tree",
1250
+ message: fillWords(words.copyChanged, { id: request.id })
1251
+ });
1252
+ return applyOp(model, Composition.Op.duplicate({
1253
+ id: request.id,
1254
+ ids: Object.fromEntries(held.map((id, at) => [id, ids[at]])),
1255
+ at: request.at
1256
+ }));
1257
+ }
1258
+ }
1259
+ }
1260
+ case "Undid":
1261
+ case "Redid": {
1262
+ const page = (message._tag === "Undid" ? History.undo : History.redo)(model.page);
1263
+ if (page === model.page) return { model };
1264
+ return {
1265
+ model: {
1266
+ ...model,
1267
+ page,
1268
+ selected: keptIn(page.present, model.selected),
1269
+ refused: Option.none(),
1270
+ editing: Option.none()
1271
+ },
1272
+ commands: announce(message._tag === "Undid" ? words.undone : words.redone)
1273
+ };
1274
+ }
1275
+ case "DragStarted": return Option.isNone(draggedOf(documentOf(model), message.source)) ? { model } : { model: {
1276
+ ...model,
1277
+ drag: Option.some({
1278
+ source: message.source,
1279
+ over: Option.none(),
1280
+ at: Option.none()
1281
+ }),
1282
+ selected: message.source._tag === "Existing" ? Option.some(message.source.id) : model.selected
1283
+ } };
1284
+ case "DraggedOver": return draggedOver(model, message.id, message.zone, Option.none());
1285
+ case "DraggedOverRegion": return draggedOver(model, message.id, "inside", Option.some(message.region));
1286
+ case "DraggedOverPage": {
1287
+ if (Option.isNone(model.drag)) return { model };
1288
+ const drag = model.drag.value;
1289
+ return { model: {
1290
+ ...model,
1291
+ drag: Option.some({
1292
+ ...drag,
1293
+ over: Option.none(),
1294
+ at: onPage(documentOf(model), drag.source)
1295
+ })
1296
+ } };
1297
+ }
1298
+ case "DraggedOff": return Option.isNone(model.drag) ? { model } : { model: {
1299
+ ...model,
1300
+ drag: Option.some({
1301
+ ...model.drag.value,
1302
+ over: Option.none(),
1303
+ at: Option.none()
1304
+ })
1305
+ } };
1306
+ case "DragDropped": {
1307
+ if (Option.isNone(model.drag)) return { model };
1308
+ const { source, over, at } = model.drag.value;
1309
+ const ended = {
1310
+ ...model,
1311
+ drag: Option.none()
1312
+ };
1313
+ const landed = Option.match(over, {
1314
+ onNone: () => Option.isSome(at) ? Option.map(onPage(documentOf(model), source), (place) => ({ at: place })) : Option.none(),
1315
+ onSome: (target) => Option.flatMap(draggedOf(documentOf(model), source), (dragged) => landing(catalog, documentOf(model), dragged, target.id, target.zone, target.region))
1316
+ });
1317
+ return Option.match(landed, {
1318
+ onNone: () => ({
1319
+ model: ended,
1320
+ commands: announce(unmoved(source))
1321
+ }),
1322
+ onSome: ({ at }) => source._tag === "Existing" ? applyOp(ended, Composition.Op.move(source.id, at)) : {
1323
+ model: ended,
1324
+ commands: mint(1, {
1325
+ _tag: "Insert",
1326
+ block: source.block,
1327
+ at
1328
+ })
1329
+ }
1330
+ });
1331
+ }
1332
+ case "DragCancelled": return Option.isNone(model.drag) ? { model } : {
1333
+ model: {
1334
+ ...model,
1335
+ drag: Option.none()
1336
+ },
1337
+ commands: announce(unmoved(model.drag.value.source))
1338
+ };
1339
+ case "PreviewChosen": return { model: {
1340
+ ...model,
1341
+ preview: {
1342
+ ...model.preview,
1343
+ [message.key]: message.value
1344
+ }
1345
+ } };
1346
+ case "PreviewCleared": {
1347
+ const { [message.key]: _, ...others } = model.preview;
1348
+ return { model: {
1349
+ ...model,
1350
+ preview: others
1351
+ } };
1352
+ }
1353
+ case "Inspected": return inspect(model, message);
1354
+ case "PanelChosen": return { model: {
1355
+ ...model,
1356
+ panel: message.panel
1357
+ } };
1358
+ case "ViewportChosen": return { model: {
1359
+ ...model,
1360
+ viewport: message.viewport
1361
+ } };
1362
+ case "GotLayersMessage":
1363
+ case "GotAnnouncerMessage": return { model };
1364
+ }
1365
+ };
1366
+ const assembled = placements.update(own);
1367
+ /**
1368
+ * Editing in place kept only while its node is the one selected: another
1369
+ * selected, or the node removed (which deselects it), ends it.
1370
+ */
1371
+ const stillEditing = (model) => Option.isSome(model.editing) && !Option.contains(model.selected, model.editing.value.id) ? {
1372
+ ...model,
1373
+ editing: Option.none()
1374
+ } : model;
1375
+ /**
1376
+ * The layers' keys, once the node they were on is removed and nothing is
1377
+ * selected, start from where it was: its next sibling left, else the one
1378
+ * before, else the nearest holder left; not the first row.
1379
+ */
1380
+ const keptCurrent = (before, next) => {
1381
+ const { current } = next.model.layers;
1382
+ const after = documentOf(next.model);
1383
+ if (current === null || Composition.index(after).has(NodeId.make(current))) return next;
1384
+ const was = documentOf(before);
1385
+ const place = Composition.index(was).get(NodeId.make(current));
1386
+ if (place === void 0) return next;
1387
+ const left = (id) => Composition.index(after).has(id);
1388
+ const siblings = place.parent === void 0 ? was.roots : was.nodes[place.parent]?.regions[place.region ?? ""] ?? [];
1389
+ const beside = [...siblings.slice(place.index + 1), ...siblings.slice(0, place.index).reverse()].find(left);
1390
+ let holder = place.parent;
1391
+ while (holder !== void 0 && !left(holder)) holder = Composition.index(was).get(holder)?.parent;
1392
+ const kept = beside ?? holder ?? null;
1393
+ return {
1394
+ ...next,
1395
+ model: {
1396
+ ...next.model,
1397
+ layers: {
1398
+ ...next.model.layers,
1399
+ current: kept
1400
+ }
1401
+ }
1402
+ };
1403
+ };
1404
+ const update = (model, message) => {
1405
+ const moved = assembled(model, message);
1406
+ const next = {
1407
+ ...moved,
1408
+ model: stillEditing(message._tag === "Inspected" ? moved.model : reconciled(model, moved.model))
1409
+ };
1410
+ if (message._tag === Layers.wrapper.tag && message.message._tag === "Focused") {
1411
+ const id = NodeId.make(message.message.id);
1412
+ return documentOf(next.model).nodes[id] === void 0 ? next : {
1413
+ ...next,
1414
+ model: {
1415
+ ...next.model,
1416
+ selected: Option.some(id)
1417
+ }
1418
+ };
1419
+ }
1420
+ if (Option.isNone(next.model.selected)) return keptCurrent(model, next);
1421
+ const selected = next.model.selected.value;
1422
+ if (selected === next.model.layers.current) return next;
1423
+ const places = Composition.index(documentOf(next.model));
1424
+ const above = /* @__PURE__ */ new Set();
1425
+ for (let at = places.get(selected)?.parent; at !== void 0; at = places.get(at)?.parent) above.add(at);
1426
+ const { layers } = next.model;
1427
+ return {
1428
+ ...next,
1429
+ model: {
1430
+ ...next.model,
1431
+ layers: {
1432
+ ...layers,
1433
+ current: selected,
1434
+ toggled: layersArgs.openByDefault ? layers.toggled.filter((id) => !above.has(id)) : [.../* @__PURE__ */ new Set([...layers.toggled, ...above])]
1435
+ }
1436
+ }
1437
+ };
1438
+ };
1439
+ const view = Submodel.defineView((model, h) => drawBuilder(model, h));
1440
+ /** The crude editor: a palette, the layers, the selected node's text props, and the page. */
1441
+ const drawBuilder = (model, h) => {
1442
+ const button = (label, message) => h.button([
1443
+ h.Type("button"),
1444
+ h.Disabled(Option.isNone(message)),
1445
+ ...Option.match(message, {
1446
+ onNone: () => [],
1447
+ onSome: (sent) => [h.OnClick(sent)]
1448
+ })
1449
+ ], [label]);
1450
+ const palette = h.nav([h.Class("builder-palette"), h.AriaLabel("Insert")], catalog.blocks.filter((block) => Object.hasOwn(starters, block.name)).map((block) => {
1451
+ return button(`Add ${block.name}`, Option.map(placeFor(catalog, documentOf(model), model.selected, block.name), (at) => Message.InsertAsked({
1452
+ block: block.name,
1453
+ at
1454
+ })));
1455
+ }));
1456
+ const layer = (id) => {
1457
+ const node = documentOf(model).nodes[id];
1458
+ if (node === void 0) return null;
1459
+ const known = Catalog.block(catalog, node.block) !== void 0;
1460
+ const children = Object.values(node.regions).flat();
1461
+ return h.li([...Option.contains(model.selected, id) ? [h.AriaCurrent("true")] : []], [button(`${known ? "" : "? "}${node.block}`, Option.some(Message.Selected({ id }))), ...children.length === 0 ? [] : [h.ul([], children.map(layer))]]);
1462
+ };
1463
+ const layers = h.ul([h.Class("builder-layers"), h.AriaLabel("Layers")], documentOf(model).roots.map(layer));
1464
+ const actions = Option.match(model.selected, {
1465
+ onNone: () => [],
1466
+ onSome: (selected) => [h.div([h.Class("builder-actions")], [
1467
+ button(words.moveUp, applied(moveBy(documentOf(model), selected, -1))),
1468
+ button(words.moveDown, applied(moveBy(documentOf(model), selected, 1))),
1469
+ button(words.duplicate, Option.map(after(documentOf(model), selected), (at) => Message.DuplicateAsked({
1470
+ id: selected,
1471
+ at
1472
+ }))),
1473
+ button(words.delete, Option.some(Message.Applied({ op: Composition.Op.remove(selected) })))
1474
+ ])]
1475
+ });
1476
+ const inspect = (id) => {
1477
+ const node = documentOf(model).nodes[id];
1478
+ if (node === void 0) return null;
1479
+ const fields = Object.entries(node.props).filter((entry) => typeof entry[1] === "string");
1480
+ return h.div([h.Class("builder-properties"), h.AriaLabel("Properties")], fields.map(([key, value]) => h.label([], [key, h.input([h.Value(value), h.OnInput((text) => Message.Applied({ op: Composition.Op.setProp(id, key, text) }))])])));
1481
+ };
1482
+ const inspector = Option.match(model.selected, {
1483
+ onNone: () => [],
1484
+ onSome: (selected) => [inspect(selected)]
1485
+ });
1486
+ return h.div([h.Class("builder")], [
1487
+ palette,
1488
+ layers,
1489
+ ...actions,
1490
+ ...inspector,
1491
+ h.div([h.Class("builder-history")], [button(words.undo, History.canUndo(model.page) ? Option.some(Message.Undid()) : Option.none()), button(words.redo, History.canRedo(model.page) ? Option.some(Message.Redid()) : Option.none())]),
1492
+ ...Option.match(model.refused, {
1493
+ onNone: () => [],
1494
+ onSome: (refused) => [h.p([h.Role("alert")], [refused.message])]
1495
+ }),
1496
+ h.div([h.Class("builder-canvas"), h.DataAttribute("viewport", model.viewport)], [...Renderer.render(renderer, documentOf(model), inertHtml, {
1497
+ mode: "edit",
1498
+ context: model.preview
1499
+ })])
1500
+ ]);
1501
+ };
1502
+ const applied = (op) => Option.map(op, (found) => Message.Applied({ op: found }));
1503
+ const bundle = Bundle.make(name, {
1504
+ Model,
1505
+ Message,
1506
+ init: () => ({ model: initial }),
1507
+ update,
1508
+ view
1509
+ });
1510
+ /** Undo and redo, which need no selection. */
1511
+ const history = (model) => ({
1512
+ undo: History.canUndo(model.page) ? Option.some(Message.Undid()) : Option.none(),
1513
+ redo: History.canRedo(model.page) ? Option.some(Message.Redid()) : Option.none()
1514
+ });
1515
+ /** A command on the selected node, which runs nothing while none is selected. */
1516
+ const onSelected = (run) => (model) => Option.flatMap(model.selected, (selected) => run(documentOf(model), selected));
1517
+ const built = [
1518
+ {
1519
+ id: "move-up",
1520
+ label: words.moveUp,
1521
+ keys: [{
1522
+ key: "ArrowUp",
1523
+ alt: true
1524
+ }],
1525
+ placement: ["node"],
1526
+ run: onSelected((document, selected) => applied(moveBy(document, selected, -1)))
1527
+ },
1528
+ {
1529
+ id: "move-down",
1530
+ label: words.moveDown,
1531
+ keys: [{
1532
+ key: "ArrowDown",
1533
+ alt: true
1534
+ }],
1535
+ placement: ["node"],
1536
+ run: onSelected((document, selected) => applied(moveBy(document, selected, 1)))
1537
+ },
1538
+ {
1539
+ id: "move-out",
1540
+ label: words.moveOut,
1541
+ keys: [{
1542
+ key: "ArrowLeft",
1543
+ alt: true
1544
+ }],
1545
+ placement: ["node"],
1546
+ run: onSelected((document, selected) => applied(outdent(document, selected)))
1547
+ },
1548
+ {
1549
+ id: "move-in",
1550
+ label: words.moveIn,
1551
+ keys: [{
1552
+ key: "ArrowRight",
1553
+ alt: true
1554
+ }],
1555
+ placement: ["node"],
1556
+ run: onSelected((document, selected) => applied(indent(catalog, document, selected)))
1557
+ },
1558
+ {
1559
+ id: "duplicate",
1560
+ label: words.duplicate,
1561
+ keys: [{
1562
+ key: "d",
1563
+ mod: true
1564
+ }],
1565
+ placement: ["node"],
1566
+ run: onSelected((document, selected) => Option.map(Option.filter(after(document, selected), (at) => hasRoom(catalog, document, at)), (at) => Message.DuplicateAsked({
1567
+ id: selected,
1568
+ at
1569
+ })))
1570
+ },
1571
+ {
1572
+ id: "copy",
1573
+ label: words.copy,
1574
+ keys: [{
1575
+ key: "c",
1576
+ mod: true
1577
+ }],
1578
+ placement: ["node"],
1579
+ run: onSelected((_, selected) => Option.some(Message.CopyAsked({ id: selected })))
1580
+ },
1581
+ {
1582
+ id: "cut",
1583
+ label: words.cutCommand,
1584
+ keys: [{
1585
+ key: "x",
1586
+ mod: true
1587
+ }],
1588
+ placement: ["node"],
1589
+ run: onSelected((_, selected) => Option.some(Message.CutAsked({ id: selected })))
1590
+ },
1591
+ {
1592
+ id: "delete",
1593
+ label: words.delete,
1594
+ keys: [{ key: "Delete" }, { key: "Backspace" }],
1595
+ placement: ["node"],
1596
+ run: onSelected((_, selected) => Option.some(Message.Applied({ op: Composition.Op.remove(selected) })))
1597
+ },
1598
+ {
1599
+ id: "undo",
1600
+ label: words.undo,
1601
+ keys: [{
1602
+ key: "z",
1603
+ mod: true,
1604
+ shift: false
1605
+ }],
1606
+ placement: ["toolbar"],
1607
+ run: (model) => history(model).undo
1608
+ },
1609
+ {
1610
+ id: "redo",
1611
+ label: words.redo,
1612
+ keys: [{
1613
+ key: "z",
1614
+ mod: true,
1615
+ shift: true
1616
+ }, {
1617
+ key: "y",
1618
+ mod: true
1619
+ }],
1620
+ placement: ["toolbar"],
1621
+ run: (model) => history(model).redo
1622
+ },
1623
+ {
1624
+ id: "paste",
1625
+ label: words.paste,
1626
+ keys: [{
1627
+ key: "v",
1628
+ mod: true
1629
+ }],
1630
+ placement: ["toolbar"],
1631
+ run: () => Option.some(Message.PasteAsked())
1632
+ },
1633
+ {
1634
+ id: "edit-text",
1635
+ label: words.editText,
1636
+ keys: [{ key: "Enter" }],
1637
+ placement: ["keyboard"],
1638
+ run: onSelected((document, selected) => Option.map(Option.fromUndefinedOr(Renderer.fields(renderer, document, selected)[0]), (key) => Message.EditingAsked({ field: fieldName(selected, key) })))
1639
+ },
1640
+ {
1641
+ id: "deselect",
1642
+ label: words.deselect,
1643
+ keys: [{ key: "Escape" }],
1644
+ placement: ["keyboard"],
1645
+ run: onSelected(() => Option.some(Message.Deselected()))
1646
+ }
1647
+ ];
1648
+ const commands = config.commands === void 0 ? built : config.commands(built);
1649
+ /**
1650
+ * The Message a key sends, for the layers panel and the canvas: the first
1651
+ * command one of whose keys it is, and whose run has one. None for a key
1652
+ * no command takes, or one whose command has nothing to do, and none at
1653
+ * all while text is edited in place: its keys are the text's.
1654
+ */
1655
+ const keyCommand = (model, key, modifiers) => {
1656
+ if (Option.isSome(model.editing)) return Option.none();
1657
+ for (const command of commands) {
1658
+ if (!command.keys.some((spec) => pressed(spec, key, modifiers))) continue;
1659
+ const sent = command.run(model);
1660
+ if (Option.isSome(sent)) return sent;
1661
+ }
1662
+ return Option.none();
1663
+ };
1664
+ /** The form control that places this Builder as a key, drawn by `drawn`. */
1665
+ const inputWith = (drawn) => Input.bundle("Composition", {
1666
+ bundle: bundle.pipe(Bundle.withView(drawn)),
1667
+ value: documentOf,
1668
+ fill: replace,
1669
+ settled: settle
1670
+ });
1671
+ return {
1672
+ name,
1673
+ catalog,
1674
+ renderer,
1675
+ bundle,
1676
+ initial,
1677
+ /** The form control that places this Builder as a key: its value is the Document. */
1678
+ input: inputWith(view),
1679
+ /**
1680
+ * The same control, drawn by another view, such as
1681
+ * `BuilderView.submodel(view)` from `foldkit-mixins-builder`.
1682
+ */
1683
+ inputWith,
1684
+ /** Where a new node of a Block goes, given the selection; none where it may not go. */
1685
+ placeFor: (document, selected, block) => placeFor(catalog, document, selected, block),
1686
+ /** Where a pattern goes, as a new node of its root's Block would; none where it may not. */
1687
+ patternAt: (document, selected, pattern) => Option.flatMap(Catalog.pattern(catalog, pattern), (found) => Option.flatMap(Option.fromUndefinedOr(found.tree.nodes[found.tree.root]), (root) => placeFor(catalog, document, selected, root.block))),
1688
+ moveBy,
1689
+ /** Where what is dragged over `target`, in `zone`, would go; none where it may not. */
1690
+ dropAt: (document, dragged, target, zone) => Option.map(Option.flatMap(draggedOf(document, dragged), (each) => landing(catalog, document, each, target, zone)), ({ at }) => at),
1691
+ replace,
1692
+ settle,
1693
+ /** The editor's commands: what a key, a node's action or the toolbar runs. */
1694
+ commands,
1695
+ keyCommand,
1696
+ /**
1697
+ * The selected node's settings form and its Model, for the inspector to
1698
+ * draw: the Model it holds for the node, else one filled from the props.
1699
+ */
1700
+ inspecting,
1701
+ /** The Blocks a new node may be, in the Catalog's order: those with starting props. */
1702
+ offered: catalog.blocks.filter((block) => Object.hasOwn(starters, block.name)).map((block) => block.name),
1703
+ /** The Document a Builder Model is editing: its history's present. */
1704
+ document: documentOf
1705
+ };
1706
+ }
1707
+ };
1708
+ //#endregion
1709
+ export { Announcer, Builder, ContextValue, Drag, DragSource, DropZone, Layers, Message, Model, Panel, Viewport, controlOf, editWords, inputOf, layersArgs, settingsOf };
1710
+
1711
+ //# sourceMappingURL=index.mjs.map