-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1835 lines (1642 loc) · 61.9 KB
/
app.js
File metadata and controls
1835 lines (1642 loc) · 61.9 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
import { marked } from "./libs/marked/marked.esm.js";
import { splitDocumentLink, resolveWorkspacePath } from "./app/workspace/path-utils.js";
import { createAssetUrlRegistry, isWorkspaceRelativeHref, resolveAssetUrl } from "./app/workspace/assets.js";
import { buildDocumentRecord, searchDocumentIndex } from "./app/workspace/document-index.js";
// ── IndexedDB History Helpers ──────────────────────────────────────────────
const DB_NAME = "markdown-explorer-db";
const DB_STORE = "history";
const HISTORY_MAX_FOLDERS = 5;
const HISTORY_MAX_FILES = 10;
let _dbConnection = null;
function initDB() {
if (_dbConnection) return Promise.resolve(_dbConnection);
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, 1);
req.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains(DB_STORE)) {
db.createObjectStore(DB_STORE, { keyPath: "folderName" });
}
};
req.onsuccess = (e) => { _dbConnection = e.target.result; resolve(_dbConnection); };
req.onerror = () => reject(req.error);
});
}
async function saveHistory(folderName, handle, recentFiles = []) {
try {
const db = await initDB();
const tx = db.transaction(DB_STORE, "readwrite");
const store = tx.objectStore(DB_STORE);
const existing = await new Promise((res) => {
const r = store.get(folderName);
r.onsuccess = () => res(r.result);
r.onerror = () => res(null);
});
const merged = existing ? existing.recentFiles : [];
for (const f of recentFiles) {
const idx = merged.findIndex((x) => x.path === f.path);
if (idx >= 0) merged.splice(idx, 1);
merged.unshift(f);
}
const record = {
folderName,
handle,
recentFiles: merged.slice(0, HISTORY_MAX_FILES),
lastOpened: Date.now(),
};
store.put(record);
await new Promise((res, rej) => {
tx.oncomplete = res;
tx.onerror = () => rej(tx.error);
});
// Trim to max folders
await trimHistory();
renderSidebarRecentPanel();
} catch (err) {
console.warn("[history] saveHistory failed:", err);
}
}
async function trimHistory() {
try {
const db = await initDB();
const tx = db.transaction(DB_STORE, "readwrite");
const store = tx.objectStore(DB_STORE);
const all = await new Promise((res) => {
const r = store.getAll();
r.onsuccess = () => res(r.result);
r.onerror = () => res([]);
});
if (all.length <= HISTORY_MAX_FOLDERS) return;
all.sort((a, b) => b.lastOpened - a.lastOpened);
const toDelete = all.slice(HISTORY_MAX_FOLDERS);
for (const item of toDelete) store.delete(item.folderName);
await new Promise((res, rej) => {
tx.oncomplete = res;
tx.onerror = () => rej(tx.error);
});
} catch (err) {
console.warn("[history] trimHistory failed:", err);
}
}
async function loadHistory() {
try {
const db = await initDB();
const tx = db.transaction(DB_STORE, "readonly");
const store = tx.objectStore(DB_STORE);
const all = await new Promise((res) => {
const r = store.getAll();
r.onsuccess = () => res(r.result);
r.onerror = () => res([]);
});
all.sort((a, b) => b.lastOpened - a.lastOpened);
return all.slice(0, HISTORY_MAX_FOLDERS);
} catch (err) {
console.warn("[history] loadHistory failed:", err);
return [];
}
}
// ── End IndexedDB History Helpers ──────────────────────────────────────────
const openFolderButton = document.getElementById("open-folder");
const themeToggle = document.getElementById("theme-toggle");
const sidebarToggle = document.getElementById("sidebar-toggle");
const treeEl = document.getElementById("tree");
const tabsEl = document.getElementById("tabs");
const previewEl = document.getElementById("preview");
const tocEl = document.getElementById("toc");
const tocContentEl = tocEl?.querySelector(".toc-content");
const tocListContainer = document.getElementById("toc-list-container");
const tocToggleBtn = document.getElementById("toc-toggle");
const viewerContainer = document.getElementById("viewer-container");
const emptyEl = document.getElementById("empty");
const statusText = document.getElementById("status-text");
const closeAllTabsBtn = document.getElementById("close-all-tabs");
const appEl = document.querySelector(".app");
const sidebarEl = document.querySelector(".sidebar");
const resizerEl = document.querySelector(".sidebar-resizer");
const viewerEl = document.querySelector(".viewer");
const workspaceEl = document.querySelector(".workspace");
const rootEl = document.documentElement;
const searchShellEl = document.querySelector(".search-shell");
const settingsToggle = document.getElementById("settings-toggle");
const langToggle = document.getElementById("lang-toggle");
const mathRendererSelect = document.getElementById("math-renderer");
const settingsDialog = document.getElementById("settings-dialog");
const settingsCloseButton = document.getElementById("settings-close");
const recentPanelEl = document.getElementById("recent-panel");
const recentPanelToggleBtn = document.getElementById("recent-panel-toggle");
const recentPanelBodyEl = document.getElementById("recent-panel-body");
const workspaceSearchInput = document.getElementById("workspace-search");
const workspaceSearchLabel = document.getElementById("workspace-search-label");
const searchResultsEl = document.getElementById("search-results");
const searchResultsLabel = document.getElementById("search-results-label");
const mathRendererLabelEl = document.getElementById("math-renderer-label");
const settingsTitleEl = document.getElementById("settings-title");
const settingsDescriptionEl = document.getElementById("settings-description");
const settingsRenderingTitleEl = document.getElementById("settings-rendering-title");
const settingsRenderingDescriptionEl = document.getElementById("settings-rendering-description");
const fontTitleEl = document.getElementById("settings-font-title");
const fontDescriptionEl = document.getElementById("settings-font-description");
const fontBtns = document.querySelectorAll(".font-control-btn[data-font]");
const fontSizeTitleEl = document.getElementById("settings-fontsize-title");
const fontSizeDescriptionEl = document.getElementById("settings-fontsize-description");
const fontSizeBtns = document.querySelectorAll(".font-control-btn[data-font-size]");
const langStorageKey = "markdown-explorer-lang";
const mathRendererStorageKey = "markdown-explorer-math-renderer";
const proseFontStorageKey = "markdown-explorer-prose-font";
const fontSizeStorageKey = "markdown-explorer-font-size";
const langTagMap = { "zh-TW": "zh-Hant-TW", en: "en" };
const MATH_RENDERERS = Object.freeze({ katex: "katex", mathjax: "mathjax" });
let currentLang = localStorage.getItem(langStorageKey) || "zh-TW";
let currentMathRenderer = normalizeMathRenderer(localStorage.getItem(mathRendererStorageKey));
let translations = {};
function normalizeMathRenderer(value) {
return value === MATH_RENDERERS.mathjax ? MATH_RENDERERS.mathjax : MATH_RENDERERS.katex;
}
const FONT_STACKS = Object.freeze({
default: '"Iosevka Aile", "Cascadia Code", ui-monospace, monospace',
serif: 'serif',
sans: 'sans-serif',
});
const FONT_SIZES = Object.freeze({ "14": "14", "16": "16", "18": "18", "20": "20" });
function normalizeProseFont(value) {
return FONT_STACKS[value] ? value : "default";
}
function normalizeFontSize(value) {
return FONT_SIZES[value] ?? "16";
}
let currentProseFont = normalizeProseFont(localStorage.getItem(proseFontStorageKey));
let currentFontSize = normalizeFontSize(localStorage.getItem(fontSizeStorageKey));
async function loadLocale(lang) {
try {
const res = await fetch(`locales/${lang}.json`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
translations = await res.json();
} catch (err) {
console.warn(`[i18n] Failed to load locale "${lang}":`, err);
if (Object.keys(translations).length === 0 && lang !== "zh-TW") {
try {
const fallback = await fetch("locales/zh-TW.json");
if (fallback.ok) translations = await fallback.json();
} catch { }
}
}
}
function t(key, vars = {}) {
let str = translations[key] ?? key;
for (const [k, v] of Object.entries(vars)) {
str = str.replaceAll(`{${k}}`, String(v));
}
return str;
}
function applyLocale(lang) {
document.documentElement.lang = langTagMap[lang] || lang;
const openFolderLabel = document.getElementById("open-folder-label");
if (openFolderLabel) openFolderLabel.textContent = t("btn.openFolder");
const hintEl = document.querySelector(".sidebar-footer .hint");
if (hintEl) hintEl.textContent = t("sidebar.hint");
const copyrightEl = document.querySelector(".sidebar-footer .copyright");
if (copyrightEl) copyrightEl.textContent = t("sidebar.copyright");
const emptyTitle = document.getElementById("empty-title");
if (emptyTitle) emptyTitle.textContent = t("empty.title");
const emptyDesc = document.getElementById("empty-desc");
if (emptyDesc) emptyDesc.textContent = t("empty.desc");
const f1 = document.getElementById("empty-feature1");
if (f1) f1.textContent = t("empty.feature1");
const f2 = document.getElementById("empty-feature2");
if (f2) f2.textContent = t("empty.feature2");
const f3 = document.getElementById("empty-feature3");
if (f3) f3.textContent = t("empty.feature3");
if (sidebarEl) sidebarEl.setAttribute("aria-label", t("aria.sidebar"));
if (tabsEl) tabsEl.setAttribute("aria-label", t("aria.tabs"));
if (previewEl) previewEl.setAttribute("aria-label", t("aria.preview"));
if (tocEl) tocEl.setAttribute("aria-label", t("toc.title"));
const tocTitleEl = tocEl?.querySelector(".toc-title");
if (tocTitleEl) tocTitleEl.textContent = t("toc.title");
const tocCollapsedLabel = document.getElementById("toc-collapsed-label");
if (tocCollapsedLabel) tocCollapsedLabel.textContent = t("toc.title");
if (tocToggleBtn) {
const isCollapsed = tocEl.classList.contains("collapsed");
tocToggleBtn.setAttribute("aria-label", isCollapsed ? t("aria.tocExpand") : t("aria.tocCollapse"));
tocToggleBtn.innerHTML = isCollapsed ? ICON_TOC_OPEN : ICON_TOC_CLOSE;
}
const currentTheme = rootEl.getAttribute("data-theme");
if (themeToggle && currentTheme) {
themeToggle.setAttribute("aria-label", currentTheme === "dark" ? t("aria.themeToLight") : t("aria.themeToDark"));
}
if (settingsToggle) {
settingsToggle.setAttribute("aria-label", t("aria.settingsOpen"));
settingsToggle.innerHTML = ICON_SETTINGS;
}
if (settingsCloseButton) {
settingsCloseButton.setAttribute("aria-label", t("aria.settingsClose"));
settingsCloseButton.innerHTML = "×";
}
if (langToggle) {
langToggle.textContent = t("lang.current");
langToggle.setAttribute("aria-label", t("lang.switchLabel"));
langToggle.setAttribute("aria-pressed", lang === "en" ? "true" : "false");
}
if (!rootHandle) statusText.textContent = t("status.waiting");
if (closeAllTabsBtn) {
closeAllTabsBtn.textContent = t("tab.closeAll");
closeAllTabsBtn.setAttribute("aria-label", t("aria.closeAllTabs"));
}
const recentTitleEl = emptyEl?.querySelector(".recent-title");
if (recentTitleEl) recentTitleEl.textContent = t("recent.title");
const recentPanelLabelEl = document.getElementById("recent-panel-label");
if (recentPanelLabelEl) recentPanelLabelEl.textContent = t("sidebar.recentPanel");
if (workspaceEl) workspaceEl.dataset.dragHint = t("dragdrop.hint");
if (workspaceSearchInput) {
workspaceSearchInput.placeholder = t("search.placeholder");
workspaceSearchInput.setAttribute("aria-label", t("search.label"));
}
if (workspaceSearchLabel) {
workspaceSearchLabel.textContent = t("search.label");
}
if (searchResultsLabel) {
searchResultsLabel.textContent = t("search.results");
}
if (mathRendererLabelEl) {
mathRendererLabelEl.textContent = t("math.rendererLabel");
}
if (settingsTitleEl) {
settingsTitleEl.textContent = t("settings.title");
}
if (settingsDescriptionEl) {
settingsDescriptionEl.textContent = t("settings.description");
}
if (settingsRenderingTitleEl) {
settingsRenderingTitleEl.textContent = t("settings.renderingTitle");
}
if (settingsRenderingDescriptionEl) {
settingsRenderingDescriptionEl.textContent = t("settings.renderingDescription");
}
if (fontTitleEl) fontTitleEl.textContent = t("settings.font.title");
if (fontDescriptionEl) fontDescriptionEl.textContent = t("settings.font.description");
const fontBtnDefault = document.getElementById("font-btn-default");
const fontBtnSerif = document.getElementById("font-btn-serif");
const fontBtnSans = document.getElementById("font-btn-sans");
if (fontBtnDefault) fontBtnDefault.textContent = t("settings.font.default");
if (fontBtnSerif) fontBtnSerif.textContent = t("settings.font.serif");
if (fontBtnSans) fontBtnSans.textContent = t("settings.font.sans");
if (fontSizeTitleEl) fontSizeTitleEl.textContent = t("settings.fontSize.title");
if (fontSizeDescriptionEl) fontSizeDescriptionEl.textContent = t("settings.fontSize.description");
const fontSizeBtnSm = document.getElementById("font-size-btn-sm");
const fontSizeBtnMd = document.getElementById("font-size-btn-md");
const fontSizeBtnLg = document.getElementById("font-size-btn-lg");
const fontSizeBtnXl = document.getElementById("font-size-btn-xl");
if (fontSizeBtnSm) fontSizeBtnSm.textContent = t("settings.fontSize.sm");
if (fontSizeBtnMd) fontSizeBtnMd.textContent = t("settings.fontSize.md");
if (fontSizeBtnLg) fontSizeBtnLg.textContent = t("settings.fontSize.lg");
if (fontSizeBtnXl) fontSizeBtnXl.textContent = t("settings.fontSize.xl");
if (mathRendererSelect) {
mathRendererSelect.setAttribute("aria-label", t("math.rendererAria"));
const katexOption = mathRendererSelect.querySelector('option[value="katex"]');
const mathJaxOption = mathRendererSelect.querySelector('option[value="mathjax"]');
if (katexOption) katexOption.textContent = t("math.katex");
if (mathJaxOption) mathJaxOption.textContent = t("math.mathjax");
mathRendererSelect.value = currentMathRenderer;
}
renderSearchResults(currentSearchResults);
}
async function setLang(lang) {
currentLang = lang;
localStorage.setItem(langStorageKey, lang);
await loadLocale(lang);
applyLocale(lang);
applyTheme(rootEl.getAttribute("data-theme") || getPreferredTheme());
if (sidebarToggle) {
const isCollapsed = appEl.classList.contains("sidebar-collapsed");
sidebarToggle.setAttribute("aria-label", isCollapsed ? t("aria.sidebarExpand") : t("aria.sidebarCollapse"));
}
renderTabs();
}
let rootHandle = null;
let activePath = null;
let cachedHeadings = [];
let tocRAFPending = false;
let activeTreeNode = null;
let pendingAnchor = "";
const handleMap = new Map();
const openFiles = new Map();
const openOrder = [];
const scrollPositions = new Map();
const previewAssets = createAssetUrlRegistry();
let draggedTabPath = null;
let dragTargetTabPath = null;
let dragTargetPosition = null;
let searchQuery = "";
let currentSearchResults = { files: [], headings: [], content: [] };
let indexBuildToken = 0;
const documentIndex = new Map();
let idSeed = 0;
function slugifyHeading(text) {
return text
.toLowerCase()
.replace(/[^\w\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af\s-]/g, "")
.trim()
.replace(/\s+/g, "-");
}
marked.use({
renderer: {
html() { return ""; },
heading({ tokens, depth, text }) {
const id = slugifyHeading(text);
const inner = this.parser.parseInline(tokens);
return `<h${depth} id="${id}">${inner}</h${depth}>\n`;
},
link({ href, title, text }) {
const safeTitle = title ? ` title="${title}"` : "";
if (href && href.startsWith("#")) {
return `<a href="${href}" class="anchor-link"${safeTitle}>${text}</a>`;
}
if (href && !/^(https?:\/\/|\/\/|mailto:)/.test(href)) {
return `<a href="${href}" class="internal-link" data-href="${href}"${safeTitle}>${text}</a>`;
}
return `<a href="${href}" target="_blank" rel="noopener noreferrer"${safeTitle}>${text}</a>`;
},
},
});
let mermaidApi = window.mermaid ?? null;
let prismApi = window.Prism ?? null;
let katexApi = window.katex ?? null;
let katexAutoRender = window.renderMathInElement ?? null;
let mathJaxApi = window.MathJax?.typesetPromise ? window.MathJax : null;
const themeStorageKey = "markdown-explorer-theme";
const sidebarWidthStorageKey = "markdown-explorer-sidebar-width";
let mermaidLoadPromise = null;
let prismLoadPromise = null;
let katexLoadPromise = null;
let mathJaxLoadPromise = null;
let mathJaxTypesetPromise = Promise.resolve();
let renderPreviewToken = 0;
const ICON_SUN = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>`;
const ICON_MOON = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>`;
const ICON_SETTINGS = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c0 .66.39 1.26 1 1.51H21a2 2 0 1 1 0 4h-.09c-.66 0-1.26.39-1.51 1Z"/></svg>`;
const ICON_PANEL_CLOSE = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><line x1="9" x2="9" y1="3" y2="21"/><path d="m16 15-3-3 3-3"/></svg>`;
const ICON_PANEL_OPEN = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><line x1="9" x2="9" y1="3" y2="21"/><path d="m12 9 3 3-3 3"/></svg>`;
const ICON_TOC_CLOSE = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg>`;
const ICON_TOC_OPEN = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg>`;
function getPreferredTheme() {
const stored = localStorage.getItem(themeStorageKey);
if (stored === "light" || stored === "dark") return stored;
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}
function applyProseFont(fontKey) {
const stack = FONT_STACKS[fontKey] ?? FONT_STACKS.default;
rootEl.style.setProperty("--prose-font-body", stack);
rootEl.style.setProperty("--prose-font-heading", stack);
fontBtns.forEach((btn) => {
btn.classList.toggle("is-selected", btn.dataset.font === fontKey);
});
}
function applyFontSize(size) {
rootEl.style.setProperty("--prose-font-size", `${size}px`);
fontSizeBtns.forEach((btn) => {
btn.classList.toggle("is-selected", btn.dataset.fontSize === size);
});
}
function applyTheme(theme) {
rootEl.setAttribute("data-theme", theme);
if (themeToggle) {
themeToggle.setAttribute("aria-pressed", theme === "dark" ? "true" : "false");
themeToggle.setAttribute("aria-label", theme === "dark" ? t("aria.themeToLight") : t("aria.themeToDark"));
themeToggle.innerHTML = theme === "dark" ? ICON_SUN : ICON_MOON;
}
}
function getMermaidTheme() { return rootEl.getAttribute("data-theme") === "dark" ? "dark" : "neutral"; }
function loadScriptOnce(src) {
return new Promise((resolve, reject) => {
const existing = document.querySelector(`script[data-dynamic-src="${src}"]`);
if (existing) {
if (existing.dataset.loaded === "true") {
resolve();
return;
}
existing.addEventListener("load", () => resolve(), { once: true });
existing.addEventListener("error", () => reject(new Error(`Failed to load ${src}`)), { once: true });
return;
}
const script = document.createElement("script");
script.src = src;
script.async = true;
script.dataset.dynamicSrc = src;
script.addEventListener("load", () => {
script.dataset.loaded = "true";
resolve();
}, { once: true });
script.addEventListener("error", () => reject(new Error(`Failed to load ${src}`)), { once: true });
document.head.appendChild(script);
});
}
function loadStylesheetOnce(href) {
return new Promise((resolve, reject) => {
const existing = document.querySelector(`link[data-dynamic-href="${href}"]`);
if (existing) {
if (existing.dataset.loaded === "true") {
resolve();
return;
}
existing.addEventListener("load", () => resolve(), { once: true });
existing.addEventListener("error", () => reject(new Error(`Failed to load ${href}`)), { once: true });
return;
}
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = href;
link.dataset.dynamicHref = href;
link.addEventListener("load", () => {
link.dataset.loaded = "true";
resolve();
}, { once: true });
link.addEventListener("error", () => reject(new Error(`Failed to load ${href}`)), { once: true });
document.head.appendChild(link);
});
}
async function ensurePrismLoaded() {
if (prismApi) return prismApi;
if (!prismLoadPromise) {
prismLoadPromise = loadScriptOnce("libs/prism/prism.js").then(() => {
prismApi = window.Prism ?? null;
return prismApi;
});
}
return prismLoadPromise;
}
async function ensureMermaidLoaded() {
if (mermaidApi) return mermaidApi;
if (!mermaidLoadPromise) {
mermaidLoadPromise = loadScriptOnce("libs/mermaid/mermaid.min.js").then(() => {
mermaidApi = window.mermaid ?? null;
initMermaid();
return mermaidApi;
});
}
return mermaidLoadPromise;
}
async function ensureKatexLoaded() {
if (katexApi && katexAutoRender) {
return { katex: katexApi, renderMathInElement: katexAutoRender };
}
if (!katexLoadPromise) {
katexLoadPromise = loadStylesheetOnce("libs/katex/katex.min.css")
.then(() => loadScriptOnce("libs/katex/katex.min.js"))
.then(() => loadScriptOnce("libs/katex/contrib/auto-render.min.js"))
.then(() => {
katexApi = window.katex ?? null;
katexAutoRender = window.renderMathInElement ?? null;
return { katex: katexApi, renderMathInElement: katexAutoRender };
});
}
return katexLoadPromise;
}
function getMathJaxConfig() {
return {
tex: {
inlineMath: [["$", "$"], ["\\(", "\\)"]],
displayMath: [["$$", "$$"], ["\\[", "\\]"]],
processEscapes: true,
},
svg: {
fontCache: "local",
},
options: {
skipHtmlTags: ["script", "noscript", "style", "textarea", "pre", "code", "option"],
},
startup: {
typeset: false,
},
};
}
async function ensureMathJaxLoaded() {
if (mathJaxApi?.typesetPromise) return mathJaxApi;
if (!mathJaxLoadPromise) {
mathJaxLoadPromise = (async () => {
const config = getMathJaxConfig();
window.MathJax = {
...(window.MathJax ?? {}),
...config,
tex: {
...(window.MathJax?.tex ?? {}),
...config.tex,
},
svg: {
...(window.MathJax?.svg ?? {}),
...config.svg,
},
options: {
...(window.MathJax?.options ?? {}),
...config.options,
},
startup: {
...(window.MathJax?.startup ?? {}),
...config.startup,
},
};
await loadScriptOnce("libs/mathjax/tex-svg.js");
mathJaxApi = window.MathJax?.typesetPromise ? window.MathJax : null;
return mathJaxApi;
})();
}
return mathJaxLoadPromise;
}
function containsMathSyntax(text) {
return /(^|[^\\])\$\$|(^|[^\\])\$[^\s$]|\\\(|\\\[/.test(text);
}
function getMathDelimiters() {
return [
{ left: "$$", right: "$$", display: true },
{ left: "\\[", right: "\\]", display: true },
{ left: "$", right: "$", display: false },
{ left: "\\(", right: "\\)", display: false },
];
}
async function renderMathWithKatex(container) {
const katex = await ensureKatexLoaded();
katex.renderMathInElement?.(container, {
delimiters: getMathDelimiters(),
ignoredTags: ["script", "noscript", "style", "textarea", "pre", "code", "option"],
throwOnError: false,
strict: "ignore",
});
}
async function renderMathWithMathJax(container) {
const mathJax = await ensureMathJaxLoaded();
if (!mathJax?.typesetPromise) return;
mathJaxTypesetPromise = mathJaxTypesetPromise
.catch(() => {})
.then(() => mathJax.typesetPromise([container]));
await mathJaxTypesetPromise;
}
async function renderMath(container) {
if (currentMathRenderer === MATH_RENDERERS.mathjax) {
await renderMathWithMathJax(container);
return;
}
await renderMathWithKatex(container);
}
function initMermaid() {
if (mermaidApi) {
mermaidApi.initialize({ startOnLoad: false, theme: getMermaidTheme(), securityLevel: "strict" });
}
}
function setMathRenderer(renderer) {
const nextRenderer = normalizeMathRenderer(renderer);
currentMathRenderer = nextRenderer;
localStorage.setItem(mathRendererStorageKey, nextRenderer);
if (mathRendererSelect) {
mathRendererSelect.value = nextRenderer;
}
if (activePath) {
scrollPositions.set(activePath, viewerEl.scrollTop);
void renderPreview();
}
}
function openSettingsDialog() {
if (!settingsDialog) return;
if (settingsDialog.open) return;
if (typeof settingsDialog.showModal === "function") {
settingsDialog.showModal();
} else {
settingsDialog.setAttribute("open", "");
}
if (settingsToggle) {
settingsToggle.setAttribute("aria-pressed", "true");
}
}
function closeSettingsDialog() {
if (!settingsDialog) return;
if (typeof settingsDialog.close === "function") {
settingsDialog.close();
} else {
settingsDialog.removeAttribute("open");
}
}
function setStatus(text, loading = false) {
statusText.textContent = text;
statusText.classList.toggle("loading", loading);
}
function showToast(message) {
const existing = document.getElementById("toast");
if (existing) existing.remove();
const toast = document.createElement("div");
toast.id = "toast";
toast.className = "toast";
toast.setAttribute("role", "alert");
toast.setAttribute("aria-live", "assertive");
const msg = document.createElement("span");
msg.className = "toast-message";
msg.textContent = message;
const closeBtn = document.createElement("button");
closeBtn.className = "toast-close";
closeBtn.setAttribute("aria-label", t("aria.toastClose") || "關閉通知");
closeBtn.textContent = "×";
closeBtn.addEventListener("click", () => toast.remove());
toast.appendChild(msg);
toast.appendChild(closeBtn);
document.body.appendChild(toast);
setTimeout(() => toast.remove(), 5000);
}
function setPreviewVisible(isVisible) {
viewerContainer.hidden = !isVisible;
previewEl.style.display = isVisible ? "block" : "none";
emptyEl.style.display = isVisible ? "none" : "flex";
if (!isVisible) renderRecentHistory();
}
async function restoreFolder(record) {
try {
const permission = await record.handle.queryPermission({ mode: "read" });
if (permission !== "granted") {
const result = await record.handle.requestPermission({ mode: "read" });
if (result !== "granted") {
showToast(t("recent.permissionDenied"));
return false;
}
}
rootHandle = record.handle;
openFiles.clear();
openOrder.length = 0;
activePath = null;
await renderTree();
await saveHistory(record.folderName, record.handle);
return true;
} catch {
showToast(t("recent.folderNotFound"));
return false;
}
}
function buildRecentHistoryContent(history, { isSidebar = false } = {}) {
const fragment = document.createDocumentFragment();
const ul = document.createElement("ul");
ul.className = "recent-list";
for (const record of history) {
const li = document.createElement("li");
li.className = "recent-folder-item";
const folderBtn = document.createElement("button");
folderBtn.className = "recent-folder-btn";
folderBtn.type = "button";
folderBtn.textContent = `📁 ${record.folderName}`;
folderBtn.addEventListener("click", async () => {
if (isSidebar && rootHandle && rootHandle.name === record.folderName) return;
folderBtn.disabled = true;
const ok = await restoreFolder(record);
if (!ok) folderBtn.disabled = false;
});
li.appendChild(folderBtn);
if (record.recentFiles && record.recentFiles.length > 0) {
const filesUl = document.createElement("ul");
filesUl.className = "recent-files-list";
for (const f of record.recentFiles) {
const fileLi = document.createElement("li");
const fileBtn = document.createElement("button");
fileBtn.className = "recent-file-btn";
fileBtn.type = "button";
fileBtn.dataset.path = f.path;
const dirPart = f.path.includes("/") ? f.path.substring(0, f.path.lastIndexOf("/") + 1) : "";
const nameSpan = document.createElement("span");
nameSpan.className = "recent-file-name";
nameSpan.textContent = `📄 ${f.name}`;
fileBtn.appendChild(nameSpan);
if (dirPart) {
const dirSpan = document.createElement("span");
dirSpan.className = "recent-file-dir";
dirSpan.textContent = dirPart;
fileBtn.appendChild(dirSpan);
}
fileBtn.addEventListener("click", async () => {
fileBtn.disabled = true;
if (isSidebar && rootHandle && rootHandle.name === record.folderName) {
// 同資料夾,直接開檔
const fileHandle = await findFileHandle(f.path);
if (fileHandle) {
await openFile(fileHandle, f.path, null);
} else {
showToast(t("alert.fileNotFound", { path: f.path }));
fileBtn.disabled = false;
}
return;
}
const ok = await restoreFolder(record);
if (!ok) { fileBtn.disabled = false; return; }
const fileHandle = await findFileHandle(f.path);
if (fileHandle) {
await openFile(fileHandle, f.path, null);
} else {
showToast(t("alert.fileNotFound", { path: f.path }));
}
});
fileLi.appendChild(fileBtn);
filesUl.appendChild(fileLi);
}
li.appendChild(filesUl);
}
ul.appendChild(li);
}
fragment.appendChild(ul);
return fragment;
}
async function renderRecentHistory() {
const existing = emptyEl.querySelector(".recent-history");
if (existing) existing.remove();
const history = await loadHistory();
if (history.length === 0) {
emptyEl.classList.remove("has-history");
return;
}
emptyEl.classList.add("has-history");
const section = document.createElement("div");
section.className = "recent-history";
const title = document.createElement("h3");
title.className = "recent-title";
title.textContent = t("recent.title");
section.appendChild(title);
section.appendChild(buildRecentHistoryContent(history));
emptyEl.appendChild(section);
}
async function renderSidebarRecentPanel() {
if (!recentPanelEl || !recentPanelBodyEl) return;
const history = await loadHistory();
if (history.length === 0) {
recentPanelEl.hidden = true;
return;
}
recentPanelEl.hidden = false;
recentPanelBodyEl.innerHTML = "";
recentPanelBodyEl.appendChild(buildRecentHistoryContent(history, { isSidebar: true }));
}
function generateTOC() {
if (!tocEl || !tocListContainer) return;
const headings = Array.from(previewEl.querySelectorAll("h1, h2, h3, h4"));
cachedHeadings = headings;
tocListContainer.innerHTML = "";
if (headings.length === 0) {
tocEl.style.display = "none";
return;
}
tocEl.style.display = "flex";
const list = document.createElement("ul");
list.className = "toc-list";
headings.forEach((heading, index) => {
const id = heading.id || `heading-${index}`;
heading.id = id;
const level = parseInt(heading.tagName[1]);
const item = document.createElement("li");
item.className = "toc-item";
item.dataset.level = level;
const link = document.createElement("a");
link.className = "toc-link";
link.href = `#${id}`;
link.textContent = heading.textContent;
link.title = heading.textContent;
link.addEventListener("click", (e) => {
e.preventDefault();
heading.scrollIntoView({ behavior: "smooth" });
});
item.appendChild(link);
list.appendChild(item);
});
tocListContainer.appendChild(list);
updateTOCActive();
}
function setTOCCollapsed(collapsed) {
if (!tocEl) return;
tocEl.classList.toggle("collapsed", collapsed);
if (tocToggleBtn) {
tocToggleBtn.setAttribute("aria-pressed", collapsed ? "true" : "false");
tocToggleBtn.setAttribute("aria-label", collapsed ? t("aria.tocExpand") : t("aria.tocCollapse"));
tocToggleBtn.innerHTML = collapsed ? ICON_TOC_OPEN : ICON_TOC_CLOSE;
}
}
function updateTOCActive() {
if (!tocEl || tocEl.classList.contains("collapsed") || tocEl.style.display === "none") return;
if (tocRAFPending) return;
tocRAFPending = true;
requestAnimationFrame(() => {
tocRAFPending = false;
const scrollPos = viewerEl.scrollTop + 64;
let activeId = null;
for (const heading of cachedHeadings) {
if (heading.offsetTop <= scrollPos) activeId = heading.id;
else break;
}
tocEl.querySelectorAll(".toc-link").forEach((link) => {
const isActive = link.getAttribute("href") === `#${activeId}`;
link.classList.toggle("active", isActive);
if (isActive && tocContentEl) {
const linkRect = link.getBoundingClientRect();
const containerRect = tocContentEl.getBoundingClientRect();
if (linkRect.top < containerRect.top || linkRect.bottom > containerRect.bottom) {
tocContentEl.scrollTop += linkRect.top - containerRect.top - containerRect.height / 2 + linkRect.height / 2;
}
}
});
});
}
function makeId() { idSeed += 1; return `node-${idSeed}`; }
async function readDirectoryEntries(dirHandle) {
const entries = [];
for await (const [name, handle] of dirHandle.entries()) {
if (handle.kind === "file" && !name.toLowerCase().endsWith(".md")) continue;
entries.push({ name, handle, kind: handle.kind });
}
entries.sort((a, b) => {
if (a.kind !== b.kind) return a.kind === "directory" ? -1 : 1;
return a.name.localeCompare(b.name, "zh-Hant");
});
return entries;
}
async function collectMarkdownPaths(dirHandle, prefix = "") {
const records = [];
for await (const [name, handle] of dirHandle.entries()) {
const path = `${prefix}${name}`;
if (handle.kind === "directory") {
records.push(...(await collectMarkdownPaths(handle, `${path}/`)));
continue;
}
if (name.toLowerCase().endsWith(".md")) {
records.push({ path, handle });
}
}
return records;
}
function runSearch(query) {
searchQuery = query;
currentSearchResults = searchDocumentIndex([...documentIndex.values()], query);
renderSearchResults(currentSearchResults);
}
async function buildWorkspaceIndex() {
if (!rootHandle) {
return;
}
const token = ++indexBuildToken;
documentIndex.clear();
setStatus(t("status.indexing"), true);
try {
const files = await collectMarkdownPaths(rootHandle);
for (const entry of files) {
if (token !== indexBuildToken) {
return;
}
const file = await entry.handle.getFile();
const content = await file.text();
documentIndex.set(entry.path, buildDocumentRecord({ path: entry.path, content }));
await new Promise((resolve) => setTimeout(resolve, 0));
}
} catch (error) {
if (token === indexBuildToken) {
console.warn("[index] Failed to build workspace index:", error);
}
} finally {
if (token !== indexBuildToken) {
return;