-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmindmap.html
More file actions
859 lines (765 loc) · 30.2 KB
/
mindmap.html
File metadata and controls
859 lines (765 loc) · 30.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title id="document-title">Mind Map</title>
<!-- Include Marked.js via CDN -->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
overflow: hidden;
}
#mindmap-container {
position: relative;
width: 100vw;
height: 100vh;
background-color: #f0f0f0;
}
.node {
position: absolute;
padding: 8px 12px;
background-color: #FFFFFF;
border-radius: 5px;
cursor: pointer;
user-select: none;
transition: background-color 0.3s, box-shadow 0.3s;
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
font-weight: bold;
border: 1px solid #999;
box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.2);
white-space: nowrap;
min-width: 100px;
min-height: 60px;
box-sizing: border-box;
overflow: auto;
}
.node:hover {
background-color: #FFA500;
box-shadow: 4px 4px 15px rgba(0, 0, 0, 0.3);
}
.node:focus {
outline: none;
box-shadow: 0 0 0 2px #0000FF, 2px 2px 10px rgba(0, 0, 0, 0.2);
}
.central-node {
font-size: 24px; /* Increased font size for central node */
background-color: #FFA500;
color: #000000; /* Default text color */
}
/* Placeholder styling for contenteditable nodes */
.node:empty::before {
content: attr(data-placeholder);
color: grey;
pointer-events: none;
display: block;
}
.color-swatch {
width: 20px;
height: 20px;
border-radius: 50%;
margin: 0 4px;
cursor: pointer;
display: inline-block;
border: 1px solid #333;
}
svg {
position: absolute;
top: 0;
left: 0;
z-index: 0;
pointer-events: none;
width: 100%;
height: 100%;
}
/* Updated styles for button-container and its child elements */
#button-container {
position: absolute;
top: 10px;
left: 10px;
display: flex;
flex-direction: column; /* Arrange children vertically */
gap: 10px; /* Space between rows */
z-index: 10;
}
/* Container for main buttons */
#main-buttons {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
/* Container for color palette and emoji buttons */
#bottom-buttons {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
/* Styles for main buttons */
#copy-text-btn, #delete-node-btn, #undo-btn, #redo-btn, #add-node-btn, #add-child-btn {
padding: 8px 16px;
background-color: #2196F3;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s;
}
#copy-text-btn:hover, #undo-btn:hover, #redo-btn:hover, #add-node-btn:hover, #add-child-btn:hover {
background-color: #1976D2;
}
#delete-node-btn {
background-color: #FF5722;
}
#delete-node-btn:hover {
background-color: #E64A19;
}
#add-child-btn {
background-color: #32CD32;
}
#add-child-btn:hover {
background-color: #2E8B57;
}
/* Styles for emoji buttons */
.emoji-btn {
padding: 4px 6px;
background-color: transparent;
border: none;
cursor: pointer;
font-size: 20px;
transition: transform 0.2s;
}
.emoji-btn:hover {
transform: scale(1.2);
}
/* Editable node styling */
.node.editable {
border: 2px dashed #4CAF50;
}
/* Add these styles to make #export-svg-btn match main buttons */
#export-svg-btn {
padding: 8px 16px;
background-color: #2196F3; /* Blue color */
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s;
}
#export-svg-btn:hover {
background-color: #1976D2; /* Darker blue on hover */
}
</style>
</head>
<body>
<div id="mindmap-container">
<svg id="svg-connections"></svg>
<!-- Central Node with Placeholder -->
<div id="central-node" class="node central-node" contenteditable="false" tabindex="0" data-placeholder="Central topic"></div>
<div id="button-container">
<!-- First Row: Main Buttons -->
<div id="main-buttons">
<button id="copy-text-btn">Copy Text</button>
<button id="delete-node-btn">Delete Node</button>
<button id="undo-btn">Undo</button>
<button id="redo-btn">Redo</button>
<button id="add-node-btn">+Node (Enter)</button>
<button id="add-child-btn">+ Child Node (Tab)</button>
<button id="export-svg-btn">Export to SVG</button> <!-- New Button -->
</div>
<!-- Second Row: Color Palette and Emoji Buttons -->
<div id="bottom-buttons">
<!-- Color Palette -->
<div id="color-palette">
<div class="color-swatch" style="background-color: #FFFFFF;" data-color="#FFFFFF"></div>
<div class="color-swatch" style="background-color: #FFD700;" data-color="#FFD700"></div>
<div class="color-swatch" style="background-color: #FF4500;" data-color="#FF4500"></div>
<div class="color-swatch" style="background-color: #32CD32;" data-color="#32CD32"></div>
<div class="color-swatch" style="background-color: #1E90FF;" data-color="#1E90FF"></div>
<div class="color-swatch" style="background-color: #BA55D3;" data-color="#BA55D3"></div>
</div>
<!-- Emoji Buttons -->
<div id="emoji-buttons">
<button class="emoji-btn" data-emoji="💡">💡</button>
<button class="emoji-btn" data-emoji="🧠">🧠</button>
<button class="emoji-btn" data-emoji="📚">📚</button>
<button class="emoji-btn" data-emoji="🎯">🎯</button>
<button class="emoji-btn" data-emoji="✅">✅</button>
<button class="emoji-btn" data-emoji="❌">❌</button>
<button class="emoji-btn" data-emoji="🛠️">🛠️</button>
<button class="emoji-btn" data-emoji="🚦">🚦</button>
<button class="emoji-btn" data-emoji="🎬">🎬</button>
</div>
</div>
</div>
</div>
<script>
// Configure Marked.js for security (sanitize the output)
marked.setOptions({
sanitize: true, // Deprecated in latest versions, consider using DOMPurify for sanitization
breaks: true,
smartLists: true,
smartypants: true
});
const container = document.getElementById('mindmap-container');
const svg = document.getElementById('svg-connections');
const centralNode = document.getElementById('central-node');
const documentTitle = document.getElementById('document-title');
const copyTextBtn = document.getElementById('copy-text-btn');
const deleteNodeBtn = document.getElementById('delete-node-btn');
const undoBtn = document.getElementById('undo-btn');
const redoBtn = document.getElementById('redo-btn');
const addNodeBtn = document.getElementById('add-node-btn');
const addChildBtn = document.getElementById('add-child-btn');
const colorPalette = document.getElementById('color-palette');
const emojiButtons = document.querySelectorAll('.emoji-btn'); // Select all emoji buttons
const colors = ['#FFFFFF', '#FFD700', '#FF4500', '#32CD32', '#1E90FF', '#BA55D3'];
let nodesData = [];
let undoStack = [];
let redoStack = [];
let selectedNodeId = null;
let siblingAngle = 0; // Angle to track placement for sibling nodes
let childAngle = 300; // Initial angle for child nodes, set to 5 o'clock (300 degrees)
function generateId() {
return 'node-' + Math.random().toString(36).substr(2, 9);
}
// Initialize central node with fixed ID and empty text
const centralNodeId = 'central-node';
nodesData.push({
id: centralNodeId,
parentId: null,
x: 0,
y: 0,
color: colors[0],
text: '' // Empty text for central node to show placeholder
});
function updateDocumentTitle() {
const centralNodeData = nodesData.find(n => n.id === centralNodeId);
if (centralNodeData) {
documentTitle.textContent = centralNodeData.text || 'Mind Map';
}
}
function renderMindMap() {
// Remove all nodes except central node
const existingNodes = container.querySelectorAll('.node');
existingNodes.forEach(node => {
if (node.id !== 'central-node') { // Preserve the central node
container.removeChild(node);
}
});
nodesData.forEach(node => {
if (node.id === centralNodeId) {
// Update central node separately
centralNode.style.left = `${node.x}px`;
centralNode.style.top = `${node.y}px`;
centralNode.style.backgroundColor = node.color;
// Render Markdown as HTML
centralNode.innerHTML = marked.parse(node.text || '');
// Attach event listeners if not already attached
if (!centralNode.dataset.listenersAttached) {
addEventListenersToNode(centralNode, node.id);
centralNode.dataset.listenersAttached = 'true';
}
return;
}
const nodeDiv = document.createElement('div');
nodeDiv.className = 'node';
nodeDiv.id = node.id;
nodeDiv.contentEditable = false; // Start in view mode
nodeDiv.tabIndex = 0;
nodeDiv.style.left = `${node.x}px`;
nodeDiv.style.top = `${node.y}px`;
nodeDiv.style.backgroundColor = node.color;
// Render Markdown as HTML
nodeDiv.innerHTML = marked.parse(node.text || '');
addEventListenersToNode(nodeDiv, node.id);
container.appendChild(nodeDiv);
});
drawConnections();
highlightSelectedNode();
updateDocumentTitle();
updateURL();
}
function addEventListenersToNode(nodeDiv, nodeId) {
nodeDiv.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent triggering container's click
setSelectedNode(nodeId);
enterEditMode(nodeDiv, nodeId);
});
nodeDiv.addEventListener('keydown', (e) => handleKeyDown(e, nodeId));
nodeDiv.addEventListener('mousedown', startDrag);
// Prevent default drag behavior for text selection
nodeDiv.addEventListener('dragstart', (e) => e.preventDefault());
}
function handleKeyDown(event, nodeId) {
const isCentralNode = nodeId === centralNodeId;
if (event.key === 'Enter' || event.key === 'Tab') {
event.preventDefault();
const nodeDiv = document.getElementById(nodeId);
if (nodeDiv.isContentEditable) {
// Store the key pressed
const keyPressed = event.key;
// Trigger blur to save the current text
nodeDiv.blur();
// Use a timeout to ensure the blur event has been processed
setTimeout(() => {
if (keyPressed === 'Enter') {
if (isCentralNode) {
addNode(nodeId); // Add child node for central node
} else {
addSiblingNode(nodeId); // Add sibling node for other nodes
}
} else if (keyPressed === 'Tab') {
addNode(nodeId); // Add child node for any node
}
}, 0);
} else {
if (isCentralNode) {
addNode(nodeId);
} else {
addSiblingNode(nodeId);
}
}
}
}
function setSelectedNode(nodeId) {
selectedNodeId = nodeId;
highlightSelectedNode();
}
function highlightSelectedNode() {
const nodes = container.querySelectorAll('.node');
nodes.forEach(node => {
if (node.id === selectedNodeId) {
node.style.border = '2px solid #0000FF';
} else {
node.style.border = '1px solid #999';
}
});
}
function addNode(parentId) {
if (!parentId) {
alert('No parent node selected.');
return;
}
const newId = generateId();
const nodeDiv = document.getElementById(parentId);
// Calculate new node position using the child angle (5 o'clock direction)
const radius = 150;
const parentX = nodeDiv.offsetLeft;
const parentY = nodeDiv.offsetTop;
const newX = parentX + radius * Math.cos(childAngle * Math.PI / 180);
const newY = parentY + radius * Math.sin(childAngle * Math.PI / 180);
const newNode = {
id: newId,
parentId: parentId,
x: newX,
y: newY,
color: colors[0],
text: ''
};
pushToUndo();
nodesData.push(newNode);
renderMindMap();
focusNode(newId);
}
function addSiblingNode(currentNodeId) {
const currentNode = nodesData.find(n => n.id === currentNodeId);
if (!currentNode) return;
// First sibling positioned at 1 o'clock direction
const siblingRadius = 200;
const siblingX = currentNode.x + siblingRadius * Math.cos(siblingAngle * Math.PI / 180);
const siblingY = currentNode.y + siblingRadius * Math.sin(siblingAngle * Math.PI / 180);
siblingAngle += 45; // Increment for next sibling
const newId = generateId();
const newNode = {
id: newId,
parentId: currentNode.parentId,
x: siblingX,
y: siblingY,
color: colors[0],
text: ''
};
pushToUndo();
nodesData.push(newNode);
renderMindMap();
focusNode(newId);
}
function deleteSelectedNode() {
if (!selectedNodeId) {
alert('No node selected for deletion.');
return;
}
if (selectedNodeId === centralNodeId) {
alert('Cannot delete the central node.');
return;
}
pushToUndo();
function deleteRecursively(id) {
const children = nodesData.filter(n => n.parentId === id);
children.forEach(child => deleteRecursively(child.id));
nodesData = nodesData.filter(n => n.id !== id);
}
deleteRecursively(selectedNodeId);
selectedNodeId = null;
renderMindMap();
}
function changeNodeColor(color) {
if (!selectedNodeId) return;
const node = nodesData.find(n => n.id === selectedNodeId);
if (node) {
pushToUndo();
node.color = color;
renderMindMap();
}
}
// Updated to handle raw Markdown
function updateNodeText(nodeId, rawMarkdown) {
const node = nodesData.find(n => n.id === nodeId);
const nodeDiv = document.getElementById(nodeId);
if (node && nodeDiv) {
node.text = rawMarkdown;
updateDocumentTitle();
updateURL();
}
}
function pushToUndo() {
undoStack.push(JSON.parse(JSON.stringify(nodesData)));
redoStack = [];
}
function undo() {
if (undoStack.length === 0) return;
redoStack.push(JSON.parse(JSON.stringify(nodesData)));
nodesData = undoStack.pop();
renderMindMap();
}
function redo() {
if (redoStack.length === 0) return;
undoStack.push(JSON.parse(JSON.stringify(nodesData)));
nodesData = redoStack.pop();
renderMindMap();
}
let isDraggingFlag = false;
let currentDraggedNodeId = null;
let dragOffsetX = 0;
let dragOffsetY = 0;
function startDrag(event) {
if (event.target.classList.contains('node')) {
isDraggingFlag = true;
currentDraggedNodeId = event.target.id;
const nodeRect = event.target.getBoundingClientRect();
const containerRect = container.getBoundingClientRect();
dragOffsetX = event.clientX - nodeRect.left;
dragOffsetY = event.clientY - nodeRect.top;
document.addEventListener('mousemove', dragNode);
document.addEventListener('mouseup', stopDrag);
}
}
function dragNode(event) {
if (!isDraggingFlag || !currentDraggedNodeId) return;
const containerRect = container.getBoundingClientRect();
let newX = event.clientX - containerRect.left - dragOffsetX;
let newY = event.clientY - containerRect.top - dragOffsetY;
newX = Math.max(0, Math.min(newX, containerRect.width - 100));
newY = Math.max(0, Math.min(newY, containerRect.height - 60));
const node = nodesData.find(n => n.id === currentDraggedNodeId);
if (node) {
node.x = newX;
node.y = newY;
renderMindMap();
}
}
function stopDrag() {
isDraggingFlag = false;
currentDraggedNodeId = null;
document.removeEventListener('mousemove', dragNode);
document.removeEventListener('mouseup', stopDrag);
updateURL();
}
function focusNode(nodeId) {
const nodeDiv = document.getElementById(nodeId);
if (nodeDiv) {
nodeDiv.focus();
setSelectedNode(nodeId);
}
}
function drawConnections() {
svg.innerHTML = '';
nodesData.forEach(node => {
if (node.parentId) {
const parentNode = nodesData.find(n => n.id === node.parentId);
if (parentNode) {
drawLine(parentNode, node);
}
}
});
}
function drawLine(parent, child) {
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', parent.x + 50); // Adjust based on node width
line.setAttribute('y1', parent.y + 30); // Adjust based on node height
line.setAttribute('x2', child.x + 50); // Adjust based on node width
line.setAttribute('y2', child.y + 30); // Adjust based on node height
line.setAttribute('stroke', 'black');
line.setAttribute('stroke-width', '2');
svg.appendChild(line);
}
function updateURL() {
const serializedData = JSON.stringify(nodesData);
const encodedData = btoa(encodeURIComponent(serializedData));
window.history.replaceState(null, null, '#' + encodedData);
}
function copyText() {
const nodeTexts = nodesData.map(node => `${'\t'.repeat(getNodeDepth(node.id))}${node.text}`);
const textToCopy = nodeTexts.join('\n');
navigator.clipboard.writeText(textToCopy)
.then(() => {
alert('Mind map text copied to clipboard!');
})
.catch(err => {
console.error('Failed to copy text: ', err);
});
}
function getNodeDepth(nodeId, depth = 0) {
const node = nodesData.find(n => n.id === nodeId);
if (node && node.parentId) {
return getNodeDepth(node.parentId, depth + 1);
}
return depth;
}
window.addEventListener('load', () => {
loadFromURL();
centralNode.focus();
setSelectedNode(centralNodeId); // Automatically select the central node on load
});
window.addEventListener('beforeunload', () => {
updateURL();
});
window.addEventListener('resize', () => {
renderMindMap();
});
// Event listeners for main buttons
copyTextBtn.addEventListener('click', copyText);
deleteNodeBtn.addEventListener('click', deleteSelectedNode);
undoBtn.addEventListener('click', undo);
redoBtn.addEventListener('click', redo);
addNodeBtn.addEventListener('click', () => addSiblingNode(selectedNodeId));
addChildBtn.addEventListener('click', () => addNode(selectedNodeId));
// Event listener for color palette
colorPalette.addEventListener('click', (event) => {
if (event.target.classList.contains('color-swatch')) {
const color = event.target.getAttribute('data-color');
changeNodeColor(color);
}
});
// Event listeners for emoji buttons
emojiButtons.forEach(button => {
button.addEventListener('click', () => {
const emoji = button.getAttribute('data-emoji');
addEmojiToSelectedNode(emoji);
});
});
function addEmojiToSelectedNode(emoji) {
if (!selectedNodeId) {
alert('No node selected.');
return;
}
const node = nodesData.find(n => n.id === selectedNodeId);
if (node) {
pushToUndo();
const emojis = ['💡', '🧠', '📚', '🎯', '✅', '❌', '🛠️', '🚦', '🎬'];
let currentText = node.text.trim();
// Find if currentText starts with any of the defined emojis
const existingEmoji = emojis.find(e => currentText.startsWith(e));
if (existingEmoji) {
// Replace the existing emoji with the new one
node.text = currentText.replace(existingEmoji, emoji);
} else {
// Prepend the new emoji with a space if there is existing text
node.text = (currentText ? emoji + ' ' + currentText : emoji);
}
renderMindMap();
}
}
function enterEditMode(nodeDiv, nodeId) {
if (nodeId === centralNodeId) {
centralNode.contentEditable = true;
} else {
nodeDiv.contentEditable = true;
}
// Add editable styling
nodeDiv.classList.add('editable');
// Replace HTML with raw Markdown
const node = nodesData.find(n => n.id === nodeId);
nodeDiv.innerText = node.text;
// Select the text for easier editing
const range = document.createRange();
range.selectNodeContents(nodeDiv);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
// Handle saving on blur
nodeDiv.addEventListener('blur', () => exitEditMode(nodeDiv, nodeId), { once: true });
}
function exitEditMode(nodeDiv, nodeId) {
nodeDiv.contentEditable = false;
nodeDiv.classList.remove('editable');
const rawMarkdown = nodeDiv.innerText;
updateNodeText(nodeId, rawMarkdown);
nodeDiv.innerHTML = marked.parse(rawMarkdown);
}
function loadFromURL() {
if (window.location.hash.length > 1) {
try {
const encodedData = window.location.hash.substring(1);
const decodedData = decodeURIComponent(atob(encodedData));
const parsedData = JSON.parse(decodedData);
// Ensure the central node has the fixed ID
const central = parsedData.find(n => n.parentId === null);
if (central) {
central.id = centralNodeId;
nodesData = parsedData.map(n => n.id === central.id ? central : n);
} else {
// If no central node found, initialize it
nodesData = [{
id: centralNodeId,
parentId: null,
x: 0,
y: 0,
color: colors[0],
text: '' // Empty text for placeholder
}];
}
renderMindMap();
} catch (error) {
console.error('Failed to load mind map from URL:', error);
centerNodePosition(centralNodeId);
renderMindMap();
}
} else {
centerNodePosition(centralNodeId);
renderMindMap();
}
}
function centerNodePosition(nodeId) {
const node = nodesData.find(n => n.id === nodeId);
if (node) {
const containerRect = container.getBoundingClientRect();
node.x = (containerRect.width / 2) - 50; // Adjust to center
node.y = (containerRect.height / 2) - 30; // Adjust to center
}
}
// Select the Export to SVG button
const exportSvgBtn = document.getElementById('export-svg-btn');
// Add click event listener
exportSvgBtn.addEventListener('click', exportToSVG);
/**
* Function to export the mind map to an SVG file.
* Preserves colors and box styles.
*/
function exportToSVG() {
// Disable the button to prevent multiple clicks
exportSvgBtn.disabled = true;
exportSvgBtn.textContent = 'Exporting...';
// Create SVG namespace
const svgNS = "http://www.w3.org/2000/svg";
// Create an SVG element
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("xmlns", svgNS);
svg.setAttribute("version", "1.1");
svg.setAttribute("width", "100%");
svg.setAttribute("height", "100%");
svg.setAttribute("viewBox", "0 0 " + container.offsetWidth + " " + container.offsetHeight);
// Optional: Add a background rectangle
const bgRect = document.createElementNS(svgNS, "rect");
bgRect.setAttribute("width", "100%");
bgRect.setAttribute("height", "100%");
bgRect.setAttribute("fill", "#f0f0f0"); // Match your container's background color
svg.appendChild(bgRect);
// Draw connections as lines
nodesData.forEach(node => {
if (node.parentId) {
const parentNode = nodesData.find(n => n.id === node.parentId);
if (parentNode) {
const line = document.createElementNS(svgNS, "line");
line.setAttribute("x1", parentNode.x + 50); // Adjust based on node width
line.setAttribute("y1", parentNode.y + 30); // Adjust based on node height
line.setAttribute("x2", node.x + 50); // Adjust based on node width
line.setAttribute("y2", node.y + 30); // Adjust based on node height
line.setAttribute("stroke", "black");
line.setAttribute("stroke-width", "2");
svg.appendChild(line);
}
}
});
// Draw nodes as rectangles with text
nodesData.forEach(node => {
// Skip if node is central node and handle separately if needed
// For this example, we'll treat all nodes similarly
const rect = document.createElementNS(svgNS, "rect");
rect.setAttribute("x", node.x);
rect.setAttribute("y", node.y);
rect.setAttribute("width", "100"); // Adjust width as needed
rect.setAttribute("height", "60"); // Adjust height as needed
rect.setAttribute("fill", node.color);
rect.setAttribute("stroke", "#000"); // Border color
rect.setAttribute("stroke-width", "1");
svg.appendChild(rect);
// Add text
const text = document.createElementNS(svgNS, "text");
text.setAttribute("x", node.x + 50); // Center horizontally
text.setAttribute("y", node.y + 35); // Center vertically
text.setAttribute("font-size", "14");
text.setAttribute("text-anchor", "middle");
text.setAttribute("dominant-baseline", "middle");
text.setAttribute("fill", "#000"); // Text color
// Handle Markdown rendering
// For simplicity, we'll strip Markdown syntax. For advanced rendering, consider using a library.
const plainText = stripMarkdown(node.text);
text.textContent = plainText;
svg.appendChild(text);
});
// Serialize the SVG XML
const serializer = new XMLSerializer();
const svgString = serializer.serializeToString(svg);
// Create a Blob from the SVG string
const blob = new Blob([svgString], { type: "image/svg+xml;charset=utf-8" });
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// Create a temporary link to trigger the download
const link = document.createElement("a");
link.href = url;
link.download = "MindMap.svg";
document.body.appendChild(link);
link.click();
// Clean up
document.body.removeChild(link);
URL.revokeObjectURL(url);
// Re-enable the button and reset text
exportSvgBtn.disabled = false;
exportSvgBtn.textContent = 'Export to SVG';
}
/**
* Utility function to strip Markdown syntax for plain text.
* @param {string} markdown - The Markdown string.
* @returns {string} - Plain text string.
*/
function stripMarkdown(markdown) {
// Simple regex-based stripping. For more complex Markdown, consider using a library.
return markdown
.replace(/[#_*~`>]/g, '') // Remove common Markdown characters
.replace(/\[(.*?)\]\(.*?\)/g, '$1') // Remove links but keep the text
.replace(/!\[.*?\]\(.*?\)/g, '') // Remove images
.trim();
}
</script>
</body>
</html>