-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathcontent.js
More file actions
1838 lines (1612 loc) · 71.8 KB
/
content.js
File metadata and controls
1838 lines (1612 loc) · 71.8 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
// Listen for messages from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "convertToMarkdown") {
try {
// Get page title from head
const headTitle = document.title || "";
// Format head title: replace slashes and pipes with dashes
const formattedHeadTitle = headTitle.replace(/[\/|]/g, '-').replace(/\s+/g, '-').replace('---','-');
// Get article title (keep unchanged)
const title =
document
.querySelector(
'.container > div:nth-child(1) a[data-selected="true"]'
)
?.textContent?.trim() ||
document
.querySelector(".container > div:nth-child(1) h1")
?.textContent?.trim() ||
document.querySelector("h1")?.textContent?.trim() ||
"Untitled";
// Get article content container (keep unchanged)
const contentContainer =
document.querySelector(".container > div:nth-child(2) .prose") ||
document.querySelector(".container > div:nth-child(2) .prose-custom") ||
document.querySelector(".container > div:nth-child(2)") ||
document.body;
let markdown = ``;
let markdownTitle = title.replace(/\s+/g, '-');
contentContainer.childNodes.forEach((child) => {
markdown += processNode(child);
});
// Normalize blank lines
markdown = markdown.trim().replace(/\n{3,}/g, "\n\n");
sendResponse({
success: true,
markdown,
markdownTitle,
headTitle: formattedHeadTitle
});
} catch (error) {
console.error("Error converting to Markdown:", error);
sendResponse({ success: false, error: error.message });
}
} else if (request.action === "extractAllPages") {
try {
// Get the head title
const headTitle = document.title || "";
// Format head title: replace slashes and pipes with dashes
const formattedHeadTitle = headTitle.replace(/[\/|]/g, '-').replace(/\s+/g, '-').replace('---','-');
// Get the base part of the current document path
const baseUrl = window.location.origin;
// Get all links in the sidebar
const sidebarLinks = Array.from(document.querySelectorAll('.border-r-border ul li a'));
// Extract link URLs and titles
const pages = sidebarLinks.map(link => {
return {
url: new URL(link.getAttribute('href'), baseUrl).href,
title: link.textContent.trim(),
selected: link.getAttribute('data-selected') === 'true'
};
});
// Get current page information for return
const currentPageTitle =
document
.querySelector(
'.container > div:nth-child(1) a[data-selected="true"]'
)
?.textContent?.trim() ||
document
.querySelector(".container > div:nth-child(1) h1")
?.textContent?.trim() ||
document.querySelector("h1")?.textContent?.trim() ||
"Untitled";
sendResponse({
success: true,
pages: pages,
currentTitle: currentPageTitle,
baseUrl: baseUrl,
headTitle: formattedHeadTitle
});
} catch (error) {
console.error("Error extracting page links:", error);
sendResponse({ success: false, error: error.message });
}
} else if (request.action === "pageLoaded") {
// Page loading complete, batch operation preparation can be handled here
// No sendResponse needed, as this is a notification from background.js
console.log("Page loaded:", window.location.href);
// Always send a response, even if empty, to avoid connection errors
sendResponse({ received: true });
} else if (request.action === "tabActivated") {
// Tab has been activated, possibly after being in bfcache
console.log("Tab activated:", window.location.href);
// Acknowledge receipt of message to avoid connection errors
sendResponse({ received: true });
}
// Always return true for asynchronous sendResponse handling
return true;
});
// Function for Flowchart (ensure this exists from previous responses)
function convertFlowchartSvgToMermaidText(svgElement) {
if (!svgElement) return null;
console.log("Starting flowchart conversion with hierarchical logic...");
let mermaidCode = "flowchart TD\n\n";
const nodes = {};
const clusters = {};
const parentMap = {}; // Maps a child SVG ID to its parent SVG ID
const allElements = {}; // All nodes and clusters, for easy lookup
// 1. Collect all nodes
svgElement.querySelectorAll('g.node').forEach(nodeEl => {
const svgId = nodeEl.id;
if (!svgId) return;
let textContent = "";
const pElementForText = nodeEl.querySelector('.label foreignObject div > span > p, .label foreignObject div > p');
if (pElementForText) {
let rawParts = [];
pElementForText.childNodes.forEach(child => {
if (child.nodeType === Node.TEXT_NODE) rawParts.push(child.textContent);
else if (child.nodeName.toUpperCase() === 'BR') rawParts.push('<br>');
else if (child.nodeType === Node.ELEMENT_NODE) rawParts.push(child.textContent || '');
});
textContent = rawParts.join('').trim().replace(/"/g, '#quot;');
}
if (!textContent.trim()) {
const nodeLabel = nodeEl.querySelector('.nodeLabel, .label, foreignObject span, foreignObject div, text');
if (nodeLabel && nodeLabel.textContent) {
textContent = nodeLabel.textContent.trim().replace(/"/g, '#quot;');
}
}
let mermaidId = svgId.replace(/^flowchart-/, '').replace(/-\d+$/, '');
const bbox = nodeEl.getBoundingClientRect();
if (bbox.width > 0 || bbox.height > 0) {
nodes[svgId] = {
type: 'node',
mermaidId: mermaidId,
text: textContent,
svgId: svgId,
bbox: bbox,
};
allElements[svgId] = nodes[svgId];
}
});
// 2. Collect all clusters
svgElement.querySelectorAll('g.cluster').forEach(clusterEl => {
const svgId = clusterEl.id;
if (!svgId) return;
let title = "";
const labelEl = clusterEl.querySelector('.cluster-label, .label');
if (labelEl && labelEl.textContent) {
title = labelEl.textContent.trim();
}
if (!title) {
title = svgId;
}
const rect = clusterEl.querySelector('rect');
const bbox = rect ? rect.getBoundingClientRect() : clusterEl.getBoundingClientRect();
if (bbox.width > 0 || bbox.height > 0) {
clusters[svgId] = {
type: 'cluster',
mermaidId: svgId, // Use stable SVG ID for mermaid ID
title: title,
svgId: svgId,
bbox: bbox,
};
allElements[svgId] = clusters[svgId];
}
});
// 3. Build hierarchy (parentMap) by checking for geometric containment
for (const childId in allElements) {
const child = allElements[childId];
let potentialParentId = null;
let minArea = Infinity;
for (const parentId in clusters) {
if (childId === parentId) continue;
const parent = clusters[parentId];
if (child.bbox.left >= parent.bbox.left &&
child.bbox.right <= parent.bbox.right &&
child.bbox.top >= parent.bbox.top &&
child.bbox.bottom <= parent.bbox.bottom) {
const area = parent.bbox.width * parent.bbox.height;
if (area < minArea) {
minArea = area;
potentialParentId = parentId;
}
}
}
if (potentialParentId) {
parentMap[childId] = potentialParentId;
}
}
// 4. Process edges and assign to their lowest common ancestor cluster
const edges = [];
const edgeLabels = {};
svgElement.querySelectorAll('g.edgeLabel').forEach(labelEl => {
const text = labelEl.textContent?.trim();
const bbox = labelEl.getBoundingClientRect();
if(text) {
edgeLabels[labelEl.id] = {
text,
x: bbox.left + bbox.width / 2,
y: bbox.top + bbox.height / 2
};
}
});
svgElement.querySelectorAll('path.flowchart-link').forEach(path => {
const pathId = path.id;
if (!pathId) return;
let sourceNode = null;
let targetNode = null;
let idParts = pathId.replace(/^(L_|FL_)/, '').split('_');
if(idParts.length > 1 && idParts[idParts.length-1].match(/^\d+$/)){
idParts.pop();
}
idParts = idParts.join('_');
for (let i = 1; i < idParts.length; i++) {
const potentialSourceName = idParts.substring(0,i);
const potentialTargetName = idParts.substring(i);
const foundSourceNode = Object.values(nodes).find(n => n.mermaidId === potentialSourceName);
const foundTargetNode = Object.values(nodes).find(n => n.mermaidId === potentialTargetName);
if(foundSourceNode && foundTargetNode){
sourceNode = foundSourceNode;
targetNode = foundTargetNode;
break;
}
}
if (!sourceNode || !targetNode) { // Fallback for complex names
const pathIdParts = pathId.replace(/^(L_|FL_)/, '').split('_');
if(pathIdParts.length > 2){
for (let i = 1; i < pathIdParts.length; i++) {
const sName = pathIdParts.slice(0, i).join('_');
const tName = pathIdParts.slice(i, pathIdParts.length -1).join('_');
const foundSourceNode = Object.values(nodes).find(n => n.mermaidId === sName);
const foundTargetNode = Object.values(nodes).find(n => n.mermaidId === tName);
if(foundSourceNode && foundTargetNode){
sourceNode = foundSourceNode;
targetNode = foundTargetNode;
break;
}
}
}
}
if (!sourceNode || !targetNode) {
console.warn("Could not determine source/target for edge:", pathId);
return;
}
let label = "";
try {
const totalLength = path.getTotalLength();
if (totalLength > 0) {
const midPoint = path.getPointAtLength(totalLength / 2);
let closestLabel = null;
let closestDist = Infinity;
for (const labelId in edgeLabels) {
const currentLabel = edgeLabels[labelId];
const dist = Math.sqrt(Math.pow(currentLabel.x - midPoint.x, 2) + Math.pow(currentLabel.y - midPoint.y, 2));
if (dist < closestDist) {
closestDist = dist;
closestLabel = currentLabel;
}
}
if (closestLabel && closestDist < 75) {
label = closestLabel.text;
}
}
} catch (e) {
console.error("Error matching label for edge " + pathId, e);
}
const labelPart = label ? `|"${label}"|` : "";
const edgeText = `${sourceNode.mermaidId} -->${labelPart} ${targetNode.mermaidId}`;
// Find Lowest Common Ancestor
const sourceAncestors = [parentMap[sourceNode.svgId]];
while (sourceAncestors[sourceAncestors.length - 1]) {
sourceAncestors.push(parentMap[sourceAncestors[sourceAncestors.length - 1]]);
}
let lca = parentMap[targetNode.svgId];
while (lca && !sourceAncestors.includes(lca)) {
lca = parentMap[lca];
}
edges.push({ text: edgeText, parentId: lca || 'root' });
});
// 5. Generate Mermaid output
const definedNodeMermaidIds = new Set();
for (const svgId in nodes) {
const node = nodes[svgId];
if (!definedNodeMermaidIds.has(node.mermaidId)) {
mermaidCode += `${node.mermaidId}["${node.text}"]\n`;
definedNodeMermaidIds.add(node.mermaidId);
}
}
mermaidCode += '\n';
// Group children and edges by parent
const childrenMap = {};
const edgeMap = {};
for (const childId in parentMap) {
const parentId = parentMap[childId];
if (!childrenMap[parentId]) childrenMap[parentId] = [];
childrenMap[parentId].push(childId);
}
edges.forEach(edge => {
const parentId = edge.parentId || 'root';
if (!edgeMap[parentId]) edgeMap[parentId] = [];
edgeMap[parentId].push(edge.text);
});
// Add top-level edges
(edgeMap['root'] || []).forEach(edgeText => {
mermaidCode += `${edgeText}\n`;
});
function buildSubgraphOutput(clusterId) {
const cluster = clusters[clusterId];
if (!cluster) return;
mermaidCode += `\nsubgraph ${cluster.mermaidId} ["${cluster.title}"]\n`;
const childItems = childrenMap[clusterId] || [];
// Render nodes within this subgraph
childItems.filter(id => nodes[id]).forEach(nodeId => {
mermaidCode += ` ${nodes[nodeId].mermaidId}\n`;
});
// Render edges within this subgraph
(edgeMap[clusterId] || []).forEach(edgeText => {
mermaidCode += ` ${edgeText}\n`;
});
// Render nested subgraphs
childItems.filter(id => clusters[id]).forEach(subClusterId => {
buildSubgraphOutput(subClusterId);
});
mermaidCode += "end\n";
}
const topLevelClusters = Object.keys(clusters).filter(id => !parentMap[id]);
topLevelClusters.forEach(buildSubgraphOutput);
if (Object.keys(nodes).length === 0 && Object.keys(clusters).length === 0) return null;
return '```mermaid\n' + mermaidCode.trim() + '\n```';
}
// Function for Class Diagram (ensure this exists from previous responses)
function convertClassDiagramSvgToMermaidText(svgElement) {
if (!svgElement) return null;
const mermaidLines = ['classDiagram'];
const classData = {};
// 1. Parse Classes and their geometric information
svgElement.querySelectorAll('g.node.default[id^="classId-"]').forEach(node => {
const classIdSvg = node.getAttribute('id');
if (!classIdSvg) return;
const classNameMatch = classIdSvg.match(/^classId-([^-]+(?:-[^-]+)*)-(\d+)$/);
if (!classNameMatch) return;
const className = classNameMatch[1];
let cx = 0, cy = 0, halfWidth = 0, halfHeight = 0;
const transform = node.getAttribute('transform');
if (transform) {
const match = transform.match(/translate\(([^,]+),\s*([^)]+)\)/);
if (match) {
cx = parseFloat(match[1]);
cy = parseFloat(match[2]);
}
}
const pathForBounds = node.querySelector('g.basic.label-container > path[d^="M-"]');
if (pathForBounds) {
const d = pathForBounds.getAttribute('d');
const dMatch = d.match(/M-([0-9.]+)\s+-([0-9.]+)/); // Extracts W and H from M-W -H
if (dMatch && dMatch.length >= 3) {
halfWidth = parseFloat(dMatch[1]);
halfHeight = parseFloat(dMatch[2]);
}
}
if (!classData[className]) {
classData[className] = {
stereotype: "",
members: [],
methods: [],
svgId: classIdSvg,
x: cx,
y: cy,
width: halfWidth * 2,
height: halfHeight * 2
};
}
const stereotypeElem = node.querySelector('g.annotation-group.text foreignObject span.nodeLabel p, g.annotation-group.text foreignObject div p');
if (stereotypeElem && stereotypeElem.textContent.trim()) {
classData[className].stereotype = stereotypeElem.textContent.trim();
}
node.querySelectorAll('g.members-group.text g.label foreignObject span.nodeLabel p, g.members-group.text g.label foreignObject div p').forEach(m => {
const txt = m.textContent.trim();
if (txt) classData[className].members.push(txt);
});
node.querySelectorAll('g.methods-group.text g.label foreignObject span.nodeLabel p, g.methods-group.text g.label foreignObject div p').forEach(m => {
const txt = m.textContent.trim();
if (txt) classData[className].methods.push(txt);
});
});
// 2. Parse Notes
const notes = [];
// Method 1: Find traditional rect.note and text.noteText
svgElement.querySelectorAll('g').forEach(g => {
const noteRect = g.querySelector('rect.note');
const noteText = g.querySelector('text.noteText');
if (noteRect && noteText) {
const text = noteText.textContent.trim();
const x = parseFloat(noteRect.getAttribute('x'));
const y = parseFloat(noteRect.getAttribute('y'));
const width = parseFloat(noteRect.getAttribute('width'));
const height = parseFloat(noteRect.getAttribute('height'));
if (text && !isNaN(x) && !isNaN(y)) {
notes.push({
text: text,
x: x,
y: y,
width: width || 0,
height: height || 0,
id: g.id || `note_${notes.length}`
});
}
}
});
// Method 2: Find other note formats (like node undefined type)
svgElement.querySelectorAll('g.node.undefined, g[id^="note"]').forEach(g => {
// Check if it's a note (by background color, id or other features)
const hasNoteBackground = g.querySelector('path[fill="#fff5ad"], path[style*="#fff5ad"], path[style*="fill:#fff5ad"]');
const isNoteId = g.id && g.id.includes('note');
if (hasNoteBackground || isNoteId) {
// Try to get text from foreignObject
let text = '';
const foreignObject = g.querySelector('foreignObject');
if (foreignObject) {
const textEl = foreignObject.querySelector('p, span.nodeLabel, .nodeLabel');
if (textEl) {
text = textEl.textContent.trim();
}
}
// If no text found, try other selectors
if (!text) {
const textEl = g.querySelector('text, .label text, tspan');
if (textEl) {
text = textEl.textContent.trim();
}
}
if (text) {
// Get position information
const transform = g.getAttribute('transform');
let x = 0, y = 0;
if (transform) {
const match = transform.match(/translate\(([^,]+),\s*([^)]+)\)/);
if (match) {
x = parseFloat(match[1]);
y = parseFloat(match[2]);
}
}
// Check if this note has already been added
const existingNote = notes.find(n => n.text === text && Math.abs(n.x - x) < 10 && Math.abs(n.y - y) < 10);
if (!existingNote) {
notes.push({
text: text,
x: x,
y: y,
width: 0,
height: 0,
id: g.id || `note_${notes.length}`
});
}
}
}
});
// 3. Parse Note-to-Class Connections
const noteTargets = {}; // Maps note.id to target className
const connectionThreshold = 50; // Increase connection threshold
// Find note connection paths, support multiple path types
const noteConnections = [
...svgElement.querySelectorAll('path.relation.edge-pattern-dotted'),
...svgElement.querySelectorAll('path[id^="edgeNote"]'),
...svgElement.querySelectorAll('path.edge-thickness-normal.edge-pattern-dotted')
];
noteConnections.forEach(pathEl => {
const dAttr = pathEl.getAttribute('d');
if (!dAttr) return;
// Improved path parsing, support Bezier curves
const pathPoints = [];
// Parse various path commands
const commands = dAttr.match(/[A-Za-z][^A-Za-z]*/g) || [];
let currentX = 0, currentY = 0;
commands.forEach(cmd => {
const parts = cmd.match(/[A-Za-z]|[-+]?\d*\.?\d+/g) || [];
const type = parts[0];
const coords = parts.slice(1).map(Number);
switch(type.toUpperCase()) {
case 'M': // Move to
if (coords.length >= 2) {
currentX = coords[0];
currentY = coords[1];
pathPoints.push({x: currentX, y: currentY});
}
break;
case 'L': // Line to
for (let i = 0; i < coords.length; i += 2) {
if (coords[i+1] !== undefined) {
currentX = coords[i];
currentY = coords[i+1];
pathPoints.push({x: currentX, y: currentY});
}
}
break;
case 'C': // Cubic bezier
for (let i = 0; i < coords.length; i += 6) {
if (coords[i+5] !== undefined) {
// Get end point coordinates
currentX = coords[i+4];
currentY = coords[i+5];
pathPoints.push({x: currentX, y: currentY});
}
}
break;
case 'Q': // Quadratic bezier
for (let i = 0; i < coords.length; i += 4) {
if (coords[i+3] !== undefined) {
currentX = coords[i+2];
currentY = coords[i+3];
pathPoints.push({x: currentX, y: currentY});
}
}
break;
}
});
if (pathPoints.length < 2) return;
const pathStart = pathPoints[0];
const pathEnd = pathPoints[pathPoints.length - 1];
// Find the closest note to path start point
let closestNote = null;
let minDistToNote = Infinity;
notes.forEach(note => {
const dist = Math.sqrt(Math.pow(note.x - pathStart.x, 2) + Math.pow(note.y - pathStart.y, 2));
if (dist < minDistToNote) {
minDistToNote = dist;
closestNote = note;
}
});
// Find the closest class to path end point
let targetClassName = null;
let minDistToClass = Infinity;
for (const currentClassName in classData) {
const classInfo = classData[currentClassName];
const classCenterX = classInfo.x;
const classCenterY = classInfo.y;
const classWidth = classInfo.width || 200; // Default width
const classHeight = classInfo.height || 200; // Default height
// Calculate distance from path end to class center
const distToCenter = Math.sqrt(
Math.pow(pathEnd.x - classCenterX, 2) +
Math.pow(pathEnd.y - classCenterY, 2)
);
// Also calculate distance to class boundary
const classLeft = classCenterX - classWidth/2;
const classRight = classCenterX + classWidth/2;
const classTop = classCenterY - classHeight/2;
const classBottom = classCenterY + classHeight/2;
const dx = Math.max(classLeft - pathEnd.x, 0, pathEnd.x - classRight);
const dy = Math.max(classTop - pathEnd.y, 0, pathEnd.y - classBottom);
const distToEdge = Math.sqrt(dx*dx + dy*dy);
// Use the smaller distance as the judgment criterion
const finalDist = Math.min(distToCenter, distToEdge + classWidth/4);
if (finalDist < minDistToClass) {
minDistToClass = finalDist;
targetClassName = currentClassName;
}
}
// Relax connection conditions
if (closestNote && targetClassName &&
minDistToNote < connectionThreshold &&
minDistToClass < connectionThreshold * 2) {
const existing = noteTargets[closestNote.id];
const currentScore = minDistToNote + minDistToClass;
if (!existing || currentScore < existing.score) {
noteTargets[closestNote.id] = {
name: targetClassName,
score: currentScore,
noteDistance: minDistToNote,
classDistance: minDistToClass
};
}
}
});
// 4. Add Note Definitions to Mermaid output
const noteMermaidLines = [];
notes.forEach(note => {
const targetInfo = noteTargets[note.id];
if (targetInfo && targetInfo.name) {
noteMermaidLines.push(` note for ${targetInfo.name} "${note.text}"`);
} else {
noteMermaidLines.push(` note "${note.text}"`);
}
});
// Insert notes after 'classDiagram' line
if (noteMermaidLines.length > 0) {
mermaidLines.splice(1, 0, ...noteMermaidLines);
}
// 5. Add Class Definitions
for (const className in classData) {
const data = classData[className];
if (data.stereotype) {
mermaidLines.push(` class ${className} {`);
mermaidLines.push(` ${data.stereotype}`);
} else {
mermaidLines.push(` class ${className} {`);
}
data.members.forEach(member => { mermaidLines.push(` ${member}`); });
data.methods.forEach(method => { mermaidLines.push(` ${method}`); });
mermaidLines.push(' }');
}
const pathElements = Array.from(svgElement.querySelectorAll('path.relation[id^="id_"]'));
const labelElements = Array.from(svgElement.querySelectorAll('g.edgeLabels .edgeLabel foreignObject p'));
pathElements.forEach((path, index) => {
const id = path.getAttribute('id');
if (!id || !id.startsWith('id_')) return;
// Remove 'id_' prefix and trailing number (e.g., '_1')
let namePart = id.substring(3).replace(/_\d+$/, '');
const idParts = namePart.split('_');
let fromClass = null;
let toClass = null;
// Iterate through possible split points to find valid class names
for (let i = 1; i < idParts.length; i++) {
const potentialFrom = idParts.slice(0, i).join('_');
const potentialTo = idParts.slice(i).join('_');
if (classData[potentialFrom] && classData[potentialTo]) {
fromClass = potentialFrom;
toClass = potentialTo;
break; // Found a valid pair
}
}
if (!fromClass || !toClass) {
console.error("Could not parse class relation from ID:", id);
return; // Skip if we couldn't parse
}
// Get key attributes
const markerEndAttr = path.getAttribute('marker-end') || "";
const markerStartAttr = path.getAttribute('marker-start') || "";
const pathClass = path.getAttribute('class') || "";
// Determine line style: solid or dashed
const isDashed = path.classList.contains('dashed-line') ||
path.classList.contains('dotted-line') ||
pathClass.includes('dashed') ||
pathClass.includes('dotted');
const lineStyle = isDashed ? ".." : "--";
let relationshipType = "";
// Inheritance relation: <|-- or --|> (corrected inheritance relationship judgment)
if (markerStartAttr.includes('extensionStart')) {
// marker-start has extension, arrow at start point, means: toClass inherits fromClass
if (isDashed) {
// Dashed inheritance (implementation relationship): fromClass <|.. toClass
relationshipType = `${fromClass} <|.. ${toClass}`;
} else {
// Solid inheritance: fromClass <|-- toClass
relationshipType = `${fromClass} <|${lineStyle} ${toClass}`;
}
}
else if (markerEndAttr.includes('extensionEnd')) {
// marker-end has extension, arrow at end point, means: fromClass inherits toClass
if (isDashed) {
// Dashed inheritance (implementation relationship): toClass <|.. fromClass
relationshipType = `${toClass} <|.. ${fromClass}`;
} else {
// Solid inheritance: toClass <|-- fromClass
relationshipType = `${toClass} <|${lineStyle} ${fromClass}`;
}
}
// Implementation relation: ..|> (corrected implementation relationship judgment)
else if (markerStartAttr.includes('lollipopStart') || markerStartAttr.includes('implementStart')) {
relationshipType = `${toClass} ..|> ${fromClass}`;
}
else if (markerEndAttr.includes('implementEnd') || markerEndAttr.includes('lollipopEnd') ||
(markerEndAttr.includes('interfaceEnd') && isDashed)) {
relationshipType = `${fromClass} ..|> ${toClass}`;
}
// Composition relation: *-- (corrected composition relationship judgment)
else if (markerStartAttr.includes('compositionStart')) {
// marker-start has composition, diamond at start point, means: fromClass *-- toClass
relationshipType = `${fromClass} *${lineStyle} ${toClass}`;
}
else if (markerEndAttr.includes('compositionEnd') ||
markerEndAttr.includes('diamondEnd') && markerEndAttr.includes('filled')) {
relationshipType = `${toClass} *${lineStyle} ${fromClass}`;
}
// Aggregation relation: o-- (corrected aggregation relationship judgment)
else if (markerStartAttr.includes('aggregationStart')) {
// marker-start has aggregation, empty diamond at start point, means: toClass --o fromClass
relationshipType = `${toClass} ${lineStyle}o ${fromClass}`;
}
else if (markerEndAttr.includes('aggregationEnd') ||
markerEndAttr.includes('diamondEnd') && !markerEndAttr.includes('filled')) {
relationshipType = `${fromClass} o${lineStyle} ${toClass}`;
}
// Dependency relation: ..> or --> (corrected dependency relationship judgment)
else if (markerStartAttr.includes('dependencyStart')) {
if (isDashed) {
relationshipType = `${toClass} <.. ${fromClass}`;
} else {
relationshipType = `${toClass} <-- ${fromClass}`;
}
}
else if (markerEndAttr.includes('dependencyEnd')) {
if (isDashed) {
relationshipType = `${fromClass} ..> ${toClass}`;
} else {
relationshipType = `${fromClass} --> ${toClass}`;
}
}
// Association relation: --> (corrected association relationship judgment)
else if (markerStartAttr.includes('arrowStart') || markerStartAttr.includes('openStart')) {
relationshipType = `${toClass} <${lineStyle} ${fromClass}`;
}
else if (markerEndAttr.includes('arrowEnd') || markerEndAttr.includes('openEnd')) {
relationshipType = `${fromClass} ${lineStyle}> ${toClass}`;
}
// Arrowless solid line link: --
else if (lineStyle === "--" && !markerEndAttr.includes('End') && !markerStartAttr.includes('Start')) {
relationshipType = `${fromClass} -- ${toClass}`;
}
// Arrowless dashed line link: ..
else if (lineStyle === ".." && !markerEndAttr.includes('End') && !markerStartAttr.includes('Start')) {
relationshipType = `${fromClass} .. ${toClass}`;
}
// Default relation
else {
relationshipType = `${fromClass} ${lineStyle} ${toClass}`;
}
// Get relationship label text
const labelText = (labelElements[index] && labelElements[index].textContent) ?
labelElements[index].textContent.trim() : "";
if (relationshipType) {
mermaidLines.push(` ${relationshipType}${labelText ? ' : ' + labelText : ''}`);
}
});
if (mermaidLines.length <= 1 && Object.keys(classData).length === 0 && notes.length === 0) return null;
return '```mermaid\n' + mermaidLines.join('\n') + '\n```';
}
/**
* Helper: Convert SVG Sequence Diagram to Mermaid code
* @param {SVGElement} svgElement - The SVG DOM element for the sequence diagram
* @returns {string|null}
*/
function convertSequenceDiagramSvgToMermaidText(svgElement) {
if (!svgElement) return null;
// 1. Parse participants
const participants = [];
console.log("Looking for sequence participants..."); // DEBUG
// Find all participant text elements
svgElement.querySelectorAll('text.actor-box').forEach((textEl) => {
const name = textEl.textContent.trim().replace(/^"|"$/g, ''); // Remove quotes
const x = parseFloat(textEl.getAttribute('x'));
console.log("Found participant:", name, "at x:", x); // DEBUG
if (name && !isNaN(x)) {
participants.push({ name, x });
}
});
console.log("Total participants found:", participants.length); // DEBUG
participants.sort((a, b) => a.x - b.x);
// Remove duplicate participants
const uniqueParticipants = [];
const seenNames = new Set();
participants.forEach(p => {
if (!seenNames.has(p.name)) {
uniqueParticipants.push(p);
seenNames.add(p.name);
}
});
// 2. Parse Notes
const notes = [];
svgElement.querySelectorAll('g').forEach(g => {
const noteRect = g.querySelector('rect.note');
const noteText = g.querySelector('text.noteText');
if (noteRect && noteText) {
const text = noteText.textContent.trim();
const x = parseFloat(noteRect.getAttribute('x'));
const width = parseFloat(noteRect.getAttribute('width'));
const leftX = x;
const rightX = x + width;
// Find all participants within note coverage range
const coveredParticipants = [];
uniqueParticipants.forEach(p => {
// Check if participant is within note's horizontal range
if (p.x >= leftX && p.x <= rightX) {
coveredParticipants.push(p);
}
});
// Sort by x coordinate
coveredParticipants.sort((a, b) => a.x - b.x);
if (coveredParticipants.length > 0) {
let noteTarget;
if (coveredParticipants.length === 1) {
// Single participant
noteTarget = coveredParticipants[0].name;
} else {
// Multiple participants, use first and last
const firstParticipant = coveredParticipants[0].name;
const lastParticipant = coveredParticipants[coveredParticipants.length - 1].name;
noteTarget = `${firstParticipant},${lastParticipant}`;
}
notes.push({
text: text,
target: noteTarget,
y: parseFloat(noteRect.getAttribute('y'))
});
}
}
});
// 3. Parse message lines and message text
const messages = [];
// Collect all message texts
const messageTexts = [];
svgElement.querySelectorAll('text.messageText').forEach(textEl => {
const text = textEl.textContent.trim();
const y = parseFloat(textEl.getAttribute('y'));
const x = parseFloat(textEl.getAttribute('x'));
if (text && !isNaN(y)) {
messageTexts.push({ text, y, x });
}
});
messageTexts.sort((a, b) => a.y - b.y);
console.log("Found message texts:", messageTexts.length); // DEBUG
// Collect all message lines
const messageLines = [];
svgElement.querySelectorAll('line.messageLine0, line.messageLine1').forEach(lineEl => {
const x1 = parseFloat(lineEl.getAttribute('x1'));
const y1 = parseFloat(lineEl.getAttribute('y1'));
const x2 = parseFloat(lineEl.getAttribute('x2'));
const y2 = parseFloat(lineEl.getAttribute('y2'));
const isDashed = lineEl.classList.contains('messageLine1');
if (!isNaN(x1) && !isNaN(y1) && !isNaN(x2) && !isNaN(y2)) {
messageLines.push({ x1, y1, x2, y2, isDashed });
}
});
// Collect all curved message paths (self messages)
svgElement.querySelectorAll('path.messageLine0, path.messageLine1').forEach(pathEl => {
const d = pathEl.getAttribute('d');
const isDashed = pathEl.classList.contains('messageLine1');
if (d) {
// Parse path, check if it's a self message
const moveMatch = d.match(/M\s*([^,\s]+)[,\s]+([^,\s]+)/);
const endMatch = d.match(/([^,\s]+)[,\s]+([^,\s]+)$/);
if (moveMatch && endMatch) {
const x1 = parseFloat(moveMatch[1]);
const y1 = parseFloat(moveMatch[2]);
const x2 = parseFloat(endMatch[1]);
const y2 = parseFloat(endMatch[2]);
// Check if it's a self message (start and end x coordinates are close)
if (Math.abs(x1 - x2) < 20) { // Allow some margin of error
messageLines.push({
x1, y1, x2, y2, isDashed,
isSelfMessage: true
});
}
}
}
});
messageLines.sort((a, b) => a.y1 - b.y1);
console.log("Found message lines:", messageLines.length); // DEBUG
// 4. Match message lines and message text
for (let i = 0; i < Math.min(messageLines.length, messageTexts.length); i++) {
const line = messageLines[i];
const messageText = messageTexts[i];
let fromParticipant = null;
let toParticipant = null;
if (line.isSelfMessage) {
// Self message - find participant closest to x1
let minDist = Infinity;
for (const p of uniqueParticipants) {
const dist = Math.abs(p.x - line.x1);
if (dist < minDist) {
minDist = dist;
fromParticipant = toParticipant = p.name;
}
}
} else {
// Find sender and receiver based on x coordinates
let minDist1 = Infinity;
for (const p of uniqueParticipants) {
const dist = Math.abs(p.x - line.x1);
if (dist < minDist1) {
minDist1 = dist;
fromParticipant = p.name;
}
}
let minDist2 = Infinity;
for (const p of uniqueParticipants) {
const dist = Math.abs(p.x - line.x2);
if (dist < minDist2) {
minDist2 = dist;