-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviewer.js
More file actions
2408 lines (2320 loc) · 108 KB
/
Copy pathviewer.js
File metadata and controls
2408 lines (2320 loc) · 108 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
/* lifecycle-map · viewer.js
* Renders a swim-lane lifecycle map from JSON or YAML.
*
* Loading priority (first match wins):
* 1. ?src=<url> → fetch + parse
* 2. #data=<base64> → decode + gunzip + parse
* 3. ?paste → show paste UI
* 4. drag-and-drop → file dropped anywhere
* 5. default → splash screen with options
*
* Multi-language: any string in the data can be either a string or an
* object keyed by language code, e.g. { "en": "User", "pt": "Usuário" }.
* The L() helper resolves the current language with fallback to the first
* available key. Language is persisted in localStorage.
*
* Themes: paper · mono · midcentury · blueprint. Each with light/dark mode.
* Persisted in localStorage. URL params: ?theme=mono&mode=dark.
*
* MIT License · https://github.com/zalkowitsch/lifecycle-map
*/
(async function () {
'use strict';
// -------- constants --------
const DEFAULT_MODES = [
{ id: 'self-serve', label: 'Self-Serve', color: '#047857' },
{ id: 'assisted', label: 'Assisted', color: '#a16207' },
{ id: 'automated', label: 'Automated', color: '#1e40af' },
{ id: 'manual', label: 'Manual', color: '#b91c1c' },
{ id: 'n-a', label: 'Not Applicable', color: '#6b6557' },
{ id: 'unknown', label: 'Unknown', color: '#6b6557' },
];
const ROMAN = ['I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII','XIII','XIV','XV'];
const THEMES = [
{ id: 'paper', name: 'Paper', desc: 'editorial schematic' },
{ id: 'mono', name: 'Mono', desc: 'brutalist terminal' },
{ id: 'midcentury', name: 'Mid-Century', desc: 'wes-anderson poster' },
{ id: 'blueprint', name: 'Blueprint', desc: 'technical drawing' },
{ id: 'solarized', name: 'Solarized', desc: 'developer classic' },
{ id: 'newsprint', name: 'Newsprint', desc: '1920s newspaper' },
{ id: 'neon', name: 'Neon', desc: 'cyberpunk minimal' },
{ id: 'botanical', name: 'Botanical', desc: 'herbarium plate' },
];
const STORAGE_THEME = 'lifecycle-map.theme';
const STORAGE_MODE = 'lifecycle-map.mode';
const STORAGE_LANG = 'lifecycle-map.lang';
// Known example slugs → file paths. Slug appears in URL as #slug.
const EXAMPLE_SLUGS = {
'hiring-pipeline': './examples/hiring-pipeline.json',
'hiring-pipeline-yaml': './examples/hiring-pipeline.yaml',
'hiring-pipeline-modules': './examples/with-modules/hiring-pipeline.json',
'multi-language': './examples/multi-language.json',
'minimal': './examples/minimal.json',
};
function slugify(s) {
return String(s || '')
.toLowerCase()
.replace(/\.(json|ya?ml)$/i, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 64) || 'untitled';
}
function setHashSlug(slug, replace = false) {
if (!slug) return;
const newHash = '#' + slug;
if (window.location.hash === newHash) return;
const url = window.location.pathname + window.location.search + newHash;
try {
if (replace) history.replaceState(null, '', url);
else history.pushState(null, '', url);
} catch (_) {
window.location.hash = slug;
}
}
const LANG_NAMES = {
en: 'EN · English',
pt: 'PT · Português',
es: 'ES · Español',
fr: 'FR · Français',
de: 'DE · Deutsch',
it: 'IT · Italiano',
ja: 'JA · 日本語',
zh: 'ZH · 中文',
ko: 'KO · 한국어',
};
// UI string dictionary. Keys are stable; values are localized per UI lang.
// The viewer chrome (settings drawer, splash, header captions) reads these
// via [data-i18n="key"] in the HTML, set on initial load and on lang change.
const UI_LANGS = ['en', 'pt', 'es'];
const UI = {
en: {
'header.walkHint': '<kbd>←</kbd> <kbd>→</kbd> walk · drag empty to pan',
'header.docs': 'docs',
'header.share.title': 'Share',
'header.settings.title': 'Settings',
'header.code.title': 'View source',
'header.zoom.title': 'Zoom',
'header.zoom.fit': 'Fit to screen',
'header.search.title': 'Search (⌘K)',
'search.placeholder': 'Search nodes…',
'search.empty': 'No nodes match.',
'code.eyebrow': 'source',
'code.title': 'Code <em>· raw source</em>',
'code.copy': 'Copy',
'code.download': 'Download',
'code.empty': 'No source available for this map.',
'code.undo': 'Undo (⌘Z)',
'code.redo': 'Redo (⌘⇧Z)',
'code.status.saved': 'applied',
'code.status.editing': 'editing',
'code.status.error': 'invalid — keeping previous',
'loading': 'Loading lifecycle data…',
'splash.title': 'lifecycle-map <em>— viewer</em>',
'splash.eyebrow': 'interactive swim-lane lifecycle viewer',
'splash.lead': 'Render any swim-lane lifecycle map from a JSON or YAML source. Five ways to load:',
'splash.example.h': 'Try an example →',
'splash.example.p': 'Load the hiring-pipeline example to explore the schema and interactions.',
'splash.exampleMl.h': 'Try multi-language →',
'splash.exampleMl.p': 'A smaller example with strings in <code>en</code>, <code>pt</code>, and <code>es</code>. Switch language in <strong>Settings → Language</strong>.',
'splash.url.h': 'Load from URL → <code>?src=https://…</code>',
'splash.url.p': 'Pass a JSON or YAML URL as a query param. Works with public Gists, raw GitHub URLs, or any CORS-enabled endpoint.',
'splash.hash.h': 'Embed in URL → <code>#data=…</code>',
'splash.hash.p': 'Self-contained URLs with gzip-compressed JSON in the fragment. Great for AI agents — no hosting needed.',
'splash.dnd.h': 'Or just drag a file in →',
'splash.dnd.p': 'Drop a <code>.json</code> or <code>.yaml</code> file anywhere on this page.',
'splash.paste.h': 'Paste JSON or YAML',
'splash.paste.render': 'Render',
'splash.paste.cancel': 'Cancel',
'splash.footer.docs': 'Documentation',
'splash.footer.github': 'GitHub',
'splash.footer.license': 'MIT License',
'settings.eyebrow': 'preferences',
'settings.title': 'Settings <em>· make it yours</em>',
'settings.theme': 'Theme',
'settings.appearance': 'Appearance',
'settings.language': 'Language',
'settings.uiLanguage': 'Interface language',
'settings.dataLanguage': 'Map language',
'settings.mode.light': 'Light',
'settings.mode.dark': 'Dark',
'settings.foot.docs': 'Read the docs',
'settings.foot.github': 'View on GitHub',
'settings.foot.license': 'MIT License',
'dnd.title': 'Drop to load',
'dnd.sub': "Release anywhere — we'll parse JSON or YAML",
},
pt: {
'header.walkHint': '<kbd>←</kbd> <kbd>→</kbd> caminhar · arraste vazio para pan',
'header.docs': 'docs',
'header.share.title': 'Compartilhar',
'header.settings.title': 'Configurações',
'header.code.title': 'Ver código-fonte',
'header.zoom.title': 'Zoom',
'header.zoom.fit': 'Caber na tela',
'header.search.title': 'Buscar (⌘K)',
'search.placeholder': 'Buscar nodes…',
'search.empty': 'Nenhum node encontrado.',
'code.eyebrow': 'código',
'code.title': 'Código <em>· fonte bruta</em>',
'code.copy': 'Copiar',
'code.download': 'Baixar',
'code.empty': 'Nenhum código-fonte disponível para este mapa.',
'code.undo': 'Desfazer (⌘Z)',
'code.redo': 'Refazer (⌘⇧Z)',
'code.status.saved': 'aplicado',
'code.status.editing': 'editando',
'code.status.error': 'inválido — mantendo anterior',
'loading': 'Carregando dados do lifecycle…',
'splash.title': 'lifecycle-map <em>— viewer</em>',
'splash.eyebrow': 'visualizador interativo de lifecycle em swim-lane',
'splash.lead': 'Renderize qualquer mapa de lifecycle a partir de JSON ou YAML. Cinco formas de carregar:',
'splash.example.h': 'Experimente um exemplo →',
'splash.example.p': 'Carregue o exemplo do pipeline de contratação para explorar o schema e as interações.',
'splash.exampleMl.h': 'Experimente multi-idioma →',
'splash.exampleMl.p': 'Um exemplo menor com strings em <code>en</code>, <code>pt</code>, e <code>es</code>. Troque o idioma em <strong>Configurações → Idioma</strong>.',
'splash.url.h': 'Carregar por URL → <code>?src=https://…</code>',
'splash.url.p': 'Passe uma URL de JSON ou YAML como parâmetro. Funciona com Gists públicos, URLs raw do GitHub, ou qualquer endpoint com CORS.',
'splash.hash.h': 'Embutir na URL → <code>#data=…</code>',
'splash.hash.p': 'URLs auto-contidas com JSON comprimido em gzip no fragment. Ótimo para agentes de IA — sem hospedagem.',
'splash.dnd.h': 'Ou só arraste um arquivo →',
'splash.dnd.p': 'Solte um arquivo <code>.json</code> ou <code>.yaml</code> em qualquer lugar desta página.',
'splash.paste.h': 'Cole JSON ou YAML',
'splash.paste.render': 'Renderizar',
'splash.paste.cancel': 'Cancelar',
'splash.footer.docs': 'Documentação',
'splash.footer.github': 'GitHub',
'splash.footer.license': 'Licença MIT',
'settings.eyebrow': 'preferências',
'settings.title': 'Configurações <em>· do seu jeito</em>',
'settings.theme': 'Tema',
'settings.appearance': 'Aparência',
'settings.language': 'Idioma',
'settings.uiLanguage': 'Idioma da interface',
'settings.dataLanguage': 'Idioma do mapa',
'settings.mode.light': 'Claro',
'settings.mode.dark': 'Escuro',
'settings.foot.docs': 'Ler os docs',
'settings.foot.github': 'Ver no GitHub',
'settings.foot.license': 'Licença MIT',
'dnd.title': 'Solte para carregar',
'dnd.sub': 'Solte em qualquer lugar — vamos parsear JSON ou YAML',
},
es: {
'header.walkHint': '<kbd>←</kbd> <kbd>→</kbd> caminar · arrastra vacío para pan',
'header.docs': 'docs',
'header.share.title': 'Compartir',
'header.settings.title': 'Configuración',
'header.code.title': 'Ver código fuente',
'header.zoom.title': 'Zoom',
'header.zoom.fit': 'Ajustar a la pantalla',
'header.search.title': 'Buscar (⌘K)',
'search.placeholder': 'Buscar nodes…',
'search.empty': 'Ningún node coincide.',
'code.eyebrow': 'código',
'code.title': 'Código <em>· fuente cruda</em>',
'code.copy': 'Copiar',
'code.download': 'Descargar',
'code.empty': 'No hay código fuente disponible para este mapa.',
'code.undo': 'Deshacer (⌘Z)',
'code.redo': 'Rehacer (⌘⇧Z)',
'code.status.saved': 'aplicado',
'code.status.editing': 'editando',
'code.status.error': 'inválido — manteniendo anterior',
'loading': 'Cargando datos del lifecycle…',
'splash.title': 'lifecycle-map <em>— viewer</em>',
'splash.eyebrow': 'visor interactivo de lifecycle en swim-lane',
'splash.lead': 'Renderiza cualquier mapa de lifecycle desde JSON o YAML. Cinco formas de cargar:',
'splash.example.h': 'Prueba un ejemplo →',
'splash.example.p': 'Carga el ejemplo de pipeline de contratación para explorar el schema y las interacciones.',
'splash.exampleMl.h': 'Prueba multi-idioma →',
'splash.exampleMl.p': 'Un ejemplo más pequeño con strings en <code>en</code>, <code>pt</code>, y <code>es</code>. Cambia el idioma en <strong>Configuración → Idioma</strong>.',
'splash.url.h': 'Cargar desde URL → <code>?src=https://…</code>',
'splash.url.p': 'Pasa una URL de JSON o YAML como parámetro. Funciona con Gists públicos, URLs raw de GitHub, o cualquier endpoint con CORS.',
'splash.hash.h': 'Embebido en URL → <code>#data=…</code>',
'splash.hash.p': 'URLs auto-contenidas con JSON comprimido en el fragment. Excelente para agentes IA — sin hospedaje.',
'splash.dnd.h': 'O simplemente arrastra un archivo →',
'splash.dnd.p': 'Suelta un archivo <code>.json</code> o <code>.yaml</code> en cualquier lugar de esta página.',
'splash.paste.h': 'Pega JSON o YAML',
'splash.paste.render': 'Renderizar',
'splash.paste.cancel': 'Cancelar',
'splash.footer.docs': 'Documentación',
'splash.footer.github': 'GitHub',
'splash.footer.license': 'Licencia MIT',
'settings.eyebrow': 'preferencias',
'settings.title': 'Configuración <em>· a tu manera</em>',
'settings.theme': 'Tema',
'settings.appearance': 'Apariencia',
'settings.language': 'Idioma',
'settings.uiLanguage': 'Idioma de la interfaz',
'settings.dataLanguage': 'Idioma del mapa',
'settings.mode.light': 'Claro',
'settings.mode.dark': 'Oscuro',
'settings.foot.docs': 'Leer la documentación',
'settings.foot.github': 'Ver en GitHub',
'settings.foot.license': 'Licencia MIT',
'dnd.title': 'Suelta para cargar',
'dnd.sub': 'Suelta en cualquier lugar — parseamos JSON o YAML',
},
};
const STORAGE_UI_LANG = 'lifecycle-map.uiLang';
let CURRENT_UI_LANG = (function () {
const stored = localStorage.getItem(STORAGE_UI_LANG);
if (stored && UI[stored]) return stored;
const browser = (navigator.language || 'en').slice(0, 2).toLowerCase();
return UI[browser] ? browser : 'en';
})();
function t(key) {
return (UI[CURRENT_UI_LANG] && UI[CURRENT_UI_LANG][key])
|| (UI.en[key])
|| key;
}
function applyUILang(lang, persist = true) {
if (!UI[lang]) return;
CURRENT_UI_LANG = lang;
if (persist) localStorage.setItem(STORAGE_UI_LANG, lang);
document.documentElement.lang = lang;
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.dataset.i18n;
const val = t(key);
if (el.dataset.i18nAttr) {
el.setAttribute(el.dataset.i18nAttr, val.replace(/<[^>]+>/g, ''));
} else {
el.innerHTML = val;
}
});
syncSettingsUI();
}
// -------- theme + lang state --------
let CURRENT_LANG = null; // set after data load; falls back to first key in any localized string
let AVAILABLE_LANGS = null; // discovered from the data
let CURRENT_DATA = null; // for re-renders on theme change
let cssCache = null; // memoized getComputedStyle values
let __PH_BORDER_DIMS = null; // dimensions captured by render() for the
// phase-header bottom border SVG
// -------- zoom --------
// CURRENT_ZOOM = 1.0 default (100%). Lower = see more at once (zoom out).
// Implementation: keep SVG viewBox at logical dimensions, but scale the
// SVG element's width/height attributes by zoom. That makes all SVG
// content render smaller at the same vector quality, scrollbars adjust
// naturally, and edge routing/sticky logic don't need to know about it.
const STORAGE_ZOOM = 'lifecycle-map.zoom';
// Discrete zoom steps used by the dropdown + Cmd/Ctrl +/- shortcuts.
// Pinch on trackpad is continuous and ignores these.
const ZOOM_LEVELS = [0.25, 0.5, 1.0];
let CURRENT_ZOOM = (function () {
const stored = parseFloat(localStorage.getItem(STORAGE_ZOOM));
return (stored && stored > 0.1 && stored <= 4) ? stored : 1.0;
})();
function applyZoom(z, persist = true) {
z = Math.max(0.1, Math.min(4, z));
CURRENT_ZOOM = z;
if (persist) localStorage.setItem(STORAGE_ZOOM, String(z));
// text-scale = 1/zoom, clamped so labels never blow up nor go invisible
// when the user zooms far in or out.
const textScale = Math.max(0.65, Math.min(1.8, 1 / z));
document.documentElement.style.setProperty('--text-scale', String(textScale));
if (CURRENT_DATA) rerenderForTheme();
updateZoomLabel();
}
function fitToScreen() {
if (!__PH_BORDER_DIMS) { applyZoom(1.0); return; }
const wrap = document.getElementById('canvas-wrap');
if (!wrap) return;
const { SVG_W, SVG_H } = __PH_BORDER_DIMS;
// Pick the smaller of width-fit and height-fit so the entire map is visible.
const viewportW = Math.max(200, wrap.clientWidth - 20);
const viewportH = Math.max(200, wrap.clientHeight - 20);
const zoomW = viewportW / SVG_W;
const zoomH = SVG_H ? viewportH / SVG_H : zoomW;
const zoom = Math.max(0.05, Math.min(1.0, Math.min(zoomW, zoomH)));
applyZoom(zoom);
// After re-render scroll to origin so everything is visible from the start
requestAnimationFrame(() => {
const w = document.getElementById('canvas-wrap');
if (w) { w.scrollLeft = 0; w.scrollTop = 0; }
});
}
function updateZoomLabel() {
const el = document.getElementById('zoom-label');
if (el) el.textContent = Math.round(CURRENT_ZOOM * 100) + '%';
document.querySelectorAll('#zoom-menu [data-zoom]').forEach(b => {
const val = parseFloat(b.dataset.zoom);
b.classList.toggle('active', Math.abs(val - CURRENT_ZOOM) < 0.001);
});
}
// (Re)paints the phase-header bottom-border SVG. Width = canvas-wrap
// scrollWidth so the line covers the full scroll content, including any
// drawer-pad area or post-SVG_W trailing space. Called from render() and
// from setDrawerPad() whenever the canvas-wrap width changes.
function updatePhaseHeaderBorder() {
if (!__PH_BORDER_DIMS) return;
const { LANE_LABEL_W, PHASE_LABEL_H } = __PH_BORDER_DIMS;
const borderSvg = document.getElementById('phase-header-border-svg');
const wrap = document.getElementById('canvas-wrap');
if (!borderSvg || !wrap) return;
// scrollWidth reflects padding-right when drawer is open
const w = Math.max(wrap.scrollWidth, wrap.clientWidth);
// Also honor zoom — border y-offset must match the scaled phase header
const Z = CURRENT_ZOOM;
borderSvg.setAttribute('width', w);
borderSvg.setAttribute('height', 1);
borderSvg.setAttribute('viewBox', `0 0 ${w} 1`);
borderSvg.style.top = (PHASE_LABEL_H * Z - 1) + 'px';
borderSvg.innerHTML = '';
borderSvg.appendChild(svgEl('line', {
x1: LANE_LABEL_W * Z, y1: 0.5, x2: w, y2: 0.5, class: 'lane-edge'
}));
}
initThemeAndMode();
initSettingsDrawer();
initCodeDrawer();
initZoomControl();
initSearch();
initDragAndDrop();
// Translate the UI to whichever language is saved/detected.
applyUILang(CURRENT_UI_LANG, false);
function initThemeAndMode() {
const params = new URLSearchParams(window.location.search);
const queryTheme = params.get('theme');
const queryMode = params.get('mode');
const storedTheme = localStorage.getItem(STORAGE_THEME);
const storedMode = localStorage.getItem(STORAGE_MODE);
const theme = queryTheme || storedTheme || 'paper';
const mode = queryMode || storedMode || (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
applyTheme(theme, false);
applyMode(mode, false);
}
function applyTheme(theme, persist = true) {
if (!THEMES.find(t => t.id === theme)) theme = 'paper';
document.documentElement.dataset.theme = theme;
if (persist) localStorage.setItem(STORAGE_THEME, theme);
cssCache = null;
syncSettingsUI();
if (CURRENT_DATA) requestAnimationFrame(rerenderForTheme);
}
function applyMode(mode, persist = true) {
if (mode !== 'dark' && mode !== 'light') mode = 'light';
document.documentElement.dataset.mode = mode;
if (persist) localStorage.setItem(STORAGE_MODE, mode);
cssCache = null;
syncSettingsUI();
if (CURRENT_DATA) requestAnimationFrame(rerenderForTheme);
}
function applyLang(lang, persist = true) {
if (!AVAILABLE_LANGS || !AVAILABLE_LANGS.includes(lang)) return;
CURRENT_LANG = lang;
if (persist) localStorage.setItem(STORAGE_LANG, lang);
syncSettingsUI();
if (CURRENT_DATA) requestAnimationFrame(rerenderForTheme);
}
function rerenderForTheme() {
if (!CURRENT_DATA) return;
document.getElementById('lanes').innerHTML = '';
document.getElementById('phases').innerHTML = '';
document.getElementById('edges').innerHTML = '';
document.getElementById('nodes').innerHTML = '';
document.getElementById('phase-header-svg').innerHTML = '';
document.getElementById('lane-labels-svg').innerHTML = '';
document.getElementById('sticky-corner-svg').innerHTML = '';
render(CURRENT_DATA);
}
function css(varName) {
if (!cssCache) cssCache = getComputedStyle(document.documentElement);
return cssCache.getPropertyValue(varName).trim();
}
// -------- settings drawer --------
function initSettingsDrawer() {
const settingsDrawer = document.getElementById('settings-drawer');
const settingsBtn = document.getElementById('settings-btn');
if (settingsBtn) settingsBtn.addEventListener('click', () => openSettings());
const settingsCloseBtn = document.getElementById('settings-close');
if (settingsCloseBtn) settingsCloseBtn.addEventListener('click', () => closeSettings());
// theme cards — each card sets its own data-theme + data-mode so the
// CSS variables resolve to that theme's palette, making the card a true
// mini-preview that follows the current light/dark mode.
const grid = document.getElementById('theme-grid');
if (grid) {
const currentMode = document.documentElement.dataset.mode || 'light';
grid.innerHTML = THEMES.map(th => `
<div class="theme-card" data-theme="${th.id}" data-mode="${currentMode}">
<div class="swatches" id="sw-${th.id}"></div>
<div class="name">${th.name}</div>
<div class="desc">${th.desc}</div>
</div>
`).join('');
grid.querySelectorAll('.theme-card').forEach(card => {
card.addEventListener('click', () => applyTheme(card.dataset.theme));
});
}
// mode toggle is now built by syncSettingsUI (so labels are localized)
// close on scrim click (overlay scrim from drawer logic, but settings doesn't open scrim — close on outside)
document.addEventListener('click', (e) => {
if (!settingsDrawer.classList.contains('open')) return;
if (settingsDrawer.contains(e.target)) return;
if (settingsBtn && settingsBtn.contains(e.target)) return;
closeSettings();
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && settingsDrawer.classList.contains('open')) closeSettings();
});
}
function openSettings() {
const d = document.getElementById('settings-drawer');
d.classList.add('open');
d.setAttribute('aria-hidden', 'false');
const btn = document.getElementById('settings-btn');
if (btn) btn.classList.add('is-active');
renderThemeSwatches();
syncSettingsUI();
}
function closeSettings() {
const d = document.getElementById('settings-drawer');
d.classList.remove('open');
d.setAttribute('aria-hidden', 'true');
const btn = document.getElementById('settings-btn');
if (btn) btn.classList.remove('is-active');
}
function renderThemeSwatches() {
// Sample each theme's palette by reading CSS variables off a hidden
// probe element. Apply the sampled colors as INLINE styles to the card
// (background, border, name color, desc color) — relying on CSS var
// inheritance from data attributes on the card itself proved
// unreliable (the html-level data-theme/data-mode cascades override
// the card-level ones for var(--bg) inside .theme-card { background:
// var(--bg) }).
const currentMode = document.documentElement.dataset.mode || 'light';
THEMES.forEach(th => {
const probe = document.createElement('div');
probe.setAttribute('data-theme', th.id);
probe.setAttribute('data-mode', currentMode);
probe.style.cssText = 'position:absolute;left:-9999px;top:-9999px;width:1px;height:1px;visibility:hidden;pointer-events:none;';
document.body.appendChild(probe);
void probe.offsetWidth;
const cs = getComputedStyle(probe);
const bg = cs.getPropertyValue('--bg').trim() || '#fff';
const bg2 = cs.getPropertyValue('--bg-2').trim() || bg;
const ink = cs.getPropertyValue('--ink').trim() || '#000';
const mute = cs.getPropertyValue('--mute').trim() || '#888';
const accent = cs.getPropertyValue('--accent').trim() || ink;
const rule = cs.getPropertyValue('--rule').trim() || mute;
const nodeBg = cs.getPropertyValue('--node-bg').trim() || bg;
probe.remove();
// paint swatches
const sw = document.getElementById('sw-' + th.id);
if (sw) {
const colors = [bg, ink, accent, nodeBg, mute];
sw.innerHTML = colors.map(c => `<div class="swatch" style="background:${c}"></div>`).join('');
}
// paint card chrome (bg + border + text colors)
const card = document.querySelector('.theme-card[data-theme="' + th.id + '"]');
if (card) {
card.style.backgroundColor = bg;
card.style.borderColor = card.classList.contains('active') ? accent : rule;
card.style.color = ink;
const name = card.querySelector('.name');
const desc = card.querySelector('.desc');
if (name) name.style.color = ink;
if (desc) desc.style.color = mute;
}
});
}
// -------- zoom control --------
function initZoomControl() {
const btn = document.getElementById('zoom-btn');
const menu = document.getElementById('zoom-menu');
if (!btn || !menu) return;
function toggleMenu(open) {
const willOpen = open != null ? open : menu.hasAttribute('hidden');
if (willOpen) {
menu.removeAttribute('hidden');
btn.classList.add('is-active');
} else {
menu.setAttribute('hidden', '');
btn.classList.remove('is-active');
}
}
btn.addEventListener('click', (e) => { e.stopPropagation(); toggleMenu(); });
menu.addEventListener('click', (e) => {
const t = e.target.closest('button');
if (!t) return;
if (t.id === 'zoom-fit') {
fitToScreen();
} else if (t.dataset.zoom) {
applyZoom(parseFloat(t.dataset.zoom));
}
toggleMenu(false);
});
document.addEventListener('click', (e) => {
if (menu.hasAttribute('hidden')) return;
if (menu.contains(e.target) || btn.contains(e.target)) return;
toggleMenu(false);
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !menu.hasAttribute('hidden')) toggleMenu(false);
// Cmd/Ctrl + 0 / - / + for quick zoom
if (!e.metaKey && !e.ctrlKey) return;
if (e.key === '0') { e.preventDefault(); applyZoom(1.0); }
else if (e.key === '-' || e.key === '_') {
e.preventDefault();
const lower = [...ZOOM_LEVELS].reverse().find(z => z < CURRENT_ZOOM - 0.001);
if (lower) applyZoom(lower);
} else if (e.key === '=' || e.key === '+') {
e.preventDefault();
const higher = ZOOM_LEVELS.find(z => z > CURRENT_ZOOM + 0.001);
if (higher) applyZoom(higher);
}
});
// Pinch on the canvas zooms the canvas (not the whole page).
// macOS trackpad pinch dispatches `wheel` with ctrlKey=true and small
// deltaY. We accumulate the gesture and ONLY re-render at the end
// (no live CSS transform preview) — the live preview deformed sticky
// headers in ugly ways while the gesture was in flight. The pinch
// feels less "live" but the result is clean: prev frame → final
// zoom in one snap, no intermediate broken states.
const wrap = document.getElementById('canvas-wrap');
if (wrap) {
let pinchScale = 1;
let pinchTimer = null;
let pinchOrigin = null;
function getFitZoom() {
if (!__PH_BORDER_DIMS) return 0.05;
const { SVG_W, SVG_H } = __PH_BORDER_DIMS;
const vw = Math.max(200, wrap.clientWidth - 20);
const vh = Math.max(200, wrap.clientHeight - 20);
return Math.max(0.05, Math.min(1.0, Math.min(vw / SVG_W, SVG_H ? vh / SVG_H : 1.0)));
}
function commitPinch() {
if (Math.abs(pinchScale - 1) < 0.001 || !pinchOrigin) { pinchScale = 1; pinchOrigin = null; return; }
const fit = getFitZoom();
const next = Math.max(fit, Math.min(3, CURRENT_ZOOM * pinchScale));
const actualFactor = next / CURRENT_ZOOM;
const origin = pinchOrigin;
pinchScale = 1;
pinchOrigin = null;
applyZoom(next);
// Adjust scroll so the focal content point lands under the same
// viewport pixel after the re-render.
requestAnimationFrame(() => {
const w = document.getElementById('canvas-wrap');
if (!w) return;
w.scrollLeft = origin.contentX * actualFactor - origin.viewportX;
w.scrollTop = origin.contentY * actualFactor - origin.viewportY;
});
}
wrap.addEventListener('wheel', (e) => {
if (!e.ctrlKey) return;
e.preventDefault();
if (!pinchOrigin) {
const rect = wrap.getBoundingClientRect();
const viewportX = e.clientX - rect.left;
const viewportY = e.clientY - rect.top;
pinchOrigin = {
viewportX, viewportY,
contentX: wrap.scrollLeft + viewportX,
contentY: wrap.scrollTop + viewportY,
};
}
const factor = Math.exp(-e.deltaY * 0.01);
const fit = getFitZoom();
const minScale = fit / CURRENT_ZOOM;
const maxScale = 3 / CURRENT_ZOOM;
pinchScale = Math.max(minScale, Math.min(maxScale, pinchScale * factor));
if (pinchTimer) clearTimeout(pinchTimer);
pinchTimer = setTimeout(commitPinch, 80);
}, { passive: false });
}
updateZoomLabel();
}
// -------- search (Cmd+K) --------
let SEARCH_RESULTS = [];
let SEARCH_ACTIVE_IDX = 0;
function initSearch() {
const btn = document.getElementById('search-btn');
const modal = document.getElementById('search-modal');
const input = document.getElementById('search-input');
const scrim = document.getElementById('search-scrim');
if (!btn || !modal || !input) return;
input.placeholder = t('search.placeholder');
btn.addEventListener('click', () => openSearch());
scrim.addEventListener('click', () => closeSearch());
document.addEventListener('keydown', (e) => {
// Cmd/Ctrl + K opens search
if ((e.metaKey || e.ctrlKey) && (e.key === 'k' || e.key === 'K')) {
e.preventDefault();
if (modal.classList.contains('open')) closeSearch();
else openSearch();
return;
}
if (!modal.classList.contains('open')) return;
if (e.key === 'Escape') { e.preventDefault(); closeSearch(); }
else if (e.key === 'ArrowDown') {
e.preventDefault();
if (SEARCH_RESULTS.length) {
SEARCH_ACTIVE_IDX = Math.min(SEARCH_ACTIVE_IDX + 1, SEARCH_RESULTS.length - 1);
updateSearchActive();
}
} else if (e.key === 'ArrowUp') {
e.preventDefault();
if (SEARCH_RESULTS.length) {
SEARCH_ACTIVE_IDX = Math.max(SEARCH_ACTIVE_IDX - 1, 0);
updateSearchActive();
}
} else if (e.key === 'Enter') {
e.preventDefault();
const r = SEARCH_RESULTS[SEARCH_ACTIVE_IDX];
if (r) selectSearchResult(r.id);
}
});
input.addEventListener('input', () => runSearch(input.value));
}
function openSearch() {
const modal = document.getElementById('search-modal');
const input = document.getElementById('search-input');
modal.classList.add('open');
modal.setAttribute('aria-hidden', 'false');
input.value = '';
SEARCH_ACTIVE_IDX = 0;
runSearch('');
setTimeout(() => input.focus(), 0);
}
function closeSearch() {
const modal = document.getElementById('search-modal');
modal.classList.remove('open');
modal.setAttribute('aria-hidden', 'true');
}
function runSearch(query) {
const list = document.getElementById('search-results');
if (!list) return;
if (!CURRENT_DATA || !CURRENT_DATA.nodes) {
list.innerHTML = `<div class="search-empty">${escapeHtml(t('search.empty'))}</div>`;
SEARCH_RESULTS = [];
return;
}
const q = (query || '').trim().toLowerCase();
const all = CURRENT_DATA.nodes.map(n => ({
id: n.id,
title: L(n.title) || n.id,
sub: L(n.sub) || '',
objective: L(n.objective) || '',
laneLabel: (CURRENT_DATA.lanes.find(l => l.id === n.lane) ? L(CURRENT_DATA.lanes.find(l => l.id === n.lane).label) : ''),
phaseLabel: (CURRENT_DATA.phases.find(p => p.id === n.phase) ? L(CURRENT_DATA.phases.find(p => p.id === n.phase).label) : ''),
}));
const matches = !q ? all : all.filter(n => {
const hay = (n.id + ' ' + n.title + ' ' + n.sub + ' ' + n.objective + ' ' + n.laneLabel + ' ' + n.phaseLabel).toLowerCase();
return hay.includes(q);
});
SEARCH_RESULTS = matches.slice(0, 50);
SEARCH_ACTIVE_IDX = 0;
if (!SEARCH_RESULTS.length) {
list.innerHTML = `<div class="search-empty">${escapeHtml(t('search.empty'))}</div>`;
return;
}
list.innerHTML = SEARCH_RESULTS.map((n, i) => `
<div class="search-result ${i === 0 ? 'active' : ''}" data-id="${escapeHtml(n.id)}" data-idx="${i}" role="option">
<div class="search-result-title">${highlightMatch(n.title, q)}</div>
<div class="search-result-meta">
<span class="id-chip">${escapeHtml(n.id)}</span>
${n.laneLabel ? ' · ' + escapeHtml(n.laneLabel) : ''}
${n.phaseLabel ? ' · ' + escapeHtml(n.phaseLabel) : ''}
${n.sub ? ' · ' + highlightMatch(n.sub, q) : ''}
</div>
</div>
`).join('');
list.querySelectorAll('.search-result').forEach(el => {
el.addEventListener('mouseenter', () => {
SEARCH_ACTIVE_IDX = parseInt(el.dataset.idx, 10);
updateSearchActive();
});
el.addEventListener('click', () => selectSearchResult(el.dataset.id));
});
}
function highlightMatch(text, q) {
if (!q) return escapeHtml(text);
const escapedText = escapeHtml(text);
const idx = text.toLowerCase().indexOf(q);
if (idx < 0) return escapedText;
// re-find in escaped text — easier: split original then escape each part
const before = escapeHtml(text.slice(0, idx));
const match = escapeHtml(text.slice(idx, idx + q.length));
const after = escapeHtml(text.slice(idx + q.length));
return `${before}<mark>${match}</mark>${after}`;
}
function updateSearchActive() {
const items = document.querySelectorAll('.search-result');
items.forEach((el, i) => el.classList.toggle('active', i === SEARCH_ACTIVE_IDX));
const activeEl = items[SEARCH_ACTIVE_IDX];
if (activeEl) activeEl.scrollIntoView({ block: 'nearest' });
}
function selectSearchResult(nodeId) {
closeSearch();
if (typeof window.__lifecycleSetActive === 'function') {
window.__lifecycleSetActive(nodeId);
}
}
// -------- code drawer (raw source viewer) --------
let CURRENT_CODE_TAB = 0;
// Per-tab undo/redo stacks. Each entry is a text snapshot.
const UNDO_STACK = {}; // tabIdx → [snapshots]
const REDO_STACK = {}; // tabIdx → [snapshots]
let __codeDebounce = null;
function initCodeDrawer() {
const btn = document.getElementById('code-btn');
const drawer = document.getElementById('code-drawer');
const closeBtn = document.getElementById('code-close');
const editor = document.getElementById('code-editor');
if (!btn || !drawer || !editor) return;
btn.addEventListener('click', () => openCodeDrawer());
if (closeBtn) closeBtn.addEventListener('click', () => closeCodeDrawer());
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && drawer.classList.contains('open') &&
document.activeElement !== editor) closeCodeDrawer();
// Undo/redo when focused in editor
if (document.activeElement === editor) {
if ((e.metaKey || e.ctrlKey) && (e.key === 'z' || e.key === 'Z')) {
e.preventDefault();
if (e.shiftKey) codeRedo(); else codeUndo();
}
}
});
document.getElementById('code-copy').addEventListener('click', async () => {
const src = CURRENT_SOURCES[CURRENT_CODE_TAB];
if (!src) return;
try { await navigator.clipboard.writeText(src.text); flashCopyButton(); }
catch (_) {}
});
document.getElementById('code-download').addEventListener('click', () => {
const src = CURRENT_SOURCES[CURRENT_CODE_TAB];
if (!src) return;
const blob = new Blob([src.text], { type: src.lang === 'yaml' ? 'application/x-yaml' : 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = src.name;
document.body.appendChild(a); a.click(); a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
});
document.getElementById('code-undo').addEventListener('click', () => codeUndo());
document.getElementById('code-redo').addEventListener('click', () => codeRedo());
editor.addEventListener('input', () => {
const idx = CURRENT_CODE_TAB;
const src = CURRENT_SOURCES[idx];
if (!src) return;
setStatus('dirty');
// debounce parse + apply
if (__codeDebounce) clearTimeout(__codeDebounce);
__codeDebounce = setTimeout(() => tryApplyEdit(editor.value, idx, true), 600);
});
window.__lifecycleRenderCodeTabs = renderCodeTabs;
}
function tryApplyEdit(newText, tabIdx, pushUndo) {
const src = CURRENT_SOURCES[tabIdx];
if (!src) return;
const prevText = src.text;
if (newText === prevText) { setStatus('saved'); return; }
let parsed;
try {
parsed = parseSource(newText, src.name);
} catch (e) {
showCodeError(e.message || String(e));
setStatus('error');
return;
}
// sanity: must be a plain object with at least lanes/phases/nodes/edges (or
// we'd render garbage). For the root source only.
if (!parsed || typeof parsed !== 'object') {
showCodeError('Top-level must be an object.');
setStatus('error');
return;
}
hideCodeError();
// push prev onto undo, clear redo
if (pushUndo) {
(UNDO_STACK[tabIdx] ||= []).push(prevText);
if (UNDO_STACK[tabIdx].length > 50) UNDO_STACK[tabIdx].shift();
REDO_STACK[tabIdx] = [];
}
src.text = newText;
// If this is the root source (idx 0), re-render the map.
if (tabIdx === 0) {
const activeBefore = (typeof window.__lifecycleGetActive === 'function')
? window.__lifecycleGetActive() : null;
try {
loadDataAndRender(parsed);
// restore active node if still present
if (activeBefore && CURRENT_DATA && CURRENT_DATA.nodes.some(n => n.id === activeBefore)) {
requestAnimationFrame(() => {
if (typeof window.__lifecycleSetActive === 'function') {
window.__lifecycleSetActive(activeBefore);
}
});
}
} catch (e) {
showCodeError('Render failed: ' + (e.message || e));
setStatus('error');
// revert
src.text = prevText;
return;
}
}
setStatus('saved');
updateUndoRedoButtons();
updateCodeMeta();
}
function codeUndo() {
const idx = CURRENT_CODE_TAB;
const stack = UNDO_STACK[idx];
const src = CURRENT_SOURCES[idx];
if (!src || !stack || !stack.length) return;
const prev = stack.pop();
(REDO_STACK[idx] ||= []).push(src.text);
const editor = document.getElementById('code-editor');
editor.value = prev;
tryApplyEdit(prev, idx, false);
setStatus('saved');
updateUndoRedoButtons();
}
function codeRedo() {
const idx = CURRENT_CODE_TAB;
const stack = REDO_STACK[idx];
const src = CURRENT_SOURCES[idx];
if (!src || !stack || !stack.length) return;
const next = stack.pop();
(UNDO_STACK[idx] ||= []).push(src.text);
const editor = document.getElementById('code-editor');
editor.value = next;
tryApplyEdit(next, idx, false);
setStatus('saved');
updateUndoRedoButtons();
}
function updateUndoRedoButtons() {
const idx = CURRENT_CODE_TAB;
const undoBtn = document.getElementById('code-undo');
const redoBtn = document.getElementById('code-redo');
if (undoBtn) undoBtn.disabled = !(UNDO_STACK[idx] && UNDO_STACK[idx].length);
if (redoBtn) redoBtn.disabled = !(REDO_STACK[idx] && REDO_STACK[idx].length);
}
function showCodeError(msg) {
const el = document.getElementById('code-error');
if (!el) return;
el.textContent = msg;
el.hidden = false;
}
function hideCodeError() {
const el = document.getElementById('code-error');
if (el) el.hidden = true;
}
function setStatus(state) {
const el = document.getElementById('code-status');
if (!el) return;
el.classList.remove('saved', 'dirty', 'error');
if (state === 'saved') { el.classList.add('saved'); el.textContent = '✓ ' + t('code.status.saved'); }
else if (state === 'dirty') { el.classList.add('dirty'); el.textContent = '… ' + t('code.status.editing'); }
else if (state === 'error') { el.classList.add('error'); el.textContent = '⚠ ' + t('code.status.error'); }
else el.textContent = '';
}
function updateCodeMeta() {
const meta = document.getElementById('code-meta');
const src = CURRENT_SOURCES[CURRENT_CODE_TAB];
if (!meta || !src) return;
const lines = src.text.split('\n').length;
const kb = (src.text.length / 1024).toFixed(1);
meta.textContent = `${lines} lines · ${kb} KB`;
}
function flashCopyButton() {
const btn = document.getElementById('code-copy');
if (!btn) return;
const orig = btn.textContent;
btn.textContent = '✓ ' + orig;
setTimeout(() => { btn.textContent = orig; }, 1400);
}
function openCodeDrawer() {
const drawer = document.getElementById('code-drawer');
drawer.classList.add('open');
drawer.setAttribute('aria-hidden', 'false');
const btn = document.getElementById('code-btn');
if (btn) btn.classList.add('is-active');
renderCodeTabs();
}
function closeCodeDrawer() {
const drawer = document.getElementById('code-drawer');
drawer.classList.remove('open');
drawer.setAttribute('aria-hidden', 'true');
const btn = document.getElementById('code-btn');
if (btn) btn.classList.remove('is-active');
}
function renderCodeTabs() {
const tabsEl = document.getElementById('code-tabs');
const editor = document.getElementById('code-editor');
const meta = document.getElementById('code-meta');
if (!tabsEl || !editor) return;
if (!CURRENT_SOURCES.length) {
tabsEl.innerHTML = '';
editor.value = '';
editor.placeholder = t('code.empty');
if (meta) meta.textContent = '';
setStatus('');
updateUndoRedoButtons();
return;
}
if (CURRENT_CODE_TAB >= CURRENT_SOURCES.length) CURRENT_CODE_TAB = 0;
tabsEl.innerHTML = CURRENT_SOURCES.map((s, i) =>
`<button class="code-tab ${i === CURRENT_CODE_TAB ? 'active' : ''}" data-idx="${i}" role="tab">
${escapeHtml(s.name)}<span class="lang-chip">${escapeHtml(s.lang)}</span>
</button>`
).join('');
tabsEl.querySelectorAll('.code-tab').forEach(tab => {
tab.addEventListener('click', () => {
CURRENT_CODE_TAB = parseInt(tab.dataset.idx, 10);
renderCodeTabs();
});
});
const src = CURRENT_SOURCES[CURRENT_CODE_TAB];
editor.value = src.text;
hideCodeError();
setStatus('saved');
updateUndoRedoButtons();
updateCodeMeta();
}
function syncSettingsUI() {
const theme = document.documentElement.dataset.theme;
const mode = document.documentElement.dataset.mode;
document.querySelectorAll('.theme-card').forEach(c => {