@daasboard/doc 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.
@@ -0,0 +1,868 @@
1
+ import { anchorSide, attachmentPoint, connectorBounds, exitOrientation, routeReadsSide, TEXT_STYLE_KEYS, sanitizeImageRef, sanitizeEmbedRef } from "@daasboard/render-core";
2
+ import { completeConn, endpointValue, isPoint, pointKeyOf } from "./connectors.js";
3
+ import { getPath, MAX_UNDO_ENTRIES, setPath, TYPING_MERGE_MS } from "./DocumentAdapter.js";
4
+ import { instKeyValue, isTextContent, normalizeNode, rawOfObject, resolveStyleValue } from "./normalize.js";
5
+ import { contentToFlat, flatToContent, normalizeTextContent } from "./text.js";
6
+ import { applyTextDeltaToParagraphs, emptyTextContent, flatTextOf, sameTextContent, textAfterDelta, textDeltaIsEmpty, textDeltaIsKeystroke, validateTextDelta } from "./textDelta.js";
7
+ function imageView(o) {
8
+ const image = o.image && sanitizeImageRef(o.image), embed = o.embed && sanitizeEmbedRef(o.embed);
9
+ if (image === o.image && embed === o.embed)
10
+ return o;
11
+ return { ...o, ...(image ? { image } : {}), ...(embed ? { embed } : {}) };
12
+ }
13
+ function stableStringify(v) {
14
+ if (v === null || typeof v !== "object")
15
+ return JSON.stringify(v) ?? "null";
16
+ if (Array.isArray(v))
17
+ return "[" + v.map(stableStringify).join(",") + "]";
18
+ const o = v;
19
+ return "{" + Object.keys(o).filter((k) => o[k] !== undefined).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(o[k])).join(",") + "}";
20
+ }
21
+ const deepEq = (a, b) => a === b || stableStringify(a) === stableStringify(b);
22
+ const setChangesNothing = (path, before, value) => path === "text" ? sameTextContent(before ?? emptyTextContent(), value ?? emptyTextContent()) : deepEq(before, value);
23
+ const TEXT_STYLE_PATHS = new Set(TEXT_STYLE_KEYS.map((k) => `style.${k}`));
24
+ const affectsText = (path) => path === "text" || TEXT_STYLE_PATHS.has(path);
25
+ const BOX_PATHS = new Set(["x", "y", "w", "h", "rot", "hidden", "kind"]);
26
+ const pointWritesOf = (ops) => (ops ?? []).flatMap((op) => (op.t === "change" ? [op.id] : []));
27
+ const movesEndpoints = (path) => BOX_PATHS.has(path) || path === "anchors" || path.startsWith("anchors.");
28
+ const BOX_KEYS = new Set(["x", "y", "w", "h"]);
29
+ const isEndpointKey = (k) => k === "start" || k === "end";
30
+ const isPointKey = (k) => k === "startAt" || k === "endAt";
31
+ function placeInOrder(order, id, parent, index, parentOf, trashed) {
32
+ const from = order.indexOf(id);
33
+ if (from >= 0) {
34
+ let visibleBefore = 0;
35
+ let visibleTotal = 0;
36
+ for (let raw = 0; raw < order.length; raw++) {
37
+ const sib = order[raw];
38
+ if (sib === id || trashed(sib) || parentOf(sib) !== parent)
39
+ continue;
40
+ if (raw < from)
41
+ visibleBefore++;
42
+ visibleTotal++;
43
+ }
44
+ const landing = index === undefined ? visibleTotal : Math.min(index, visibleTotal);
45
+ if (visibleBefore === landing)
46
+ return false;
47
+ order.splice(from, 1);
48
+ }
49
+ let to = order.length;
50
+ if (index !== undefined) {
51
+ let visible = 0;
52
+ for (let raw = 0; raw < order.length; raw++) {
53
+ const sib = order[raw];
54
+ if (trashed(sib) || parentOf(sib) !== parent)
55
+ continue;
56
+ if (visible === index) {
57
+ to = raw;
58
+ break;
59
+ }
60
+ visible++;
61
+ }
62
+ }
63
+ order.splice(to, 0, id);
64
+ return from !== to;
65
+ }
66
+ export class MemoryDocument {
67
+ scene;
68
+ undoStack = [];
69
+ redoStack = [];
70
+ listeners = new Set();
71
+ now;
72
+ lastTyping = null;
73
+ trash = new Set();
74
+ derivedHidden = new Set();
75
+ attachedTo = new Map();
76
+ constructor(scene, opts = {}) {
77
+ this.scene = scene;
78
+ this.now = opts.now ?? Date.now;
79
+ for (const o of scene.objects.values())
80
+ this.trackAttachment(o);
81
+ }
82
+ trackAttachment(o) {
83
+ if (o.kind !== "connector" || !o.conn)
84
+ return;
85
+ for (const e of [o.conn.start, o.conn.end]) {
86
+ if (!e?.ref)
87
+ continue;
88
+ let set = this.attachedTo.get(e.ref);
89
+ if (!set)
90
+ this.attachedTo.set(e.ref, (set = new Set()));
91
+ set.add(o.id);
92
+ }
93
+ }
94
+ untrackAttachment(o) {
95
+ if (o.kind !== "connector" || !o.conn)
96
+ return;
97
+ for (const e of [o.conn.start, o.conn.end])
98
+ if (e?.ref)
99
+ this.attachedTo.get(e.ref)?.delete(o.id);
100
+ }
101
+ get(id) {
102
+ const o = this.scene.objects.get(id);
103
+ if (!o || this.trash.has(id))
104
+ return undefined;
105
+ return imageView(o);
106
+ }
107
+ order() {
108
+ return this.trash.size === 0 ? this.scene.order : this.scene.order.filter((id) => !this.trash.has(id));
109
+ }
110
+ problems() {
111
+ return [];
112
+ }
113
+ canUndo() {
114
+ return this.undoStack.length > 0;
115
+ }
116
+ canRedo() {
117
+ return this.redoStack.length > 0;
118
+ }
119
+ endTyping() {
120
+ this.lastTyping = null;
121
+ }
122
+ subscribe(l) {
123
+ this.listeners.add(l);
124
+ return () => this.listeners.delete(l);
125
+ }
126
+ emit(cs, label, origin) {
127
+ const sanitize = (objects) => {
128
+ let result = objects;
129
+ for (let i = 0; i < objects.length; i++) {
130
+ const view = imageView(objects[i]);
131
+ if (view !== objects[i]) {
132
+ if (result === objects)
133
+ result = objects.slice();
134
+ result[i] = view;
135
+ }
136
+ }
137
+ return result;
138
+ };
139
+ const added = sanitize(cs.added), updated = sanitize(cs.updated);
140
+ if (added !== cs.added || updated !== cs.updated)
141
+ cs = { ...cs, added, updated };
142
+ let thrown;
143
+ let threw = false;
144
+ for (const l of this.listeners) {
145
+ try {
146
+ l(cs, { label, origin });
147
+ }
148
+ catch (err) {
149
+ if (!threw) {
150
+ threw = true;
151
+ thrown = err;
152
+ }
153
+ }
154
+ }
155
+ if (threw)
156
+ throw thrown;
157
+ }
158
+ applyEntry(e, direction) {
159
+ const updated = new Map();
160
+ const added = [];
161
+ const removed = [];
162
+ const rawBefore = [...this.scene.order];
163
+ const touch = (id) => {
164
+ const o = this.scene.objects.get(id);
165
+ if (o) {
166
+ o.version++;
167
+ updated.set(id, o);
168
+ }
169
+ };
170
+ const change = (c, value) => {
171
+ const o = this.scene.objects.get(c.id);
172
+ if (!o)
173
+ return;
174
+ const reattach = c.path === "conn" || c.path.startsWith("conn.");
175
+ if (reattach)
176
+ this.untrackAttachment(o);
177
+ setPath(o, c.path, c.path === "text" ? normalizeTextContent(value) : value);
178
+ if (reattach && o.conn && Object.keys(o.conn).length === 0)
179
+ delete o.conn;
180
+ if (c.path.startsWith("anchors.") && o.anchors && Object.keys(o.anchors).length === 0)
181
+ delete o.anchors;
182
+ if (c.path.startsWith("inst.") && o.inst && Object.keys(o.inst).length === 0)
183
+ delete o.inst;
184
+ if (c.path === "hidden")
185
+ this.derivedHidden.delete(c.id);
186
+ if (reattach)
187
+ this.trackAttachment(o);
188
+ if (affectsText(c.path) && (o.text !== undefined || o.textVersion !== undefined))
189
+ o.textVersion = (o.textVersion ?? 0) + 1;
190
+ touch(c.id);
191
+ };
192
+ const apply = (op) => {
193
+ switch (op.t) {
194
+ case "create": {
195
+ const c = op.obj;
196
+ this.scene.objects.set(c.id, c);
197
+ this.trash.delete(c.id);
198
+ if (!this.scene.order.includes(c.id))
199
+ this.scene.order.push(c.id);
200
+ else if (op.undoneAt)
201
+ this.reorder(c.id, op.undoneAt.parent, op.undoneAt.index);
202
+ this.trackAttachment(c);
203
+ if (op.undoneAt) {
204
+ if (op.undoneAt.hidden)
205
+ c.hidden = true;
206
+ else
207
+ delete c.hidden;
208
+ }
209
+ c.version++;
210
+ added.push(c);
211
+ return;
212
+ }
213
+ case "change":
214
+ change(op, op.after);
215
+ return;
216
+ case "move":
217
+ this.reorder(op.id, op.toParent, op.toIndex);
218
+ touch(op.id);
219
+ return;
220
+ case "delete": {
221
+ this.trash.add(op.id);
222
+ const o = this.scene.objects.get(op.id);
223
+ if (o) {
224
+ o.hidden = true;
225
+ touch(op.id);
226
+ }
227
+ return;
228
+ }
229
+ }
230
+ };
231
+ const revert = (op) => {
232
+ switch (op.t) {
233
+ case "delete": {
234
+ this.trash.delete(op.id);
235
+ const o = this.scene.objects.get(op.id);
236
+ if (!o)
237
+ return;
238
+ if (op.prevHidden === undefined)
239
+ delete o.hidden;
240
+ else
241
+ o.hidden = op.prevHidden;
242
+ this.reorder(op.id, op.fromParent, op.fromIndex);
243
+ touch(op.id);
244
+ return;
245
+ }
246
+ case "move":
247
+ this.reorder(op.id, op.fromParent, op.fromIndex);
248
+ touch(op.id);
249
+ return;
250
+ case "change":
251
+ change(op, op.before);
252
+ return;
253
+ case "create": {
254
+ const c = op.obj;
255
+ op.undoneAt = { parent: c.parent ?? null, index: this.visibleIndexOf(c.id), hidden: !!c.hidden && !this.derivedHidden.has(c.id) };
256
+ this.trash.add(c.id);
257
+ c.hidden = true;
258
+ touch(c.id);
259
+ return;
260
+ }
261
+ }
262
+ };
263
+ for (const op of e.inverseAnchors ?? [])
264
+ revert(op);
265
+ delete e.inverseAnchors;
266
+ if (direction === "do")
267
+ for (const op of e.ops)
268
+ apply(op);
269
+ else
270
+ for (let i = e.ops.length - 1; i >= 0; i--)
271
+ revert(e.ops[i]);
272
+ const cs = { added, updated: [...updated.values()].filter((o) => !added.includes(o)), removed };
273
+ const after = this.scene.order;
274
+ const beforeIds = added.length ? new Set(rawBefore) : undefined;
275
+ const fresh = new Set(added.filter((o) => !beforeIds.has(o.id)).map((o) => o.id));
276
+ let at = 0;
277
+ for (const id of rawBefore) {
278
+ while (at < after.length && fresh.has(after[at]))
279
+ at++;
280
+ if (after[at++] !== id) {
281
+ cs.reordered = true;
282
+ break;
283
+ }
284
+ }
285
+ return cs;
286
+ }
287
+ pushUndo(e) {
288
+ this.undoStack.push(e);
289
+ if (this.undoStack.length > MAX_UNDO_ENTRIES)
290
+ this.undoStack.shift();
291
+ }
292
+ refreshAnchors(e, cs, record = e.ops, repointed = []) {
293
+ const conns = new Set();
294
+ for (const op of e.ops) {
295
+ if (op.t === "change") {
296
+ if (movesEndpoints(op.path))
297
+ for (const cid of this.attachedTo.get(op.id) ?? [])
298
+ conns.add(cid);
299
+ else if (op.path === "conn" || op.path.startsWith("conn."))
300
+ conns.add(op.id);
301
+ }
302
+ else if (op.t === "create" && op.obj.conn)
303
+ conns.add(op.obj.id);
304
+ else if (op.t === "delete" && !this.trash.has(op.id)) {
305
+ for (const cid of this.attachedTo.get(op.id) ?? [])
306
+ conns.add(cid);
307
+ conns.add(op.id);
308
+ }
309
+ }
310
+ for (const cid of repointed)
311
+ conns.add(cid);
312
+ for (const cid of conns) {
313
+ const conn = this.get(cid);
314
+ if (!conn?.conn)
315
+ continue;
316
+ for (const key of ["start", "end"]) {
317
+ const ep = conn.conn[key];
318
+ if (!ep || typeof ep !== "object")
319
+ continue;
320
+ const at = this.derivedPoint(ep, (id) => this.get(id));
321
+ if (!at)
322
+ continue;
323
+ const pointKey = pointKeyOf(key);
324
+ const cur = conn.conn[pointKey];
325
+ if (isPoint(cur) && cur[0] === at[0] && cur[1] === at[1])
326
+ continue;
327
+ const path = `conn.${pointKey}`;
328
+ record.push({ t: "change", id: cid, path, before: cur, after: at });
329
+ setPath(conn, path, at);
330
+ conn.version++;
331
+ if (!cs.added.includes(conn) && !cs.updated.includes(conn))
332
+ cs.updated.push(conn);
333
+ }
334
+ }
335
+ for (const op of e.ops) {
336
+ if (op.t !== "change" || !(op.path === "anchors" || op.path.startsWith("anchors.")))
337
+ continue;
338
+ for (const cid of this.attachedTo.get(op.id) ?? []) {
339
+ const c = this.get(cid);
340
+ if (!c?.conn)
341
+ continue;
342
+ for (const [end, ep] of [["start", c.conn.start], ["end", c.conn.end]]) {
343
+ if (!ep || ep.ref !== op.id || ep.anchor === undefined || !routeReadsSide(c.conn, end))
344
+ continue;
345
+ const name = ep.anchor;
346
+ if (op.path !== "anchors" && op.path !== `anchors.${name}`)
347
+ continue;
348
+ const uv = (v) => (op.path === "anchors" ? v?.[name] : v);
349
+ const side = (v) => (isPoint(v) ? anchorSide(v) : ep.side);
350
+ const s = c.conn.startAt;
351
+ const t = c.conn.endAt;
352
+ if (s && t && exitOrientation(side(uv(op.before)), s, t) === exitOrientation(side(uv(op.after)), s, t))
353
+ continue;
354
+ c.version++;
355
+ if (!cs.added.includes(c) && !cs.updated.includes(c))
356
+ cs.updated.push(c);
357
+ break;
358
+ }
359
+ }
360
+ }
361
+ }
362
+ refreshGroups(cs) {
363
+ const live = this.order();
364
+ const withChildren = new Set();
365
+ for (const id of live) {
366
+ const p = this.scene.objects.get(id)?.parent;
367
+ if (p)
368
+ withChildren.add(p);
369
+ }
370
+ for (const id of [...this.derivedHidden])
371
+ if (this.trash.has(id) || !this.scene.objects.has(id))
372
+ this.derivedHidden.delete(id);
373
+ const report = (o) => {
374
+ o.version++;
375
+ if (!cs.added.includes(o) && !cs.updated.includes(o))
376
+ cs.updated.push(o);
377
+ };
378
+ for (const id of live) {
379
+ const g = this.scene.objects.get(id);
380
+ if (!g)
381
+ continue;
382
+ if (g.kind !== "group") {
383
+ if (this.derivedHidden.has(id)) {
384
+ delete g.hidden;
385
+ this.derivedHidden.delete(id);
386
+ report(g);
387
+ }
388
+ continue;
389
+ }
390
+ const empty = !withChildren.has(id);
391
+ if (empty && !g.hidden) {
392
+ g.hidden = true;
393
+ this.derivedHidden.add(id);
394
+ report(g);
395
+ }
396
+ else if (!empty && this.derivedHidden.has(id)) {
397
+ delete g.hidden;
398
+ this.derivedHidden.delete(id);
399
+ report(g);
400
+ }
401
+ }
402
+ }
403
+ reboundConnectors(cs) {
404
+ const listed = new Set([...cs.added, ...cs.updated]);
405
+ const todo = new Set();
406
+ for (const o of listed) {
407
+ if (o.kind === "connector" && o.conn)
408
+ todo.add(o.id);
409
+ for (const cid of this.attachedTo.get(o.id) ?? [])
410
+ todo.add(cid);
411
+ }
412
+ for (const cid of todo) {
413
+ const c = this.get(cid);
414
+ if (!c?.conn)
415
+ continue;
416
+ const b = connectorBounds(c.conn, this.scene, c);
417
+ if (c.x === b.x && c.y === b.y && c.w === b.w && c.h === b.h)
418
+ continue;
419
+ Object.assign(c, b);
420
+ if (!listed.has(c)) {
421
+ c.version++;
422
+ cs.updated.push(c);
423
+ }
424
+ }
425
+ }
426
+ derivedPoint(ep, lookup) {
427
+ const target = ep.ref ? lookup(ep.ref) : undefined;
428
+ if (!target || target.kind === "connector")
429
+ return undefined;
430
+ return attachmentPoint(target, ep);
431
+ }
432
+ drawnPoint(ep, lookup) {
433
+ const target = ep.ref ? lookup(ep.ref) : undefined;
434
+ return target?.hidden ? undefined : this.derivedPoint(ep, lookup);
435
+ }
436
+ visibleIndexOf(id) {
437
+ const parent = this.scene.objects.get(id)?.parent ?? null;
438
+ let i = 0;
439
+ for (const x of this.scene.order) {
440
+ if (x === id)
441
+ return i;
442
+ if (!this.trash.has(x) && (this.scene.objects.get(x)?.parent ?? null) === parent)
443
+ i++;
444
+ }
445
+ return i;
446
+ }
447
+ reorder(id, parent, index) {
448
+ const o = this.scene.objects.get(id);
449
+ if (!o)
450
+ return false;
451
+ o.parent = parent;
452
+ return placeInOrder(this.scene.order, id, parent ?? null, index, (x) => this.scene.objects.get(x)?.parent ?? null, (x) => this.trash.has(x));
453
+ }
454
+ transact(label, fn) {
455
+ const e = { label, ops: [] };
456
+ const textEdits = [];
457
+ const self = this;
458
+ const workOrder = [...this.scene.order];
459
+ const workParent = new Map();
460
+ const created = new Map();
461
+ const deleted = new Set();
462
+ const parentOf = (id) => (workParent.has(id) ? workParent.get(id) : (self.scene.objects.get(id)?.parent ?? null));
463
+ const trashed = (id) => self.trash.has(id) || deleted.has(id);
464
+ const live = (id) => {
465
+ const o = created.get(id) ?? self.scene.objects.get(id);
466
+ return o && !trashed(id) ? o : undefined;
467
+ };
468
+ const visibleSiblings = (parent, except) => workOrder.filter((x) => x !== except && !trashed(x) && parentOf(x) === parent);
469
+ const hiddenWritten = new Set();
470
+ const pendingView = (id, o) => {
471
+ let view;
472
+ for (const op of e.ops) {
473
+ if (op.t !== "change" || op.id !== id)
474
+ continue;
475
+ view ??= { ...o };
476
+ setPath(view, op.path, op.after);
477
+ }
478
+ return view ?? o;
479
+ };
480
+ const pendingLookup = (id) => {
481
+ const o = live(id);
482
+ return o ? pendingView(id, o) : undefined;
483
+ };
484
+ const textModels = new Map();
485
+ const flatOf = (content) => flatTextOf(content ?? emptyTextContent());
486
+ const lastTextRewrite = (id) => {
487
+ for (let i = e.ops.length - 1; i >= 0; i--) {
488
+ const op = e.ops[i];
489
+ if (op.t === "change" && op.id === id && op.path === "text")
490
+ return op;
491
+ }
492
+ return undefined;
493
+ };
494
+ const modelOf = (id, o) => {
495
+ const m = textModels.get(id);
496
+ if (m !== undefined)
497
+ return m;
498
+ const rewrite = lastTextRewrite(id);
499
+ return flatOf(rewrite ? rewrite.after : o.text);
500
+ };
501
+ const validatedAfter = (id, model, delta) => {
502
+ try {
503
+ validateTextDelta(model, delta);
504
+ }
505
+ catch (err) {
506
+ throw new Error(`editText(${id}): ${err instanceof Error ? err.message : String(err)}`);
507
+ }
508
+ return textAfterDelta(model, delta);
509
+ };
510
+ const tx = {
511
+ set(id, path, value) {
512
+ const o = live(id);
513
+ if (!o)
514
+ return;
515
+ const view = pendingView(id, o);
516
+ const parts = path.split(".");
517
+ if (parts[0] === "extId")
518
+ return;
519
+ if (parts[0] === "style" && parts.length !== 2)
520
+ return;
521
+ if (BOX_KEYS.has(path) && o.kind === "connector")
522
+ return;
523
+ if (path === "kind") {
524
+ if (value === "connector" || o.kind === "connector" || value === "trash" || value === "instance")
525
+ return;
526
+ }
527
+ else if (parts[0] === "conn") {
528
+ const isConnector = o.kind === "connector";
529
+ const current = getPath(view, "conn") ?? {};
530
+ const derived = (k, ends) => {
531
+ const ep = ends[k === "startAt" ? "start" : "end"];
532
+ return !!ep && typeof ep === "object" && self.derivedPoint(ep, pendingLookup) !== undefined;
533
+ };
534
+ const keepDrawn = (k, cur, next, into) => {
535
+ const drawn = cur && typeof cur === "object" ? self.drawnPoint(cur, pendingLookup) : undefined;
536
+ if (!drawn || (next && typeof next === "object" && self.derivedPoint(next, pendingLookup)))
537
+ return;
538
+ const stored = into[pointKeyOf(k)];
539
+ if (!(isPoint(stored) && stored[0] === drawn[0] && stored[1] === drawn[1]))
540
+ into[pointKeyOf(k)] = drawn;
541
+ };
542
+ if (parts.length === 1) {
543
+ if (!value || typeof value !== "object") {
544
+ if (isConnector)
545
+ return;
546
+ value = undefined;
547
+ }
548
+ else {
549
+ const merged = { ...current };
550
+ const entries = Object.entries(value);
551
+ for (const [k, raw] of entries) {
552
+ if (!isEndpointKey(k))
553
+ continue;
554
+ const v = endpointValue(raw);
555
+ if (isConnector && (!v || typeof v !== "object"))
556
+ continue;
557
+ if (isConnector)
558
+ keepDrawn(k, merged[k], v, merged);
559
+ if (v === undefined)
560
+ delete merged[k];
561
+ else
562
+ merged[k] = v;
563
+ }
564
+ for (const [k, v] of entries) {
565
+ if (isEndpointKey(k))
566
+ continue;
567
+ if (isConnector && isPointKey(k)) {
568
+ if (isPoint(v) && !derived(k, merged))
569
+ merged[k] = v;
570
+ continue;
571
+ }
572
+ if (v === undefined)
573
+ delete merged[k];
574
+ else
575
+ merged[k] = v;
576
+ }
577
+ value = Object.keys(merged).length ? merged : undefined;
578
+ }
579
+ }
580
+ else if (isEndpointKey(parts[1])) {
581
+ if (parts.length > 2) {
582
+ const group = { ...(getPath(view, `conn.${parts[1]}`) ?? {}) };
583
+ if (value === undefined)
584
+ delete group[parts[2]];
585
+ else
586
+ group[parts[2]] = value;
587
+ value = group;
588
+ path = `conn.${parts[1]}`;
589
+ }
590
+ value = endpointValue(value);
591
+ if (isConnector && (!value || typeof value !== "object"))
592
+ return;
593
+ if (isConnector) {
594
+ const end = parts[1];
595
+ const pk = pointKeyOf(end);
596
+ const scratch = { [pk]: current[pk] };
597
+ keepDrawn(end, current[end], value, scratch);
598
+ if (scratch[pk] !== current[pk])
599
+ e.ops.push({ t: "change", id, path: `conn.${pk}`, before: current[pk], after: scratch[pk] });
600
+ }
601
+ }
602
+ else if (parts.length > 2)
603
+ return;
604
+ else if (isConnector && isPointKey(parts[1]) && (!isPoint(value) || derived(parts[1], current)))
605
+ return;
606
+ }
607
+ else if (parts[0] === "anchors") {
608
+ if (parts.length === 1) {
609
+ if (!value || typeof value !== "object")
610
+ value = undefined;
611
+ else {
612
+ const merged = { ...(getPath(view, "anchors") ?? {}) };
613
+ for (const [k, v] of Object.entries(value)) {
614
+ if (v === undefined)
615
+ delete merged[k];
616
+ else if (isPoint(v))
617
+ merged[k] = v;
618
+ }
619
+ value = Object.keys(merged).length ? merged : undefined;
620
+ }
621
+ }
622
+ else if (parts.length !== 2 || !(value === undefined || isPoint(value)))
623
+ return;
624
+ }
625
+ else if (parts[0] === "inst") {
626
+ if (view.kind !== "instance")
627
+ return;
628
+ if (parts.length === 1) {
629
+ if (!value || typeof value !== "object")
630
+ value = undefined;
631
+ else {
632
+ const merged = { ...(getPath(view, "inst") ?? {}) };
633
+ for (const [k, v] of Object.entries(value)) {
634
+ const r = instKeyValue(k, v);
635
+ if (!r.ok)
636
+ continue;
637
+ if (r.value === undefined)
638
+ delete merged[k];
639
+ else
640
+ merged[k] = r.value;
641
+ }
642
+ value = Object.keys(merged).length ? merged : undefined;
643
+ }
644
+ }
645
+ else if (parts.length === 2) {
646
+ const r = instKeyValue(parts[1], value);
647
+ if (!r.ok)
648
+ return;
649
+ value = r.value;
650
+ }
651
+ else
652
+ return;
653
+ }
654
+ else if (parts.length > 1 && parts[0] !== "style")
655
+ return;
656
+ if (parts[0] === "style" && parts.length === 2)
657
+ value = resolveStyleValue(parts[1], value);
658
+ const before = path === "hidden" && self.derivedHidden.has(id) && !hiddenWritten.has(id) ? undefined : getPath(view, path);
659
+ if (setChangesNothing(path, before, value))
660
+ return;
661
+ e.ops.push({ t: "change", id, path, before, after: value });
662
+ if (path === "hidden")
663
+ hiddenWritten.add(id);
664
+ if (path === "text") {
665
+ let model = flatOf(value);
666
+ for (const t of textEdits)
667
+ if (t.id === id)
668
+ model = validatedAfter(id, model, t.delta);
669
+ textModels.set(id, model);
670
+ }
671
+ },
672
+ move(id, parent, index) {
673
+ const o = live(id);
674
+ if (!o)
675
+ return;
676
+ if (parent !== null && !live(parent))
677
+ return;
678
+ const fromParent = parentOf(id);
679
+ const fromVisible = visibleSiblings(fromParent).indexOf(id);
680
+ const sibsTo = visibleSiblings(parent ?? null, id);
681
+ if (fromParent === (parent ?? null)) {
682
+ const landing = index === undefined ? sibsTo.length : Math.min(index, sibsTo.length);
683
+ if (fromVisible === landing)
684
+ return;
685
+ }
686
+ placeInOrder(workOrder, id, parent ?? null, index, parentOf, trashed);
687
+ workParent.set(id, parent ?? null);
688
+ e.ops.push({ t: "move", id, fromParent, fromIndex: fromVisible, toParent: parent, toIndex: index });
689
+ },
690
+ create(obj) {
691
+ if (obj.parent && !live(obj.parent))
692
+ obj.parent = null;
693
+ const norm = isTextContent(obj.text) ? normalizeTextContent(flatToContent(contentToFlat(obj.text))) : undefined;
694
+ if (norm) {
695
+ obj.text = norm;
696
+ if (obj.textVersion === undefined)
697
+ obj.textVersion = 1;
698
+ }
699
+ else {
700
+ delete obj.text;
701
+ delete obj.textVersion;
702
+ }
703
+ const shaped = normalizeNode(obj.id, rawOfObject(obj), { x: 0, y: 0 }, obj.parent ?? null).object;
704
+ if (!shaped)
705
+ return;
706
+ for (const key of ["rot", "style", "hidden", "locked", "autoWidth", "autoHeight", "name", "extId", "anchors", "embed", "inst", "clip", "path", "image"]) {
707
+ if (shaped[key] === undefined)
708
+ delete obj[key];
709
+ else
710
+ obj[key] = shaped[key];
711
+ }
712
+ if (obj.conn) {
713
+ const full = completeConn(obj.conn, obj);
714
+ const start = endpointValue(full.start);
715
+ const end = endpointValue(full.end);
716
+ obj.conn = { ...full, start, end, startAt: self.derivedPoint(start, pendingLookup) ?? full.startAt, endAt: self.derivedPoint(end, pendingLookup) ?? full.endAt };
717
+ }
718
+ created.set(obj.id, obj);
719
+ if (!workOrder.includes(obj.id))
720
+ workOrder.push(obj.id);
721
+ workParent.set(obj.id, obj.parent ?? null);
722
+ e.ops.push({ t: "create", obj });
723
+ },
724
+ delete(id) {
725
+ const o = live(id);
726
+ if (!o)
727
+ return;
728
+ const box = pendingView(id, o);
729
+ for (const cid of o.kind === "connector" || box.hidden ? [] : (self.attachedTo.get(id) ?? [])) {
730
+ const c = live(cid);
731
+ if (!c?.conn)
732
+ continue;
733
+ const cv = pendingView(cid, c);
734
+ for (const key of ["start", "end"]) {
735
+ const ep = cv.conn?.[key];
736
+ if (!ep || typeof ep !== "object" || ep.ref !== id)
737
+ continue;
738
+ const at = attachmentPoint(box, ep);
739
+ if (!at)
740
+ continue;
741
+ const pointKey = pointKeyOf(key);
742
+ const cur = cv.conn?.[pointKey];
743
+ if (isPoint(cur) && cur[0] === at[0] && cur[1] === at[1])
744
+ continue;
745
+ e.ops.push({ t: "change", id: cid, path: `conn.${pointKey}`, before: cur, after: at });
746
+ }
747
+ }
748
+ const fromParent = parentOf(id);
749
+ const fromIndex = visibleSiblings(fromParent).indexOf(id);
750
+ deleted.add(id);
751
+ e.ops.push({ t: "delete", id, prevHidden: self.derivedHidden.has(id) ? undefined : o.hidden, fromParent, fromIndex });
752
+ },
753
+ editText(id, delta) {
754
+ const o = live(id);
755
+ if (!o)
756
+ return;
757
+ textModels.set(id, validatedAfter(id, modelOf(id, o), delta));
758
+ textEdits.push({ id, delta });
759
+ },
760
+ };
761
+ let threw = false;
762
+ let thrown;
763
+ try {
764
+ fn(tx);
765
+ }
766
+ catch (err) {
767
+ threw = true;
768
+ thrown = err;
769
+ }
770
+ if (threw) {
771
+ e.ops = e.ops.filter((op) => !(op.t === "change" && op.path === "text"));
772
+ if (e.ops.length) {
773
+ const cs = this.applyEntry(e, "do");
774
+ this.refreshAnchors(e, cs);
775
+ this.refreshGroups(cs);
776
+ this.reboundConnectors(cs);
777
+ this.pushUndo(e);
778
+ this.lastTyping = null;
779
+ this.redoStack = [];
780
+ try {
781
+ this.emit(cs, label, "local");
782
+ }
783
+ catch {
784
+ }
785
+ }
786
+ throw thrown;
787
+ }
788
+ const editedId = textEdits[0]?.id;
789
+ let typingId = editedId !== undefined &&
790
+ textEdits.every((t) => t.id === editedId && textDeltaIsKeystroke(t.delta)) &&
791
+ e.ops.every((op) => op.t === "change" && op.id === editedId && op.path === "h")
792
+ ? editedId
793
+ : null;
794
+ const textChanges = new Map();
795
+ for (const { id, delta } of textEdits) {
796
+ const o = created.get(id) ?? this.scene.objects.get(id);
797
+ if (!o || textDeltaIsEmpty(delta))
798
+ continue;
799
+ const own = textChanges.get(id);
800
+ const pendingSet = own ? undefined : lastTextRewrite(id);
801
+ const base = (own ? own.after : pendingSet ? pendingSet.after : o.text);
802
+ const { content: after, changed } = applyTextDeltaToParagraphs(base ?? emptyTextContent(), delta);
803
+ if (!changed)
804
+ continue;
805
+ if (own)
806
+ own.after = after;
807
+ else
808
+ textChanges.set(id, { t: "change", id, path: "text", before: base, after });
809
+ }
810
+ if (typingId !== null && !textChanges.has(typingId))
811
+ typingId = null;
812
+ e.ops.push(...textChanges.values());
813
+ if (!e.ops.length)
814
+ return;
815
+ const now = this.now();
816
+ const merge = typingId !== null && this.lastTyping !== null && this.lastTyping.id === typingId && now - this.lastTyping.at <= TYPING_MERGE_MS ? this.lastTyping : null;
817
+ const cs = this.applyEntry(e, "do");
818
+ this.refreshAnchors(e, cs);
819
+ this.refreshGroups(cs);
820
+ this.reboundConnectors(cs);
821
+ if (merge) {
822
+ const target = merge.entry.ops.find((op) => op.t === "change" && op.id === merge.id && op.path === "text");
823
+ target.after = textChanges.get(merge.id).after;
824
+ merge.entry.ops.push(...e.ops.filter((op) => !(op.t === "change" && op.path === "text")));
825
+ merge.at = now;
826
+ }
827
+ else {
828
+ this.pushUndo(e);
829
+ this.lastTyping = typingId !== null ? { id: typingId, at: now, entry: e } : null;
830
+ }
831
+ this.redoStack = [];
832
+ this.emit(cs, label, "local");
833
+ }
834
+ undo() {
835
+ const e = this.undoStack.pop();
836
+ if (!e)
837
+ return false;
838
+ this.lastTyping = null;
839
+ const repointed = pointWritesOf(e.inverseAnchors);
840
+ const cs = this.applyEntry(e, "undo");
841
+ const derived = [];
842
+ this.refreshAnchors(e, cs, derived, repointed);
843
+ if (derived.length)
844
+ e.inverseAnchors = derived;
845
+ this.refreshGroups(cs);
846
+ this.reboundConnectors(cs);
847
+ this.redoStack.push(e);
848
+ this.emit(cs, e.label, "undo");
849
+ return true;
850
+ }
851
+ redo() {
852
+ const e = this.redoStack.pop();
853
+ if (!e)
854
+ return false;
855
+ this.lastTyping = null;
856
+ const repointed = pointWritesOf(e.inverseAnchors);
857
+ const cs = this.applyEntry(e, "do");
858
+ const derived = [];
859
+ this.refreshAnchors(e, cs, derived, repointed);
860
+ if (derived.length)
861
+ e.inverseAnchors = derived;
862
+ this.refreshGroups(cs);
863
+ this.reboundConnectors(cs);
864
+ this.pushUndo(e);
865
+ this.emit(cs, e.label, "redo");
866
+ return true;
867
+ }
868
+ }