jsmind 0.9.0 → 2.0.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.
Files changed (40) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +78 -67
  3. package/README.zh.md +81 -0
  4. package/dist/cli.js +4482 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/jsmind.cjs +4101 -0
  7. package/dist/jsmind.cjs.map +1 -0
  8. package/dist/jsmind.d.ts +1269 -0
  9. package/dist/jsmind.js +4099 -0
  10. package/dist/jsmind.js.map +1 -0
  11. package/dist/jsmind.umd.js +4107 -0
  12. package/dist/jsmind.umd.js.map +1 -0
  13. package/package.json +65 -52
  14. package/es6/README-en.md +0 -37
  15. package/es6/README.md +0 -34
  16. package/es6/jsmind.draggable-node.js +0 -9
  17. package/es6/jsmind.draggable-node.js.map +0 -1
  18. package/es6/jsmind.js +0 -9
  19. package/es6/jsmind.js.map +0 -1
  20. package/es6/jsmind.screenshot.js +0 -9
  21. package/es6/jsmind.screenshot.js.map +0 -1
  22. package/style/jsmind.css +0 -408
  23. package/types/generated/index.d.ts +0 -8
  24. package/types/generated/jsmind.common.d.ts +0 -66
  25. package/types/generated/jsmind.d.ts +0 -343
  26. package/types/generated/jsmind.data_provider.d.ts +0 -56
  27. package/types/generated/jsmind.dom.d.ts +0 -59
  28. package/types/generated/jsmind.format.d.ts +0 -100
  29. package/types/generated/jsmind.graph.d.ts +0 -180
  30. package/types/generated/jsmind.layout_provider.d.ts +0 -182
  31. package/types/generated/jsmind.mind.d.ts +0 -121
  32. package/types/generated/jsmind.node.d.ts +0 -62
  33. package/types/generated/jsmind.option.d.ts +0 -64
  34. package/types/generated/jsmind.plugin.d.ts +0 -21
  35. package/types/generated/jsmind.shortcut_provider.d.ts +0 -52
  36. package/types/generated/jsmind.util.d.ts +0 -26
  37. package/types/generated/jsmind.view_provider.d.ts +0 -347
  38. package/types/generated/plugins/jsmind.draggable-node.d.ts +0 -229
  39. package/types/generated/plugins/jsmind.screenshot.d.ts +0 -83
  40. package/types/tsconfig.declaration.json +0 -19
