Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
3292 lines (2862 loc) · 129 KB
/
Copy pathapp.js
File metadata and controls
3292 lines (2862 loc) · 129 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
// --- Predefined Templates ---
const templates = {
ecom: `title: Checkout funnel Flow
# Declare personas for roles-based view filtering
persona: Customer
persona: Admin
# Reusable Components Master Library
element: Promo Code {id: discount_code, status: warning, flags: [reusable], comment: "Applies coupon discounts"}
element: Apply Discount {id: apply_code}
element: Proceed to Pay {id: pay_btn_primary, flags: [primary], href: payment_details_group}
page: Checkout Funnel {status: success, id: start_checkout_page}
group: Step 1: Shopping Cart
input: {id: discount_code}
button: {id: apply_code}
button: {id: pay_btn_primary}
group: Step 2: Payment Details {id: payment_details_group}
input: Credit Card Number {id: card_num, personas: [Customer, Admin], comment: "Accepts Visa, Mastercard, Amex"}
calendar: Expiry Date {id: card_expiry, personas: [Customer]}
input: {id: discount_code, flags: [optional], comment: "Double-check before applying coupon"}
button: {id: apply_code}
button: Submit Payment {id: pay_btn_submit, status: success, flags: [secure, primary], href: receipt_page}
group: Step 3: Success Confirmation
page: Receipt Screen {id: receipt_page}
button: Print Invoice {id: print_invoice, status: info}
button: Print Discount Coupon {id: print_discount, status: draft, href: start_checkout_page}
button: Refund Transaction {id: refund_btn, status: danger, personas: [Admin], comment: "System Admins only"}`,
saas: `title: SaaS Dashboard Map
persona: Moderator
persona: Member
# Sidebar navigation reference template
element: Dashboard Home {id: link_dash}
element: Settings Screen {id: link_settings}
element: Workspace Title {id: ws_name, flags: [required]}
page: User Admin Portal
group: Nav Sidebar
button: {id: link_dash}
button: {id: link_settings, href: settings_panel_group}
button: Quick Search {id: global_search, status: info, comment: "Global cross-index finder"}
group: Dashboard View
group: Main Control Panel
button: Open Search Panel {id: global_search, flags: [popup]}
input: {id: ws_name}
group: Settings Panel {status: warning, id: settings_panel_group}
input: {id: ws_name, flags: [disabled], comment: "Modifiable inside root billing portal only"}
button: Save Configuration {id: save_all_configs, status: success, personas: [Moderator]}
button: Return Home {id: link_dash}`,
simple: `title: Standard Registration
persona: Applicant
persona: Reviewer
element: Master Input {id: user_input, flags: [required], comment: "Master profile input template"}
page: Home Screen
group: Form Section
input: {id: user_input, personas: [Applicant]}
input: User Profile Name {id: user_input, comment: "Must match passport spelling"}
button: Submit {status: success, personas: [Applicant]}
button: Accept Profile {status: success, personas: [Reviewer]}
button: Reject Profile {status: error, personas: [Reviewer]}`,
conditional: `title: Conditional Access Journey
persona: Member
persona: Admin
page: Sign In
input: Email Address
button: Submit Credentials {action: "start authentication"}
decision: Credentials valid?
page: Workspace Home {condition: "yes"}
selector: Available modules
page: Reports {condition: "analytics enabled"}
page: Billing {condition: "billing access"}
branch: Recovery route {condition: "no"}
page: Reset Password {condition: "known email"}
continue: Contact Support {condition: "account locked"}
concurrent: Notify & redirect
file: Audit Log {action: "write security event"}
reference: MFA Flow {id: mfa_reference, href: mfa_flow, action: "challenge required"}
flow: MFA Flow {id: mfa_flow}
entry: One-time code
decision: Code accepted?
exit: Resume sign in {condition: "verified"}
page: Retry MFA {condition: "failed"}`,
selectorcluster: `title: Selector & Cluster (VisVocab)
page: Account plan
branch: Choose tier
page: Free tier {condition: "free"}
cluster: Premium bundle {condition: "premium"}
page: Advanced Dashboard
page: Priority Support
page: Custom Reports
page: Search
selector: Search results
page: Products {condition: "matches query"}
page: Articles {condition: "matches query"}
page: People {condition: "matches query"}`
};
// --- State Variables ---
let zoomLevel = 1.0;
let panX = 40;
let panY = 50;
let isDragging = false;
let startX = 0;
let startY = 0;
let orientation = 'horizontal'; // 'horizontal' or 'vertical'
let showConnections = true;
let activeNodes = [];
let hoveredNodeId = null; // Stores shared ID of hovered element to glow connection paths
let selectedNodePathId = null; // Store path identifier of selected card
const collapsedPaths = new Set(); // Store hierarchy path identifiers of collapsed nodes
const collapsedTextLines = new Set(); // Store folded source line indices in the editor
let selectedPersona = 'all'; // Current persona filter: 'all' or specific persona name
let selectedTag = 'all'; // Current tag selector: 'all' or a specific node flag
let currentErrorMessage = null; // Active parse error message (null when valid)
let currentErrorLineIndex = null; // 0-based source line the active error points at
let showInspector = false; // Collapsible Right sidebar Inspector toggle state
let activeTopMenu = null; // Active top-bar persona/tag/glossary panel
let hasPersonaMenu = false;
let hasTagMenu = false;
let hasGlossaryMenu = false;
let serviceWorkerReadyPromise = null;
let draftSaveTimer = null;
let isRestoringDraft = false;
let fullSyntaxText = '';
let visibleEditorLineIndices = [];
let editorMetricsProbe = null;
// Setup color cache for shared instances
const idColorCache = {};
const DRAFT_SAVE_DELAY_MS = 300;
const LOCAL_DRAFT_STORAGE_KEY = `infoarchdiagram-draft:${window.location.pathname}`;
// --- Dom Elements ---
const diagramSvg = document.getElementById('diagramSvg');
const viewport = document.getElementById('viewport');
const canvasContainer = document.getElementById('canvas-container');
const syntaxInput = document.getElementById('syntaxInput');
const lineNumbersContent = document.getElementById('lineNumbersContent');
const emptyState = document.getElementById('empty-state');
const btnOrientHorizontal = document.getElementById('btn-orient-horizontal');
const btnOrientVertical = document.getElementById('btn-orient-vertical');
const btnToggleConnections = document.getElementById('btn-toggle-connections');
function shouldUseLocalDraftStorage() {
return window.location.protocol === 'file:' || !('serviceWorker' in navigator);
}
function saveDraftToLocalStorage(text) {
try {
localStorage.setItem(LOCAL_DRAFT_STORAGE_KEY, JSON.stringify({
text: typeof text === 'string' ? text : '',
updatedAt: Date.now()
}));
} catch (error) {
console.warn('Local draft saving failed.', error);
}
}
function loadDraftFromLocalStorage() {
try {
const raw = localStorage.getItem(LOCAL_DRAFT_STORAGE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed.text !== 'string') return null;
return parsed;
} catch (error) {
console.warn('Local draft restore failed.', error);
return null;
}
}
function clearDraftFromLocalStorage() {
try {
localStorage.removeItem(LOCAL_DRAFT_STORAGE_KEY);
} catch (error) {
console.warn('Local draft clearing failed.', error);
}
}
function isFoldableEditorLine(line) {
const trimmed = line.trim();
return Boolean(trimmed) && !trimmed.startsWith('#') && !trimmed.startsWith('//');
}
function isEditorMetadataLine(line) {
const trimmed = line.trim().toLowerCase();
return trimmed.startsWith('title:') || trimmed.startsWith('persona:');
}
function isEditorHierarchyLine(line) {
if (!isFoldableEditorLine(line) || isEditorMetadataLine(line)) {
return false;
}
return line.trim().includes(':');
}
function getEditorLineIndent(line) {
const indentMatch = line.match(/^(\s*)/);
return indentMatch ? indentMatch[1].length : 0;
}
function getEditorFoldRegions(lines) {
const foldRegions = new Map();
const hierarchyLines = [];
lines.forEach((line, index) => {
if (!isEditorHierarchyLine(line)) return;
hierarchyLines.push({
index,
indent: getEditorLineIndent(line)
});
});
hierarchyLines.forEach((node, hierarchyIndex) => {
const nextNode = hierarchyLines[hierarchyIndex + 1];
if (!nextNode || nextNode.indent <= node.indent) return;
let endIndex = node.index;
for (let cursor = node.index + 1; cursor < lines.length; cursor += 1) {
const cursorLine = lines[cursor];
if (isFoldableEditorLine(cursorLine) && getEditorLineIndent(cursorLine) <= node.indent) {
break;
}
endIndex = cursor;
}
if (endIndex > node.index) {
foldRegions.set(node.index, endIndex);
}
});
return foldRegions;
}
function translateVisibleOffsetToFullOffset(offset) {
const clampedOffset = Math.max(0, Math.min(Number(offset) || 0, syntaxInput?.value.length || 0));
const sourceLines = fullSyntaxText.split('\n');
if (visibleEditorLineIndices.length === 0) {
return Math.min(clampedOffset, fullSyntaxText.length);
}
let remainingOffset = clampedOffset;
for (let visibleIndex = 0; visibleIndex < visibleEditorLineIndices.length; visibleIndex += 1) {
const sourceLineIndex = visibleEditorLineIndices[visibleIndex];
const sourceLine = sourceLines[sourceLineIndex] ?? '';
const visibleLineLength = sourceLine.length;
const lineSpan = visibleLineLength + (visibleIndex < visibleEditorLineIndices.length - 1 ? 1 : 0);
if (remainingOffset <= lineSpan) {
const columnOffset = Math.min(remainingOffset, visibleLineLength);
let fullOffset = 0;
for (let sourceIndex = 0; sourceIndex < sourceLineIndex; sourceIndex += 1) {
fullOffset += (sourceLines[sourceIndex] ?? '').length + 1;
}
return fullOffset + columnOffset;
}
remainingOffset -= lineSpan;
}
return fullSyntaxText.length;
}
function getSourcePositionFromFullOffset(offset) {
const sourceLines = fullSyntaxText.split('\n');
const clampedOffset = Math.max(0, Math.min(Number(offset) || 0, fullSyntaxText.length));
let remainingOffset = clampedOffset;
for (let lineIndex = 0; lineIndex < sourceLines.length; lineIndex += 1) {
const sourceLine = sourceLines[lineIndex] ?? '';
if (remainingOffset <= sourceLine.length) {
return {
lineIndex,
columnOffset: remainingOffset
};
}
remainingOffset -= sourceLine.length;
if (lineIndex < sourceLines.length - 1) {
if (remainingOffset === 0) {
return {
lineIndex: lineIndex + 1,
columnOffset: 0
};
}
remainingOffset -= 1;
}
}
return {
lineIndex: Math.max(sourceLines.length - 1, 0),
columnOffset: (sourceLines[sourceLines.length - 1] || '').length
};
}
function getCollapsedEditorAncestorLine(lineIndex) {
const foldRegions = getEditorFoldRegions(fullSyntaxText.split('\n'));
let collapsedAncestor = null;
Array.from(collapsedTextLines).forEach((collapsedLineIndex) => {
const endIndex = foldRegions.get(collapsedLineIndex);
if (!endIndex) return;
if (lineIndex > collapsedLineIndex && lineIndex <= endIndex) {
if (collapsedAncestor === null || collapsedLineIndex > collapsedAncestor) {
collapsedAncestor = collapsedLineIndex;
}
}
});
return collapsedAncestor;
}
function translateFullOffsetToVisibleOffset(offset, options = {}) {
const { lineIndex, columnOffset } = getSourcePositionFromFullOffset(offset);
let targetLineIndex = lineIndex;
let targetColumnOffset = columnOffset;
const visibleLineIndex = visibleEditorLineIndices.indexOf(lineIndex);
if (visibleLineIndex === -1) {
const collapsedAncestor = getCollapsedEditorAncestorLine(lineIndex);
if (collapsedAncestor === null) {
return null;
}
targetLineIndex = collapsedAncestor;
targetColumnOffset = options.snapToCollapsedLineStart ? 0 : Math.min(columnOffset, (fullSyntaxText.split('\n')[collapsedAncestor] ?? '').length);
}
const resolvedVisibleLineIndex = visibleEditorLineIndices.indexOf(targetLineIndex);
if (resolvedVisibleLineIndex === -1) {
return null;
}
let visibleOffset = 0;
const sourceLines = fullSyntaxText.split('\n');
for (let i = 0; i < resolvedVisibleLineIndex; i += 1) {
const sourceLineIndex = visibleEditorLineIndices[i];
visibleOffset += (sourceLines[sourceLineIndex] ?? '').length + 1;
}
const visibleLineLength = (sourceLines[targetLineIndex] ?? '').length;
return visibleOffset + Math.min(targetColumnOffset, visibleLineLength);
}
function syncLineNumberScroll() {
if (!syntaxInput || !lineNumbersContent) return;
lineNumbersContent.style.transform = `translateY(-${syntaxInput.scrollTop}px)`;
}
function ensureEditorMetricsProbe() {
if (editorMetricsProbe || typeof document === 'undefined') return editorMetricsProbe;
editorMetricsProbe = document.createElement('div');
editorMetricsProbe.setAttribute('aria-hidden', 'true');
editorMetricsProbe.style.position = 'absolute';
editorMetricsProbe.style.visibility = 'hidden';
editorMetricsProbe.style.pointerEvents = 'none';
editorMetricsProbe.style.left = '-99999px';
editorMetricsProbe.style.top = '0';
editorMetricsProbe.style.whiteSpace = 'pre-wrap';
editorMetricsProbe.style.overflowWrap = 'anywhere';
editorMetricsProbe.style.wordBreak = 'break-word';
editorMetricsProbe.style.boxSizing = 'content-box';
editorMetricsProbe.style.padding = '0';
editorMetricsProbe.style.border = '0';
document.body.appendChild(editorMetricsProbe);
return editorMetricsProbe;
}
function getEditorWrappedLayout(lines = fullSyntaxText.split('\n')) {
if (!syntaxInput) {
return {
lineHeight: 18,
rowCounts: lines.map(() => 1)
};
}
const computedStyle = window.getComputedStyle(syntaxInput);
const lineHeight = parseFloat(computedStyle.lineHeight) || 18;
const contentWidth = Math.max(
syntaxInput.clientWidth - parseFloat(computedStyle.paddingLeft || '0') - parseFloat(computedStyle.paddingRight || '0'),
1
);
const probe = ensureEditorMetricsProbe();
if (!probe) {
return {
lineHeight,
rowCounts: lines.map(() => 1)
};
}
probe.style.width = `${contentWidth}px`;
probe.style.font = computedStyle.font;
probe.style.fontSize = computedStyle.fontSize;
probe.style.fontFamily = computedStyle.fontFamily;
probe.style.fontWeight = computedStyle.fontWeight;
probe.style.fontStyle = computedStyle.fontStyle;
probe.style.letterSpacing = computedStyle.letterSpacing;
probe.style.lineHeight = computedStyle.lineHeight;
probe.style.tabSize = computedStyle.tabSize;
probe.style.textTransform = computedStyle.textTransform;
probe.style.textIndent = computedStyle.textIndent;
const rowCounts = lines.map((line) => {
probe.textContent = line.length > 0 ? line : '\u00a0';
const measuredHeight = probe.getBoundingClientRect().height;
return Math.max(1, Math.ceil(measuredHeight / lineHeight));
});
probe.textContent = '';
return { lineHeight, rowCounts };
}
function getVisualRowsBeforeOffset(offset) {
const clampedOffset = Math.max(0, Math.min(Number(offset) || 0, fullSyntaxText.length));
const sourceLines = fullSyntaxText.split('\n');
const { lineHeight, rowCounts } = getEditorWrappedLayout(sourceLines);
const { lineIndex, columnOffset } = getSourcePositionFromFullOffset(clampedOffset);
let visualRows = 0;
for (let i = 0; i < lineIndex; i += 1) {
visualRows += rowCounts[i] || 1;
}
const currentLine = sourceLines[lineIndex] ?? '';
const currentLinePrefix = currentLine.slice(0, columnOffset);
const { rowCounts: partialRows } = getEditorWrappedLayout([currentLinePrefix.length > 0 ? currentLinePrefix : '\u00a0']);
visualRows += Math.max((partialRows[0] || 1) - 1, 0);
return { visualRows, lineHeight };
}
function renderEditorText() {
if (!syntaxInput || !lineNumbersContent) return;
const selectionStart = syntaxInput.selectionStart;
const selectionEnd = syntaxInput.selectionEnd;
const scrollTop = syntaxInput.scrollTop;
const sourceLines = fullSyntaxText.split('\n');
const { lineHeight, rowCounts } = getEditorWrappedLayout(sourceLines);
const gutterRows = [];
sourceLines.forEach((line, index) => {
const totalRows = rowCounts[index] || 1;
if (index === currentErrorLineIndex) {
gutterRows.push(`
<div style="height:${lineHeight}px" class="pr-2 flex items-center justify-end gap-1 whitespace-nowrap">
<button type="button" onclick="openErrorPopover(event)" title="${escapeHtml(currentErrorMessage || '')}" class="material-symbols-outlined text-[14px] text-rose-500 hover:text-rose-400 cursor-pointer leading-none animate-pulse">error</button>
<span class="w-6 text-right block text-rose-400 font-bold">${index + 1}</span>
</div>
`);
} else {
gutterRows.push(`
<div style="height:${lineHeight}px" class="pr-3 flex items-center justify-end whitespace-nowrap">
<span class="w-8 text-right block">${index + 1}</span>
</div>
`);
}
for (let rowIndex = 1; rowIndex < totalRows; rowIndex += 1) {
gutterRows.push(`
<div style="height:${lineHeight}px" class="pr-3 flex items-center justify-end whitespace-nowrap">
<span class="w-8 text-right block"> </span>
</div>
`);
}
});
syntaxInput.value = fullSyntaxText;
visibleEditorLineIndices = sourceLines.map((_, index) => index);
collapsedTextLines.clear();
syntaxInput.readOnly = false;
syntaxInput.selectionStart = Math.min(selectionStart, syntaxInput.value.length);
syntaxInput.selectionEnd = Math.min(selectionEnd, syntaxInput.value.length);
syntaxInput.scrollTop = scrollTop;
lineNumbersContent.innerHTML = gutterRows.join('');
syncLineNumberScroll();
}
function toggleTextFold() {
return;
}
function setFullSyntaxText(text) {
fullSyntaxText = String(text ?? '');
collapsedTextLines.clear();
renderEditorText();
}
function expandAllTextFolds() {
return;
}
function sendServiceWorkerMessage(type, payload = {}) {
if (!('serviceWorker' in navigator)) {
return Promise.resolve(null);
}
return ensureServiceWorkerReady().then((worker) => {
if (!worker) return null;
return new Promise((resolve, reject) => {
const channel = new MessageChannel();
const timeoutId = window.setTimeout(() => reject(new Error(`Service worker message timed out: ${type}`)), 4000);
channel.port1.onmessage = (event) => {
window.clearTimeout(timeoutId);
const data = event.data || {};
if (data.ok === false) {
reject(new Error(data.error || `Service worker request failed: ${type}`));
return;
}
resolve(data.payload ?? null);
};
worker.postMessage({ type, payload }, [channel.port2]);
});
});
}
function ensureServiceWorkerReady() {
if (!('serviceWorker' in navigator)) {
return Promise.resolve(null);
}
if (!serviceWorkerReadyPromise) {
serviceWorkerReadyPromise = navigator.serviceWorker
.register('./service-worker.js')
.then(() => navigator.serviceWorker.ready)
.then((registration) => registration.active || registration.waiting || registration.installing || null)
.catch((error) => {
console.warn('Service worker registration failed.', error);
return null;
});
}
return serviceWorkerReadyPromise;
}
function persistDraftNow() {
if (isRestoringDraft) return Promise.resolve();
const currentText = fullSyntaxText;
if (shouldUseLocalDraftStorage()) {
if (!currentText.trim()) {
clearDraftFromLocalStorage();
} else {
saveDraftToLocalStorage(currentText);
}
return Promise.resolve();
}
if (!currentText.trim()) {
return sendServiceWorkerMessage('clear-draft').catch((error) => {
console.warn('Draft clearing failed.', error);
});
}
return sendServiceWorkerMessage('save-draft', { text: currentText }).catch((error) => {
console.warn('Draft saving failed.', error);
});
}
function scheduleDraftSave() {
if (isRestoringDraft) return;
window.clearTimeout(draftSaveTimer);
draftSaveTimer = window.setTimeout(() => {
persistDraftNow();
}, DRAFT_SAVE_DELAY_MS);
}
async function restoreDraftFromServiceWorker() {
if (shouldUseLocalDraftStorage()) {
const payload = loadDraftFromLocalStorage();
if (!payload || typeof payload.text !== 'string' || !payload.text.trim()) {
return;
}
isRestoringDraft = true;
setFullSyntaxText(payload.text);
isRestoringDraft = false;
return;
}
try {
const payload = await sendServiceWorkerMessage('load-draft');
if (!payload || typeof payload.text !== 'string' || !payload.text.trim()) {
return;
}
isRestoringDraft = true;
setFullSyntaxText(payload.text);
} catch (error) {
console.warn('Draft restore failed.', error);
} finally {
isRestoringDraft = false;
}
}
// --- Initialization ---
window.addEventListener('load', async () => {
// Start completely blank/empty as requested
setFullSyntaxText("");
// Auto-detect theme preference
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.classList.add('dark');
const themeIcon = document.getElementById('theme-icon');
if (themeIcon) themeIcon.textContent = 'light_mode';
} else {
const themeIcon = document.getElementById('theme-icon');
if (themeIcon) themeIcon.textContent = 'dark_mode';
}
// Add Mouse Pan Event Listeners
canvasContainer.addEventListener('mousedown', startPan);
window.addEventListener('mousemove', dragPan);
window.addEventListener('mouseup', endPan);
canvasContainer.addEventListener('wheel', handleWheel, { passive: false });
// Add touch capabilities
canvasContainer.addEventListener('touchstart', (e) => {
if (e.touches.length === 1) {
isDragging = true;
startX = e.touches[0].clientX - panX;
startY = e.touches[0].clientY - panY;
}
});
canvasContainer.addEventListener('touchmove', (e) => {
if (isDragging && e.touches.length === 1) {
panX = e.touches[0].clientX - startX;
panY = e.touches[0].clientY - startY;
applyTransform();
}
});
canvasContainer.addEventListener('touchend', () => { isDragging = false; });
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
window.clearTimeout(draftSaveTimer);
persistDraftNow();
}
});
window.addEventListener('pagehide', () => {
window.clearTimeout(draftSaveTimer);
persistDraftNow();
});
syntaxInput.addEventListener('scroll', syncLineNumberScroll);
window.addEventListener('resize', renderEditorText);
// Dismiss the error popover on any click outside it (except the gutter icon that opens it).
document.addEventListener('mousedown', (e) => {
const popover = document.getElementById('error-popover');
if (!popover || popover.classList.contains('hidden')) return;
if (popover.contains(e.target)) return;
if (e.target.closest && e.target.closest('button[onclick^="openErrorPopover"]')) return;
closeErrorPopover();
});
if ('ResizeObserver' in window) {
const editorResizeObserver = new ResizeObserver(() => {
renderEditorText();
});
editorResizeObserver.observe(syntaxInput);
const editorPanel = document.getElementById('editor-panel');
if (editorPanel) {
editorResizeObserver.observe(editorPanel);
}
}
// Add custom Tab key handler to the syntax editor
setupTabKeyHandler();
await restoreDraftFromServiceWorker();
renderEditorText();
// Run initial parse (will show empty/guide view)
parseAndRender();
});
// --- File Import System ---
function triggerFileInput() {
const fileInput = document.getElementById('fileInput');
if (fileInput) fileInput.click();
}
// handleFileUpload function
function handleFileUpload(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
setFullSyntaxText(e.target.result);
// Clean up previous states
selectedNodePathId = null;
collapsedPaths.clear();
selectedPersona = 'all';
selectedTag = 'all';
parseAndRender();
resetZoom();
persistDraftNow();
};
reader.readAsText(file);
}
// --- File Save System ---
function saveToFile() {
const text = fullSyntaxText;
let filename = "untitled-diagram.txt";
// Extract title if available in the text
const titleMatch = text.match(/^title:\s*(.+)$/m);
if (titleMatch && titleMatch[1].trim()) {
const sanitizedTitle = titleMatch[1].trim()
.toLowerCase()
.replace(/[^a-z0-9\s_-]/g, '')
.replace(/\s+/g, '-');
if (sanitizedTitle) {
filename = `${sanitizedTitle}.txt`;
}
}
const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
// --- Tab key and Shift+Tab handler ---
function setupTabKeyHandler() {
syntaxInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
const start = this.selectionStart;
const end = this.selectionEnd;
const value = this.value;
const beforeCursor = value.substring(0, start);
const lineStartPos = beforeCursor.lastIndexOf('\n') + 1;
const currentLine = value.substring(lineStartPos, start);
const leadingWhitespace = currentLine.match(/^\s*/)?.[0] || '';
const insertion = `\n${leadingWhitespace}`;
this.value = value.substring(0, start) + insertion + value.substring(end);
this.selectionStart = this.selectionEnd = start + insertion.length;
fullSyntaxText = this.value;
renderEditorText();
parseAndRender();
scheduleDraftSave();
return;
}
if (e.key === 'Tab') {
e.preventDefault(); // Stop focus navigation
const start = this.selectionStart;
const end = this.selectionEnd;
const value = this.value;
const tabChar = " "; // Using 2 spaces for a clean standard indent layout
if (!e.shiftKey) {
// CASE 1: Standard Indentation
if (start === end) {
// No text highlighted: Insert 2 spaces at current cursor position
this.value = value.substring(0, start) + tabChar + value.substring(end);
this.selectionStart = this.selectionEnd = start + tabChar.length;
} else {
// Text highlighted: Indent all lines within the selection
const selectedText = value.substring(start, end);
const lines = selectedText.split('\n');
const indentedLines = lines.map(line => tabChar + line);
const newText = indentedLines.join('\n');
this.value = value.substring(0, start) + newText + value.substring(end);
this.selectionStart = start;
this.selectionEnd = start + newText.length;
}
} else {
// CASE 2: Outdent (Shift + Tab)
if (start === end) {
// Single line unindentation
const beforeCursor = value.substring(0, start);
const lineStartPos = beforeCursor.lastIndexOf('\n') + 1;
const currentLine = value.substring(lineStartPos, start);
if (currentLine.startsWith(' ')) {
this.value = value.substring(0, lineStartPos) + currentLine.substring(2) + value.substring(start);
this.selectionStart = this.selectionEnd = start - 2;
} else if (currentLine.startsWith(' ')) {
this.value = value.substring(0, lineStartPos) + currentLine.substring(1) + value.substring(start);
this.selectionStart = this.selectionEnd = start - 1;
} else if (currentLine.startsWith('\t')) {
this.value = value.substring(0, lineStartPos) + currentLine.substring(1) + value.substring(start);
this.selectionStart = this.selectionEnd = start - 1;
}
} else {
// Block selection unindentation
const selectedText = value.substring(start, end);
const lines = selectedText.split('\n');
const outdentedLines = lines.map(line => {
if (line.startsWith(' ')) return line.substring(2);
if (line.startsWith(' ')) return line.substring(1);
if (line.startsWith('\t')) return line.substring(1);
return line;
});
const newText = outdentedLines.join('\n');
this.value = value.substring(0, start) + newText + value.substring(end);
this.selectionStart = start;
this.selectionEnd = start + newText.length;
}
}
// Trigger rendering engine on key modification
fullSyntaxText = this.value;
renderEditorText();
parseAndRender();
scheduleDraftSave();
}
});
}
// --- Recursive path identifier generator ---
function assignPaths(node, parentPath = "") {
const currentPath = parentPath === "" ? String(node.indexInParent) : `${parentPath}.${node.indexInParent}`;
node.pathId = currentPath;
node.children.forEach((child, idx) => {
child.indexInParent = idx;
assignPaths(child, currentPath);
});
}
function normalizePersonaValue(value) {
if (!value) return '';
let normalized = String(value).trim();
if (
(normalized.startsWith('"') && normalized.endsWith('"')) ||
(normalized.startsWith("'") && normalized.endsWith("'"))
) {
normalized = normalized.substring(1, normalized.length - 1).trim();
}
return normalized.toLowerCase();
}
function normalizeTagValue(value) {
return String(value || '').trim().toLowerCase();
}
function createAttributeState() {
return {
id: '',
status: 'default',
flags: [],
personas: [],
comment: '',
description: '',
href: '',
condition: '',
action: '',
customIdSet: false,
hasStatusSet: false,
hasFlagsSet: false
};
}
function splitAttributeParts(rawAttr) {
const parts = [];
let currentPart = '';
let inQuotes = false;
let quoteChar = '';
let bracketDepth = 0;
for (let i = 0; i < rawAttr.length; i += 1) {
const char = rawAttr[i];
if ((char === '"' || char === "'") && (i === 0 || rawAttr[i - 1] !== '\\')) {
if (inQuotes && char === quoteChar) {
inQuotes = false;
} else if (!inQuotes) {
inQuotes = true;
quoteChar = char;
}
}
if (!inQuotes) {
if (char === '[') bracketDepth += 1;
if (char === ']') bracketDepth -= 1;
}
if (char === ',' && !inQuotes && bracketDepth === 0) {
parts.push(currentPart);
currentPart = '';
} else {
currentPart += char;
}
}
if (currentPart) {
parts.push(currentPart);
}
return parts;
}
function parseAttributes(rawAttr, personasMap, baseAttributes = createAttributeState()) {
const attributes = { ...baseAttributes };
if (!rawAttr) return attributes;
splitAttributeParts(rawAttr).forEach(part => {
const kv = part.split(':');
if (kv.length < 2) return;
const key = kv[0].trim().toLowerCase();
const val = kv.slice(1).join(':').trim();
if (key === 'id') {
attributes.id = val;
attributes.customIdSet = true;
} else if (key === 'status') {
attributes.status = val.toLowerCase();
attributes.hasStatusSet = true;
} else if (key === 'comment') {
attributes.comment = cleanAttributeValue(val);
} else if (key === 'description') {
attributes.description = cleanAttributeValue(val);
} else if (key === 'href') {
attributes.href = val.trim();
} else if (key === 'condition') {
attributes.condition = cleanAttributeValue(val);
} else if (key === 'action') {
attributes.action = cleanAttributeValue(val);
} else if (key === 'flags') {
attributes.flags = parseFlagValues(val);
if (attributes.flags.length > 0) {
attributes.hasFlagsSet = true;
}
} else if (key === 'personas' || key === 'persona') {
attributes.personas = parsePersonaValues(val, personasMap);
}
});
return attributes;
}
function registerPersonaValue(rawPersona, personasMap, description = '') {
const personaLabel = String(rawPersona || '').trim().replace(/^['"]|['"]$/g, '').trim();
const personaKey = normalizePersonaValue(personaLabel);
const cleanDescription = cleanAttributeValue(description);
if (!personaKey) return '';
if (!personasMap.has(personaKey)) {
personasMap.set(personaKey, {
name: personaLabel,
description: cleanDescription
});
} else if (cleanDescription && !personasMap.get(personaKey).description) {
const existingPersona = personasMap.get(personaKey);
personasMap.set(personaKey, {
...existingPersona,
description: cleanDescription
});
}
return personasMap.get(personaKey).name;
}
function parsePersonaValues(rawValue, personasMap) {
const personaMatch = String(rawValue || '').trim().match(/^\[(.*)\]$/);
const rawPersonas = personaMatch ? personaMatch[1].split(',') : [rawValue];
return rawPersonas
.map(persona => registerPersonaValue(persona, personasMap))
.filter(Boolean);
}
function parseFlagValues(rawValue) {