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