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