package/dist/jsmind.js ADDED
@@ -0,0 +1,4099 @@
1
+ /**
2
+ * @license BSD-3-Clause
3
+ * @copyright 2014-2025 hizzgdev@163.com
4
+ *
5
+ * Project Home:
6
+ * https://github.com/hizzgdev/jsmind-v2/
7
+ */
8
+ /**
9
+ * Custom error class for jsMind operations.
10
+ *
11
+ * @public
12
+ */
13
+ class JsMindError extends Error {
14
+ /** The data associated with the error. */
15
+ data;
16
+ /**
17
+ * Stable machine-readable code, when the failure has one.
18
+ *
19
+ * @remarks
20
+ * Callers branch on this rather than on `message`, which is written for
21
+ * humans and may be reworded at any time.
22
+ */
23
+ code;
24
+ /**
25
+ * Creates a new JsMindError instance.
26
+ *
27
+ * @param message - The error message.
28
+ * @param data - Extra data carried with the error.
29
+ * @param code - Stable machine-readable code, if any.
30
+ */
31
+ constructor(message, data = {}, code) {
32
+ super(message);
33
+ this.data = data;
34
+ if (code !== undefined) {
35
+ this.code = code;
36
+ }
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Manager for observers of an observed object.
42
+ *
43
+ * @public
44
+ */
45
+ class JmObserverManager {
46
+ /** The object being observed. */
47
+ observedObject;
48
+ /** @internal */
49
+ _observers;
50
+ /**
51
+ * Creates an observer manager for an observed object.
52
+ *
53
+ * @param observedObject - The object to observe.
54
+ */
55
+ constructor(observedObject) {
56
+ this.observedObject = observedObject;
57
+ this._observers = [];
58
+ }
59
+ /**
60
+ * Adds an observer to the observed object.
61
+ *
62
+ * @param observer - An object that contains an `update(observedObject, event)` method.
63
+ * @throws {@link JsMindError} If the observer is not a valid JmObserver instance.
64
+ */
65
+ addObserver(observer) {
66
+ if (!observer || !('update' in observer) || typeof observer.update !== 'function') {
67
+ throw new JsMindError('observer is not a valid JmObserver instance');
68
+ }
69
+ this._observers.push(observer);
70
+ }
71
+ /**
72
+ * Removes an observer that was previously added by the `addObserver` method.
73
+ *
74
+ * @param observer - The observer to remove.
75
+ */
76
+ removeObserver(observer) {
77
+ this._observers = this._observers.filter(o => o !== observer);
78
+ }
79
+ /**
80
+ * Removes all observers from the object.
81
+ */
82
+ clearObservers() {
83
+ this._observers = [];
84
+ }
85
+ /**
86
+ * Notifies the event to all observers.
87
+ *
88
+ * @remarks
89
+ * This is an asynchronous method. Each observer is notified in a separate
90
+ * asynchronous operation.
91
+ *
92
+ * @param event - Events are defined by different observed objects, which
93
+ * represent specific information about the changes.
94
+ */
95
+ async notifyObservers(event) {
96
+ this._observers.forEach(async (observer) => {
97
+ await new Promise((resolve) => {
98
+ setTimeout(() => {
99
+ observer.update(this.observedObject, event);
100
+ resolve();
101
+ });
102
+ });
103
+ });
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Edge of mind map.
109
+ *
110
+ * @remarks
111
+ * Edges represent additional relationships between nodes (not parent-child relationships).
112
+ *
113
+ * @public
114
+ */
115
+ class JmEdge {
116
+ /** The unique identifier of the edge. */
117
+ id;
118
+ /** The ID of the source node. */
119
+ sourceNodeId;
120
+ /** The ID of the target node. */
121
+ targetNodeId;
122
+ /** The type of the edge. */
123
+ type;
124
+ /** The optional label of the edge. */
125
+ label;
126
+ /**
127
+ * Visual style of the edge line.
128
+ *
129
+ * @remarks
130
+ * Uses the same `JmLineStyle` as `JmNodeStyle.incoming` so that
131
+ * hierarchical and additional relationships share one vocabulary.
132
+ */
133
+ style;
134
+ /**
135
+ * Creates a new edge.
136
+ *
137
+ * @param id - The unique identifier of the edge.
138
+ * @param sourceNodeId - The ID of the source node.
139
+ * @param targetNodeId - The ID of the target node.
140
+ * @param type - The type of the edge.
141
+ * @param label - Optional label for the edge.
142
+ * @throws {@link JsMindError} If any of the required parameters are invalid.
143
+ */
144
+ constructor(id, sourceNodeId, targetNodeId, type, label = null) {
145
+ if (!id) {
146
+ throw new JsMindError('invalid edge id');
147
+ }
148
+ if (!sourceNodeId) {
149
+ throw new JsMindError('invalid source node id');
150
+ }
151
+ if (!targetNodeId) {
152
+ throw new JsMindError('invalid target node');
153
+ }
154
+ if (!type) {
155
+ throw new JsMindError('invalid edge type');
156
+ }
157
+ this.id = id;
158
+ this.sourceNodeId = sourceNodeId;
159
+ this.targetNodeId = targetNodeId;
160
+ this.type = type;
161
+ this.label = label;
162
+ }
163
+ }
164
+ /**
165
+ * Type of edge - only for additional relationships (not parent-child).
166
+ *
167
+ * @public
168
+ */
169
+ const JmEdgeType = {
170
+ /** Link edge type. */
171
+ Link: 'link',
172
+ };
173
+
174
+ /**
175
+ * Represents a size with width and height.
176
+ *
177
+ * @public
178
+ */
179
+ class JmSize {
180
+ /** The width value. */
181
+ width;
182
+ /** The height value. */
183
+ height;
184
+ /**
185
+ * Creates a new size instance.
186
+ *
187
+ * @param width - The width value.
188
+ * @param height - The height value.
189
+ */
190
+ constructor(width, height) {
191
+ this.width = width;
192
+ this.height = height;
193
+ }
194
+ }
195
+ class JmPoint {
196
+ x;
197
+ y;
198
+ constructor(x, y) {
199
+ this.x = x;
200
+ this.y = y;
201
+ }
202
+ offset(offset) {
203
+ return new JmPoint(this.x + offset.x, this.y + offset.y);
204
+ }
205
+ static Zero = new JmPoint(0, 0);
206
+ }
207
+ class JmBounds {
208
+ center;
209
+ size;
210
+ constructor(center, size) {
211
+ this.center = center;
212
+ this.size = size;
213
+ }
214
+ }
215
+
216
+ class JmNodeViewData {
217
+ element = null;
218
+ expander = null;
219
+ leadingLine = null;
220
+ }
221
+ class JmNodeLayoutData {
222
+ side = JmNodeSide.Center;
223
+ visible = true;
224
+ size = new JmSize(0, 0);
225
+ withDescendantsSize = new JmSize(0, 0);
226
+ offsetToParent = new JmPoint(0, 0);
227
+ }
228
+ class NodeInternalData {
229
+ view = new JmNodeViewData();
230
+ layout = new JmNodeLayoutData();
231
+ }
232
+ /**
233
+ * Node of mind map.
234
+ *
235
+ * @public
236
+ */
237
+ class JmNode {
238
+ /** The unique identifier of the node. */
239
+ id;
240
+ /** The content of the node. */
241
+ content;
242
+ /** The parent node, or null if this is the root node. */
243
+ parent;
244
+ /** Array of child nodes. */
245
+ children;
246
+ /** Whether the node is folded (collapsed). */
247
+ folded;
248
+ /** The direction of the node. */
249
+ side;
250
+ /** Additional data associated with the node. */
251
+ data;
252
+ /**
253
+ * Visual overrides for this node.
254
+ *
255
+ * @remarks
256
+ * Unset fields fall back to the theme. Storing only the difference keeps
257
+ * theme changes propagating to every node that did not override anything.
258
+ */
259
+ style;
260
+ /** View data associated with the node. */
261
+ _data;
262
+ /**
263
+ * Creates a new node.
264
+ *
265
+ * @param id - The unique identifier of the node.
266
+ * @param content - The content of the node.
267
+ * @throws {@link JsMindError} If the node ID or content is invalid.
268
+ */
269
+ constructor(id, content) {
270
+ if (!id) {
271
+ throw new JsMindError('Invalid node id');
272
+ }
273
+ if (!content) {
274
+ throw new JsMindError('Content is required');
275
+ }
276
+ this.id = id;
277
+ this.content = content;
278
+ this.parent = null;
279
+ this.children = [];
280
+ this.folded = false;
281
+ this.side = JmNodeSide.SideA;
282
+ this.data = {};
283
+ this._data = new NodeInternalData();
284
+ }
285
+ /**
286
+ * Lists all subnode IDs recursively.
287
+ *
288
+ * @returns Array of all subnode IDs including this node's children and their descendants.
289
+ */
290
+ getAllSubnodeIds() {
291
+ const nodeIds = [];
292
+ if (this.children.length > 0) {
293
+ this.children.forEach((node) => {
294
+ nodeIds.push(node.id);
295
+ nodeIds.push(...node.getAllSubnodeIds());
296
+ });
297
+ }
298
+ return nodeIds;
299
+ }
300
+ /**
301
+ * Compares this node with another node.
302
+ *
303
+ * @param other - The other node to compare with.
304
+ * @returns True if they are equal, false otherwise.
305
+ */
306
+ equals(other) {
307
+ return this.id === other.id
308
+ && this.content.type === other.content.type
309
+ && this.content.value === other.content.value
310
+ && this.folded === other.folded
311
+ && this.side === other.side
312
+ && ((this.parent === null && other.parent === null) || (this.parent.id === other.parent.id))
313
+ && this.children.length === other.children.length
314
+ && this.children.every((child, idx, _) => { return child.id === other.children[idx].id; });
315
+ }
316
+ /**
317
+ * Checks if this node is a descendant of another node.
318
+ *
319
+ * @param potentialAncestor - The potential ancestor node.
320
+ * @returns True if this node is a descendant of potentialAncestor.
321
+ */
322
+ isDescendant(potentialAncestor) {
323
+ if (!potentialAncestor || !potentialAncestor.children) {
324
+ return false;
325
+ }
326
+ for (const child of potentialAncestor.children) {
327
+ if (child.id === this.id) {
328
+ return true;
329
+ }
330
+ if (this.isDescendant(child)) {
331
+ return true;
332
+ }
333
+ }
334
+ return false;
335
+ }
336
+ isRoot() {
337
+ return this.parent === null;
338
+ }
339
+ }
340
+ /**
341
+ * Enumeration for directions of node.
342
+ *
343
+ * @public
344
+ */
345
+ const JmNodeSide = {
346
+ /** Left direction. */
347
+ SideB: -1,
348
+ /** Center direction. */
349
+ Center: 0,
350
+ /** Right direction. */
351
+ SideA: 1,
352
+ };
353
+
354
+ /**
355
+ * Content types and utilities for JsMind nodes.
356
+ *
357
+ * @packageDocumentation
358
+ */
359
+ /**
360
+ * Enumeration for content types of node.
361
+ *
362
+ * @public
363
+ */
364
+ const JmNodeContentType = {
365
+ /** Text content type. */
366
+ Text: 'text',
367
+ };
368
+ /**
369
+ * Content of mind map node.
370
+ *
371
+ * @public
372
+ */
373
+ class JmNodeContent {
374
+ /** The type of the content. */
375
+ type;
376
+ /** The actual content value. */
377
+ value;
378
+ /**
379
+ * Creates a content object.
380
+ *
381
+ * @param type - The type of content.
382
+ * @param value - The actual content value.
383
+ * @throws {@link Error} If the content type is invalid.
384
+ */
385
+ constructor(type, value) {
386
+ if (!type || !Object.values(JmNodeContentType).includes(type)) {
387
+ throw new Error(`Invalid content type: ${type}`);
388
+ }
389
+ this.type = type;
390
+ this.value = value;
391
+ }
392
+ /**
393
+ * Checks if content is of specific type.
394
+ *
395
+ * @param type - The type to check.
396
+ * @returns True if content is of the specified type.
397
+ */
398
+ hasType(type) {
399
+ return this.type === type;
400
+ }
401
+ /**
402
+ * Checks if content is text type.
403
+ *
404
+ * @returns True if content is text type.
405
+ */
406
+ isText() {
407
+ return this.hasType(JmNodeContentType.Text);
408
+ }
409
+ getText() {
410
+ if (!this.isText()) {
411
+ throw new Error('Content is not text type');
412
+ }
413
+ return this.value;
414
+ }
415
+ /**
416
+ * Creates a text content object.
417
+ *
418
+ * @param text - The text content.
419
+ * @returns The content object.
420
+ */
421
+ static createText(text) {
422
+ return new JmNodeContent(JmNodeContentType.Text, text);
423
+ }
424
+ /**
425
+ * Creates a content object from an object with type and value.
426
+ *
427
+ * @param obj - The object to create content from.
428
+ * @returns The content object.
429
+ */
430
+ static fromObject(obj) {
431
+ return new JmNodeContent(obj.type, obj.value);
432
+ }
433
+ }
434
+
435
+ /**
436
+ * Plain-object helpers.
437
+ *
438
+ * @packageDocumentation
439
+ */
440
+ /**
441
+ * Merges user values over default values, returning a new object.
442
+ *
443
+ * @remarks
444
+ * A one-level merge: nested objects are replaced, not merged field by field.
445
+ * Callers that need a deeper merge must merge each nested section themselves.
446
+ *
447
+ * The user values being absent returns a copy of the defaults rather than the
448
+ * defaults themselves, so the result can be mutated without reaching back into
449
+ * whatever constant was passed in.
450
+ *
451
+ * @param defaultValues - The base values.
452
+ * @param userValues - Values to apply on top, if any.
453
+ * @returns A new object; neither input is mutated.
454
+ *
455
+ * @public
456
+ */
457
+ function mergeObjects(defaultValues, userValues) {
458
+ if (!userValues) {
459
+ return { ...defaultValues };
460
+ }
461
+ return {
462
+ ...defaultValues,
463
+ ...userValues
464
+ };
465
+ }
466
+
467
+ /**
468
+ * Metadata for the mind map.
469
+ *
470
+ * @public
471
+ */
472
+ const ViewExpanderStyle = {
473
+ Char: 'char',
474
+ Number: 'number'
475
+ };
476
+ const DEFAULT_METADATA = {
477
+ author: 'hizzgdev@163.com',
478
+ name: 'jsMind Mindmap',
479
+ version: '1.0'
480
+ };
481
+ const DEFAULT_OPTIONS = {
482
+ mind: {
483
+ rootNodeId: 'root'
484
+ },
485
+ view: {
486
+ padding: {
487
+ left: 100,
488
+ right: 100,
489
+ top: 50,
490
+ bottom: 50
491
+ },
492
+ expander: {
493
+ style: ViewExpanderStyle.Char
494
+ // expanded: '\u229D', // ⊝
495
+ // collapsed: '\u2295' // ⊕
496
+ }
497
+ },
498
+ layout: {
499
+ parentChildSpace: 30,
500
+ siblingSpace: 20,
501
+ cousinSpace: 15,
502
+ expanderSize: 13
503
+ }
504
+ };
505
+ /**
506
+ * Merges the provided options with the default options and returns a new options object.
507
+ *
508
+ * @param options - Partial options to merge with default options
509
+ * @returns A new merged options object
510
+ *
511
+ * @public
512
+ */
513
+ function mergeJsMindOptions(options) {
514
+ if (!options) {
515
+ return { ...DEFAULT_OPTIONS };
516
+ }
517
+ return {
518
+ mind: {
519
+ ...mergeObjects(DEFAULT_OPTIONS.mind, options.mind)
520
+ },
521
+ view: {
522
+ ...mergeObjects(DEFAULT_OPTIONS.view, options.view)
523
+ },
524
+ layout: {
525
+ ...mergeObjects(DEFAULT_OPTIONS.layout, options.layout)
526
+ }
527
+ };
528
+ }
529
+
530
+ /**
531
+ * Interface for generating unique IDs.
532
+ *
533
+ * @remarks
534
+ * IdGenerator is an interface for generating unique IDs.
535
+ *
536
+ * @example
537
+ * ```typescript
538
+ * class MyIdGenerator extends IdGenerator {
539
+ * constructor() {
540
+ * super();
541
+ * this._seq = 0;
542
+ * }
543
+ * newId() {
544
+ * return 'my' + (this._seq++);
545
+ * }
546
+ * }
547
+ * ```
548
+ *
549
+ * @public
550
+ */
551
+ class IdGenerator {
552
+ /**
553
+ * Generates a new unique ID.
554
+ *
555
+ * @returns A new unique ID.
556
+ * @throws {@link Error} If not implemented.
557
+ */
558
+ newId() {
559
+ throw new Error('not implemented');
560
+ }
561
+ }
562
+ /**
563
+ * Simple implementation of IdGenerator.
564
+ *
565
+ * @public
566
+ */
567
+ class SimpleIdGenerator extends IdGenerator {
568
+ /** The seed value for ID generation. */
569
+ seed;
570
+ /** The sequence counter. */
571
+ seq;
572
+ /** The prefix for generated IDs. */
573
+ prefix;
574
+ /**
575
+ * Creates a new SimpleIdGenerator instance.
576
+ *
577
+ * @param prefix - Optional prefix for generated IDs. Defaults to empty string.
578
+ */
579
+ constructor(prefix) {
580
+ super();
581
+ this.seed = new Date().getTime();
582
+ this.seq = 0;
583
+ this.prefix = prefix || '';
584
+ }
585
+ /**
586
+ * Generates a new unique ID.
587
+ *
588
+ * @returns A new unique ID with the format: prefix + (seed + seq).toString(36)
589
+ */
590
+ newId() {
591
+ this.seq++;
592
+ return this.prefix + (this.seed + this.seq).toString(36);
593
+ }
594
+ }
595
+ /**
596
+ * Global ID generator instance.
597
+ *
598
+ * @public
599
+ */
600
+ new SimpleIdGenerator('jm-');
601
+
602
+ /**
603
+ * Enumeration of mind map event types.
604
+ *
605
+ * @public
606
+ */
607
+ const JmMindEventType = {
608
+ /** Event fired when a node is added. */
609
+ NodeAdded: 1,
610
+ /** Event fired when a node is removed. */
611
+ NodeRemoved: 2,
612
+ /** Event fired when a node is updated. */
613
+ NodeUpdated: 3,
614
+ /** Event fired when a node is moved. */
615
+ NodeMoved: 4,
616
+ /** Event fired when an edge is added. */
617
+ EdgeAdded: 5,
618
+ /** Event fired when an edge is removed. */
619
+ EdgeRemoved: 6,
620
+ };
621
+
622
+ /**
623
+ * Event data containing the state change in JmMind.
624
+ *
625
+ * @public
626
+ */
627
+ class JmMindEvent {
628
+ /** The type of the event. */
629
+ type;
630
+ /** The event data. */
631
+ data;
632
+ /**
633
+ * Creates a new JmMindEvent instance.
634
+ *
635
+ * @param type - The type of the event.
636
+ * @param data - The event data.
637
+ */
638
+ constructor(type, data) {
639
+ this.type = type;
640
+ this.data = data;
641
+ }
642
+ static onNodeAdded(node) {
643
+ return new JmMindEvent(JmMindEventType.NodeAdded, new JmMindEventDataOnNodeAdded(node));
644
+ }
645
+ static onNodeRemoved(node, removedNodeIds, removedEdgeIds) {
646
+ return new JmMindEvent(JmMindEventType.NodeRemoved, new JmMindEventDataOnNodeRemoved(node, removedNodeIds, removedEdgeIds));
647
+ }
648
+ static onNodeUpdated(node, property, originValue, newValue) {
649
+ return new JmMindEvent(JmMindEventType.NodeUpdated, new JmMindEventDataOnNodeUpdated(node, property, originValue, newValue));
650
+ }
651
+ static onNodeMoved(node, oldParentId, oldPosition, oldSide) {
652
+ return new JmMindEvent(JmMindEventType.NodeMoved, new JmMindEventDataOnNodeMoved(node, oldParentId, oldPosition, oldSide));
653
+ }
654
+ static onEdgeAdded(edge) {
655
+ return new JmMindEvent(JmMindEventType.EdgeAdded, new JmMindEventDataOnEdgeAdded(edge));
656
+ }
657
+ static onEdgeRemoved(edge) {
658
+ return new JmMindEvent(JmMindEventType.EdgeRemoved, new JmMindEventDataOnEdgeRemoved(edge));
659
+ }
660
+ }
661
+ class JmMindEventDataOnNodeAdded {
662
+ node;
663
+ constructor(node) {
664
+ this.node = node;
665
+ }
666
+ }
667
+ class JmMindEventDataOnNodeRemoved {
668
+ node;
669
+ removedNodeIds;
670
+ removedEdgeIds;
671
+ constructor(node, removedNodeIds, removedEdgeIds) {
672
+ this.node = node;
673
+ this.removedNodeIds = removedNodeIds.slice();
674
+ this.removedEdgeIds = removedEdgeIds.slice();
675
+ }
676
+ }
677
+ class JmMindEventDataOnNodeUpdated {
678
+ node;
679
+ property;
680
+ originValue;
681
+ newValue;
682
+ constructor(node, property, originValue, newValue) {
683
+ this.node = node;
684
+ this.property = property;
685
+ this.originValue = originValue;
686
+ this.newValue = newValue;
687
+ }
688
+ }
689
+ class JmMindEventDataOnNodeMoved {
690
+ node;
691
+ oldParentId;
692
+ oldPosition;
693
+ oldSide;
694
+ constructor(node, oldParentId, oldPosition, oldSide) {
695
+ this.node = node;
696
+ this.oldParentId = oldParentId;
697
+ this.oldPosition = oldPosition;
698
+ this.oldSide = oldSide;
699
+ }
700
+ }
701
+ class JmMindEventDataOnEdgeAdded {
702
+ edge;
703
+ constructor(edge) {
704
+ this.edge = edge;
705
+ }
706
+ }
707
+ class JmMindEventDataOnEdgeRemoved {
708
+ edge;
709
+ constructor(edge) {
710
+ this.edge = edge;
711
+ }
712
+ }
713
+
714
+ /**
715
+ * Represents a mind map with nodes and edges.
716
+ *
717
+ * @public
718
+ */
719
+ class JmMind {
720
+ /** Metadata for the mind map. */
721
+ meta;
722
+ /** Configuration options for the mind map. */
723
+ options;
724
+ /**
725
+ * Style declaration for the mind map.
726
+ *
727
+ * @remarks
728
+ * This mind map inherits from `style.theme` (default `"default"`) and
729
+ * overrides whatever else the declaration lists. Resolution and deep
730
+ * merging happen at render time via `resolveJmStyle`, not here — this
731
+ * field only stores what the file said.
732
+ */
733
+ style;
734
+ /** Manager for observers of this mind map. */
735
+ observerManager;
736
+ /** Manager for node operations. */
737
+ nodeManager;
738
+ /** @internal Internal ID generator for nodes and edges. */
739
+ _idGenerator;
740
+ /** @internal Dictionary of all nodes by ID. */
741
+ _nodes;
742
+ /** @internal Dictionary of all edges by ID. */
743
+ _edges;
744
+ /** @internal The root node of the mind map. */
745
+ _root;
746
+ /**
747
+ * Creates a new mind map.
748
+ *
749
+ * @param metadata - Metadata for the mind map.
750
+ * @param options - Configuration options for the mind map.
751
+ */
752
+ constructor(metadata = {}, options = {}) {
753
+ this.meta = mergeObjects(DEFAULT_METADATA, metadata);
754
+ this.options = mergeObjects(DEFAULT_OPTIONS.mind, options);
755
+ this.observerManager = new JmObserverManager(this);
756
+ this.nodeManager = new JmNodeManager(this);
757
+ this._idGenerator = new SimpleIdGenerator('jm-');
758
+ this._nodes = {};
759
+ this._edges = {};
760
+ this._root = this._createRootNode();
761
+ }
762
+ /**
763
+ * Gets the root node.
764
+ *
765
+ * @returns The root node.
766
+ */
767
+ get root() {
768
+ return this.lite(this._root);
769
+ }
770
+ /**
771
+ * Adds an edge between two nodes.
772
+ *
773
+ * @param sourceNodeId - The source node ID.
774
+ * @param targetNodeId - The target node ID.
775
+ * @param type - The edge type.
776
+ * @param options - Optional edge creation options.
777
+ * @returns The created edge.
778
+ * @throws {@link JsMindError} If the source or target node does not exist.
779
+ */
780
+ addEdge(sourceNodeId, targetNodeId, type, options) {
781
+ // Validate nodes exist
782
+ this._getNodeById(sourceNodeId);
783
+ this._getNodeById(targetNodeId);
784
+ const edgeId = (options && options.edgeId) || this._idGenerator.newId();
785
+ const label = (options && options.label) || null;
786
+ const edge = new JmEdge(edgeId, sourceNodeId, targetNodeId, type, label);
787
+ if (options && options.style !== undefined) {
788
+ edge.style = options.style;
789
+ }
790
+ this._edges[edgeId] = edge;
791
+ // Emit event
792
+ this.observerManager.notifyObservers(JmMindEvent.onEdgeAdded(edge));
793
+ return edge;
794
+ }
795
+ addChildNode(content, parentId) {
796
+ if (!parentId) {
797
+ throw new JsMindError('parentId is required for addChildNode');
798
+ }
799
+ if (!content) {
800
+ throw new JsMindError('content is required for addChildNode');
801
+ }
802
+ let nodeContent;
803
+ if (content instanceof JmNodeContent) {
804
+ nodeContent = content;
805
+ }
806
+ else if (typeof content === 'string') {
807
+ nodeContent = JmNodeContent.createText(content);
808
+ }
809
+ else {
810
+ throw new JsMindError('content must be a string or a JmNodeContent object');
811
+ }
812
+ return this.addNode(nodeContent, { parentId: parentId });
813
+ }
814
+ /**
815
+ * Adds a new node to the mind map at a specific destination.
816
+ *
817
+ * @param content - Content for the new node.
818
+ * @param destOptions - Destination options (required).
819
+ * @param nodeOptions - Optional node creation options.
820
+ * @returns The created node.
821
+ * @throws {@link JsMindError} If destOptions.parentId is missing.
822
+ */
823
+ addNode(content, destOptions, nodeOptions) {
824
+ // Validate destination options
825
+ if (!destOptions || !destOptions.parentId) {
826
+ throw new JsMindError('destOptions.parentId is required for addNode');
827
+ }
828
+ // Get target parent
829
+ const targetParent = this._getNodeById(destOptions.parentId);
830
+ // Create node content
831
+ const nodeContent = content instanceof JmNodeContent ? content : JmNodeContent.fromObject(content);
832
+ // Create and initialize the node
833
+ const node = this._newNode(nodeContent, nodeOptions);
834
+ // Use existing helper method for placement
835
+ this._addNodeToParent(node, targetParent, destOptions.position);
836
+ // Apply destination side if specified
837
+ if (destOptions.side !== undefined && destOptions.side !== null) {
838
+ node.side = destOptions.side;
839
+ }
840
+ // Emit event
841
+ this.observerManager.notifyObservers(JmMindEvent.onNodeAdded(node));
842
+ return this.lite(node);
843
+ }
844
+ /**
845
+ * Finds a node from the mind map by the given ID.
846
+ *
847
+ * @param nodeId - The given node ID.
848
+ * @returns The corresponding node in this mind map if it exists, otherwise null.
849
+ */
850
+ findNodeById(nodeId) {
851
+ const node = this._nodes[nodeId];
852
+ return !!node ? this.lite(node) : null;
853
+ }
854
+ /**
855
+ * Gets all edges for a specific node.
856
+ *
857
+ * @param nodeId - The node ID.
858
+ * @param type - Optional edge type filter.
859
+ * @returns Array of edges involving the node.
860
+ */
861
+ getEdges(nodeId, type = null) {
862
+ return Object.values(this._edges).filter(edge => {
863
+ return (edge.sourceNodeId === nodeId || edge.targetNodeId === nodeId) &&
864
+ (!type || edge.type === type);
865
+ });
866
+ }
867
+ /**
868
+ * Moves a node to a new parent and position.
869
+ *
870
+ * @param nodeId - The ID of the node to move.
871
+ * @param destOptions - Destination options.
872
+ * @returns The moved node.
873
+ * @throws {@link JsMindError} If destOptions are missing, node not found, or invalid move operation.
874
+ */
875
+ moveNode(nodeId, destOptions) {
876
+ if (!destOptions || Object.keys(destOptions).length === 0) {
877
+ throw new JsMindError('destOptions are required for moveNode operation');
878
+ }
879
+ const node = this._getNodeById(nodeId);
880
+ if (!node) {
881
+ throw new JsMindError(`Node with ID '${nodeId}' not found`);
882
+ }
883
+ // Skip all logic for root node - it cannot be moved
884
+ if (node === this.root) {
885
+ return this.lite(node);
886
+ }
887
+ // Extract options
888
+ const targetParentId = destOptions.parentId;
889
+ const targetPosition = destOptions.position;
890
+ const targetSide = destOptions.side;
891
+ // Capture original values before any changes
892
+ const oldParent = node.parent;
893
+ const oldPosition = node.parent ? node.parent.children.indexOf(node) : -1;
894
+ const oldSide = node.side;
895
+ // 1. Update parent and position if the node parent is provided and changed
896
+ if (targetParentId && (!node.parent || node.parent.id !== targetParentId)) {
897
+ const targetParent = this._getNodeById(targetParentId);
898
+ if (!targetParent) {
899
+ throw new JsMindError(`Target parent with ID '${targetParentId}' not found`);
900
+ }
901
+ // Validate that we're not moving a node to be its own descendant
902
+ if (targetParent.isDescendant(node)) {
903
+ throw new JsMindError('Cannot move a node to be its own descendant');
904
+ }
905
+ // Remove from current parent
906
+ this._removeNodeFromParent(node);
907
+ // Add to new parent at specified position and create edge
908
+ this._addNodeToParent(node, targetParent, targetPosition);
909
+ }
910
+ // 2. Reposition if the node parent is not provided or is not changed, and the targetPosition is provided and changed
911
+ if ((!targetParentId || (node.parent && node.parent.id === targetParentId)) &&
912
+ targetPosition !== undefined && targetPosition !== null) {
913
+ this._repositionNode(node, targetPosition);
914
+ }
915
+ // 3. Update side if the target side is provided and changed
916
+ if (targetSide !== undefined && targetSide !== null) {
917
+ node.side = targetSide;
918
+ }
919
+ // 4. Emit event only if something actually changed
920
+ this._emitNodeMovedEventIfChanged(node, oldParent, oldPosition, oldSide);
921
+ return this.lite(node);
922
+ }
923
+ /**
924
+ * Removes an edge by ID.
925
+ *
926
+ * @param edgeId - The edge ID to remove.
927
+ * @returns True if the edge was removed, false if not found.
928
+ */
929
+ removeEdge(edgeId) {
930
+ const edge = this._edges[edgeId];
931
+ if (edge) {
932
+ delete this._edges[edgeId];
933
+ // Emit event
934
+ this.observerManager.notifyObservers(JmMindEvent.onEdgeRemoved(edge));
935
+ return true;
936
+ }
937
+ return false;
938
+ }
939
+ /**
940
+ * Removes a node and all its descendants.
941
+ *
942
+ * @param nodeId - The ID of the node to remove.
943
+ * @throws {@link JsMindError} If trying to remove the root node.
944
+ */
945
+ removeNode(nodeId) {
946
+ const node = this._getNodeById(nodeId);
947
+ if (nodeId == this._root.id) {
948
+ throw new JsMindError('root node can not be removed');
949
+ }
950
+ // remove node from parent's children
951
+ const nodeIndex = node.parent.children.indexOf(node);
952
+ node.parent.children.splice(nodeIndex, 1);
953
+ // identify all nodes that need to be cleared
954
+ const nodeIds = node.getAllSubnodeIds();
955
+ nodeIds.push(node.id);
956
+ // remove those nodes
957
+ nodeIds.forEach((id) => delete this._nodes[id]);
958
+ // remove all relevant edges
959
+ const edgeIds = Object.values(this._edges)
960
+ .filter((e) => nodeIds.includes(e.sourceNodeId) || nodeIds.includes(e.targetNodeId))
961
+ .map((e) => e.id);
962
+ edgeIds.forEach((id) => delete this._edges[id]);
963
+ // emit event
964
+ this.observerManager.notifyObservers(JmMindEvent.onNodeRemoved(node, nodeIds, edgeIds));
965
+ }
966
+ /**
967
+ * Adds a node to a new parent at a specific position.
968
+ *
969
+ * @private
970
+ * @param node - The node to add.
971
+ * @param targetParent - The new parent node.
972
+ * @param targetPosition - The position index among siblings.
973
+ */
974
+ _addNodeToParent(node, targetParent, targetPosition) {
975
+ node.parent = targetParent;
976
+ if (targetPosition === undefined || targetPosition === null) {
977
+ // Add to the end if no position specified
978
+ targetParent.children.push(node);
979
+ }
980
+ else {
981
+ // Insert at specific position
982
+ const position = Math.max(0, Math.min(targetPosition, targetParent.children.length));
983
+ targetParent.children.splice(position, 0, node);
984
+ }
985
+ }
986
+ /**
987
+ * Creates the root node.
988
+ *
989
+ * @private
990
+ * @returns The created root node.
991
+ */
992
+ _createRootNode() {
993
+ const nodeOptions = {
994
+ nodeId: this.options.rootNodeId,
995
+ side: JmNodeSide.Center
996
+ };
997
+ return this._newNode(JmNodeContent.createText(this.meta.name), nodeOptions);
998
+ }
999
+ /**
1000
+ * Emits NodeMoved event only if something actually changed.
1001
+ *
1002
+ * @private
1003
+ * @param node - The node that was moved.
1004
+ * @param oldParent - The old parent node.
1005
+ * @param oldPosition - The old position index.
1006
+ * @param oldSide - The old side.
1007
+ */
1008
+ _emitNodeMovedEventIfChanged(node, oldParent, oldPosition, oldSide) {
1009
+ // Compare actual updated node properties with old values
1010
+ const parentChanged = oldParent.id !== node.parent.id;
1011
+ const positionChanged = oldPosition !== node.parent.children.indexOf(node);
1012
+ const sideChanged = oldSide !== node.side;
1013
+ if (parentChanged || positionChanged || sideChanged) {
1014
+ const oldParentId = parentChanged ? oldParent.id : null;
1015
+ const oldPositionData = positionChanged ? oldPosition : null;
1016
+ const oldSideData = sideChanged ? oldSide : null;
1017
+ this.observerManager.notifyObservers(JmMindEvent.onNodeMoved(node, oldParentId, oldPositionData, oldSideData));
1018
+ }
1019
+ }
1020
+ /**
1021
+ * Creates a new node and adds it to the mind map.
1022
+ *
1023
+ * @private
1024
+ * @param content - Content for the node.
1025
+ * @param nodeOptions - Optional node creation options.
1026
+ * @returns The created node.
1027
+ */
1028
+ _newNode(content, nodeOptions) {
1029
+ const nodeId = (nodeOptions && nodeOptions.nodeId) || this._idGenerator.newId();
1030
+ const node = new JmNode(nodeId, content);
1031
+ if (nodeOptions) {
1032
+ if (nodeOptions.folded !== undefined) {
1033
+ node.folded = nodeOptions.folded;
1034
+ }
1035
+ if (nodeOptions.side !== undefined) {
1036
+ node.side = nodeOptions.side;
1037
+ }
1038
+ if (nodeOptions.data !== undefined) {
1039
+ node.data = nodeOptions.data;
1040
+ }
1041
+ if (nodeOptions.style !== undefined) {
1042
+ node.style = nodeOptions.style;
1043
+ }
1044
+ }
1045
+ this._nodes[nodeId] = node;
1046
+ return node;
1047
+ }
1048
+ /**
1049
+ * Handles node update events.
1050
+ *
1051
+ * @private
1052
+ * @param node - The node that was updated.
1053
+ * @param prop - The property that was updated.
1054
+ * @param originValue - The original value.
1055
+ * @param newValue - The new value.
1056
+ */
1057
+ _onNodeUpdated(node, prop, originValue, newValue) {
1058
+ this.observerManager.notifyObservers(JmMindEvent.onNodeUpdated(node, prop, originValue, newValue));
1059
+ }
1060
+ /**
1061
+ * Removes a node from its current parent.
1062
+ *
1063
+ * @private
1064
+ * @param node - The node to remove from parent.
1065
+ */
1066
+ _removeNodeFromParent(node) {
1067
+ if (!node.parent) {
1068
+ return;
1069
+ }
1070
+ const parent = node.parent;
1071
+ const index = parent.children.indexOf(node);
1072
+ if (index > -1) {
1073
+ parent.children.splice(index, 1);
1074
+ }
1075
+ node.parent = null;
1076
+ }
1077
+ /**
1078
+ * Repositions a node within the same parent (optimized operation).
1079
+ *
1080
+ * @private
1081
+ * @param node - The node to reposition.
1082
+ * @param targetPosition - The new position index among siblings.
1083
+ */
1084
+ _repositionNode(node, targetPosition) {
1085
+ if (targetPosition === undefined || targetPosition === null) {
1086
+ return;
1087
+ }
1088
+ const parent = node.parent;
1089
+ const currentIndex = parent.children.indexOf(node);
1090
+ const newPosition = Math.max(0, Math.min(targetPosition, parent.children.length));
1091
+ if (currentIndex !== newPosition) {
1092
+ parent.children.splice(currentIndex, 1);
1093
+ parent.children.splice(newPosition, 0, node);
1094
+ }
1095
+ }
1096
+ /**
1097
+ * Retrieves a node by node ID.
1098
+ *
1099
+ * @private
1100
+ * @param nodeId - The node ID.
1101
+ * @returns The corresponding node.
1102
+ * @throws {@link JsMindError} If the node doesn't exist.
1103
+ */
1104
+ _getNodeById(nodeId) {
1105
+ const node = this._nodes[nodeId];
1106
+ if (!!node) {
1107
+ return node;
1108
+ }
1109
+ throw new JsMindError(`node[id=${nodeId}] does not exist`);
1110
+ }
1111
+ lite(node) {
1112
+ return this.nodeManager.manage(node);
1113
+ }
1114
+ }
1115
+ /**
1116
+ * Manager for node operations with proxy-based access control.
1117
+ *
1118
+ * @internal
1119
+ */
1120
+ class JmNodeManager {
1121
+ /** The mind map instance. */
1122
+ mind;
1123
+ /** Set of readonly field names. */
1124
+ readonlyFields;
1125
+ /** Set of unsafe array method names. */
1126
+ unsafeArrayMethods;
1127
+ /**
1128
+ * Creates a new JmNodeManager instance.
1129
+ *
1130
+ * @param mind - The mind map instance.
1131
+ */
1132
+ constructor(mind) {
1133
+ this.mind = mind;
1134
+ this.readonlyFields = new Set(['id', 'parent', 'children', 'data']);
1135
+ this.unsafeArrayMethods = new Set(['fill', 'pop', 'push', 'shift', 'unshift', 'reverse', 'sort', 'splice']);
1136
+ }
1137
+ /**
1138
+ * Manages a node with proxy-based access control.
1139
+ *
1140
+ * @param node - The node to manage.
1141
+ * @returns The managed node with proxy.
1142
+ */
1143
+ manage(node) {
1144
+ return new Proxy(node, {
1145
+ get: this.getterTrap.bind(this),
1146
+ set: this.setterTrap.bind(this)
1147
+ });
1148
+ }
1149
+ /**
1150
+ * Getter trap for the proxy.
1151
+ *
1152
+ * @param node - The node.
1153
+ * @param prop - The property name.
1154
+ * @returns The property value.
1155
+ */
1156
+ getterTrap(node, prop) {
1157
+ const ori = node[prop];
1158
+ if (prop === 'children') {
1159
+ const itemManagedArray = ori.map((n) => this.manage(n));
1160
+ return new Proxy(itemManagedArray, {
1161
+ get: (arr, prop) => {
1162
+ if (this.unsafeArrayMethods.has(prop)) {
1163
+ return function () {
1164
+ throw new JsMindError(`unsupported method ${String(prop)} on node.children, please follow the document to operate the mindmap.`);
1165
+ };
1166
+ }
1167
+ return arr[prop];
1168
+ }
1169
+ });
1170
+ }
1171
+ if (prop === 'parent') {
1172
+ return !!ori ? this.manage(ori) : null;
1173
+ }
1174
+ return ori;
1175
+ }
1176
+ /**
1177
+ * Setter trap for the proxy.
1178
+ *
1179
+ * @param node - The node.
1180
+ * @param prop - The property name.
1181
+ * @param value - The new value.
1182
+ * @returns True if the operation succeeded.
1183
+ * @throws {@link JsMindError} If trying to set a readonly property.
1184
+ */
1185
+ setterTrap(node, prop, value) {
1186
+ if (this.readonlyFields.has(prop)) {
1187
+ throw new JsMindError(`the property[${String(prop)}] is readonly`);
1188
+ }
1189
+ const ori = node[prop];
1190
+ if (ori !== value) {
1191
+ node[prop] = value;
1192
+ this.mind._onNodeUpdated(node, prop, ori, value);
1193
+ }
1194
+ return true;
1195
+ }
1196
+ }
1197
+
1198
+ const untilNextFrame = () => {
1199
+ return new Promise(resolve => {
1200
+ requestAnimationFrame(resolve);
1201
+ });
1202
+ };
1203
+ class JmDomUtility {
1204
+ static createElement(tagName, className, jmAttrs = {}) {
1205
+ const element = document.createElement(tagName);
1206
+ const jmElement = new JmElement(element);
1207
+ jmElement.classList.add(className);
1208
+ for (const [key, value] of Object.entries(jmAttrs)) {
1209
+ jmElement.setAttribute(key, value);
1210
+ }
1211
+ return jmElement;
1212
+ }
1213
+ static async measureElement(element, container) {
1214
+ const element_ = element instanceof JmElement ? element.element : element;
1215
+ const container_ = container instanceof JmElement ? container.element : container;
1216
+ return await DomUtility.measureElement(element_, container_);
1217
+ }
1218
+ }
1219
+ class DomUtility {
1220
+ static createElement(tagName, className) {
1221
+ const element = document.createElement(tagName);
1222
+ element.classList.add(className);
1223
+ return element;
1224
+ }
1225
+ static async measureElement(element, container) {
1226
+ const originalDisplay = element.style.display;
1227
+ const originalVisibility = element.style.visibility;
1228
+ element.style.visibility = 'hidden';
1229
+ if (originalDisplay === 'none') {
1230
+ element.style.display = 'unset';
1231
+ }
1232
+ container.appendChild(element);
1233
+ await untilNextFrame();
1234
+ const rect = element.getBoundingClientRect();
1235
+ container.removeChild(element);
1236
+ element.style.display = originalDisplay;
1237
+ element.style.visibility = originalVisibility;
1238
+ return rect;
1239
+ }
1240
+ static async ensureElementVisible(element) {
1241
+ return new Promise((resolve) => {
1242
+ new IntersectionObserver((entities, observer) => {
1243
+ if (entities[0]?.isIntersecting) {
1244
+ observer.unobserve(element);
1245
+ resolve();
1246
+ }
1247
+ }).observe(element);
1248
+ });
1249
+ }
1250
+ ;
1251
+ }
1252
+ class JmElement {
1253
+ ATTR_PREFIX = 'data-jm-';
1254
+ _element;
1255
+ _cachedRect = null;
1256
+ constructor(element) {
1257
+ if (!element) {
1258
+ throw new Error('Element is required');
1259
+ }
1260
+ this._element = element;
1261
+ }
1262
+ get element() {
1263
+ return this._element;
1264
+ }
1265
+ get classList() {
1266
+ return this._element.classList;
1267
+ }
1268
+ get innerHTML() {
1269
+ return this._element.innerHTML;
1270
+ }
1271
+ set innerHTML(value) {
1272
+ this._element.innerHTML = value;
1273
+ }
1274
+ get cachedRect() {
1275
+ if (!this._cachedRect) {
1276
+ throw new JsMindError('Rect is not measured yet', { element: this._element });
1277
+ }
1278
+ return this._cachedRect;
1279
+ }
1280
+ set cachedRect(rect) {
1281
+ this._cachedRect = rect;
1282
+ }
1283
+ get style() {
1284
+ return this._element.style;
1285
+ }
1286
+ get clientWidth() {
1287
+ return this._element.clientWidth;
1288
+ }
1289
+ get clientHeight() {
1290
+ return this._element.clientHeight;
1291
+ }
1292
+ hide() {
1293
+ this._element.style.visibility = 'hidden';
1294
+ this._element.style.top = '0px';
1295
+ this._element.style.left = '0px';
1296
+ }
1297
+ show(position) {
1298
+ this._element.style.top = `${position.y}px`;
1299
+ this._element.style.left = `${position.x}px`;
1300
+ this._element.style.visibility = 'visible';
1301
+ }
1302
+ setAttribute(key, value) {
1303
+ this._element.setAttribute(this.ATTR_PREFIX + key, value);
1304
+ }
1305
+ getAttribute(key) {
1306
+ return this._element.getAttribute(this.ATTR_PREFIX + key);
1307
+ }
1308
+ removeAttribute(key) {
1309
+ this._element.removeAttribute(this.ATTR_PREFIX + key);
1310
+ }
1311
+ appendChild(child) {
1312
+ if (child instanceof JmElement) {
1313
+ this._element.appendChild(child.element);
1314
+ }
1315
+ else {
1316
+ this._element.appendChild(child);
1317
+ }
1318
+ }
1319
+ }
1320
+
1321
+ /**
1322
+ * Style and theme data structures for JsMind mind maps.
1323
+ *
1324
+ * @remarks
1325
+ * This module only defines data. Nothing here draws anything — the rendering
1326
+ * layer consumes these values but never appears in this file.
1327
+ *
1328
+ * @packageDocumentation
1329
+ */
1330
+ /**
1331
+ * Semantic tone. Expresses color only, never geometry.
1332
+ *
1333
+ * @remarks
1334
+ * Semantic roles are about color; geometry is orthogonal (a node can be
1335
+ * warning-colored, thick-bordered and large-font at once). Keeping them apart
1336
+ * gives the agent fewer side effects per change, which makes generated output
1337
+ * more controllable.
1338
+ *
1339
+ * @public
1340
+ */
1341
+ const JmTone = {
1342
+ /** Default tone, resolved from the theme's neutral palette. */
1343
+ Default: 'default',
1344
+ /** Primary or emphasis tone. */
1345
+ Primary: 'primary',
1346
+ /** Success or positive tone. */
1347
+ Success: 'success',
1348
+ /** Warning or caution tone. */
1349
+ Warning: 'warning',
1350
+ /** Danger or negative tone. */
1351
+ Danger: 'danger',
1352
+ /** Informational or neutral-accent tone. */
1353
+ Info: 'info',
1354
+ /**
1355
+ * Accent tone for an element that stands out without carrying a judgement.
1356
+ *
1357
+ * @remarks
1358
+ * `primary` already means "this is the important one", which is a claim
1359
+ * about the content. `accent` is the option for "make this one visually
1360
+ * distinct" with no claim attached — the purple that v1 exposed as
1361
+ * `theme-wisteria` and that none of the semantic tones could absorb.
1362
+ */
1363
+ Accent: 'accent',
1364
+ };
1365
+ /**
1366
+ * Line dash style.
1367
+ *
1368
+ * @public
1369
+ */
1370
+ const JmLinePattern = {
1371
+ /** Continuous line. */
1372
+ Solid: 'solid',
1373
+ /** Dashed line. */
1374
+ Dashed: 'dashed',
1375
+ /** Dotted line. */
1376
+ Dotted: 'dotted',
1377
+ };
1378
+ /**
1379
+ * How a line travels between its two endpoints.
1380
+ *
1381
+ * @remarks
1382
+ * A different axis from {@link JmLinePattern}: `pattern` says whether the
1383
+ * stroke is dashed, `curve` says what shape it traces. They are separable on
1384
+ * purpose - a straight dashed line and a curved dashed line both need to exist,
1385
+ * and a single `style` string (as in v1's `line_style`) could only ever express
1386
+ * one of the two.
1387
+ *
1388
+ * @public
1389
+ */
1390
+ const JmLineCurve = {
1391
+ /** Straight segment from one endpoint to the other. */
1392
+ Straight: 'straight',
1393
+ /**
1394
+ * Cubic bezier leaving each endpoint horizontally.
1395
+ *
1396
+ * @remarks
1397
+ * The default, and what v1 drew. Edges leaving a node always read better
1398
+ * when they depart along the horizontal axis: siblings sit in a column, so a
1399
+ * straight segment between two of them cuts diagonally across the layout.
1400
+ */
1401
+ Bezier: 'bezier',
1402
+ };
1403
+ /**
1404
+ * The only theme built into this version.
1405
+ *
1406
+ * @remarks
1407
+ * Dark mode is a separate theme, not a light/dark variant pair of the same
1408
+ * theme, because a dark palette is not a mechanical inversion of a light one.
1409
+ *
1410
+ * @public
1411
+ */
1412
+ const JSMIND_THEME_DEFAULT = {
1413
+ background: '#ffffff',
1414
+ // Filled solids with white text, taken from v1 — a node carrying a tone
1415
+ // that only tints its background barely reads as "this one is different"
1416
+ // from across the canvas. The v1 palette names that map onto these tones
1417
+ // (belizehole, nephrite, pumpkin, pomegranate) are the same hue a few
1418
+ // degrees away, so they fold in rather than getting their own entry.
1419
+ tones: {
1420
+ default: { fillColor: '#ffffff', textColor: '#333333', borderColor: '#cccccc', lineColor: '#b0b0b0' },
1421
+ primary: { fillColor: '#428bca', textColor: '#ffffff', borderColor: '#357ebd', lineColor: '#689ece' },
1422
+ success: { fillColor: '#5cb85c', textColor: '#ffffff', borderColor: '#4cae4c', lineColor: '#79c279' },
1423
+ warning: { fillColor: '#f0ad4e', textColor: '#ffffff', borderColor: '#eea236', lineColor: '#f2b968' },
1424
+ danger: { fillColor: '#d9534f', textColor: '#ffffff', borderColor: '#d43f3a', lineColor: '#df6f6b' },
1425
+ info: { fillColor: '#5dc0de', textColor: '#ffffff', borderColor: '#46b8da', lineColor: '#74cae3' },
1426
+ accent: { fillColor: '#9b59b6', textColor: '#ffffff', borderColor: '#8e44ad', lineColor: '#aa73c2' },
1427
+ },
1428
+ node: {
1429
+ radius: 5,
1430
+ padding: 10,
1431
+ fontSize: 16,
1432
+ rootFontSize: 24,
1433
+ fontFamily: 'Verdana, Arial, Helvetica, sans-serif',
1434
+ lineHeight: 1.125,
1435
+ // Zero, because the stylesheet drew no border: the depth came from the
1436
+ // shadow below. Tone palettes still carry a borderColor for themes that
1437
+ // do want one.
1438
+ borderWidth: 0,
1439
+ maxWidth: 400,
1440
+ shadow: {
1441
+ normal: { offsetX: 1, offsetY: 1, blur: 1, color: '#666666' },
1442
+ hover: { offsetX: 2, offsetY: 2, blur: 8, color: '#000000' },
1443
+ selected: { offsetX: 2, offsetY: 2, blur: 8, color: '#000000' },
1444
+ },
1445
+ },
1446
+ line: {
1447
+ width: 2,
1448
+ pattern: JmLinePattern.Solid,
1449
+ curve: JmLineCurve.Bezier,
1450
+ },
1451
+ expander: {
1452
+ size: 13,
1453
+ radius: 6.5,
1454
+ fontSize: 8,
1455
+ lineHeight: 11,
1456
+ borderWidth: 1,
1457
+ },
1458
+ };
1459
+ /**
1460
+ * Built-in theme presets, keyed by name.
1461
+ *
1462
+ * @public
1463
+ */
1464
+ const JSMIND_THEME_PRESETS = {
1465
+ default: JSMIND_THEME_DEFAULT,
1466
+ };
1467
+ /**
1468
+ * Checks whether a value is a plain object that can be merged.
1469
+ *
1470
+ * @param value - The value to check.
1471
+ * @returns True for plain objects, false for arrays, null and primitives.
1472
+ */
1473
+ function isPlainObject(value) {
1474
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
1475
+ }
1476
+ /**
1477
+ * Deeply merges theme overrides onto a base theme.
1478
+ *
1479
+ * @remarks
1480
+ * A shallow merge is not enough. `tones: { primary: { fill: "#f00" } }` merged
1481
+ * shallowly would replace the whole `primary` entry, dropping `text`, `border`
1482
+ * and `line`, and the node would render black-on-black. Deep merge keeps the
1483
+ * fields the override did not mention.
1484
+ *
1485
+ * @param base - The theme to merge onto.
1486
+ * @param override - The partial theme to apply.
1487
+ * @returns A new merged theme; neither input is mutated.
1488
+ *
1489
+ * @public
1490
+ */
1491
+ function mergeJmTheme(base, override) {
1492
+ const result = { ...base };
1493
+ // `theme` names the preset to inherit from and is consumed by
1494
+ // resolveJmStyle before this runs, so there is nothing to carry over here.
1495
+ if (override.background !== undefined) {
1496
+ result.background = override.background;
1497
+ }
1498
+ // node/line/expander each hold scalars, so they merge one level deep with
1499
+ // the same flat merge the options layer uses. Spread the base first:
1500
+ // mergeObjects replaces a missing default wholesale, which would drop
1501
+ // every field the override did not mention.
1502
+ if (override.node) {
1503
+ // `shadow` is decomposed first: it nests further than the rest
1504
+ // (state -> layer), and `mergeObjects` cannot express that in one call.
1505
+ const { shadow: shadowOverride, ...nodeRest } = override.node;
1506
+ const merged = mergeObjects({ ...base.node }, nodeRest);
1507
+ // A shallow merge would let an override that only restyles `hover`
1508
+ // replace the whole shadow block, dropping `normal` and `selected` and
1509
+ // leaving the node with no resting shadow at all.
1510
+ const baseShadow = base.node?.shadow;
1511
+ if (baseShadow && shadowOverride) {
1512
+ merged.shadow = mergeShadow(baseShadow, shadowOverride);
1513
+ }
1514
+ result.node = merged;
1515
+ }
1516
+ if (override.line) {
1517
+ result.line = mergeObjects({ ...base.line }, override.line);
1518
+ }
1519
+ if (override.expander) {
1520
+ result.expander = mergeObjects({ ...base.expander }, override.expander);
1521
+ }
1522
+ // `tones` is the one section nested two levels deep: tone -> palette. Each
1523
+ // palette must be merged field by field, or an override that names only
1524
+ // `fillColor` would drop textColor/borderColor/lineColor and the node
1525
+ // would render black on black.
1526
+ if (override.tones) {
1527
+ result.tones = mergeTonePalettes(base.tones, override.tones);
1528
+ }
1529
+ return result;
1530
+ }
1531
+ /**
1532
+ * Merges shadow overrides into a complete shadow.
1533
+ *
1534
+ * @remarks
1535
+ * Two levels deep: state, then layer. Each state the override does not mention
1536
+ * is passed through, and each layer is merged field by field so `hover.blur`
1537
+ * alone is a legal override.
1538
+ *
1539
+ * @param base - The complete shadow to merge onto.
1540
+ * @param override - The partial shadow to apply.
1541
+ * @returns A new complete shadow; neither input is mutated.
1542
+ *
1543
+ * @private
1544
+ */
1545
+ function mergeShadow(base, override) {
1546
+ const result = { ...base };
1547
+ for (const state of ['normal', 'hover', 'selected']) {
1548
+ const layer = override[state];
1549
+ if (layer) {
1550
+ result[state] = mergeObjects({ ...base[state] }, layer);
1551
+ }
1552
+ }
1553
+ return result;
1554
+ }
1555
+ /**
1556
+ * Merges tone palette overrides into a set of palettes.
1557
+ *
1558
+ * @remarks
1559
+ * Per tone, the palette is merged field by field. Tones the override does not
1560
+ * mention are passed through untouched.
1561
+ *
1562
+ * @param base - The palettes to merge onto, possibly absent.
1563
+ * @param override - The per-tone overrides to apply.
1564
+ * @returns New palettes; neither input is mutated.
1565
+ *
1566
+ * @private
1567
+ */
1568
+ function mergeTonePalettes(base, override) {
1569
+ const tones = { ...base };
1570
+ for (const key of Object.keys(override)) {
1571
+ const overridePalette = override[key];
1572
+ if (!overridePalette) {
1573
+ continue;
1574
+ }
1575
+ tones[key] = mergeObjects(tones[key], overridePalette);
1576
+ }
1577
+ return tones;
1578
+ }
1579
+ /**
1580
+ * Resolves a style declaration into a complete theme.
1581
+ *
1582
+ * @remarks
1583
+ * `style.theme` picks the preset to inherit from (default `"default"`), then
1584
+ * every other field in `style` is merged on top of it, deeply.
1585
+ *
1586
+ * @param style - The style declaration, if the data carried one.
1587
+ * @returns A fully populated theme; never partial.
1588
+ * @throws {@link Error} If the named preset does not exist.
1589
+ *
1590
+ * @public
1591
+ */
1592
+ function resolveJmStyle(style) {
1593
+ if (style === undefined || style === null) {
1594
+ return { ...JSMIND_THEME_DEFAULT };
1595
+ }
1596
+ if (!isPlainObject(style)) {
1597
+ throw new Error('invalid style declaration');
1598
+ }
1599
+ const themeName = style.theme ?? 'default';
1600
+ if (typeof themeName !== 'string') {
1601
+ throw new Error('invalid theme name');
1602
+ }
1603
+ const preset = JSMIND_THEME_PRESETS[themeName];
1604
+ if (!preset) {
1605
+ throw new Error(`unknown theme: ${themeName}`);
1606
+ }
1607
+ return mergeJmTheme(preset, style);
1608
+ }
1609
+
1610
+ /**
1611
+ * @license BSD
1612
+ * @copyright 2014-2025 hizzgdev@163.com
1613
+ *
1614
+ * Project Home:
1615
+ * https://github.com/hizzgdev/jsmind-v2/
1616
+ */
1617
+ /**
1618
+ * Styles installed into the shadow root.
1619
+ *
1620
+ * @remarks
1621
+ * Two kinds of rule live here.
1622
+ *
1623
+ * Positioning (`absolute`, `z-index`, `overflow`) is decided here and nowhere
1624
+ * else. It is how the renderer finds room for a node at a coordinate it
1625
+ * computed, not a matter of taste, so it is not a theme field.
1626
+ *
1627
+ * Everything that decides how a node *looks* reads a custom property rather
1628
+ * than naming a value. Those values come from the theme, written onto the host
1629
+ * element by {@link applyThemeToHost}. The indirection is what lets one
1630
+ * stylesheet serve every theme while a single node still carries its own tone
1631
+ * color: custom properties inherit, so a value set on one node wins for that
1632
+ * node alone.
1633
+ *
1634
+ * These rules used to be an external stylesheet the caller had to remember to
1635
+ * load. Forgetting it stacked every node at 0,0 and reported no error.
1636
+ *
1637
+ * @private
1638
+ */
1639
+ const JSMIND_VIEW_STYLES = `
1640
+ :host {
1641
+ display: block;
1642
+ position: relative;
1643
+ width: 100%;
1644
+ height: 100%;
1645
+ outline: none;
1646
+ -webkit-user-select: none;
1647
+ user-select: none;
1648
+ background-color: var(--jm-background);
1649
+ }
1650
+
1651
+ .jsmind-inner {
1652
+ position: relative;
1653
+ overflow: auto;
1654
+ width: 100%;
1655
+ height: 100%;
1656
+ outline: none;
1657
+ -webkit-user-select: none;
1658
+ user-select: none;
1659
+ }
1660
+
1661
+ /* Transparent, not omitted: a node is appended here to be measured, and
1662
+ the box needs its own background layer or the measured width collapses. */
1663
+ .jsmind-nodes {
1664
+ position: absolute;
1665
+ z-index: 2;
1666
+ background-color: rgba(0, 0, 0, 0);
1667
+ }
1668
+
1669
+ .jsmind-edges {
1670
+ position: absolute;
1671
+ z-index: 1;
1672
+ }
1673
+
1674
+ .jsmind-node {
1675
+ position: absolute;
1676
+ cursor: default;
1677
+
1678
+ padding: var(--jm-node-padding);
1679
+ border-radius: var(--jm-node-radius);
1680
+ border: var(--jm-node-border-width) solid var(--jm-node-border-color);
1681
+ max-width: var(--jm-node-max-width);
1682
+ font-family: var(--jm-node-font-family);
1683
+ font-size: var(--jm-node-font-size);
1684
+ line-height: var(--jm-node-line-height);
1685
+ background-color: var(--jm-node-fill);
1686
+ color: var(--jm-node-text);
1687
+ box-shadow: var(--jm-node-shadow-normal);
1688
+ }
1689
+
1690
+ /* Hover and selection change colour as well as shadow. Those two colours
1691
+ are interaction state, not theme: the theme describes what a node looks
1692
+ like at rest, and its tones say what a node means. Folding state colours
1693
+ into that would make --jm-node-fill mean two things at once. */
1694
+ .jsmind-node:hover {
1695
+ box-shadow: var(--jm-node-shadow-hover);
1696
+ background-color: #ebebeb;
1697
+ color: #333333;
1698
+ }
1699
+
1700
+ .jsmind-node-selected {
1701
+ box-shadow: var(--jm-node-shadow-selected);
1702
+ background-color: #11f;
1703
+ color: #ffffff;
1704
+ }
1705
+
1706
+ .jsmind-node-root {
1707
+ font-size: var(--jm-node-root-font-size);
1708
+ }
1709
+
1710
+ /* The expander is a control, not content. Size and radius are theme fields
1711
+ because they belong to the layout budget; everything else here — the
1712
+ transparent fill, the clipping, the 18px glyph below — is how the control
1713
+ itself is drawn and is fixed.
1714
+ *
1715
+ * No border on this variant. A border here would sit inside border-box and
1716
+ shrink the content area to 11px, so a 13px-wide glyph would be clipped
1717
+ unevenly and read as off-centre. The number variant is the one with a
1718
+ border, and it is declared there. */
1719
+ .jsmind-node-expander {
1720
+ position: absolute;
1721
+ overflow: hidden;
1722
+ cursor: pointer;
1723
+
1724
+ /* Flex centring rather than text-align plus a negative margin-top.
1725
+ The glyph is 18px inside a 13px box, so it overflows on both axes and
1726
+ the clipping has to be even. text-align centres the line box, but
1727
+ where the ink sits inside that line box comes from the font's ascent
1728
+ and side bearings — which differ between Arial, DejaVu, Liberation
1729
+ and whatever a given machine substitutes. A hand-tuned margin
1730
+ compensates for exactly one font and reads as a 1px drift on every
1731
+ other. Flex centres the painted glyph itself. */
1732
+ display: flex;
1733
+ align-items: center;
1734
+ justify-content: center;
1735
+
1736
+ width: var(--jm-expander-size);
1737
+ height: var(--jm-expander-size);
1738
+ border-radius: var(--jm-expander-radius);
1739
+ box-sizing: border-box;
1740
+ }
1741
+
1742
+ /* 18px glyph inside a 13px circle: deliberately larger than the box, with
1743
+ the overhang clipped on both sides. Sizing it to match node text instead
1744
+ would let a theme's font size push the +/- out of the control. */
1745
+ .jsmind-node-expander-expanded::after {
1746
+ font-family: Arial, sans-serif;
1747
+ font-size: 18px;
1748
+ line-height: 1;
1749
+ content: '\\229D';
1750
+ }
1751
+
1752
+ .jsmind-node-expander-collapsed::after {
1753
+ font-family: Arial, sans-serif;
1754
+ font-size: 18px;
1755
+ line-height: 1;
1756
+ content: '\\2295';
1757
+ }
1758
+
1759
+ /* The only variant that draws a border, and it keeps the neutral #666 the
1760
+ v1 stylesheet used. Not var(--jm-node-border-color): that would follow the
1761
+ node's tone, and the default tone's border is #cccccc — a barely visible
1762
+ ring on a white background. The control is an affordance drawn beside the
1763
+ node, not part of what the node means. */
1764
+ .jsmind-node-expander-number {
1765
+ font-size: var(--jm-expander-font-size);
1766
+ text-align: center;
1767
+ line-height: var(--jm-expander-line-height);
1768
+ border: solid var(--jm-expander-border-width) #666666;
1769
+ }
1770
+
1771
+ /* Lighter than a node's hover shadow on purpose — the expander is small and
1772
+ a full-strength shadow would swamp it. */
1773
+ .jsmind-node-expander:hover {
1774
+ box-shadow: 1px 1px 8px #000000;
1775
+ background-color: #ebebeb;
1776
+ color: #333333;
1777
+ }
1778
+
1779
+
1780
+
1781
+ .jmnode-overflow-wrap .jsmind-nodes {
1782
+ min-width: 420px;
1783
+ }
1784
+
1785
+ .jmnode-overflow-hidden .jsmind-node {
1786
+ white-space: nowrap;
1787
+ overflow: hidden;
1788
+ text-overflow: ellipsis;
1789
+ }
1790
+ `;
1791
+ /**
1792
+ * Formats a theme shadow layer as a CSS `box-shadow` value.
1793
+ *
1794
+ * @param layer - The layer to format.
1795
+ * @returns A value like `1px 1px 1px #666666`.
1796
+ *
1797
+ * @private
1798
+ */
1799
+ function formatShadow(layer) {
1800
+ return `${layer.offsetX}px ${layer.offsetY}px ${layer.blur}px ${layer.color}`;
1801
+ }
1802
+ /**
1803
+ * Writes a theme's values onto the host element as custom properties.
1804
+ *
1805
+ * @remarks
1806
+ * Done on the host rather than on the shadow root because custom properties
1807
+ * inherit: set here, every rule inside sees them, and a value set on a single
1808
+ * node overrides it for that node alone. That is what makes per-node tone
1809
+ * colors possible without generating a stylesheet per mind map.
1810
+ *
1811
+ * Values are written complete, with units (`10px`, not `10`), because the
1812
+ * stylesheet interpolates them directly into positions where a bare number is
1813
+ * not a valid length.
1814
+ *
1815
+ * The `default` tone is applied here too, as the fallback for nodes that name
1816
+ * no tone of their own.
1817
+ *
1818
+ * @param root - The shadow root whose host should carry the values.
1819
+ * @param theme - The fully resolved theme.
1820
+ *
1821
+ * @private
1822
+ */
1823
+ function applyThemeToHost(root, theme) {
1824
+ const host = root.host;
1825
+ /** Sets a custom property only when the theme actually carries a value. */
1826
+ const set = (name, value, unit = '') => {
1827
+ if (value !== undefined) {
1828
+ host.style.setProperty(name, `${value}${unit}`);
1829
+ }
1830
+ };
1831
+ set('--jm-background', theme.background);
1832
+ const node = theme.node;
1833
+ if (node) {
1834
+ set('--jm-node-padding', node.padding, 'px');
1835
+ set('--jm-node-radius', node.radius, 'px');
1836
+ set('--jm-node-border-width', node.borderWidth, 'px');
1837
+ set('--jm-node-max-width', node.maxWidth, 'px');
1838
+ set('--jm-node-font-family', node.fontFamily);
1839
+ set('--jm-node-font-size', node.fontSize, 'px');
1840
+ set('--jm-node-root-font-size', node.rootFontSize, 'px');
1841
+ // Unitless on purpose: it is a multiplier of the font size, and CSS
1842
+ // would read a pixel value as an absolute line box instead.
1843
+ set('--jm-node-line-height', node.lineHeight);
1844
+ const shadow = node.shadow;
1845
+ if (shadow) {
1846
+ set('--jm-node-shadow-normal', formatShadow(shadow.normal));
1847
+ set('--jm-node-shadow-hover', formatShadow(shadow.hover));
1848
+ set('--jm-node-shadow-selected', formatShadow(shadow.selected));
1849
+ }
1850
+ }
1851
+ const expander = theme.expander;
1852
+ if (expander) {
1853
+ set('--jm-expander-size', expander.size, 'px');
1854
+ set('--jm-expander-radius', expander.radius, 'px');
1855
+ set('--jm-expander-border-width', expander.borderWidth, 'px');
1856
+ set('--jm-expander-font-size', expander.fontSize, 'px');
1857
+ set('--jm-expander-line-height', expander.lineHeight, 'px');
1858
+ }
1859
+ // The default tone is the fallback for nodes that name no tone of their
1860
+ // own; a node with a tone overrides all four on its own element.
1861
+ const fallback = theme.tones?.default;
1862
+ if (fallback) {
1863
+ // ShadowRoot.host is typed as Element; at runtime it is the host element
1864
+ // the view was opened on, so style is there.
1865
+ applyTonePalette(root.host, fallback);
1866
+ }
1867
+ }
1868
+ /**
1869
+ * Writes a tone palette's three colours onto an element as custom properties.
1870
+ *
1871
+ * @remarks
1872
+ * One function rather than two copies of the same three lines. `applyThemeToHost`
1873
+ * calls it for the default tone, which becomes the fallback for every node that
1874
+ * names no tone of its own; `JmNodeView` calls it per node, where the value wins
1875
+ * for that node and nothing else. Keeping the mapping here means a tone that
1876
+ * gains a field gains it in both places at once.
1877
+ *
1878
+ * The expander is deliberately not a consumer: it sits outside the node box,
1879
+ * and colouring its outline from the node's tone would make a white-toned node
1880
+ * grow a white outline. It keeps the neutral #666 its stylesheet specifies.
1881
+ *
1882
+ * @param target - Anything with a `style` object. Typed structurally because the
1883
+ * two callers pass different things — `JmElement` for a node, a plain `Element`
1884
+ * for the host — and `style.setProperty` is all this needs from either.
1885
+ * @param palette - Tone to apply. Undefined leaves the target untouched.
1886
+ * @returns Nothing.
1887
+ */
1888
+ function applyTonePalette(target, palette) {
1889
+ if (!palette) {
1890
+ return;
1891
+ }
1892
+ const set = (name, value) => {
1893
+ if (value !== undefined) {
1894
+ target.style.setProperty(name, value);
1895
+ }
1896
+ };
1897
+ set('--jm-node-fill', palette.fillColor);
1898
+ set('--jm-node-text', palette.textColor);
1899
+ set('--jm-node-border-color', palette.borderColor);
1900
+ }
1901
+ /**
1902
+ * Attaches a shadow root to the host element and installs the styles in it.
1903
+ *
1904
+ * @remarks
1905
+ * `open` rather than `closed` so the rendered DOM stays inspectable — for
1906
+ * debugging, for the tests, and for anyone who needs to reach a node element
1907
+ * from outside. The isolation is about styles, not secrecy.
1908
+ *
1909
+ * A host that already has a shadow root keeps it. Calling `attachShadow` twice
1910
+ * throws, and constructing the view again on the same host (which happens when
1911
+ * a mind map is reloaded) must not.
1912
+ *
1913
+ * @param container - The host element supplied by the caller.
1914
+ * @returns The shadow root that rendered content belongs in.
1915
+ *
1916
+ * @private
1917
+ */
1918
+ function attachViewShadowRoot(container) {
1919
+ const existing = container.shadowRoot;
1920
+ const root = existing ?? container.attachShadow({ mode: 'open' });
1921
+ // Reuse the style element this function created earlier, so repeated view
1922
+ // construction on the same host does not stack copies of the rules.
1923
+ const marker = 'data-jsmind-view-styles';
1924
+ let style = root.querySelector(`style[${marker}]`);
1925
+ if (!style) {
1926
+ style = document.createElement('style');
1927
+ style.setAttribute(marker, '');
1928
+ root.appendChild(style);
1929
+ }
1930
+ style.textContent = JSMIND_VIEW_STYLES;
1931
+ return root;
1932
+ }
1933
+
1934
+ /**
1935
+ * View operator for nodes.
1936
+ * Handles rendering and manipulation of node elements in the view.
1937
+ *
1938
+ * @public
1939
+ */
1940
+ class JmNodeView {
1941
+ /** The container element for nodes. */
1942
+ container;
1943
+ /** The view options. */
1944
+ options;
1945
+ /** The resolved theme, or null until one is applied. */
1946
+ theme = null;
1947
+ /**
1948
+ * Creates a new node view operator.
1949
+ *
1950
+ * @param innerContainer - The inner container element to append the nodes container to.
1951
+ */
1952
+ constructor(innerContainer, viewOptions) {
1953
+ this.container = this._initNodesContainer(innerContainer);
1954
+ this.options = viewOptions;
1955
+ }
1956
+ /**
1957
+ * Sets the theme whose tone palettes node elements resolve against.
1958
+ *
1959
+ * @remarks
1960
+ * Only the palettes are needed here. Geometry is written onto the host as
1961
+ * custom properties once per map, and every node inherits it — repeating a
1962
+ * padding value on every element would multiply work by node count for no
1963
+ * benefit.
1964
+ *
1965
+ * @param theme - The resolved theme.
1966
+ */
1967
+ setTheme(theme) {
1968
+ this.theme = theme;
1969
+ }
1970
+ async createAndMeasure(node) {
1971
+ const existingElement = node._data.view.element;
1972
+ if (existingElement) {
1973
+ return new JmSize(existingElement.cachedRect.width, existingElement.cachedRect.height);
1974
+ }
1975
+ const sizePromise = this._createNodeElement(node)
1976
+ .then((element) => {
1977
+ node._data.view.element = element;
1978
+ this.container.appendChild(element.element);
1979
+ return new JmSize(element.cachedRect.width, element.cachedRect.height);
1980
+ });
1981
+ if (!node.isRoot()) {
1982
+ const expanderElement = this._createNodeExpander(node);
1983
+ node._data.view.expander = expanderElement;
1984
+ this.container.appendChild(expanderElement.element);
1985
+ }
1986
+ return sizePromise;
1987
+ }
1988
+ removeNode(node) {
1989
+ const element = node._data.view.element;
1990
+ if (element) {
1991
+ element.element.remove();
1992
+ }
1993
+ }
1994
+ updateCanvasSize(viewSize) {
1995
+ this.container.style.width = `${viewSize.width}px`;
1996
+ this.container.style.height = `${viewSize.height}px`;
1997
+ }
1998
+ placeNode(node, absolutePoint) {
1999
+ const element = node._data.view.element;
2000
+ element.innerHTML = node.content.getText();
2001
+ element.show(absolutePoint);
2002
+ }
2003
+ placeNodeExpander(node, absolutePoint) {
2004
+ if (node.isRoot()) {
2005
+ return;
2006
+ }
2007
+ if (node.children.length === 0) {
2008
+ return;
2009
+ }
2010
+ const element = node._data.view.expander;
2011
+ if (this.options.expander.style === ViewExpanderStyle.Char) {
2012
+ if (node.folded) {
2013
+ element.classList.add('jsmind-node-expander-collapsed');
2014
+ }
2015
+ else {
2016
+ element.classList.add('jsmind-node-expander-expanded');
2017
+ }
2018
+ }
2019
+ else if (this.options.expander.style === ViewExpanderStyle.Number) {
2020
+ element.classList.add('jsmind-node-expander-number');
2021
+ element.innerHTML = `${node.children.length}`;
2022
+ }
2023
+ element.show(absolutePoint);
2024
+ }
2025
+ hideNode(node) {
2026
+ const element = node._data.view.element;
2027
+ element.hide();
2028
+ }
2029
+ hideNodeExpander(node) {
2030
+ const expanderElement = node._data.view.expander;
2031
+ expanderElement.hide();
2032
+ }
2033
+ /**
2034
+ * Initializes the nodes container element.
2035
+ *
2036
+ * @param innerContainer - The inner container element.
2037
+ * @returns The created nodes container element.
2038
+ */
2039
+ _initNodesContainer(innerContainer) {
2040
+ const jmElement = JmDomUtility.createElement('div', 'jsmind-nodes');
2041
+ innerContainer.appendChild(jmElement.element);
2042
+ jmElement.style.width = `${innerContainer.clientWidth}px`;
2043
+ jmElement.style.height = `${innerContainer.clientHeight}px`;
2044
+ return jmElement;
2045
+ }
2046
+ async _createNodeElement(node) {
2047
+ const element = JmDomUtility.createElement('div', 'jsmind-node', { 'node-id': node.id });
2048
+ element.hide();
2049
+ if (node.content.isText()) {
2050
+ element.innerHTML = node.content.getText();
2051
+ }
2052
+ else {
2053
+ element.innerHTML = 'unsupported content type';
2054
+ }
2055
+ if (node.isRoot()) {
2056
+ element.classList.add('jsmind-node-root');
2057
+ }
2058
+ this._applyTone(element, node);
2059
+ const rect = await JmDomUtility.measureElement(element, this.container);
2060
+ element.cachedRect = rect;
2061
+ return element;
2062
+ }
2063
+ _createNodeExpander(node) {
2064
+ const element = JmDomUtility.createElement('div', 'jsmind-node-expander', { 'node-id': node.id });
2065
+ element.hide();
2066
+ // No tone here on purpose. The expander sits outside the node's box and
2067
+ // its stylesheet draws a neutral outline; feeding it the node's palette
2068
+ // would put a white circle beside every untoned node.
2069
+ return element;
2070
+ }
2071
+ /**
2072
+ * Resolves a node's tone and its own style overrides into custom properties.
2073
+ *
2074
+ * @remarks
2075
+ * Written on the element, not on the host, because that is the whole point
2076
+ * of the tone concept: one node differs while its siblings do not. Custom
2077
+ * properties inherit downward, so a value set here wins for this subtree and
2078
+ * nothing else.
2079
+ *
2080
+ * Precedence follows `JmNodeStyle`'s contract — a field the node states
2081
+ * beats the tone beats the theme.
2082
+ *
2083
+ * @param element - The element to paint.
2084
+ * @param node - The node it represents.
2085
+ *
2086
+ * @private
2087
+ */
2088
+ _applyTone(element, node) {
2089
+ const style = node.style;
2090
+ const tone = style?.tone ?? JmTone.Default;
2091
+ applyTonePalette(element, this.theme?.tones?.[tone]);
2092
+ if (!style) {
2093
+ return;
2094
+ }
2095
+ /** Sets a custom property only when the node actually states it. */
2096
+ const set = (name, value) => {
2097
+ if (value !== undefined) {
2098
+ element.style.setProperty(name, value);
2099
+ }
2100
+ };
2101
+ // Explicit fields win over the tone they sat alongside.
2102
+ set('--jm-node-fill', style.background);
2103
+ set('--jm-node-text', style.color);
2104
+ set('--jm-node-border-color', style.borderColor);
2105
+ if (style.borderWidth !== undefined) {
2106
+ element.style.borderWidth = `${style.borderWidth}px`;
2107
+ }
2108
+ if (style.borderStyle !== undefined) {
2109
+ element.style.borderStyle = style.borderStyle;
2110
+ }
2111
+ // Font size and weight are set inline rather than through a custom
2112
+ // property: only the root adjusts size through the stylesheet, so a
2113
+ // per-node value has to override a rule rather than a default.
2114
+ if (style.fontSize !== undefined) {
2115
+ element.style.fontSize = `${style.fontSize}px`;
2116
+ }
2117
+ if (style.fontWeight !== undefined) {
2118
+ element.style.fontWeight = style.fontWeight;
2119
+ }
2120
+ }
2121
+ }
2122
+
2123
+ /**
2124
+ * View operator for edges.
2125
+ * Handles rendering and manipulation of edge elements in the view.
2126
+ *
2127
+ * @public
2128
+ */
2129
+ class JmEdgeView {
2130
+ /** The container element for edges (SVG). */
2131
+ container;
2132
+ /**
2133
+ * Creates a new edge view operator.
2134
+ *
2135
+ * @param innerContainer - The inner container element to append the edges container to.
2136
+ */
2137
+ constructor(innerContainer) {
2138
+ this.container = this._initEdgesContainer(innerContainer);
2139
+ }
2140
+ updateEdgeViewsSize(viewSize) {
2141
+ this.container.style.width = `${viewSize.width}px`;
2142
+ this.container.style.height = `${viewSize.height}px`;
2143
+ }
2144
+ drawLine(node, sourcePoint, targetPoint, style) {
2145
+ let line = node._data.view.leadingLine;
2146
+ if (!line) {
2147
+ line = this._createLine();
2148
+ node._data.view.leadingLine = line;
2149
+ }
2150
+ line.setAttribute('d', this._buildPath(sourcePoint, targetPoint, style.curve));
2151
+ // Written on every draw, not just at creation: the element outlives
2152
+ // redraws, and a node can change tone while its line stays the same
2153
+ // element.
2154
+ line.setAttribute('stroke', style.color);
2155
+ line.setAttribute('stroke-width', String(style.width));
2156
+ // Round caps, matching what v1 did on canvas (`ctx.lineCap = 'round'`).
2157
+ // Required for the dotted pattern to be made of dots at all: with the
2158
+ // default `butt` cap a zero-length dash paints nothing.
2159
+ line.setAttribute('stroke-linecap', 'round');
2160
+ const dash = this._dashPattern(style);
2161
+ if (dash) {
2162
+ line.setAttribute('stroke-dasharray', dash);
2163
+ }
2164
+ else {
2165
+ // Removing the attribute is what makes a line solid. Leaving it set
2166
+ // would keep an element dashed after its style went back to solid.
2167
+ line.removeAttribute('stroke-dasharray');
2168
+ }
2169
+ line.style.visibility = 'visible';
2170
+ }
2171
+ eraseLine(node) {
2172
+ const line = node._data.view.leadingLine;
2173
+ if (!!line) {
2174
+ line.style.visibility = 'hidden';
2175
+ line.setAttribute('d', 'M 0 0 L 0 0');
2176
+ }
2177
+ }
2178
+ /**
2179
+ * Builds the path data for one line.
2180
+ *
2181
+ * @remarks
2182
+ * The bezier puts both control points on the horizontal midpoint, so the
2183
+ * line leaves the source and enters the target along the horizontal axis and
2184
+ * the bend stays symmetric. v1 used `x1 + 2*(x2-x1)/3` for the first control
2185
+ * point and the untouched `x1` for the second, which drags the bulge towards
2186
+ * the source and reads as lopsided once the vertical span is large.
2187
+ */
2188
+ _buildPath(source, target, curve) {
2189
+ if (curve === JmLineCurve.Straight) {
2190
+ return `M ${source.x} ${source.y} L ${target.x} ${target.y}`;
2191
+ }
2192
+ const midX = (source.x + target.x) / 2;
2193
+ return `M ${source.x} ${source.y} C ${midX} ${source.y}, ${midX} ${target.y}, ${target.x} ${target.y}`;
2194
+ }
2195
+ /**
2196
+ * Turns a dash pattern into an SVG `stroke-dasharray` value.
2197
+ *
2198
+ * @returns The dash array, or `null` for a solid line.
2199
+ *
2200
+ * @remarks
2201
+ * Dash lengths scale with the stroke width so a thicker line keeps the same
2202
+ * rhythm instead of collapsing into near-solid strokes.
2203
+ */
2204
+ _dashPattern(style) {
2205
+ switch (style.pattern) {
2206
+ case JmLinePattern.Dashed:
2207
+ return `${style.width * 4} ${style.width * 3}`;
2208
+ case JmLinePattern.Dotted:
2209
+ // Zero-length dash plus a round cap is the only way to get a
2210
+ // circle: the cap extends half the stroke width past each end of
2211
+ // the dash, so `0` renders a dot of diameter `stroke-width`.
2212
+ // A non-zero dash would paint a short rectangle instead.
2213
+ return `0 ${style.width * 2}`;
2214
+ case JmLinePattern.Solid:
2215
+ default:
2216
+ return null;
2217
+ }
2218
+ }
2219
+ _createLine() {
2220
+ const line = document.createElementNS('http://www.w3.org/2000/svg', 'path');
2221
+ line.setAttribute('fill', 'transparent');
2222
+ line.setAttribute('d', 'M 0 0 L 0 0');
2223
+ line.style.visibility = 'hidden';
2224
+ this.container.appendChild(line);
2225
+ return line;
2226
+ }
2227
+ /**
2228
+ * Initializes the edges container element (SVG).
2229
+ *
2230
+ * @param innerContainer - The inner container element.
2231
+ * @returns The created edges container element.
2232
+ */
2233
+ _initEdgesContainer(innerContainer) {
2234
+ const element = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
2235
+ element.classList.add('jsmind-edges');
2236
+ innerContainer.appendChild(element);
2237
+ element.style.width = `${innerContainer.clientWidth}px`;
2238
+ element.style.height = `${innerContainer.clientHeight}px`;
2239
+ return element;
2240
+ }
2241
+ _clearEdges() {
2242
+ }
2243
+ }
2244
+
2245
+ /**
2246
+ * Small string helpers the SVG wrapper needs.
2247
+ *
2248
+ * Pulled out of `export.ts` so they can be tested - hence the name. Everything left in that file
2249
+ * talks to the browser - cloning nodes, decoding images, encoding canvases -
2250
+ * and none of it runs under the unit suite. These do, and they are the parts
2251
+ * that failed silently when they were wrong:
2252
+ *
2253
+ * - an unescaped quote in an attribute ends it early, and the SVG fails to
2254
+ * parse with an error that names no line
2255
+ * - reading custom properties by iterating `CSSStyleDeclaration` yields
2256
+ * indices rather than property names, so the filter matched nothing and every
2257
+ * node lost its fill
2258
+ *
2259
+ * Both were bugs that produced a plausible-looking but wrong image.
2260
+ *
2261
+ * @packageDocumentation
2262
+ */
2263
+ /**
2264
+ * Escapes a value for use inside a double-quoted XML attribute.
2265
+ *
2266
+ * Computed values arrive unescaped: `font-family` on a document with a quoted
2267
+ * family yields the quotes themselves.
2268
+ *
2269
+ * @param value - Raw attribute value.
2270
+ * @returns The value with `&`, `<`, `>` and `"` replaced by entities.
2271
+ */
2272
+ function escapeAttribute(value) {
2273
+ return value
2274
+ .replace(/&/g, '&amp;')
2275
+ .replace(/</g, '&lt;')
2276
+ .replace(/>/g, '&gt;')
2277
+ .replace(/"/g, '&quot;');
2278
+ }
2279
+ /**
2280
+ * Escapes text content for XML.
2281
+ *
2282
+ * Quotes are left alone: they are only special inside an attribute value.
2283
+ *
2284
+ * @param value - Raw text.
2285
+ * @returns The text with `&`, `<` and `>` replaced by entities.
2286
+ */
2287
+ function escapeText(value) {
2288
+ return value.replace(/&/g, '&amp;').replace(/</g, '&lt;')
2289
+ .replace(/>/g, '&gt;');
2290
+ }
2291
+ /**
2292
+ * Extracts the theme's custom properties from an inline style declaration.
2293
+ *
2294
+ * The theme reaches the DOM as `--jm-*` properties set inline on the host
2295
+ * element. A clone of the inner content keeps the ones set on nodes themselves,
2296
+ * but not these, so without copying them every node loses its fill, border,
2297
+ * radius and shadow and the export comes out as bare text.
2298
+ *
2299
+ * Takes the attribute string rather than the element on purpose: parsing it is
2300
+ * the part that has been wrong before, and it does not need a DOM to get right.
2301
+ *
2302
+ * @param styleAttribute - The host's inline `style` attribute, or `null`.
2303
+ * @returns The `--jm-*` declarations, joined with semicolons; empty when none.
2304
+ */
2305
+ function collectHostVariables(styleAttribute) {
2306
+ if (styleAttribute === null) {
2307
+ return '';
2308
+ }
2309
+ return styleAttribute
2310
+ .split(';')
2311
+ .map(part => part.trim())
2312
+ .filter(part => part.startsWith('--jm-'))
2313
+ .join(';');
2314
+ }
2315
+
2316
+ /**
2317
+ * @fileoverview Turns the rendered content of the view's shadow root into an image.
2318
+ *
2319
+ * The browser has no API that converts a DOM subtree into pixels. Element
2320
+ * Capture and Region Capture come closest, but both sit on top of the Screen
2321
+ * Capture API and need the user to grant a capture prompt, which rules them out
2322
+ * for an export a script can call.
2323
+ *
2324
+ * What every DOM-to-image library does instead, and what this does, is hand the
2325
+ * markup back to the browser as an SVG `<foreignObject>` and let the rendering
2326
+ * engine paint it. Canvas only appears at the very end, to turn those pixels
2327
+ * into a file: `drawImage` then `toBlob`. Nothing is redrawn by hand, so the
2328
+ * output matches the view exactly, including text wrapping, shadows and the
2329
+ * theme.
2330
+ *
2331
+ * Excluded from the unit coverage figure (see `test:coverage` in package.json).
2332
+ * Everything left here talks to the browser - cloneNode, Image, canvas - so the
2333
+ * unit suite cannot reach a line of it. The UI suite exercises it for real,
2334
+ * against the built bundle, but a bundle carries no source line numbers to
2335
+ * report coverage against. The parts worth asserting in isolation live in
2336
+ * `export-svg.ts`; what remains is calls into browser APIs with no logic to check.
2337
+ */
2338
+ /** Image formats a caller may ask for. */
2339
+ const JmImageType = {
2340
+ Png: 'image/png'};
2341
+ const DEFAULT_SCALE = 2;
2342
+ /**
2343
+ * Reads the shadow root's stylesheet back out.
2344
+ *
2345
+ * External stylesheets cannot reach into a shadow tree, which is why the view
2346
+ * carries its CSS as a string in the first place - that same string is what gets
2347
+ * inlined here.
2348
+ */
2349
+ function collectStyles(root) {
2350
+ const sheets = root.querySelectorAll('style');
2351
+ return Array.from(sheets)
2352
+ .map(sheet => sheet.textContent ?? '')
2353
+ .join('\n');
2354
+ }
2355
+ /**
2356
+ * Renders the shadow root's content to an image blob.
2357
+ *
2358
+ * The size is the content's own size, as laid out: the view sizes the map to
2359
+ * the larger of the container and the content, so whitespace the map does not
2360
+ * fill is kept and a map larger than its container is not cropped.
2361
+ *
2362
+ * @param host - The element the shadow root is attached to.
2363
+ * @param root - The view's shadow root.
2364
+ * @param size - The content size in CSS pixels, from the view.
2365
+ * @param options - Scale, format and quality.
2366
+ * @returns The encoded image plus its dimensions.
2367
+ * @throws {@link JsMindError} If there is nothing to capture, if the generated
2368
+ * SVG does not parse, or if the browser refuses to encode the canvas.
2369
+ */
2370
+ async function captureShadowContent(host, root, size, options = {}) {
2371
+ const scale = options.scale ?? DEFAULT_SCALE;
2372
+ const type = options.type ?? JmImageType.Png;
2373
+ const inner = root.querySelector('.jsmind-inner');
2374
+ if (!inner) {
2375
+ throw new JsMindError('Nothing to capture: the view has no rendered content.');
2376
+ }
2377
+ // The size comes from the caller, not from the element. The inner container
2378
+ // is sized by its own container through CSS, so `clientWidth` reports the
2379
+ // viewport, not the map: a map larger than the box would be captured
2380
+ // cropped to the box. The view keeps the real size separately and hands it
2381
+ // over here.
2382
+ const cssWidth = size.width;
2383
+ const cssHeight = size.height;
2384
+ if (cssWidth === 0 || cssHeight === 0) {
2385
+ throw new JsMindError(`Nothing to capture: the rendered content has no size (${cssWidth}x${cssHeight}).`);
2386
+ }
2387
+ const clone = inner.cloneNode(true);
2388
+ clone.style.position = 'absolute';
2389
+ clone.style.left = '0';
2390
+ clone.style.top = '0';
2391
+ clone.style.margin = '0';
2392
+ // The container scrolls; inside a picture that would paint scrollbars.
2393
+ clone.style.overflow = 'visible';
2394
+ // It is already positioned in the export, not offset by a view pan.
2395
+ clone.style.transform = 'none';
2396
+ // `outerHTML` of a live <svg> carries no xmlns: the element is in the SVG
2397
+ // namespace already, so the serializer omits it. Reparsed as XHTML it is an
2398
+ // unknown element and paints nothing at all - which is how the edge layer
2399
+ // silently disappears from the export.
2400
+ for (const svg of Array.from(clone.querySelectorAll('svg'))) {
2401
+ svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
2402
+ }
2403
+ const hostStyle = getComputedStyle(host);
2404
+ const wrapperStyle = escapeAttribute([
2405
+ `width:${cssWidth}px`,
2406
+ `height:${cssHeight}px`,
2407
+ 'position:relative',
2408
+ 'overflow:hidden',
2409
+ `background:${hostStyle.backgroundColor}`,
2410
+ `font-family:${hostStyle.fontFamily}`,
2411
+ collectHostVariables(host.getAttribute('style')),
2412
+ ]
2413
+ .filter(Boolean)
2414
+ .join(';'));
2415
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${cssWidth}" height="${cssHeight}">` +
2416
+ '<foreignObject x="0" y="0" width="100%" height="100%">' +
2417
+ `<div xmlns="http://www.w3.org/1999/xhtml" style="${wrapperStyle}">` +
2418
+ `<style>${escapeText(collectStyles(root))}</style>` +
2419
+ clone.outerHTML +
2420
+ '</div></foreignObject></svg>';
2421
+ const parsed = new DOMParser().parseFromString(svg, 'image/svg+xml');
2422
+ if (parsed.querySelector('parsererror')) {
2423
+ throw new JsMindError('Failed to render the view to an image: the generated SVG is malformed.');
2424
+ }
2425
+ // A blob: URL taints the canvas once the SVG carries a foreignObject, so
2426
+ // toBlob throws SecurityError. A data: URL keeps the document same-origin.
2427
+ const dataUrl = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
2428
+ const image = await loadImage(dataUrl);
2429
+ const canvas = document.createElement('canvas');
2430
+ canvas.width = Math.round(cssWidth * scale);
2431
+ canvas.height = Math.round(cssHeight * scale);
2432
+ const context = canvas.getContext('2d');
2433
+ if (!context) {
2434
+ throw new JsMindError('Failed to render the view to an image: 2D canvas is unavailable.');
2435
+ }
2436
+ context.scale(scale, scale);
2437
+ context.drawImage(image, 0, 0);
2438
+ const blob = await encodeCanvas(canvas, type, options.quality);
2439
+ return {
2440
+ blob,
2441
+ width: canvas.width,
2442
+ height: canvas.height,
2443
+ cssWidth,
2444
+ cssHeight,
2445
+ };
2446
+ }
2447
+ /** Loads a data URL into a decoded image. */
2448
+ function loadImage(src) {
2449
+ return new Promise((resolve, reject) => {
2450
+ const image = new Image();
2451
+ image.onload = () => resolve(image);
2452
+ // The error event carries no detail beyond "failed to load", so the
2453
+ // message has to say where to look.
2454
+ image.onerror = () => reject(new JsMindError('Failed to render the view to an image: the SVG did not load.'));
2455
+ image.src = src;
2456
+ });
2457
+ }
2458
+ /** Encodes a canvas, passing a quality only for the lossy formats. */
2459
+ function encodeCanvas(canvas, type, quality) {
2460
+ return new Promise((resolve, reject) => {
2461
+ const done = (blob) => {
2462
+ if (blob === null) {
2463
+ reject(new JsMindError(`Failed to encode the image as ${type}.`));
2464
+ }
2465
+ else {
2466
+ resolve(blob);
2467
+ }
2468
+ };
2469
+ // PNG has no quality knob; passing one makes some browsers treat the
2470
+ // argument as a format hint and fall back to a different encoder.
2471
+ if (type === JmImageType.Png || quality === undefined) {
2472
+ canvas.toBlob(done, type);
2473
+ }
2474
+ else {
2475
+ canvas.toBlob(done, type, quality);
2476
+ }
2477
+ });
2478
+ }
2479
+
2480
+ /**
2481
+ * View of mind map.
2482
+ * @public
2483
+ */
2484
+ class JmView {
2485
+ container;
2486
+ shadowRoot;
2487
+ innerContainer;
2488
+ nodeView;
2489
+ edgeView;
2490
+ arranger;
2491
+ options;
2492
+ /**
2493
+ * The theme resolved from the mind map's style, kept so that per-node
2494
+ * decisions at render time (tone lookup, line fallbacks) do not have to
2495
+ * re-resolve it for every node.
2496
+ *
2497
+ * Starts at the built-in default rather than null: a node can be rendered
2498
+ * before `applyTheme` runs, and a null theme would force every lookup to
2499
+ * carry an optional chain and a hardcoded colour of its own.
2500
+ */
2501
+ theme = JSMIND_THEME_DEFAULT;
2502
+ viewSize = new JmSize(1, 1);
2503
+ viewOffset = new JmPoint(0, 0);
2504
+ constructor(container, shadowRoot, innerContainer, nodeView, edgeView, arranger, options) {
2505
+ this.container = container;
2506
+ this.shadowRoot = shadowRoot;
2507
+ this.innerContainer = innerContainer;
2508
+ this.nodeView = nodeView;
2509
+ this.edgeView = edgeView;
2510
+ this.arranger = arranger;
2511
+ this.options = options;
2512
+ }
2513
+ static async create(container, arranger, options) {
2514
+ const jmContainer = await this._initContainer(container);
2515
+ // Rendered content lives in a shadow root: the map's structural rules
2516
+ // are installed there, so the host page cannot reach them and they
2517
+ // cannot reach the host page.
2518
+ const shadowRoot = attachViewShadowRoot(jmContainer);
2519
+ const innerContainer = this._initInnerContainer(shadowRoot);
2520
+ const nodeView = new JmNodeView(innerContainer, options);
2521
+ const edgeView = new JmEdgeView(innerContainer);
2522
+ return new JmView(jmContainer, shadowRoot, innerContainer, nodeView, edgeView, arranger, options);
2523
+ }
2524
+ static async _initContainer(container) {
2525
+ if (!container) {
2526
+ throw new JsMindError('Container is required');
2527
+ }
2528
+ if (typeof container === 'string') {
2529
+ const element = document.getElementById(container);
2530
+ if (!element) {
2531
+ throw new JsMindError(`Container element with ID '${container}' is not found`);
2532
+ }
2533
+ await DomUtility.ensureElementVisible(element);
2534
+ return element;
2535
+ }
2536
+ return container;
2537
+ }
2538
+ static _initInnerContainer(shadowRoot) {
2539
+ const jmElement = JmDomUtility.createElement('div', 'jsmind-inner');
2540
+ jmElement.classList.add('jsmind-inner');
2541
+ // Appended to the shadow root, not to its host: this is what puts the
2542
+ // rendered tree inside the style boundary.
2543
+ shadowRoot.appendChild(jmElement.element);
2544
+ return jmElement;
2545
+ }
2546
+ /**
2547
+ * Resolves the mind map's style and pushes it onto the rendered tree.
2548
+ *
2549
+ * @remarks
2550
+ * Must run before measuring: a node's measured size depends on its padding,
2551
+ * font size and line height, and those come from the theme. Applying it
2552
+ * afterwards would lay the map out to the previous theme's geometry and
2553
+ * leave the rendered nodes disagreeing with the coordinates beside them.
2554
+ *
2555
+ * @param mind - The mind map about to be rendered.
2556
+ */
2557
+ applyTheme(mind) {
2558
+ const theme = resolveJmStyle(mind.style);
2559
+ this.theme = theme;
2560
+ applyThemeToHost(this.shadowRoot, theme);
2561
+ this.nodeView.setTheme(theme);
2562
+ }
2563
+ async measureNodeSizes(mind) {
2564
+ const promises = Object.values(mind._nodes).map((node) => this.measureNodeSize(node));
2565
+ await Promise.all(promises);
2566
+ }
2567
+ async measureNodeSize(node) {
2568
+ return this.nodeView.createAndMeasure(node)
2569
+ .then((size) => {
2570
+ this.arranger.recordNodeSize(node, size);
2571
+ return size;
2572
+ });
2573
+ }
2574
+ async settle(mind, _changedNodeIds = []) {
2575
+ this._updateViewSize(mind);
2576
+ this.nodeView.updateCanvasSize(this.viewSize);
2577
+ this.edgeView.updateEdgeViewsSize(this.viewSize);
2578
+ this._settleNode(mind, this.viewOffset);
2579
+ this._renderEdges(mind, this.viewOffset);
2580
+ }
2581
+ _settleNode(mind, viewOffset) {
2582
+ Object.values(mind._nodes).forEach((node) => {
2583
+ if (this.arranger.isNodeVisible(node)) {
2584
+ // reset custom style
2585
+ const nodePoint = this.arranger.calculateNodePoint(node);
2586
+ const absolutePoint = nodePoint.offset(viewOffset);
2587
+ this.nodeView.placeNode(node, absolutePoint);
2588
+ const nodeExpanderPoint = this.arranger.calculateNodeExpanderPoint(node);
2589
+ const absoluteExpanderPoint = nodeExpanderPoint.offset(viewOffset);
2590
+ this.nodeView.placeNodeExpander(node, absoluteExpanderPoint);
2591
+ }
2592
+ else {
2593
+ this.nodeView.hideNode(node);
2594
+ this.nodeView.hideNodeExpander(node);
2595
+ }
2596
+ });
2597
+ }
2598
+ _renderEdges(mind, viewOffset) {
2599
+ Object.values(mind._nodes)
2600
+ .filter((node) => !node.isRoot())
2601
+ .forEach((node) => {
2602
+ if (this.arranger.isNodeVisible(node)) {
2603
+ const sourcePoint = this.arranger.calculateNodeOutgoingPoint(node.parent);
2604
+ const targetPoint = this.arranger.calculateNodeIncomingPoint(node);
2605
+ const absoluteSourcePoint = sourcePoint.offset(viewOffset);
2606
+ const absoluteTargetPoint = targetPoint.offset(viewOffset);
2607
+ this.edgeView.drawLine(node, absoluteSourcePoint, absoluteTargetPoint, this._resolveLineStyle(node));
2608
+ }
2609
+ else {
2610
+ this.edgeView.eraseLine(node);
2611
+ }
2612
+ });
2613
+ }
2614
+ /**
2615
+ * Resolves the style of the line that connects a node to its parent.
2616
+ *
2617
+ * @remarks
2618
+ * Three layers, most specific first:
2619
+ *
2620
+ * 1. `node.style.incoming` — this one line.
2621
+ * 2. The node's tone — a subtree reads as one visual grouping, because the
2622
+ * tone's `lineColor` differs from the fill rather than repeating it.
2623
+ * 3. The theme's `line` block — width, pattern and curve for the map.
2624
+ *
2625
+ * The line belongs to the child, not the parent: a line connects exactly one
2626
+ * child, so the child is the natural owner and can restyle its own
2627
+ * connection without touching its siblings. v1 did the same, reading
2628
+ * `leading-line-color` off the child's `data`.
2629
+ *
2630
+ * `curve` deliberately does not fall back to the tone. A tone is a colour,
2631
+ * and letting it carry geometry would make two nodes of the same tone but
2632
+ * different shapes impossible to express.
2633
+ */
2634
+ _resolveLineStyle(node) {
2635
+ const theme = this.theme;
2636
+ const incoming = node.style?.incoming;
2637
+ const tone = node.style?.tone ?? JmTone.Default;
2638
+ // The default palette is the last resort for an unknown or unstyled
2639
+ // tone, and it comes from the same constant the theme was built from, so
2640
+ // an untoned node never falls through to a colour of its own.
2641
+ const palette = theme.tones?.[tone] ?? JSMIND_THEME_DEFAULT.tones?.[JmTone.Default];
2642
+ // Every fallback reads the theme. The final literal is unreachable while
2643
+ // JSMIND_THEME_DEFAULT defines a default tone - it exists so the type is
2644
+ // `string`, not as a second source of truth that could drift.
2645
+ return {
2646
+ color: incoming?.color ?? palette?.lineColor ?? '#b0b0b0',
2647
+ width: incoming?.width ?? theme.line?.width ?? 2,
2648
+ pattern: incoming?.pattern ?? theme.line?.pattern ?? JmLinePattern.Solid,
2649
+ curve: incoming?.curve ?? theme.line?.curve ?? JmLineCurve.Bezier,
2650
+ };
2651
+ }
2652
+ /**
2653
+ * Renders the current content to an image.
2654
+ *
2655
+ * Kept on the view rather than reached into from outside: the host element
2656
+ * and the shadow root are both private, and they are exactly what the
2657
+ * capture needs.
2658
+ *
2659
+ * @param options - Scale, format and quality.
2660
+ * @returns The encoded image plus its dimensions.
2661
+ */
2662
+ async capture(options) {
2663
+ return await captureShadowContent(this.container, this.shadowRoot, this.viewSize, options);
2664
+ }
2665
+ _updateViewSize(mind) {
2666
+ const mindBounds = this.arranger.calculateMindBounds(mind);
2667
+ const mindViewSize = mindBounds.size;
2668
+ const minWidth = mindViewSize.width + this.options.padding.left + this.options.padding.right;
2669
+ const minHeight = mindViewSize.height + this.options.padding.top + this.options.padding.bottom;
2670
+ this.viewSize.width = Math.max(this.innerContainer.clientWidth, minWidth);
2671
+ this.viewSize.height = Math.max(this.innerContainer.clientHeight, minHeight);
2672
+ const centerOffset = mindBounds.center;
2673
+ this.viewOffset.x = this.viewSize.width / 2 - centerOffset.x;
2674
+ this.viewOffset.y = this.viewSize.height / 2 - centerOffset.y;
2675
+ }
2676
+ }
2677
+
2678
+ /**
2679
+ * Generic cache for storing function results with any key and value types.
2680
+ * @public
2681
+ */
2682
+ class JmCache {
2683
+ cache;
2684
+ name;
2685
+ keySelector;
2686
+ hits = 0;
2687
+ misses = 0;
2688
+ constructor(name, keySelector) {
2689
+ this.name = name;
2690
+ this.cache = new Map();
2691
+ this.keySelector = keySelector;
2692
+ }
2693
+ /**
2694
+ * Gets the cached value for the given key.
2695
+ *
2696
+ * @param key - The key to get the cached value for
2697
+ * @returns The cached value, or undefined if not found
2698
+ */
2699
+ get(key) {
2700
+ const cacheKey = this.keySelector(key);
2701
+ const exists = this.cache.has(cacheKey);
2702
+ if (exists) {
2703
+ this.hits++;
2704
+ }
2705
+ else {
2706
+ this.misses++;
2707
+ }
2708
+ return this.cache.get(cacheKey);
2709
+ }
2710
+ /**
2711
+ * Stores a value in the cache for the given key.
2712
+ *
2713
+ * @param key - The key to cache the value for
2714
+ * @param value - The value to cache
2715
+ */
2716
+ put(key, value) {
2717
+ this.cache.set(this.keySelector(key), value);
2718
+ }
2719
+ /**
2720
+ * Clears all cached values.
2721
+ */
2722
+ clear() {
2723
+ this.cache.clear();
2724
+ this.hits = 0;
2725
+ this.misses = 0;
2726
+ }
2727
+ /**
2728
+ * Gets cache statistics including hit rate.
2729
+ *
2730
+ * @returns An object containing hits, misses, total requests, and hit rate
2731
+ */
2732
+ stat() {
2733
+ const total = this.hits + this.misses;
2734
+ const hitRate = total > 0 ? this.hits / total : 0;
2735
+ return {
2736
+ hits: this.hits,
2737
+ misses: this.misses,
2738
+ total,
2739
+ hitRate,
2740
+ };
2741
+ }
2742
+ wrap(key, func) {
2743
+ const cached = this.get(key);
2744
+ if (cached !== undefined) {
2745
+ return cached;
2746
+ }
2747
+ const value = func();
2748
+ this.put(key, value);
2749
+ return value;
2750
+ }
2751
+ /**
2752
+ * Prints cache statistics to the console.
2753
+ */
2754
+ printStats() {
2755
+ const stats = this.stat();
2756
+ console.log(`${this.name} Statistics:`);
2757
+ console.log(` Hits: ${stats.hits}`);
2758
+ console.log(` Misses: ${stats.misses}`);
2759
+ console.log(` Total: ${stats.total} (${(stats.hitRate * 100).toFixed(2)}%)`);
2760
+ }
2761
+ }
2762
+
2763
+ class MindmapArranger {
2764
+ nodeInSidePredicateA = (node) => { return node.side === JmNodeSide.SideA; };
2765
+ nodeInSidePredicateB = (node) => { return node.side === JmNodeSide.SideB; };
2766
+ nodeHasCousinsPredicate = (node) => {
2767
+ return !node.folded && node.children.length > 0 && (node.parent?.children?.length ?? 0) > 1;
2768
+ };
2769
+ nodeInComingPointCache = new JmCache('nodeInComingPointCache', (node) => node.id);
2770
+ options;
2771
+ expanderSize;
2772
+ constructor(options) {
2773
+ this.options = options;
2774
+ this.expanderSize = new JmSize(options.expanderSize, options.expanderSize);
2775
+ }
2776
+ /**
2777
+ * Calculate the layout of the mind map.
2778
+ * @param mind - The mind map data model
2779
+ */
2780
+ calculate(mind) {
2781
+ this.nodeInComingPointCache.clear();
2782
+ const rootNode = mind._root;
2783
+ this._arrange(rootNode);
2784
+ this._markInvisibleNodes(rootNode);
2785
+ this._calculateOffset(rootNode);
2786
+ }
2787
+ calculateMindBounds(mind) {
2788
+ const rootLayoutData = mind._root._data.layout;
2789
+ const rootMaxX = rootLayoutData.size.width / 2;
2790
+ const rootMinX = 0 - rootMaxX;
2791
+ const outcomePointsX = Object.values(mind._nodes)
2792
+ .filter((node) => node._data.layout.visible)
2793
+ .map((node) => this.calculateNodeOutgoingPoint(node))
2794
+ .map((p) => p.x);
2795
+ const minX = Math.min(...outcomePointsX, rootMinX);
2796
+ const maxX = Math.max(...outcomePointsX, rootMaxX);
2797
+ const width = maxX - minX;
2798
+ const height = rootLayoutData.withDescendantsSize.height;
2799
+ const size = new JmSize(width, height);
2800
+ const center = new JmPoint((minX + maxX) / 2, 0);
2801
+ return new JmBounds(center, size);
2802
+ }
2803
+ calculateNodePoint(node) {
2804
+ const size = node._data.layout.size;
2805
+ const incomingPoint = this.calculateNodeIncomingPoint(node);
2806
+ const offsetToIncomingPoint = new JmPoint((size.width * (node._data.layout.side - 1)) / 2, -size.height / 2);
2807
+ return incomingPoint.offset(offsetToIncomingPoint);
2808
+ }
2809
+ calculateNodeExpanderPoint(node) {
2810
+ if (node.isRoot()) {
2811
+ return JmPoint.Zero;
2812
+ }
2813
+ const outgoingPoint = this.calculateNodeOutgoingPoint(node);
2814
+ const offsetToOutgoingPoint = new JmPoint(this.options.expanderSize * (node._data.layout.side + 1) / -2, -this.options.expanderSize / 2);
2815
+ return outgoingPoint.offset(offsetToOutgoingPoint);
2816
+ }
2817
+ calculateNodeOutgoingPoint(node) {
2818
+ if (node.isRoot()) {
2819
+ return JmPoint.Zero;
2820
+ }
2821
+ const incomingPoint = this.calculateNodeIncomingPoint(node);
2822
+ const offsetToIncomingPointX = (node._data.layout.size.width + this.options.expanderSize) * node._data.layout.side;
2823
+ const offsetToIncomingPoint = new JmPoint(offsetToIncomingPointX, 0);
2824
+ return incomingPoint.offset(offsetToIncomingPoint);
2825
+ }
2826
+ calculateNodeIncomingPoint(node) {
2827
+ if (node.isRoot()) {
2828
+ return JmPoint.Zero;
2829
+ }
2830
+ return this.nodeInComingPointCache.wrap(node, () => {
2831
+ const parentIncomingPoint = this.calculateNodeIncomingPoint(node.parent);
2832
+ return parentIncomingPoint.offset(node._data.layout.offsetToParent);
2833
+ });
2834
+ }
2835
+ isNodeVisible(node) {
2836
+ return node._data.layout.visible;
2837
+ }
2838
+ recordNodeSize(node, size) {
2839
+ node._data.layout.size = size;
2840
+ }
2841
+ printCacheStats() {
2842
+ this.nodeInComingPointCache.printStats();
2843
+ }
2844
+ _arrange(rootNode) {
2845
+ rootNode._data.layout.side = JmNodeSide.Center;
2846
+ rootNode.children
2847
+ .filter(this.nodeInSidePredicateA)
2848
+ .forEach((node) => this._arrangeSide(node, JmNodeSide.SideA));
2849
+ rootNode.children
2850
+ .filter(this.nodeInSidePredicateB)
2851
+ .forEach((node) => this._arrangeSide(node, JmNodeSide.SideB));
2852
+ }
2853
+ _arrangeSide(node, side) {
2854
+ node._data.layout.side = side;
2855
+ node.children.forEach((n) => this._arrangeSide(n, side));
2856
+ }
2857
+ _markInvisibleNodes(node) {
2858
+ if (node.folded) {
2859
+ this._applyToDescendants(node, (n) => { n._data.layout.visible = false; });
2860
+ }
2861
+ else {
2862
+ this._applyToDescendants(node, (n) => { this._markInvisibleNodes(n); });
2863
+ }
2864
+ }
2865
+ _calculateOffset(rootNode) {
2866
+ const nodesOnSideA = rootNode.children.filter(this.nodeInSidePredicateA);
2867
+ const nodesOnSideB = rootNode.children.filter(this.nodeInSidePredicateB);
2868
+ const heightRoot = rootNode._data.layout.size.height;
2869
+ const heightA = this._calculateNodesOffset(nodesOnSideA, true);
2870
+ const heightB = this._calculateNodesOffset(nodesOnSideB, true);
2871
+ // debug('calculateOffset', heightRoot, heightA, heightB);
2872
+ rootNode._data.layout.withDescendantsSize.height = Math.max(heightRoot, heightA, heightB);
2873
+ }
2874
+ /**
2875
+ * Calculate the offset for the nodes, from bottom to top.
2876
+ * @param nodes - The nodes to calculate the offset for, the first item should be the bottom node
2877
+ * @param isFirstLevelNodes - Whether the nodes are the first level nodes
2878
+ * @returns The total height of the nodes
2879
+ */
2880
+ _calculateNodesOffset(nodes, isFirstLevelNodes) {
2881
+ let offsetY = 0;
2882
+ let totalHeight = 0;
2883
+ const visibleNodes = nodes.filter((node) => node._data.layout.visible);
2884
+ // debug('visibleNodes', visibleNodes.length, isFirstLevelNodes);
2885
+ // debug('calculateNodesOffset options', this.options);
2886
+ visibleNodes.forEach((node) => {
2887
+ const parentLayout = node.parent._data.layout;
2888
+ const layoutData = node._data.layout;
2889
+ const expanderSpace = !!isFirstLevelNodes ? 0 : this.options.expanderSize * layoutData.side;
2890
+ const cousinSpace = this.nodeHasCousinsPredicate(node) ? this.options.cousinSpace : 0;
2891
+ const height = Math.max(this._calculateNodesOffset(node.children, false), layoutData.size.height) + cousinSpace;
2892
+ layoutData.withDescendantsSize.height = height;
2893
+ layoutData.offsetToParent.y = offsetY + height / 2;
2894
+ // debug(`calculateNodesOffset for node ${node.content.getText()}`, offsetY, height);
2895
+ layoutData.offsetToParent.x = this.options.parentChildSpace * layoutData.side + parentLayout.size.width * (parentLayout.side + layoutData.side) / 2 + expanderSpace;
2896
+ offsetY = offsetY + height + this.options.siblingSpace;
2897
+ totalHeight += height;
2898
+ });
2899
+ if (visibleNodes.length > 1) {
2900
+ totalHeight += this.options.siblingSpace * (visibleNodes.length - 1);
2901
+ }
2902
+ const halfTotalHeight = totalHeight / 2;
2903
+ visibleNodes.forEach((node) => {
2904
+ node._data.layout.offsetToParent.y -= halfTotalHeight;
2905
+ });
2906
+ return totalHeight;
2907
+ }
2908
+ /**
2909
+ * Traverse the node and its children recursively.
2910
+ * @param nodes - The nodes to start traversing from
2911
+ * @param func - The function to call for each node
2912
+ */
2913
+ _applyToDescendants(node, func) {
2914
+ node.children.forEach((n) => {
2915
+ func(n);
2916
+ this._applyToDescendants(n, func);
2917
+ });
2918
+ }
2919
+ }
2920
+
2921
+ class JmMindObserver {
2922
+ update(observedObject, event) {
2923
+ const eventData = event;
2924
+ switch (eventData.type) {
2925
+ case JmMindEventType.NodeAdded:
2926
+ this.onNodeAdded(observedObject, eventData.data);
2927
+ break;
2928
+ case JmMindEventType.NodeRemoved:
2929
+ this.onNodeRemoved(observedObject, eventData.data);
2930
+ break;
2931
+ case JmMindEventType.NodeUpdated:
2932
+ this.onNodeUpdated(observedObject, eventData.data);
2933
+ break;
2934
+ case JmMindEventType.NodeMoved:
2935
+ this.onNodeMoved(observedObject, eventData.data);
2936
+ break;
2937
+ case JmMindEventType.EdgeAdded:
2938
+ this.onEdgeAdded(observedObject, eventData.data);
2939
+ break;
2940
+ case JmMindEventType.EdgeRemoved:
2941
+ this.onEdgeRemoved(observedObject, eventData.data);
2942
+ break;
2943
+ }
2944
+ }
2945
+ }
2946
+
2947
+ const debug = (label, ...objArray) => {
2948
+ const titleLength = 80;
2949
+ const title = `================= [DEBUG] ${label} `.padEnd(titleLength, '=');
2950
+ console.log(title);
2951
+ objArray.forEach((obj) => {
2952
+ const objString = JSON.stringify(obj, (key, value) => {
2953
+ if (key === 'parent') {
2954
+ return value?.id ?? null;
2955
+ }
2956
+ return value;
2957
+ }, 2).replace(/\n/g, '\n ');
2958
+ console.log(` ${typeof obj}:`, objString);
2959
+ });
2960
+ const separator = '-'.repeat(titleLength);
2961
+ console.log(separator);
2962
+ console.log('');
2963
+ };
2964
+
2965
+ class JmMindChangeCoordinator extends JmMindObserver {
2966
+ arranger;
2967
+ view;
2968
+ constructor(arranger, view) {
2969
+ super();
2970
+ this.arranger = arranger;
2971
+ this.view = view;
2972
+ }
2973
+ async onMindMapOpened(mind) {
2974
+ // Before measuring, not after: a node's measured size depends on the
2975
+ // theme's padding, font size and line height. Applying it later would
2976
+ // lay the map out to the previous theme's geometry.
2977
+ this.view.applyTheme(mind);
2978
+ await this.view.measureNodeSizes(mind);
2979
+ this.arranger.calculate(mind);
2980
+ await this.view.settle(mind);
2981
+ if (this.arranger instanceof MindmapArranger) {
2982
+ this.arranger.printCacheStats();
2983
+ }
2984
+ }
2985
+ onMindMapClosed(_mind) {
2986
+ // Empty for now - can be extended in the future
2987
+ // for cleanup operations like removing observers, clearing caches, etc.
2988
+ }
2989
+ async onNodeAdded(mind, event) {
2990
+ debug('onNodeAdded', mind.meta.name, event);
2991
+ await this.view.measureNodeSize(event.node);
2992
+ this.arranger.calculate(mind);
2993
+ await this.view.settle(mind);
2994
+ if (this.arranger instanceof MindmapArranger) {
2995
+ this.arranger.printCacheStats();
2996
+ }
2997
+ }
2998
+ onNodeRemoved(mind, event) {
2999
+ debug('onNodeRemoved', mind.meta.name, event);
3000
+ }
3001
+ onNodeUpdated(mind, event) {
3002
+ debug('onNodeUpdated', mind.meta.name, event);
3003
+ }
3004
+ onNodeMoved(mind, event) {
3005
+ debug('onNodeMoved', mind.meta.name, event);
3006
+ }
3007
+ onEdgeAdded(mind, event) {
3008
+ debug('onEdgeAdded', mind.meta.name, event);
3009
+ }
3010
+ onEdgeRemoved(mind, event) {
3011
+ debug('onEdgeRemoved', mind.meta.name, event);
3012
+ }
3013
+ }
3014
+
3015
+ /**
3016
+ * Application-level commands.
3017
+ *
3018
+ * The counterpart to the change coordinator. The coordinator answers "the mind
3019
+ * changed, update the view"; the commander answers "the caller asked for
3020
+ * something, do it". Between them they cover both directions of traffic, and
3021
+ * both hold the view the same way - as a narrow handle, not as the class.
3022
+ *
3023
+ * Existing as its own object rather than as methods on `JsMind` is what makes
3024
+ * these commands addressable: a menu item, a keyboard shortcut or a future
3025
+ * toolbar can hold a reference to one and call it without knowing where the
3026
+ * view lives or how it works. Methods buried in the facade are reachable only
3027
+ * by whoever holds the facade.
3028
+ *
3029
+ * @packageDocumentation
3030
+ */
3031
+ /**
3032
+ * Issues commands that change what is displayed, never what is stored.
3033
+ *
3034
+ * @public
3035
+ */
3036
+ class JmCommander {
3037
+ /** What commands may ask of the view. */
3038
+ view;
3039
+ /**
3040
+ * Creates a commander.
3041
+ *
3042
+ * @param view - The view's capabilities.
3043
+ */
3044
+ constructor(view) {
3045
+ this.view = view;
3046
+ }
3047
+ /**
3048
+ * Renders the displayed map to an image.
3049
+ *
3050
+ * @param options - Scale, format and quality.
3051
+ * @returns The encoded image plus its dimensions.
3052
+ */
3053
+ async exportImage(options) {
3054
+ return await this.view.capture(options);
3055
+ }
3056
+ }
3057
+
3058
+ /**
3059
+ * FreeMind serializer for mind maps (not yet implemented).
3060
+ *
3061
+ * @public
3062
+ */
3063
+ class JmMindFreeMindSerializer {
3064
+ /**
3065
+ * Gets the format name this serializer supports.
3066
+ *
3067
+ * @returns The format name.
3068
+ */
3069
+ getFormatName() {
3070
+ return 'freemind';
3071
+ }
3072
+ /**
3073
+ * Serializes a mind map to FreeMind format.
3074
+ *
3075
+ * @param mind - The mind map to serialize.
3076
+ * @returns The serialized data.
3077
+ * @throws {@link JsMindError} FreeMind serialization is not yet implemented.
3078
+ */
3079
+ serialize(mind) {
3080
+ throw new JsMindError('FreeMind serialization is not yet implemented', { cause: mind });
3081
+ }
3082
+ /**
3083
+ * Deserializes FreeMind data to a mind map.
3084
+ *
3085
+ * @param data - The data to deserialize.
3086
+ * @returns The deserialized mind map.
3087
+ * @throws {@link JsMindError} FreeMind deserialization is not yet implemented.
3088
+ */
3089
+ deserialize(data) {
3090
+ throw new JsMindError('FreeMind deserialization is not yet implemented', { cause: data });
3091
+ }
3092
+ /**
3093
+ * Validates if the data can be deserialized by this serializer.
3094
+ *
3095
+ * @remarks
3096
+ * Basic validation - will be implemented later.
3097
+ *
3098
+ * @param data - The data to validate.
3099
+ * @returns True if the data is valid for this format.
3100
+ */
3101
+ validate(data) {
3102
+ return false;
3103
+ }
3104
+ }
3105
+
3106
+ /**
3107
+ * Validation for v2 mind map data.
3108
+ *
3109
+ * @remarks
3110
+ * Every check returns a coded issue instead of throwing. A caller (the CLI, a
3111
+ * host application, an agent) branches on `code`; the `message` is for humans
3112
+ * to read and must never be parsed.
3113
+ *
3114
+ * @packageDocumentation
3115
+ */
3116
+ /**
3117
+ * Error codes for v2 data validation.
3118
+ *
3119
+ * @remarks
3120
+ * Codes are stable identifiers. Messages may be reworded at any time; these
3121
+ * may not.
3122
+ *
3123
+ * @public
3124
+ */
3125
+ const JmValidationCode = {
3126
+ /** Top-level `format` missing or not "jsmind_v2". */
3127
+ Format: 'E_FORMAT',
3128
+ /** `meta` missing or its fields are not strings. */
3129
+ Meta: 'E_META',
3130
+ /** The top-level `nodes` object is absent or not an object. */
3131
+ NodesMissing: 'E_NODES_MISSING',
3132
+ /** The top-level `edges` object is absent or not an object. */
3133
+ EdgesMissing: 'E_EDGES_MISSING',
3134
+ /** `root` does not point at an existing node. */
3135
+ RootMissing: 'E_ROOT_MISSING',
3136
+ /** A `nodes` key differs from the `id` of its value. */
3137
+ NodeKeyMismatch: 'E_NODE_KEY_MISMATCH',
3138
+ /** An `edges` key differs from the `id` of its value. */
3139
+ EdgeKeyMismatch: 'E_EDGE_KEY_MISMATCH',
3140
+ /** A node's `parent` points at a node that is not present. */
3141
+ NodeParentMissing: 'E_NODE_PARENT_MISSING',
3142
+ /** A node's `children` lists an id that is not present. */
3143
+ NodeChildMissing: 'E_NODE_CHILD_MISSING',
3144
+ /** An edge endpoint points at a node that is not present. */
3145
+ EdgeNodeMissing: 'E_EDGE_NODE_MISSING',
3146
+ /** More than one node has `parent === null`. */
3147
+ MultipleRoots: 'E_MULTIPLE_ROOTS',
3148
+ /** The root node has a non-null `parent`. */
3149
+ RootParentSet: 'E_ROOT_PARENT_SET',
3150
+ /** A non-root node uses `side: 0`, which belongs to the root alone. */
3151
+ NonRootSideCenter: 'E_NON_ROOT_SIDE_CENTER',
3152
+ /** `parent.children` and `child.parent` disagree. */
3153
+ ParentChildMismatch: 'E_PARENT_CHILD_MISMATCH',
3154
+ /** Following `parent` links returns to where it started. */
3155
+ Cycle: 'E_CYCLE',
3156
+ /** `content.type` is not a known content type. */
3157
+ ContentType: 'E_CONTENT_TYPE',
3158
+ /** `edge.type` is not a known edge type. */
3159
+ EdgeType: 'E_EDGE_TYPE',
3160
+ /** `side` is not a known side value. */
3161
+ Side: 'E_SIDE',
3162
+ /** `style.tone` is not one of the known tones. */
3163
+ Tone: 'E_TONE',
3164
+ /** A line pattern is not solid/dashed/dotted. */
3165
+ LineStyle: 'E_LINE_STYLE',
3166
+ /** A numeric style value is out of range. */
3167
+ StyleRange: 'E_STYLE_RANGE',
3168
+ /** `style.theme` names a preset that does not exist. */
3169
+ ThemeUnknown: 'E_THEME_UNKNOWN',
3170
+ };
3171
+ /** Edge types accepted for `edge.type`. */
3172
+ const EDGE_TYPES = new Set(Object.values(JmEdgeType));
3173
+ /** Numeric side values accepted for a node. */
3174
+ const SIDE_VALUES = new Set(Object.values(JmNodeSide));
3175
+ /** Line patterns accepted for `borderStyle` and `incoming.pattern`. */
3176
+ const LINE_PATTERNS = new Set(Object.values(JmLinePattern));
3177
+ /** Tones accepted for `style.tone`. */
3178
+ const TONES = new Set(Object.values(JmTone));
3179
+ /** Content types accepted for `content.type`. */
3180
+ const CONTENT_TYPES = new Set(Object.values(JmNodeContentType));
3181
+ /**
3182
+ * Narrows to a plain object.
3183
+ *
3184
+ * @param value - Value to test.
3185
+ * @returns True for non-null, non-array objects.
3186
+ */
3187
+ function isRecord(value) {
3188
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
3189
+ }
3190
+ /**
3191
+ * Reads a string field, or null when absent or not a string.
3192
+ *
3193
+ * @param holder - Object to read from.
3194
+ * @param key - Field name.
3195
+ * @returns The string, or null.
3196
+ */
3197
+ function str(holder, key) {
3198
+ const value = holder[key];
3199
+ return typeof value === 'string' ? value : null;
3200
+ }
3201
+ /**
3202
+ * Validates v2 data against every rule in the format specification.
3203
+ *
3204
+ * @remarks
3205
+ * Never throws for malformed input: anything structurally wrong becomes an
3206
+ * issue with a code. The one thing it cannot represent is a non-object root,
3207
+ * which it reports as `E_FORMAT` since nothing can be read from it.
3208
+ *
3209
+ * @param data - Candidate data, typically parsed JSON.
3210
+ * @returns Every issue found; `valid` is true only when the list is empty.
3211
+ *
3212
+ * @public
3213
+ */
3214
+ function validateMindData(data) {
3215
+ const errors = [];
3216
+ if (!isRecord(data)) {
3217
+ errors.push({
3218
+ code: JmValidationCode.Format,
3219
+ path: '',
3220
+ message: 'Data is not an object.',
3221
+ });
3222
+ return { valid: false, errors };
3223
+ }
3224
+ // ---- format ----
3225
+ if (data.format !== 'jsmind_v2') {
3226
+ errors.push({
3227
+ code: JmValidationCode.Format,
3228
+ path: 'format',
3229
+ message: `Expected format "jsmind_v2", got ${JSON.stringify(data.format) ?? 'nothing'}.`,
3230
+ });
3231
+ }
3232
+ // ---- meta ----
3233
+ const meta = data.meta;
3234
+ if (!isRecord(meta)) {
3235
+ errors.push({
3236
+ code: JmValidationCode.Meta,
3237
+ path: 'meta',
3238
+ message: 'Missing "meta" object.',
3239
+ });
3240
+ }
3241
+ else {
3242
+ for (const key of ['name', 'author', 'version']) {
3243
+ if (typeof meta[key] !== 'string') {
3244
+ errors.push({
3245
+ code: JmValidationCode.Meta,
3246
+ path: `meta/${key}`,
3247
+ message: `"meta.${key}" must be a string.`,
3248
+ });
3249
+ }
3250
+ }
3251
+ }
3252
+ // ---- nodes / edges containers ----
3253
+ const nodes = data.nodes;
3254
+ const edges = data.edges;
3255
+ // Both container checks run before the early return: a document missing both
3256
+ // should learn about both, not just whichever is checked first.
3257
+ if (!isRecord(nodes)) {
3258
+ errors.push({
3259
+ code: JmValidationCode.NodesMissing,
3260
+ path: 'nodes',
3261
+ message: 'Missing "nodes" object.',
3262
+ });
3263
+ }
3264
+ if (!isRecord(edges)) {
3265
+ errors.push({
3266
+ code: JmValidationCode.EdgesMissing,
3267
+ path: 'edges',
3268
+ message: 'Missing "edges" object.',
3269
+ });
3270
+ }
3271
+ if (!isRecord(nodes)) {
3272
+ // Without nodes there is not a single reference in the document that can
3273
+ // be resolved, so every later rule would only repeat itself.
3274
+ return { valid: false, errors };
3275
+ }
3276
+ const nodeIds = new Set(Object.keys(nodes));
3277
+ // ---- root ----
3278
+ const rootId = str(data, 'root');
3279
+ if (!rootId) {
3280
+ errors.push({
3281
+ code: JmValidationCode.RootMissing,
3282
+ path: 'root',
3283
+ message: '"root" must be a non-empty string.',
3284
+ });
3285
+ }
3286
+ else if (!nodeIds.has(rootId)) {
3287
+ errors.push({
3288
+ code: JmValidationCode.RootMissing,
3289
+ path: 'root',
3290
+ message: `"root" points at "${rootId}", which is not in "nodes".`,
3291
+ });
3292
+ }
3293
+ // ---- node keys ----
3294
+ for (const [key, node] of Object.entries(nodes)) {
3295
+ if (!isRecord(node)) {
3296
+ errors.push({
3297
+ code: JmValidationCode.NodeKeyMismatch,
3298
+ path: `nodes/${key}`,
3299
+ message: `Node under key "${key}" is not an object.`,
3300
+ });
3301
+ continue;
3302
+ }
3303
+ if (node.id !== key) {
3304
+ errors.push({
3305
+ code: JmValidationCode.NodeKeyMismatch,
3306
+ path: `nodes/${key}`,
3307
+ message: `Key "${key}" does not match the node's own id ${JSON.stringify(node.id)}.`,
3308
+ });
3309
+ }
3310
+ }
3311
+ // ---- edge keys ----
3312
+ if (isRecord(edges)) {
3313
+ for (const [key, edge] of Object.entries(edges)) {
3314
+ if (!isRecord(edge)) {
3315
+ errors.push({
3316
+ code: JmValidationCode.EdgeKeyMismatch,
3317
+ path: `edges/${key}`,
3318
+ message: `Edge under key "${key}" is not an object.`,
3319
+ });
3320
+ continue;
3321
+ }
3322
+ if (edge.id !== key) {
3323
+ errors.push({
3324
+ code: JmValidationCode.EdgeKeyMismatch,
3325
+ path: `edges/${key}`,
3326
+ message: `Key "${key}" does not match the edge's own id ${JSON.stringify(edge.id)}.`,
3327
+ });
3328
+ }
3329
+ }
3330
+ }
3331
+ // ---- per-node checks ----
3332
+ const parentOf = new Map();
3333
+ for (const [key, node] of Object.entries(nodes)) {
3334
+ if (!isRecord(node)) {
3335
+ continue;
3336
+ }
3337
+ const at = `nodes/${key}`;
3338
+ // content
3339
+ const content = node.content;
3340
+ if (!isRecord(content)) {
3341
+ errors.push({
3342
+ code: JmValidationCode.ContentType,
3343
+ path: `${at}/content`,
3344
+ message: 'Missing "content" object.',
3345
+ });
3346
+ }
3347
+ else {
3348
+ const type = content.type;
3349
+ if (typeof type !== 'string' || !CONTENT_TYPES.has(type)) {
3350
+ errors.push({
3351
+ code: JmValidationCode.ContentType,
3352
+ path: `${at}/content/type`,
3353
+ message: `Unknown content type ${JSON.stringify(type)}. Expected one of ${[...CONTENT_TYPES].join(', ')}.`,
3354
+ });
3355
+ }
3356
+ }
3357
+ // parent reference
3358
+ const parent = node.parent;
3359
+ if (parent === null) {
3360
+ parentOf.set(key, null);
3361
+ }
3362
+ else if (typeof parent === 'string') {
3363
+ parentOf.set(key, parent);
3364
+ if (!nodeIds.has(parent)) {
3365
+ errors.push({
3366
+ code: JmValidationCode.NodeParentMissing,
3367
+ path: `${at}/parent`,
3368
+ message: `Parent "${parent}" is not in "nodes".`,
3369
+ });
3370
+ }
3371
+ }
3372
+ else {
3373
+ errors.push({
3374
+ code: JmValidationCode.NodeParentMissing,
3375
+ path: `${at}/parent`,
3376
+ message: '"parent" must be a node id or null.',
3377
+ });
3378
+ // Deliberately NOT recorded as null. A malformed parent is
3379
+ // undetermined, not root-like: recording it as null makes the root
3380
+ // count below report an extra E_MULTIPLE_ROOTS for the same broken
3381
+ // field, which is a false positive on a different code.
3382
+ }
3383
+ // children references
3384
+ const children = node.children;
3385
+ if (!Array.isArray(children)) {
3386
+ errors.push({
3387
+ code: JmValidationCode.NodeChildMissing,
3388
+ path: `${at}/children`,
3389
+ message: '"children" must be an array.',
3390
+ });
3391
+ }
3392
+ else {
3393
+ for (const childId of children) {
3394
+ if (typeof childId !== 'string' || !nodeIds.has(childId)) {
3395
+ errors.push({
3396
+ code: JmValidationCode.NodeChildMissing,
3397
+ path: `${at}/children`,
3398
+ message: `Child ${JSON.stringify(childId)} is not in "nodes".`,
3399
+ });
3400
+ }
3401
+ }
3402
+ }
3403
+ // side is a number in the JSON, per the format spec: -1 left, 0 centre,
3404
+ // 1 right. No name conversion happens at this layer.
3405
+ const side = node.side;
3406
+ if (typeof side !== 'number' || !SIDE_VALUES.has(side)) {
3407
+ errors.push({
3408
+ code: JmValidationCode.Side,
3409
+ path: `${at}/side`,
3410
+ message: `"side" must be -1, 0 or 1, got ${JSON.stringify(side)}.`,
3411
+ });
3412
+ }
3413
+ else if (side === JmNodeSide.Center && parent !== null) {
3414
+ // Centre is not a position, it is the absence of one: it tells the
3415
+ // layout to place the node relative to the root, which only the root
3416
+ // itself can do. A child carrying it is laid out nowhere and does
3417
+ // not paint at all - the data validates, the node silently vanishes
3418
+ // from the picture, and nothing downstream says why.
3419
+ errors.push({
3420
+ code: JmValidationCode.NonRootSideCenter,
3421
+ path: `${at}/side`,
3422
+ message: 'Only the root may use side 0 (centre); a child must be -1 (left) or 1 (right).',
3423
+ });
3424
+ }
3425
+ // per-node style
3426
+ validateNodeStyle(node.style, `${at}/style`, errors);
3427
+ }
3428
+ // ---- parent/children agreement ----
3429
+ for (const [key, node] of Object.entries(nodes)) {
3430
+ if (!isRecord(node) || !Array.isArray(node.children)) {
3431
+ continue;
3432
+ }
3433
+ for (const childId of node.children) {
3434
+ if (typeof childId !== 'string') {
3435
+ continue;
3436
+ }
3437
+ const child = nodes[childId];
3438
+ if (!isRecord(child)) {
3439
+ continue;
3440
+ }
3441
+ if (child.parent !== key) {
3442
+ errors.push({
3443
+ code: JmValidationCode.ParentChildMismatch,
3444
+ path: `nodes/${childId}/parent`,
3445
+ message: `Listed as a child of "${key}", but its parent is ${JSON.stringify(child.parent)}.`,
3446
+ });
3447
+ }
3448
+ }
3449
+ }
3450
+ // ---- exactly one root ----
3451
+ // Nodes with a malformed parent are absent from parentOf entirely, so a
3452
+ // broken field cannot masquerade as a second root.
3453
+ const roots = [...parentOf.entries()].filter(([, parent]) => parent === null).map(([id]) => id);
3454
+ if (roots.length > 1) {
3455
+ errors.push({
3456
+ code: JmValidationCode.MultipleRoots,
3457
+ path: 'nodes',
3458
+ message: `${roots.length} nodes have a null parent: ${roots.join(', ')}. Exactly one is allowed.`,
3459
+ });
3460
+ }
3461
+ if (rootId && parentOf.has(rootId) && parentOf.get(rootId) !== null) {
3462
+ errors.push({
3463
+ code: JmValidationCode.RootParentSet,
3464
+ path: `nodes/${rootId}/parent`,
3465
+ message: 'The root node must have a null parent.',
3466
+ });
3467
+ }
3468
+ // ---- cycles ----
3469
+ // A node whose parent chain runs INTO a cycle but does not belong to one
3470
+ // must not be blamed: walking up from D (D -> A -> B -> C -> A) does revisit
3471
+ // a node, but it is A, not D. Report the cycle's own members instead.
3472
+ const reportedCycles = new Set();
3473
+ for (const startId of nodeIds) {
3474
+ const cycle = findParentCycle(startId, parentOf);
3475
+ if (cycle === null) {
3476
+ continue;
3477
+ }
3478
+ // Same cycle reached from different entry points yields the same member
3479
+ // set; sort it so one cycle is reported exactly once, and pick a stable
3480
+ // node to hang the issue on.
3481
+ const members = [...cycle].sort();
3482
+ const key = members.join(',');
3483
+ if (reportedCycles.has(key)) {
3484
+ continue;
3485
+ }
3486
+ reportedCycles.add(key);
3487
+ errors.push({
3488
+ code: JmValidationCode.Cycle,
3489
+ path: `nodes/${members[0]}`,
3490
+ message: `Following "parent" from this node returns to it (cycle: ${members.join(' -> ')} -> ${members[0]}).`,
3491
+ });
3492
+ }
3493
+ // ---- edges ----
3494
+ if (isRecord(edges)) {
3495
+ for (const [key, edge] of Object.entries(edges)) {
3496
+ if (!isRecord(edge)) {
3497
+ continue;
3498
+ }
3499
+ const at = `edges/${key}`;
3500
+ const edgeType = edge.type;
3501
+ if (typeof edgeType !== 'string' || !EDGE_TYPES.has(edgeType)) {
3502
+ errors.push({
3503
+ code: JmValidationCode.EdgeType,
3504
+ path: `${at}/type`,
3505
+ message: `Unknown edge type ${JSON.stringify(edgeType)}. Expected one of ${[...EDGE_TYPES].join(', ')}.`,
3506
+ });
3507
+ }
3508
+ for (const field of ['sourceNodeId', 'targetNodeId']) {
3509
+ const endpoint = edge[field];
3510
+ if (typeof endpoint !== 'string' || !nodeIds.has(endpoint)) {
3511
+ errors.push({
3512
+ code: JmValidationCode.EdgeNodeMissing,
3513
+ path: `${at}/${field}`,
3514
+ message: `Edge endpoint ${JSON.stringify(endpoint)} is not in "nodes".`,
3515
+ });
3516
+ }
3517
+ }
3518
+ validateLineStyle(edge.style, `${at}/style`, errors);
3519
+ }
3520
+ }
3521
+ // ---- mind map style ----
3522
+ validateMindStyle(data.style, errors);
3523
+ return { valid: errors.length === 0, errors };
3524
+ }
3525
+ /**
3526
+ * Walks parent links from a node and returns the members of the cycle it hits.
3527
+ *
3528
+ * @remarks
3529
+ * Returns the cycle itself, not the starting node. Walking up from a node that
3530
+ * merely points *into* a cycle passes through that cycle without belonging to
3531
+ * it — the caller needs the members to blame the right nodes and to recognise
3532
+ * the same cycle reached from different starting points.
3533
+ *
3534
+ * @param startId - Node to start from.
3535
+ * @param parentOf - Parent map built during the walk.
3536
+ * @returns Member ids of the cycle, in traversal order; null when the chain
3537
+ * ends without looping.
3538
+ */
3539
+ function findParentCycle(startId, parentOf) {
3540
+ const path = [];
3541
+ const indexOf = new Map();
3542
+ let cursor = startId;
3543
+ while (cursor !== null && cursor !== undefined) {
3544
+ const seenAt = indexOf.get(cursor);
3545
+ if (seenAt !== undefined) {
3546
+ // Everything from the first sighting onwards is the cycle; what came
3547
+ // before it is the tail that led in and is not part of it.
3548
+ return path.slice(seenAt);
3549
+ }
3550
+ indexOf.set(cursor, path.length);
3551
+ path.push(cursor);
3552
+ cursor = parentOf.get(cursor);
3553
+ }
3554
+ return null;
3555
+ }
3556
+ /**
3557
+ * Validates the per-node style block.
3558
+ *
3559
+ * @param style - Candidate style value.
3560
+ * @param at - Path prefix for messages.
3561
+ * @param errors - Collector.
3562
+ */
3563
+ function validateNodeStyle(style, at, errors) {
3564
+ if (style === undefined) {
3565
+ return;
3566
+ }
3567
+ if (!isRecord(style)) {
3568
+ errors.push({
3569
+ code: JmValidationCode.StyleRange,
3570
+ path: at,
3571
+ message: '"style" must be an object.',
3572
+ });
3573
+ return;
3574
+ }
3575
+ const tone = style.tone;
3576
+ if (tone !== undefined && (typeof tone !== 'string' || !TONES.has(tone))) {
3577
+ errors.push({
3578
+ code: JmValidationCode.Tone,
3579
+ path: `${at}/tone`,
3580
+ message: `Unknown tone ${JSON.stringify(tone)}. Expected one of ${[...TONES].join(', ')}.`,
3581
+ });
3582
+ }
3583
+ const borderPattern = style.borderStyle;
3584
+ if (borderPattern !== undefined) {
3585
+ if (typeof borderPattern !== 'string' || !LINE_PATTERNS.has(borderPattern)) {
3586
+ errors.push({
3587
+ code: JmValidationCode.LineStyle,
3588
+ path: `${at}/borderStyle`,
3589
+ message: `Unknown line pattern ${JSON.stringify(borderPattern)}. Expected one of ${[...LINE_PATTERNS].join(', ')}.`,
3590
+ });
3591
+ }
3592
+ }
3593
+ for (const field of ['borderWidth', 'fontSize']) {
3594
+ const value = style[field];
3595
+ if (value !== undefined && (typeof value !== 'number' || !(value > 0))) {
3596
+ errors.push({
3597
+ code: JmValidationCode.StyleRange,
3598
+ path: `${at}/${field}`,
3599
+ message: `"${field}" must be a positive number, got ${JSON.stringify(value)}.`,
3600
+ });
3601
+ }
3602
+ }
3603
+ if (style.incoming !== undefined) {
3604
+ validateLineStyle(style.incoming, `${at}/incoming`, errors);
3605
+ }
3606
+ }
3607
+ /**
3608
+ * Validates a line style block, shared by node `incoming` and edge `style`.
3609
+ *
3610
+ * @param style - Candidate line style.
3611
+ * @param at - Path prefix for messages.
3612
+ * @param errors - Collector.
3613
+ */
3614
+ function validateLineStyle(style, at, errors) {
3615
+ if (style === undefined) {
3616
+ return;
3617
+ }
3618
+ if (!isRecord(style)) {
3619
+ errors.push({
3620
+ code: JmValidationCode.LineStyle,
3621
+ path: at,
3622
+ message: 'Line style must be an object.',
3623
+ });
3624
+ return;
3625
+ }
3626
+ if (style.pattern !== undefined) {
3627
+ const pattern = style.pattern;
3628
+ if (typeof pattern !== 'string' || !LINE_PATTERNS.has(pattern)) {
3629
+ errors.push({
3630
+ code: JmValidationCode.LineStyle,
3631
+ path: `${at}/pattern`,
3632
+ message: `Unknown line pattern ${JSON.stringify(pattern)}. Expected one of ${[...LINE_PATTERNS].join(', ')}.`,
3633
+ });
3634
+ }
3635
+ }
3636
+ const width = style.width;
3637
+ if (width !== undefined && (typeof width !== 'number' || !(width > 0))) {
3638
+ errors.push({
3639
+ code: JmValidationCode.StyleRange,
3640
+ path: `${at}/width`,
3641
+ message: `"width" must be a positive number, got ${JSON.stringify(width)}.`,
3642
+ });
3643
+ }
3644
+ }
3645
+ /**
3646
+ * Validates the mind map level style declaration.
3647
+ *
3648
+ * @param style - Candidate style declaration.
3649
+ * @param errors - Collector.
3650
+ */
3651
+ function validateMindStyle(style, errors) {
3652
+ if (style === undefined) {
3653
+ return;
3654
+ }
3655
+ if (!isRecord(style)) {
3656
+ errors.push({
3657
+ code: JmValidationCode.StyleRange,
3658
+ path: 'style',
3659
+ message: '"style" must be an object.',
3660
+ });
3661
+ return;
3662
+ }
3663
+ const themeName = style.theme;
3664
+ if (themeName !== undefined) {
3665
+ if (typeof themeName !== 'string') {
3666
+ errors.push({
3667
+ code: JmValidationCode.ThemeUnknown,
3668
+ path: 'style/theme',
3669
+ message: '"style.theme" must be a string.',
3670
+ });
3671
+ }
3672
+ else if (!(themeName in JSMIND_THEME_PRESETS)) {
3673
+ errors.push({
3674
+ code: JmValidationCode.ThemeUnknown,
3675
+ path: 'style/theme',
3676
+ message: `Unknown theme ${JSON.stringify(themeName)}. Known themes: ${Object.keys(JSMIND_THEME_PRESETS).join(', ')}.`,
3677
+ });
3678
+ }
3679
+ }
3680
+ if (style.tones !== undefined) {
3681
+ if (!isRecord(style.tones)) {
3682
+ errors.push({
3683
+ code: JmValidationCode.StyleRange,
3684
+ path: 'style/tones',
3685
+ message: '"style.tones" must be an object.',
3686
+ });
3687
+ }
3688
+ else {
3689
+ for (const toneName of Object.keys(style.tones)) {
3690
+ if (!TONES.has(toneName)) {
3691
+ errors.push({
3692
+ code: JmValidationCode.Tone,
3693
+ path: `style/tones/${toneName}`,
3694
+ message: `Unknown tone ${JSON.stringify(toneName)}.`,
3695
+ });
3696
+ }
3697
+ }
3698
+ }
3699
+ }
3700
+ for (const section of ['node', 'line', 'expander']) {
3701
+ if (style[section] === undefined) {
3702
+ continue;
3703
+ }
3704
+ if (!isRecord(style[section])) {
3705
+ errors.push({
3706
+ code: JmValidationCode.StyleRange,
3707
+ path: `style/${section}`,
3708
+ message: `"style.${section}" must be an object.`,
3709
+ });
3710
+ }
3711
+ }
3712
+ }
3713
+
3714
+ /**
3715
+ * Format identifier written to every v2 data file.
3716
+ *
3717
+ * @public
3718
+ */
3719
+ const JSMIND_FORMAT_V2 = 'jsmind_v2';
3720
+ /**
3721
+ * JSON serializer for mind maps.
3722
+ *
3723
+ * @public
3724
+ */
3725
+ class JmMindJsonSerializer {
3726
+ /**
3727
+ * Gets the format name this serializer supports.
3728
+ *
3729
+ * @returns The format name.
3730
+ */
3731
+ getFormatName() {
3732
+ return 'json';
3733
+ }
3734
+ /**
3735
+ * Serializes a mind map to JSON format.
3736
+ *
3737
+ * @param mind - The mind map to serialize.
3738
+ * @returns The serialized JSON data.
3739
+ * @throws {@link JsMindError} If the mind map is not provided.
3740
+ */
3741
+ serialize(mind) {
3742
+ if (!mind) {
3743
+ throw new JsMindError('Mind map is required for serialization');
3744
+ }
3745
+ const serializedData = {
3746
+ format: JSMIND_FORMAT_V2,
3747
+ meta: mind.meta,
3748
+ root: mind._root.id,
3749
+ nodes: {},
3750
+ edges: {}
3751
+ };
3752
+ if (mind.style !== undefined) {
3753
+ serializedData.style = mind.style;
3754
+ }
3755
+ // Serialize all nodes
3756
+ Object.values(mind._nodes).forEach(node => {
3757
+ serializedData.nodes[node.id] = this._serializeNode(node);
3758
+ });
3759
+ // Serialize all additional edges
3760
+ Object.values(mind._edges).forEach(edge => {
3761
+ serializedData.edges[edge.id] = this._serializeEdge(edge);
3762
+ });
3763
+ return serializedData;
3764
+ }
3765
+ /**
3766
+ * Deserializes JSON data to a mind map.
3767
+ *
3768
+ * @param data - The JSON data to deserialize.
3769
+ * @returns The deserialized mind map.
3770
+ * @throws {@link JsMindError} If the JSON data format is invalid.
3771
+ */
3772
+ deserialize(data) {
3773
+ const result = this.check(data);
3774
+ if (!result.valid) {
3775
+ throw new JsMindError(`Invalid JSON data format: ${summarise(result.errors)}`, { errors: result.errors }, result.errors[0].code);
3776
+ }
3777
+ // Create mind map with metadata and options
3778
+ const mind = new JmMind(data.meta, { rootNodeId: data.root });
3779
+ if (data.style !== undefined) {
3780
+ mind.style = data.style;
3781
+ }
3782
+ // Restore nodes
3783
+ Object.values(data.nodes).forEach((nodeData) => {
3784
+ const node = this._deserializeNode(nodeData);
3785
+ mind._nodes[node.id] = node;
3786
+ });
3787
+ // Restore additional edges
3788
+ if (data.edges) {
3789
+ Object.values(data.edges).forEach((edgeData) => {
3790
+ const edge = this._deserializeEdge(edgeData);
3791
+ mind._edges[edge.id] = edge;
3792
+ });
3793
+ }
3794
+ // Restore root
3795
+ mind._root = mind._nodes[data.root];
3796
+ // Restore parent-child relationships
3797
+ this._restoreNodeRelationships(mind, data);
3798
+ return mind;
3799
+ }
3800
+ /**
3801
+ * Validates if the data can be deserialized by this serializer.
3802
+ *
3803
+ * @param data - The data to validate.
3804
+ * @returns True if the data is valid for this format.
3805
+ */
3806
+ validate(data) {
3807
+ return this.check(data).valid;
3808
+ }
3809
+ /**
3810
+ * Validates data and returns every problem found.
3811
+ *
3812
+ * @remarks
3813
+ * Use this instead of `validate` when the caller needs to know *why* data
3814
+ * was rejected. Each issue carries a stable `code`, a `path` into the
3815
+ * document, and a message written for humans.
3816
+ *
3817
+ * @param data - The data to validate.
3818
+ * @returns Every issue found; `valid` is true only when there are none.
3819
+ */
3820
+ check(data) {
3821
+ return validateMindData(data);
3822
+ }
3823
+ /**
3824
+ * Serializes a single node.
3825
+ *
3826
+ * @private
3827
+ * @param node - The node to serialize.
3828
+ * @returns The serialized node data.
3829
+ */
3830
+ _serializeNode(node) {
3831
+ return {
3832
+ id: node.id,
3833
+ content: {
3834
+ type: node.content.type,
3835
+ value: node.content.value
3836
+ },
3837
+ parent: node.parent ? node.parent.id : null,
3838
+ children: node.children.map(child => child.id),
3839
+ folded: node.folded,
3840
+ side: node.side,
3841
+ data: { ...node.data },
3842
+ ...(node.style ? { style: copyNodeStyle(node.style) } : {})
3843
+ };
3844
+ }
3845
+ /**
3846
+ * Deserializes a single node.
3847
+ *
3848
+ * @private
3849
+ * @param nodeData - The node data to deserialize.
3850
+ * @returns The deserialized node.
3851
+ */
3852
+ _deserializeNode(nodeData) {
3853
+ const content = new JmNodeContent(nodeData.content.type, nodeData.content.value);
3854
+ const node = new JmNode(nodeData.id, content);
3855
+ node.folded = nodeData.folded;
3856
+ node.side = nodeData.side;
3857
+ node.data = { ...nodeData.data };
3858
+ if (nodeData.style) {
3859
+ node.style = copyNodeStyle(nodeData.style);
3860
+ }
3861
+ return node;
3862
+ }
3863
+ /**
3864
+ * Serializes a single edge.
3865
+ *
3866
+ * @private
3867
+ * @param edge - The edge to serialize.
3868
+ * @returns The serialized edge data.
3869
+ */
3870
+ _serializeEdge(edge) {
3871
+ return {
3872
+ id: edge.id,
3873
+ sourceNodeId: edge.sourceNodeId,
3874
+ targetNodeId: edge.targetNodeId,
3875
+ type: edge.type,
3876
+ label: edge.label,
3877
+ ...(edge.style ? { style: copyLineStyle(edge.style) } : {})
3878
+ };
3879
+ }
3880
+ /**
3881
+ * Deserializes a single edge.
3882
+ *
3883
+ * @private
3884
+ * @param edgeData - The edge data to deserialize.
3885
+ * @returns The deserialized edge.
3886
+ */
3887
+ _deserializeEdge(edgeData) {
3888
+ const edge = new JmEdge(edgeData.id, edgeData.sourceNodeId, edgeData.targetNodeId, edgeData.type, edgeData.label);
3889
+ if (edgeData.style) {
3890
+ edge.style = copyLineStyle(edgeData.style);
3891
+ }
3892
+ return edge;
3893
+ }
3894
+ /**
3895
+ * Restores parent-child relationships between nodes.
3896
+ *
3897
+ * @private
3898
+ * @param mind - The mind map to restore relationships for.
3899
+ * @param data - The serialized data containing parent and children information.
3900
+ */
3901
+ _restoreNodeRelationships(mind, data) {
3902
+ // Restore parent relationships
3903
+ Object.values(data.nodes).forEach((nodeData) => {
3904
+ const node = mind._nodes[nodeData.id];
3905
+ if (nodeData.parent !== null) {
3906
+ const parentNode = mind._nodes[nodeData.parent];
3907
+ if (parentNode) {
3908
+ node.parent = parentNode;
3909
+ }
3910
+ }
3911
+ else {
3912
+ node.parent = null;
3913
+ }
3914
+ });
3915
+ // Restore children relationships
3916
+ Object.values(data.nodes).forEach((nodeData) => {
3917
+ const node = mind._nodes[nodeData.id];
3918
+ node.children = nodeData.children
3919
+ .map((childId) => mind._nodes[childId])
3920
+ .filter((child) => child !== undefined);
3921
+ });
3922
+ }
3923
+ }
3924
+ /**
3925
+ * Summarises validation issues into one readable sentence.
3926
+ *
3927
+ * @remarks
3928
+ * The first issue carries the most useful detail; the remaining count tells
3929
+ * the reader whether to expect more. Full detail is in `error.data.errors`.
3930
+ *
3931
+ * @param errors - Issues to summarise.
3932
+ * @returns A single human-readable line.
3933
+ */
3934
+ function summarise(errors) {
3935
+ const first = errors[0];
3936
+ const rest = errors.length - 1;
3937
+ const suffix = rest > 0 ? ` (and ${rest} more)` : '';
3938
+ return `${first.code} at ${first.path || '<root>'}: ${first.message}${suffix}`;
3939
+ }
3940
+ /**
3941
+ * Copies a node style so the serialized snapshot does not share nested objects
3942
+ * with the live model.
3943
+ *
3944
+ * @remarks
3945
+ * `incoming` is the only nested field, so a two-level copy covers the whole
3946
+ * structure. Sharing it would let a later edit to `node.style.incoming` reach
3947
+ * back into data that was already serialized.
3948
+ *
3949
+ * @param style - The style to copy.
3950
+ * @returns A detached copy.
3951
+ */
3952
+ function copyNodeStyle(style) {
3953
+ return style.incoming
3954
+ ? { ...style, incoming: copyLineStyle(style.incoming) }
3955
+ : { ...style };
3956
+ }
3957
+ /**
3958
+ * Copies a line style.
3959
+ *
3960
+ * @remarks
3961
+ * `JmLineStyle` holds scalars only, so a spread is a full copy. Kept as a
3962
+ * named function so node styles and edge styles go through one path — if the
3963
+ * shape ever grows a nested field, only this function needs to change.
3964
+ *
3965
+ * @param style - The line style to copy.
3966
+ * @returns A detached copy.
3967
+ */
3968
+ function copyLineStyle(style) {
3969
+ return { ...style };
3970
+ }
3971
+
3972
+ class JmMindSerializerFactory {
3973
+ static create(format) {
3974
+ switch (format) {
3975
+ case 'json':
3976
+ return new JmMindJsonSerializer();
3977
+ case 'freemind':
3978
+ return new JmMindFreeMindSerializer();
3979
+ default:
3980
+ throw new JsMindError(`Invalid serializer format: ${format}`);
3981
+ }
3982
+ }
3983
+ }
3984
+
3985
+ /**
3986
+ * Main class for jsMind mind map operations.
3987
+ *
3988
+ * @public
3989
+ */
3990
+ class JsMind {
3991
+ /**
3992
+ * Gets the version of jsMind.
3993
+ *
3994
+ * @returns The version string.
3995
+ */
3996
+ static get Version() { return '2.0'; }
3997
+ /**
3998
+ * Gets the author of jsMind.
3999
+ *
4000
+ * @returns The author string.
4001
+ */
4002
+ static get Author() { return 'hizzgdev@163.com'; }
4003
+ /**
4004
+ * Exported classes for browser use.
4005
+ */
4006
+ static Mind = JmMind;
4007
+ static Serializer = JmMindSerializerFactory;
4008
+ static NodeSide = JmNodeSide;
4009
+ /** The options for this jsMind instance. */
4010
+ options;
4011
+ /** The currently opened mind map, or null if none is open. */
4012
+ mind = null;
4013
+ /** The state coordinator instance for managing the state of the mind map. */
4014
+ coordinator;
4015
+ /** Issues display-affecting commands. */
4016
+ commander;
4017
+ /**
4018
+ * Creates a new jsMind instance.
4019
+ *
4020
+ * @param options - Configuration options for the jsMind instance.
4021
+ */
4022
+ constructor(options, mindChangeCoordinator, commander) {
4023
+ this.options = options;
4024
+ this.coordinator = mindChangeCoordinator;
4025
+ this.commander = commander;
4026
+ }
4027
+ static async create(container, options) {
4028
+ const mergedOptions = mergeJsMindOptions(options);
4029
+ const arranger = new MindmapArranger(mergedOptions.layout);
4030
+ const view = await JmView.create(container, arranger, mergedOptions.view);
4031
+ const mindChangeCoordinator = new JmMindChangeCoordinator(arranger, view);
4032
+ const commander = new JmCommander(view);
4033
+ return new JsMind(mergedOptions, mindChangeCoordinator, commander);
4034
+ }
4035
+ /**
4036
+ * Opens a mind map.
4037
+ *
4038
+ * @param mind - The mind map instance to open.
4039
+ * @returns The opened mind map instance.
4040
+ */
4041
+ async open(mind) {
4042
+ this.mind = mind;
4043
+ await this.coordinator.onMindMapOpened(mind);
4044
+ mind.observerManager.addObserver(this.coordinator);
4045
+ }
4046
+ /**
4047
+ * Closes the current mind map (cleanup method).
4048
+ *
4049
+ * @remarks
4050
+ * This method can be extended in the future for cleanup operations
4051
+ * like removing observers, clearing caches, etc.
4052
+ */
4053
+ close() {
4054
+ if (this.mind) {
4055
+ this.coordinator.onMindMapClosed(this.mind);
4056
+ this.mind = null;
4057
+ }
4058
+ }
4059
+ /**
4060
+ * Serializes the current mind map to JSON.
4061
+ *
4062
+ * @returns JSON string representation of the mind map.
4063
+ * @throws {@link Error} If no mind map is open or serialization fails.
4064
+ */
4065
+ serialize() {
4066
+ if (!this.mind) {
4067
+ throw new Error('No mind map is currently open');
4068
+ }
4069
+ const serializer = JmMindSerializerFactory.create('json');
4070
+ const data = serializer.serialize(this.mind);
4071
+ return JSON.stringify(data);
4072
+ }
4073
+ /**
4074
+ * Renders the open mind map to an image.
4075
+ *
4076
+ * The size is the rendered content's own size: whitespace inside the
4077
+ * container is part of the picture, and a map larger than its container is
4078
+ * not cropped.
4079
+ *
4080
+ * @param options - Scale, format and quality. Defaults to PNG at 2x.
4081
+ * @returns The encoded image, as a Blob, plus its pixel dimensions.
4082
+ * @throws {@link JsMindError} If no mind map is open, or if the browser
4083
+ * cannot encode the result.
4084
+ */
4085
+ async exportImage(options) {
4086
+ if (!this.mind) {
4087
+ throw new JsMindError('No mind map is currently open');
4088
+ }
4089
+ return await this.commander.exportImage(options);
4090
+ }
4091
+ }
4092
+ // Example pages and the CLI image export look the library up as a global.
4093
+ // Package consumers use the default export from the ESM bundle, or the CJS
4094
+ // entry at `dist/jsmind.cjs`. A classic script tag loads `dist/jsmind.umd.js`,
4095
+ // which assigns this same global without an `export`.
4096
+ globalThis.jsMind = JsMind;
4097
+
4098
+ export { JsMind as default };
4099
+ //# sourceMappingURL=jsmind.js.map