Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
2098 lines (1954 loc) · 87.2 KB
/
Copy pathapp.js
File metadata and controls
2098 lines (1954 loc) · 87.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(() => {
"use strict";
const STORAGE_KEY = "mindflow-line-workspace-v2";
const STAGE = { width: 3600, height: 2600 };
const PALETTE = ["#d93472", "#b45cff", "#7a63ff", "#ff6f61", "#ef476f", "#4a7dff", "#ff9f43", "#607d8b"];
const ICONS = ["", "🎯", "💡", "✅", "⭐", "📌", "🚀", "📊", "🧩", "📝", "⚡", "🔎"];
const THEMES = {
forest: {
label: "示意图",
root: "#b45cff",
branches: ["#d93472", "#b45cff", "#7a63ff", "#ff6f61", "#ef476f", "#4a7dff"],
rootText: "#111111"
},
studio: {
label: "洋红",
root: "#d93472",
branches: ["#d93472", "#ff5f8f", "#ff7b54", "#b45cff", "#7a63ff", "#ff9f43"],
rootText: "#111111"
},
daylight: {
label: "蓝紫",
root: "#7a63ff",
branches: ["#7a63ff", "#4a7dff", "#b45cff", "#d93472", "#ff6f61", "#ef476f"],
rootText: "#111111"
},
paper: {
label: "极简",
root: "#6d6bff",
branches: ["#cf2f73", "#b45cff", "#6d6bff", "#ff6f61", "#f43f5e", "#f59e0b"],
rootText: "#111111"
}
};
const els = {};
let saveTimer = null;
let suppressClickUntil = 0;
let pointerSession = null;
let pendingSummaryTargets = [];
const state = {
title: "中断",
nodes: [],
relationships: [],
summaries: [],
selectedId: null,
inspectorTab: "style",
themeName: "forest",
uiTheme: "light",
viewport: { x: 0, y: 0, scale: 1 },
history: [],
future: [],
leftCollapsed: false,
rightCollapsed: true,
gridVisible: false,
minimapVisible: false,
connectionSource: null,
presentation: false
};
function uid(prefix = "node") {
if (window.crypto?.randomUUID) return `${prefix}-${window.crypto.randomUUID().slice(0, 8)}`;
return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
}
function icon(name, className = "") {
return `<svg${className ? ` class="${className}"` : ""} aria-hidden="true"><use href="#i-${name}"/></svg>`;
}
function escapeHtml(value = "") {
return String(value)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function escapeXml(value = "") {
return escapeHtml(value);
}
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
function node(id, parentId, text, x, y, options = {}) {
return {
id,
parentId,
text,
x,
y,
width: options.width || (parentId ? 228 : 168),
height: options.height || (parentId ? 64 : 74),
color: options.color || PALETTE[0],
background: options.background || "",
textColor: options.textColor || "",
side: options.side || "right",
shape: options.shape || "line",
icon: options.icon || "",
note: options.note || "",
tags: options.tags || [],
priority: options.priority || "",
link: options.link || "",
attachment: options.attachment || "",
image: options.image || "",
bold: Boolean(options.bold),
italic: Boolean(options.italic),
fontSize: options.fontSize || (parentId ? 16 : 22),
collapsed: Boolean(options.collapsed),
autoColor: options.autoColor !== false,
summaryLabel: options.summaryLabel || "",
summaryTargets: options.summaryTargets || []
};
}
function makeDefaultMap() {
return [
node("root", null, "中断", 88, 300, { width: 170, height: 82, color: "#b45cff", textColor: "#111111", bold: true, fontSize: 28 }),
node("inner", "root", "内部异常", 320, 210, { width: 230, height: 72, color: "#d93472", bold: false, fontSize: 18, summaryLabel: "软件中断", summaryTargets: ["fault", "trap"] }),
node("fault", "inner", "故障(故障)", 548, 120, { width: 240, height: 66, color: "#d93472", fontSize: 18 }),
node("trap", "inner", "自陷(Trap)", 548, 210, { width: 230, height: 66, color: "#d93472", fontSize: 18 }),
node("abort", "inner", "终止(中止)", 548, 300, { width: 236, height: 66, color: "#d93472", fontSize: 18 }),
node("outer", "root", "外部中断(硬件)", 320, 430, { width: 270, height: 76, color: "#b45cff", fontSize: 18, summaryLabel: "硬件中断", summaryTargets: ["intr", "nmi"] }),
node("intr", "outer", "可屏蔽中断(INTR)", 610, 386, { width: 286, height: 66, color: "#b45cff", fontSize: 18 }),
node("nmi", "outer", "不可屏蔽中断(NMI)", 610, 474, { width: 296, height: 66, color: "#b45cff", fontSize: 18 })
];
}
function makeBlankMap() {
return [node("root", null, "中心主题", 88, 300, {
width: 180,
height: 82,
color: THEMES[state.themeName].root,
bold: true,
fontSize: 28,
textColor: "#111111"
})];
}
function makeDefaultSummaries() {
return [
{ id: "summary-software", label: "软件中断", targetIds: ["fault", "trap"] },
{ id: "summary-hardware", label: "硬件中断", targetIds: ["intr", "nmi"] }
];
}
function normalizeSummaries(rawSummaries, nodes = state.nodes) {
if (!Array.isArray(rawSummaries)) return [];
const ids = new Set(nodes.map((item) => item.id));
return rawSummaries.map((summary) => ({
id: String(summary?.id || uid("summary")),
label: String(summary?.label || "概要"),
targetIds: Array.isArray(summary?.targetIds) ? summary.targetIds.map(String).filter((id) => ids.has(id)) : []
})).filter((summary) => summary.targetIds.length >= 2);
}
function cacheElements() {
[
"app-shell", "document-title", "save-state-text", "left-panel", "left-panel-content",
"canvas-area", "canvas-viewport", "canvas-stage", "connections-layer", "nodes-layer",
"relationship-layer", "node-action-bar", "breadcrumb-text", "zoom-value", "minimap", "minimap-canvas",
"right-panel", "inspector-content", "node-count", "selected-label", "status-message",
"menu-layer", "modal-layer", "toast-region", "file-input"
].forEach((id) => {
els[id.replaceAll("-", "_")] = document.getElementById(id);
});
els.workspace = document.querySelector(".workspace");
els.saveState = document.querySelector(".save-state");
}
function normalizeLoadedNode(raw) {
const isRoot = !raw.parentId;
return node(
String(raw.id || uid()),
raw.parentId ? String(raw.parentId) : null,
String(raw.text || (isRoot ? "中心主题" : "新主题")),
Number.isFinite(Number(raw.x)) ? Number(raw.x) : 1000,
Number.isFinite(Number(raw.y)) ? Number(raw.y) : 500,
{
...raw,
width: Number(raw.width) || (isRoot ? 194 : 154),
height: Number(raw.height) || (isRoot ? 64 : 46)
}
);
}
function loadWorkspace() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return false;
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed.nodes) || !parsed.nodes.length) return false;
const normalized = parsed.nodes.map(normalizeLoadedNode);
const ids = new Set(normalized.map((item) => item.id));
if (!normalized.some((item) => item.parentId === null)) return false;
state.nodes = normalized.filter((item) => item.parentId === null || ids.has(item.parentId));
state.relationships = Array.isArray(parsed.relationships) ? parsed.relationships : [];
state.summaries = normalizeSummaries(parsed.summaries, state.nodes);
state.title = String(parsed.title || state.nodes.find((item) => !item.parentId)?.text || "未命名导图");
state.themeName = THEMES[parsed.themeName] ? parsed.themeName : "forest";
state.uiTheme = parsed.uiTheme === "dark" ? "dark" : "light";
state.selectedId = ids.has(parsed.selectedId) ? parsed.selectedId : state.nodes.find((item) => !item.parentId)?.id;
state.nodes.forEach((item) => {
item.side = "right";
item.shape = "line";
});
return true;
} catch (error) {
console.warn("Unable to restore workspace", error);
return false;
}
}
function initState() {
const restored = loadWorkspace();
if (!restored) {
state.nodes = makeDefaultMap();
state.summaries = makeDefaultSummaries();
state.selectedId = "root";
}
state.nodes.forEach((item) => {
if (!item.parentId) item.color = THEMES[state.themeName].root;
});
if (!state.summaries.length && state.nodes.some((item) => item.id === "inner")) {
state.summaries = makeDefaultSummaries();
}
if (!restored) layoutTree();
}
function snapshot() {
return JSON.stringify({
title: state.title,
nodes: state.nodes,
relationships: state.relationships,
selectedId: state.selectedId,
themeName: state.themeName,
uiTheme: state.uiTheme,
viewport: state.viewport,
summaries: state.summaries,
layoutMode: "line-tree"
});
}
function restoreSnapshot(serialized) {
const data = JSON.parse(serialized);
state.title = data.title;
state.nodes = data.nodes.map(normalizeLoadedNode);
state.relationships = data.relationships || [];
state.summaries = normalizeSummaries(data.summaries, state.nodes);
state.selectedId = data.selectedId;
state.themeName = THEMES[data.themeName] ? data.themeName : "forest";
state.uiTheme = data.uiTheme === "dark" ? "dark" : "light";
if (data.viewport) {
state.viewport = {
x: Number(data.viewport.x) || 0,
y: Number(data.viewport.y) || 0,
scale: clamp(Number(data.viewport.scale) || 1, 0.18, 2.2)
};
}
applyUiTheme();
renderAll();
scheduleSave();
}
function pushHistory() {
state.history.push(snapshot());
if (state.history.length > 60) state.history.shift();
state.future = [];
}
function mutate(mutator, options = {}) {
pushHistory();
mutator();
if (!options.keepSelection && !getNode(state.selectedId)) {
state.selectedId = getRoot()?.id || null;
}
renderAll();
scheduleSave();
}
function undo() {
if (!state.history.length) {
toast("没有可撤销的操作", "undo");
return;
}
state.future.push(snapshot());
restoreSnapshot(state.history.pop());
toast("已撤销", "undo");
}
function redo() {
if (!state.future.length) {
toast("没有可重做的操作", "redo");
return;
}
state.history.push(snapshot());
restoreSnapshot(state.future.pop());
toast("已重做", "redo");
}
function scheduleSave() {
els.saveState?.classList.add("saving");
if (els.save_state_text) els.save_state_text.textContent = "正在保存…";
if (els.status_message) els.status_message.textContent = "正在保存更改";
clearTimeout(saveTimer);
saveTimer = setTimeout(saveNow, 380);
}
function saveNow() {
clearTimeout(saveTimer);
try {
localStorage.setItem(STORAGE_KEY, snapshot());
els.saveState?.classList.remove("saving");
if (els.save_state_text) els.save_state_text.textContent = "已保存到本地";
if (els.status_message) els.status_message.textContent = "所有更改已保存";
} catch (error) {
console.warn("Unable to save workspace", error);
if (els.save_state_text) els.save_state_text.textContent = "保存失败";
if (els.status_message) els.status_message.textContent = "本地存储空间不足";
}
}
function getNode(id) {
return state.nodes.find((item) => item.id === id) || null;
}
function getRoot() {
return state.nodes.find((item) => !item.parentId) || null;
}
function getChildren(id) {
return state.nodes.filter((item) => item.parentId === id);
}
function getDescendantIds(id) {
const result = [];
const walk = (parentId) => {
getChildren(parentId).forEach((child) => {
result.push(child.id);
walk(child.id);
});
};
walk(id);
return result;
}
function getDepth(id) {
let depth = 0;
let current = getNode(id);
const visited = new Set();
while (current?.parentId && !visited.has(current.id)) {
visited.add(current.id);
depth += 1;
current = getNode(current.parentId);
}
return depth;
}
function isNodeVisible(item) {
let current = item;
const visited = new Set();
while (current?.parentId && !visited.has(current.id)) {
visited.add(current.id);
const parent = getNode(current.parentId);
if (!parent) return false;
if (parent.collapsed) return false;
current = parent;
}
return true;
}
function getVisibleNodes() {
return state.nodes.filter(isNodeVisible);
}
function nodeMetrics(item) {
const width = Number(item.width) || (item.parentId ? 228 : 168);
const baseHeight = Number(item.height) || (item.parentId ? 64 : 74);
const fontSize = Number(item.fontSize) || (item.parentId ? 16 : 22);
const textWidth = Array.from(String(item.text || "")).reduce((total, character) => {
if (/\s/.test(character)) return total + fontSize * 0.34;
if (/[\u0020-\u007e]/.test(character)) return total + fontSize * 0.58;
return total + fontSize;
}, 0);
const measuredWidth = item.parentId ? Math.max(width, Math.round(textWidth + 62)) : Math.max(width, Math.round(textWidth + 78));
return { width: measuredWidth, height: baseHeight };
}
function nodeAnchor(item, metrics = nodeMetrics(item)) {
return {
x: item.x + metrics.width - 14,
y: item.y + metrics.height - 18
};
}
function getBounds(nodes = getVisibleNodes()) {
if (!nodes.length) return { x: 0, y: 0, width: STAGE.width, height: STAGE.height };
const boxes = nodes.map((item) => ({ ...nodeMetrics(item), x: item.x, y: item.y }));
const root = getRoot();
const minX = Math.min(...boxes.map((box) => box.x), root ? root.x - 90 : Infinity);
let minY = Math.min(...boxes.map((box) => box.y));
let maxX = Math.max(...boxes.map((box) => box.x + box.width));
let maxY = Math.max(...boxes.map((box) => box.y + box.height));
state.summaries.forEach((summary) => {
const geometry = summaryGeometry(summary);
if (!geometry) return;
maxX = Math.max(maxX, geometry.labelX + 150);
maxY = Math.max(maxY, geometry.bottom + 24);
minY = Math.min(minY, geometry.top - 10);
});
return { x: minX, y: minY, width: Math.max(1, maxX - minX), height: Math.max(1, maxY - minY) };
}
function connectionGeometry(parent, child, offset = { x: 0, y: 0 }) {
const start = nodeAnchor(parent, nodeMetrics(parent));
const end = nodeAnchor(child, nodeMetrics(child));
const startX = start.x - offset.x;
const startY = start.y - offset.y;
const endX = end.x - offset.x;
const endY = end.y - offset.y;
const direction = endX >= startX ? 1 : -1;
const desiredCurveEnd = child.x + 18 - offset.x;
const curveEndX = direction > 0
? clamp(desiredCurveEnd, startX + 32, endX - 40)
: clamp(desiredCurveEnd, endX + 40, startX - 32);
const bend = Math.abs(curveEndX - startX);
return {
startX, startY, endX, endY,
path: `M ${startX} ${startY} C ${startX + direction * bend * 0.36} ${startY}, ${startX + direction * bend * 0.56} ${endY}, ${curveEndX} ${endY} L ${endX} ${endY}`
};
}
function summaryGeometry(summary, offset = { x: 0, y: 0 }) {
const targets = summary.targetIds.map(getNode).filter((item) => item && isNodeVisible(item));
if (!targets.length) return null;
const anchors = targets.map((item) => nodeAnchor(item, nodeMetrics(item)));
const minY = Math.min(...anchors.map((item) => item.y));
const maxY = Math.max(...anchors.map((item) => item.y));
const maxX = Math.max(...anchors.map((item) => item.x));
const x = maxX + 70 - offset.x;
const top = minY - 28 - offset.y;
const bottom = maxY + 12 - offset.y;
const mid = (top + bottom) / 2;
const turn = clamp((bottom - top) * 0.15, 14, 22);
const spineX = x + 16;
const pointX = x + 32;
return {
path: `M ${x} ${top} C ${x + 11} ${top}, ${spineX} ${top + 7}, ${spineX} ${top + turn} L ${spineX} ${mid - turn} C ${spineX} ${mid - 8}, ${pointX - 8} ${mid - 4}, ${pointX} ${mid} C ${pointX - 8} ${mid + 4}, ${spineX} ${mid + 8}, ${spineX} ${mid + turn} L ${spineX} ${bottom - turn} C ${spineX} ${bottom - 7}, ${x + 11} ${bottom}, ${x} ${bottom}`,
x,
top,
bottom,
labelX: pointX + 12,
labelY: mid + 7
};
}
function layoutTree() {
const root = getRoot();
if (!root) return;
const leafGap = 88;
const topLevelGap = 48;
const rootAnchorX = 300;
let cursorY = 150;
const anchorYs = new Map();
const place = (item, depth) => {
const children = getChildren(item.id);
if (!children.length) {
anchorYs.set(item.id, cursorY);
cursorY += leafGap;
return anchorYs.get(item.id);
}
const childYs = [];
children.forEach((child, index) => {
if (depth === 0 && index > 0) cursorY += topLevelGap;
childYs.push(place(child, depth + 1));
});
const y = childYs.reduce((sum, value) => sum + value, 0) / childYs.length;
anchorYs.set(item.id, y);
return y;
};
place(root, 0);
const depthWidths = new Map();
let maxDepth = 0;
state.nodes.forEach((item) => {
const depth = getDepth(item.id);
maxDepth = Math.max(maxDepth, depth);
depthWidths.set(depth, Math.max(depthWidths.get(depth) || 0, nodeMetrics(item).width));
});
const anchorXs = [rootAnchorX];
for (let depth = 1; depth <= maxDepth; depth += 1) {
anchorXs[depth] = anchorXs[depth - 1] + Math.max(250, (depthWidths.get(depth) || 228) + 36);
}
state.nodes.forEach((item) => {
const depth = getDepth(item.id);
const metrics = nodeMetrics(item);
const anchorX = anchorXs[depth] || rootAnchorX;
const anchorY = anchorYs.get(item.id) ?? 360;
item.x = clamp(anchorX - metrics.width + 14, 24, STAGE.width - metrics.width - 24);
item.y = clamp(anchorY - metrics.height + 18, 24, STAGE.height - metrics.height - 24);
item.side = "right";
item.shape = "line";
});
}
function renderConnections() {
const visibleIds = new Set(getVisibleNodes().map((item) => item.id));
const paths = [];
const root = getRoot();
if (root && visibleIds.has(root.id)) {
const rootMetrics = nodeMetrics(root);
const rootPoint = nodeAnchor(root, rootMetrics);
paths.push(`<path class="connection-path lead" d="M ${root.x - 76} ${rootPoint.y} L ${rootPoint.x} ${rootPoint.y}" style="--connection-color:${escapeHtml(root.color)};--connection-width:4px"/>`);
}
state.nodes.forEach((child) => {
if (!child.parentId || !visibleIds.has(child.id) || !visibleIds.has(child.parentId)) return;
const parent = getNode(child.parentId);
if (!parent) return;
const geometry = connectionGeometry(parent, child);
const depth = getDepth(child.id);
paths.push(`<path class="connection-path${depth === 1 ? " trunk" : ""}" d="${geometry.path}" style="--connection-color:${escapeHtml(child.color)};--connection-width:${depth === 1 ? 4 : 4}px"/>`);
});
const relationshipPaths = state.relationships.map((relation) => {
const from = getNode(relation.from);
const to = getNode(relation.to);
if (!from || !to || !visibleIds.has(from.id) || !visibleIds.has(to.id)) return "";
const fm = nodeMetrics(from);
const tm = nodeMetrics(to);
const x1 = from.x + fm.width / 2;
const y1 = from.y + fm.height / 2;
const x2 = to.x + tm.width / 2;
const y2 = to.y + tm.height / 2;
const midY = Math.min(y1, y2) - 75;
const path = `M ${x1} ${y1} Q ${(x1 + x2) / 2} ${midY}, ${x2} ${y2}`;
const labelX = (x1 + x2) / 2;
const labelY = midY + 8;
return `<path class="relationship-path" d="${path}" marker-end="url(#relationship-arrow)"/><text class="relationship-label" x="${labelX}" y="${labelY}" text-anchor="middle">${escapeXml(relation.label || "联系")}</text>`;
}).join("");
const summaryMarkup = state.summaries.map((summary) => {
const geometry = summaryGeometry(summary);
if (!geometry) return "";
return `<path class="summary-brace" d="${geometry.path}"/><text class="summary-label" x="${geometry.labelX}" y="${geometry.labelY}">${escapeXml(summary.label)}</text>`;
}).join("");
els.connections_layer.innerHTML = `
<defs>
<marker id="relationship-arrow" markerWidth="7" markerHeight="7" refX="6" refY="3.5" orient="auto"><path d="M0,0 L7,3.5 L0,7 Z" fill="var(--coral)"/></marker>
</defs>
${paths.join("")}${relationshipPaths}${summaryMarkup}`;
}
function renderNodes() {
const visible = getVisibleNodes();
els.nodes_layer.innerHTML = visible.map((item) => {
const depth = getDepth(item.id);
const metrics = nodeMetrics(item);
const children = getChildren(item.id);
const type = !item.parentId ? "root" : depth === 1 ? "branch" : "leaf";
const selected = item.id === state.selectedId ? "selected" : "";
const textClasses = `${item.bold ? "bold" : ""} ${item.italic ? "italic" : ""}`;
const collapse = children.length
? `<button class="collapse-control side-right${item.collapsed ? " has-hidden" : ""}" data-collapse-id="${item.id}" title="${item.collapsed ? "展开分支" : "收起分支"}" aria-label="${item.collapsed ? "展开分支" : "收起分支"}">${icon(item.collapsed ? "plus" : "minus")}</button>`
: "";
const textColor = item.textColor || "var(--text)";
const labelClass = item.parentId ? "node-label line-label" : "node-label root-label";
return `<div class="mind-node ${type} line-node ${selected}" data-node-id="${item.id}" tabindex="0" role="treeitem" aria-selected="${item.id === state.selectedId}" style="left:${item.x}px;top:${item.y}px;--node-width:${metrics.width}px;--node-height:${metrics.height}px;--node-color:${item.color};--node-text:${textColor};font-size:${item.fontSize}px">
<div class="node-content">
<span class="${labelClass} ${textClasses}">${escapeHtml(item.text)}</span>
<button class="node-junction${item.parentId ? "" : " root-junction"}" data-action="add-child" data-parent-id="${item.id}" title="为“${escapeHtml(item.text)}”添加子节点" aria-label="为“${escapeHtml(item.text)}”添加子节点">+</button>
</div>
${collapse}
</div>`;
}).join("");
}
function renderMap() {
renderConnections();
renderNodes();
applyTransform();
renderMinimap();
}
function renderSidebar() {
const root = getRoot();
const rows = root ? outlineRows(root, 0) : "";
els.left_panel_content.innerHTML = `<div class="sidebar-section">
<div class="sidebar-heading"><div><span class="eyebrow">结构导航</span><h2>文字大纲</h2></div><button class="icon-button subtle" data-action="collapse-all" title="全部收起" aria-label="全部收起">${icon("collapse")}</button></div>
<div class="search-field">${icon("search")}<input id="outline-search" type="search" placeholder="搜索主题" autocomplete="off" /></div>
<div class="outline-tree" id="outline-tree">${rows}</div>
<div class="sidebar-action-row">
<button class="sidebar-footer-action" data-action="add-child">${icon("plus")}添加节点</button>
<button class="sidebar-footer-action danger" data-action="delete-node">${icon("trash")}删除</button>
</div>
</div>`;
}
function outlineRows(item, depth) {
const children = getChildren(item.id);
const row = `<button class="outline-row${item.id === state.selectedId ? " active" : ""}${item.collapsed ? " collapsed" : ""}" data-outline-id="${item.id}" data-search-text="${escapeHtml(item.text.toLowerCase())}" style="--outline-indent:${4 + depth * 13}px;--node-color:${item.color}">
<span class="outline-toggle${children.length ? "" : " empty"}" data-outline-toggle="${item.id}">${icon("arrow-down")}</span>
<span class="outline-label">${escapeHtml(item.text)}</span><span class="outline-meta"></span>
</button>`;
if (!children.length || item.collapsed) return row;
return row + children.map((child) => outlineRows(child, depth + 1)).join("");
}
function renderInspector() {
const selected = getNode(state.selectedId);
if (!selected) {
els.inspector_content.innerHTML = `<div class="inspector-empty">${icon("cursor")}<p>选择一个节点以查看属性</p></div>`;
return;
}
const tabs = `<div class="inspector-tabs" role="tablist">
<button class="inspector-tab${state.inspectorTab === "style" ? " active" : ""}" data-inspector-tab="style">样式</button>
<button class="inspector-tab${state.inspectorTab === "icon" ? " active" : ""}" data-inspector-tab="icon">图标</button>
<button class="inspector-tab${state.inspectorTab === "note" ? " active" : ""}" data-inspector-tab="note">备注</button>
</div>`;
if (state.inspectorTab === "icon") {
els.inspector_content.innerHTML = tabs + renderIconInspector(selected);
return;
}
if (state.inspectorTab === "note") {
els.inspector_content.innerHTML = tabs + renderNoteInspector(selected);
return;
}
els.inspector_content.innerHTML = tabs + renderStyleInspector(selected);
}
function renderStyleInspector(selected) {
return `<div class="inspector-section">
<div class="section-title"><h3>主题文字</h3><span>${Array.from(selected.text).length} 字</span></div>
<label class="field-label" for="node-text-field">内容</label>
<input class="text-field" id="node-text-field" data-node-field="text" value="${escapeHtml(selected.text)}" />
<div class="format-row" style="margin-top:9px">
<button class="segmented-button${selected.bold ? " active" : ""}" data-action="toggle-bold" title="粗体"><strong>B</strong></button>
<button class="segmented-button${selected.italic ? " active" : ""}" data-action="toggle-italic" title="斜体"><em>I</em></button>
<button class="segmented-button" data-action="decrease-font" title="减小字号">A−</button>
<button class="segmented-button" data-action="increase-font" title="增大字号">A+</button>
</div>
</div>
<div class="inspector-section">
<div class="section-title"><h3>分支颜色</h3><span>${escapeHtml(selected.color.toUpperCase())}</span></div>
<div class="color-grid">${PALETTE.map((color) => `<button class="color-swatch${color.toLowerCase() === selected.color.toLowerCase() ? " active" : ""}" data-node-color="${color}" style="--swatch:${color}" title="${color}" aria-label="设置颜色 ${color}"></button>`).join("")}</div>
</div>
<div class="inspector-section">
<div class="section-title"><h3>线条与文字</h3><span>${selected.width}px</span></div>
<label class="field-label" for="node-width-range">线段长度</label>
<input class="range-field" id="node-width-range" data-node-range="width" type="range" min="120" max="420" step="2" value="${selected.width}" />
<label class="field-label" for="node-font-range" style="margin-top:10px">字号</label>
<input class="range-field" id="node-font-range" data-node-range="fontSize" type="range" min="11" max="22" step="1" value="${selected.fontSize}" />
</div>
<div class="inspector-section">
<div class="section-title"><h3>整图主题</h3><span>${escapeHtml(THEMES[state.themeName].label)}</span></div>
<div class="theme-grid">${Object.entries(THEMES).map(([key, theme]) => themeMarkup(key, theme)).join("")}</div>
</div>`;
}
function themeMarkup(key, theme) {
return `<button class="theme-tile${state.themeName === key ? " active" : ""}" data-map-theme="${key}" title="${escapeHtml(theme.label)}" style="--theme-root:${theme.root};--theme-branch:${theme.branches[0]};--theme-branch-2:${theme.branches[1]};--theme-branch-3:${theme.branches[2]}">
<span class="theme-map-root"></span><span class="theme-map-branch b1"></span><span class="theme-map-branch b2"></span><span class="theme-map-branch b3"></span>
</button>`;
}
function renderIconInspector(selected) {
return `<div class="inspector-section">
<div class="section-title"><h3>节点图标</h3><span>${selected.icon ? "已添加" : "无"}</span></div>
<div class="icon-grid">${ICONS.map((item) => `<button class="icon-choice${item === selected.icon ? " active" : ""}" data-node-icon="${escapeHtml(item)}" title="${item ? `使用 ${item}` : "清除图标"}">${item || "×"}</button>`).join("")}</div>
</div>
<div class="inspector-section">
<div class="section-title"><h3>优先级</h3></div>
<div class="format-row">
${["", "P0", "P1", "P2"].map((value) => `<button class="segmented-button${selected.priority === value ? " active" : ""}" data-node-priority="${value}">${value || "无"}</button>`).join("")}
</div>
</div>
<div class="inspector-section">
<div class="section-title"><h3>标记</h3><button class="status-link" data-action="add-tag">添加</button></div>
<div class="tag-list">${selected.tags?.length ? selected.tags.map((tag, index) => `<span class="tag-chip">${escapeHtml(tag)}<button data-remove-tag="${index}" aria-label="移除标记">×</button></span>`).join("") : `<span style="color:var(--text-faint);font-size:10px">暂无标记</span>`}</div>
</div>`;
}
function renderNoteInspector(selected) {
return `<div class="inspector-section">
<div class="section-title"><h3>节点备注</h3><span>自动保存</span></div>
<textarea class="note-field" data-node-field="note" placeholder="记录补充信息、结论或待办…">${escapeHtml(selected.note)}</textarea>
</div>
<div class="inspector-section">
<div class="section-title"><h3>链接</h3><button class="status-link" data-action="open-node-link">${selected.link ? "编辑" : "添加"}</button></div>
${selected.link ? `<a href="${escapeHtml(selected.link)}" target="_blank" rel="noopener" style="display:flex;align-items:center;gap:6px;color:var(--accent);font-size:11px;overflow-wrap:anywhere">${icon("external")}${escapeHtml(selected.link)}</a>` : `<span style="color:var(--text-faint);font-size:10px">暂无链接</span>`}
</div>
<div class="inspector-section">
<div class="section-title"><h3>附件</h3><button class="status-link" data-action="add-attachment">${selected.attachment ? "替换" : "添加"}</button></div>
${selected.attachment ? `<div class="tag-chip">${icon("paperclip")}${escapeHtml(selected.attachment)}</div>` : `<span style="color:var(--text-faint);font-size:10px">暂无附件</span>`}
</div>`;
}
function renderStatus() {
const selected = getNode(state.selectedId);
if (els.node_count) els.node_count.textContent = `${state.nodes.length} 个节点`;
if (els.selected_label) els.selected_label.textContent = selected ? `已选择:${selected.text}` : "未选择节点";
if (els.breadcrumb_text) els.breadcrumb_text.textContent = state.title;
if (els.document_title && els.document_title !== document.activeElement) els.document_title.value = state.title;
if (els.zoom_value) els.zoom_value.textContent = `${Math.round(state.viewport.scale * 100)}%`;
renderNodeActionBar();
updateActionAvailability();
}
function renderAll() {
applyUiState();
renderMap();
renderSidebar();
renderInspector();
renderStatus();
}
function updateActionAvailability() {
document.querySelectorAll('[data-action="undo"]').forEach((button) => { button.disabled = state.history.length === 0; });
document.querySelectorAll('[data-action="redo"]').forEach((button) => { button.disabled = state.future.length === 0; });
document.querySelectorAll('[data-action="delete-node"]').forEach((button) => { button.disabled = state.selectedId === getRoot()?.id; });
}
function applyUiTheme() {
document.body.dataset.theme = state.uiTheme;
const themeButton = document.querySelector('[data-action="toggle-theme"]');
if (themeButton) {
const svg = themeButton.querySelector("use");
if (svg) svg.setAttribute("href", state.uiTheme === "dark" ? "#i-moon" : "#i-sun");
}
}
function applyUiState() {
applyUiTheme();
els.workspace.classList.toggle("left-collapsed", state.leftCollapsed);
els.workspace.classList.toggle("right-collapsed", state.rightCollapsed);
els.canvas_viewport.classList.toggle("grid-hidden", !state.gridVisible);
els.minimap.hidden = !state.minimapVisible;
}
function applyTransform() {
const { x, y, scale } = state.viewport;
els.canvas_stage.style.transform = `translate(${x}px, ${y}px) scale(${scale})`;
const gridSize = Math.max(8, 22 * scale);
els.canvas_viewport.style.backgroundPosition = `${x % gridSize}px ${y % gridSize}px`;
els.canvas_viewport.style.backgroundSize = `${gridSize}px ${gridSize}px`;
if (els.zoom_value) els.zoom_value.textContent = `${Math.round(scale * 100)}%`;
renderNodeActionBar();
}
function fitView(animate = true) {
const viewportRect = els.canvas_viewport.getBoundingClientRect();
if (!viewportRect.width || !viewportRect.height) return;
const bounds = getBounds();
const paddingX = viewportRect.width < 600 ? 66 : 120;
const paddingY = viewportRect.height < 500 ? 66 : 110;
const scale = clamp(Math.min(
(viewportRect.width - paddingX) / bounds.width,
(viewportRect.height - paddingY) / bounds.height
), viewportRect.width < 600 ? 0.18 : 0.3, 1.08);
state.viewport.scale = scale;
state.viewport.x = (viewportRect.width - bounds.width * scale) / 2 - bounds.x * scale;
state.viewport.y = (viewportRect.height - bounds.height * scale) / 2 - bounds.y * scale;
if (animate) {
els.canvas_stage.style.transition = "transform 220ms ease";
setTimeout(() => { els.canvas_stage.style.transition = ""; }, 240);
}
applyTransform();
renderMinimap();
}
function centerNode(id = state.selectedId) {
const selected = getNode(id);
if (!selected) return;
const rect = els.canvas_viewport.getBoundingClientRect();
const metrics = nodeMetrics(selected);
state.viewport.x = rect.width / 2 - (selected.x + metrics.width / 2) * state.viewport.scale;
state.viewport.y = rect.height / 2 - (selected.y + metrics.height / 2) * state.viewport.scale;
els.canvas_stage.style.transition = "transform 200ms ease";
applyTransform();
setTimeout(() => { els.canvas_stage.style.transition = ""; }, 220);
}
function frameMobileView() {
const root = getRoot();
const rect = els.canvas_viewport.getBoundingClientRect();
if (!root || !rect.width || !rect.height) return;
const scale = 0.52;
const anchor = nodeAnchor(root, nodeMetrics(root));
state.viewport.scale = scale;
state.viewport.x = rect.width * 0.36 - anchor.x * scale;
state.viewport.y = rect.height * 0.5 - anchor.y * scale;
applyTransform();
renderMinimap();
}
function zoomAt(nextScale, clientX, clientY) {
const rect = els.canvas_viewport.getBoundingClientRect();
const oldScale = state.viewport.scale;
const scale = clamp(nextScale, 0.28, 2.2);
const pointX = clientX == null ? rect.width / 2 : clientX - rect.left;
const pointY = clientY == null ? rect.height / 2 : clientY - rect.top;
const stageX = (pointX - state.viewport.x) / oldScale;
const stageY = (pointY - state.viewport.y) / oldScale;
state.viewport.scale = scale;
state.viewport.x = pointX - stageX * scale;
state.viewport.y = pointY - stageY * scale;
applyTransform();
}
function renderMinimap() {
if (!state.minimapVisible || !els.minimap_canvas) return;
const visible = getVisibleNodes();
const bounds = getBounds(visible);
const width = 190;
const height = 98;
const scale = Math.min((width - 18) / bounds.width, (height - 16) / bounds.height);
const offsetX = (width - bounds.width * scale) / 2 - bounds.x * scale;
const offsetY = (height - bounds.height * scale) / 2 - bounds.y * scale;
els.minimap_canvas.innerHTML = visible.map((item) => {
const metrics = nodeMetrics(item);
return `<span class="mini-node-dot" style="left:${item.x * scale + offsetX}px;top:${item.y * scale + offsetY}px;width:${Math.max(4, metrics.width * scale)}px;height:${Math.max(3, metrics.height * scale)}px;--node-color:${item.color}"></span>`;
}).join("");
}
function renderNodeActionBar() {
const bar = els.node_action_bar;
const selected = getNode(state.selectedId);
if (!bar || !selected || state.presentation) {
if (bar) bar.hidden = true;
return;
}
const metrics = nodeMetrics(selected);
const areaRect = els.canvas_area.getBoundingClientRect();
const screenX = state.viewport.x + (selected.x + metrics.width / 2) * state.viewport.scale;
const screenTop = state.viewport.y + selected.y * state.viewport.scale;
const screenBottom = screenTop + metrics.height * state.viewport.scale;
const placeBelow = screenTop < 72;
const halfWidth = window.innerWidth <= 560 ? 132 : 154;
bar.hidden = false;
bar.classList.toggle("below", placeBelow);
bar.style.left = `${clamp(screenX, halfWidth + 8, areaRect.width - halfWidth - 8)}px`;
bar.style.top = `${placeBelow ? screenBottom : screenTop}px`;
if (bar.dataset.nodeId !== selected.id) {
bar.dataset.nodeId = selected.id;
bar.innerHTML = `
<button class="node-action-button add" data-action="add-child" title="添加子节点(Tab)">${icon("plus-circle")}<span>添加子节点</span></button>
<button class="node-action-button" data-action="add-sibling" title="添加同级节点(Enter)">${icon("branch")}<span>同级</span></button>
<span class="node-action-divider" aria-hidden="true"></span>
<button class="node-action-button delete" data-action="delete-node" title="${selected.parentId ? "删除节点(Delete)" : "中心主题不能删除,请使用清空"}" ${selected.parentId ? "" : "disabled"}>${icon("trash")}<span>删除</span></button>`;
}
}
function selectNode(id, options = {}) {
const selected = getNode(id);
if (!selected) return;
if (state.connectionSource && state.connectionSource !== id) {
const source = state.connectionSource;
mutate(() => {
const exists = state.relationships.some((item) => (item.from === source && item.to === id) || (item.from === id && item.to === source));
if (!exists) state.relationships.push({ id: uid("rel"), from: source, to: id, label: "联系" });
state.connectionSource = null;
state.selectedId = id;
}, { keepSelection: true });
document.querySelector('[data-action="add-connection"]')?.classList.remove("active");
toast("已建立节点联系", "connector");
return;
}
state.selectedId = id;
renderNodes();
renderSidebar();
renderInspector();
renderStatus();
if (options.center) centerNode(id);
}
function addChild(parentId = state.selectedId, text = "新主题", overrides = {}) {
const parent = getNode(parentId) || getRoot();
if (!parent) return;
const siblings = getChildren(parent.id);
const width = overrides.width || 228;
const color = overrides.color || (parent.parentId ? parent.color : THEMES[state.themeName].branches[siblings.length % THEMES[state.themeName].branches.length]);
const newId = uid();
mutate(() => {
parent.collapsed = false;
state.nodes.push(node(newId, parent.id, text, 0, 0, { width, color, side: "right", shape: "line", ...overrides }));
state.selectedId = newId;
layoutTree();
}, { keepSelection: true });
requestAnimationFrame(() => centerNode(newId));
setTimeout(() => startNodeEdit(newId), 240);
}
function addSibling(id = state.selectedId) {
const selected = getNode(id);
if (!selected) return;
if (!selected.parentId) {
addChild(selected.id);
return;
}
const parent = getNode(selected.parentId);
const newId = uid();
mutate(() => {
parent.collapsed = false;
state.nodes.push(node(newId, parent.id, "新主题", 0, 0, {
width: selected.width,
height: selected.height,
color: selected.color,
side: "right",
shape: "line"
}));
state.selectedId = newId;
layoutTree();
}, { keepSelection: true });
requestAnimationFrame(() => centerNode(newId));
setTimeout(() => startNodeEdit(newId), 240);
}
function deleteSelected() {
const selected = getNode(state.selectedId);
const root = getRoot();
if (!selected || selected.id === root?.id) {
toast("中心主题不能删除", "lock");
return;
}
const parentId = selected.parentId;
const ids = new Set([selected.id, ...getDescendantIds(selected.id)]);
mutate(() => {
state.nodes = state.nodes.filter((item) => !ids.has(item.id));
state.relationships = state.relationships.filter((item) => !ids.has(item.from) && !ids.has(item.to));
state.summaries = state.summaries
.map((summary) => ({ ...summary, targetIds: summary.targetIds.filter((id) => !ids.has(id)) }))
.filter((summary) => summary.targetIds.length >= 2);
if (state.connectionSource && ids.has(state.connectionSource)) state.connectionSource = null;
state.selectedId = parentId;
layoutTree();
}, { keepSelection: true });
toast(`已删除 ${ids.size} 个节点,可撤销恢复`, "trash");
}
function showClearDialog() {
showModal(`<div class="modal small">
<div class="modal-header"><div class="modal-title"><h2>清空导图</h2><p>当前共有 ${state.nodes.length} 个节点</p></div><button class="icon-button subtle" data-close-modal title="关闭" aria-label="关闭">${icon("close")}</button></div>
<div class="modal-body">
<div class="clear-warning">${icon("trash")}<div><strong>删除全部分支与联系线</strong><span>清空后会保留一个可编辑的“中心主题”。此操作可以通过撤销恢复。</span></div></div>
</div>
<div class="modal-footer"><button class="outline-button" data-close-modal>取消</button><button class="primary-button danger-primary" data-action="confirm-clear">${icon("trash")}清空导图</button></div>
</div>`);
}
function performClear() {
mutate(() => {
state.nodes = makeBlankMap();
state.relationships = [];
state.summaries = [];
state.selectedId = "root";
state.title = "中心主题";
state.connectionSource = null;
layoutTree();
}, { keepSelection: true });
closeModal();
requestAnimationFrame(() => fitView(false));
setTimeout(() => startNodeEdit("root"), 180);
toast("导图已清空,可撤销恢复", "trash");
}
function duplicateSelected() {
const selected = getNode(state.selectedId);
if (!selected) return;
if (!selected.parentId) {
toast("中心主题不能复制为同级", "copy");
return;
}
const subtree = [selected.id, ...getDescendantIds(selected.id)].map(getNode).filter(Boolean);
const idMap = new Map(subtree.map((item) => [item.id, uid()]));
mutate(() => {
subtree.forEach((item) => {
const clone = normalizeLoadedNode({
...item,
id: idMap.get(item.id),
parentId: item.id === selected.id ? item.parentId : idMap.get(item.parentId),
x: item.x,
y: item.y + 84,
text: item.id === selected.id ? `${item.text} 副本` : item.text
});
state.nodes.push(clone);
});
state.selectedId = idMap.get(selected.id);
layoutTree();
}, { keepSelection: true });
centerNode(state.selectedId);
toast("已复制分支", "copy");
}