-
-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathMarkdownViewer.svelte
More file actions
3499 lines (3131 loc) · 109 KB
/
Copy pathMarkdownViewer.svelte
File metadata and controls
3499 lines (3131 loc) · 109 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
<script lang="ts">
import { invoke, convertFileSrc } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { getCurrentWindow } from '@tauri-apps/api/window';
import { onMount, tick, untrack } from 'svelte';
import { fly } from 'svelte/transition';
import { cubicOut } from 'svelte/easing';
import { openUrl } from '@tauri-apps/plugin-opener';
import { open, save, ask } from '@tauri-apps/plugin-dialog';
import Installer from './Installer.svelte';
import Uninstaller from './Uninstaller.svelte';
import Settings from './components/Settings.svelte';
import TitleBar from './components/TitleBar.svelte';
import Editor from './components/Editor.svelte';
import Modal from './components/Modal.svelte';
import UpdateDialog from './components/UpdateDialog.svelte';
import { updateStore } from './stores/update.svelte.js';
import ContextMenu, { type ContextMenuItem } from './components/ContextMenu.svelte';
import Toc from './components/Toc.svelte';
import Toast from './components/Toast.svelte';
import FindBar from './components/FindBar.svelte';
import { exportAsHtml as _exportHtml, exportAsPdf } from './utils/export';
import ZoomOverlay from './components/ZoomOverlay.svelte';
import { processMarkdownHtml } from './utils/markdown';
const appWindow = getCurrentWindow();
import DOMPurify from 'dompurify';
import HomePage from './components/HomePage.svelte';
import { tabManager } from './stores/tabs.svelte.js';
import { settings } from './stores/settings.svelte.js';
import { t } from './utils/i18n.js';
// syntax highlighting & latex
let hljs: any = $state(null);
let katex: any = $state(null);
let renderMathInElement: any = $state(null);
let mermaid: any = $state(null);
import 'highlight.js/styles/github-dark.css';
import 'katex/dist/katex.min.css';
let mode = $state<'loading' | 'app' | 'installer' | 'uninstall'>('loading');
let showSettings = $state(false);
let uiLanguage = $state(settings.language);
$effect(() => {
uiLanguage = settings.language;
});
let recentFiles = $state<string[]>([]);
let isFocused = $state(true);
let containerEl: HTMLElement;
let markdownBody: HTMLElement | null = $state(null);
const renderDebounceMs = 50;
let renderTimeout: ReturnType<typeof setTimeout> | null = null;
const highlightColorMap: Record<string, string> = {
default: 'color-mix(in srgb, var(--color-accent-fg) 40%, transparent)',
yellow: 'rgba(255, 208, 0, 0.4)',
orange: 'rgba(255, 140, 0, 0.4)',
red: 'rgba(255, 60, 60, 0.4)',
pink: 'rgba(255, 105, 180, 0.4)',
purple: 'rgba(164, 108, 244, 0.4)',
blue: 'rgba(67, 138, 243, 0.4)',
cyan: 'rgba(43, 185, 178, 0.4)',
green: 'rgba(77, 177, 88, 0.4)',
};
let editorPane = $state<{
syncScrollToLine: (line: number, ratio?: number) => void;
handleDroppedFile: (path: string, x: number, y: number) => Promise<void>;
updateDragCaret: (x: number, y: number) => void;
hideDragCaret: () => void;
undo: () => void;
redo: () => void;
revealHeader: (text: string) => void;
triggerFind: () => void;
} | null>(null);
let liveMode = $state(false);
let findOpen = $state(false);
let findBar = $state<{ reapply: () => void; clearHighlights: () => void } | null>(null);
// Decide where Cmd/Ctrl+F should land based on what's visible and where
// focus is. Used by both the JS keydown handler (Win/Linux + macOS in-page
// shortcut) and the macOS native menu listener (which fires Cmd+F via the
// Edit menu accelerator and bypasses the JS keydown path).
function triggerFindAction() {
const active = document.activeElement as Node | null;
const editorHasFocus = !!editorPaneEl && !!active && editorPaneEl.contains(active);
const previewVisible = !isEditing || !!tabManager.activeTab?.isSplit;
if (editorHasFocus || !previewVisible) {
editorPane?.triggerFind?.();
} else if (markdownBody) {
findOpen = true;
}
}
let isDragging = $state(false);
let dragTarget = $state<'editor' | 'preview' | null>(null);
let editorPaneEl = $state<HTMLElement>();
let viewerPaneEl = $state<HTMLElement>();
let isProgrammaticScroll = false;
let toasts = $state<{ id: string; message: string; type: 'info' | 'error' | 'warning' }[]>([]);
function addToast(message: string, type: 'info' | 'error' | 'warning' = 'info') {
const id = crypto.randomUUID();
toasts.push({ id, message, type });
}
// --- Auto-save bookkeeping (see saveContent + auto-save $effect below) ---
// Per-tab debounce timers so switching tabs cannot kill another tab's pending save.
const autoSaveTimers = new Map<string, ReturnType<typeof setTimeout>>();
// Per-tab last-seen rawContent value, used by the auto-save effect to
// detect which tab actually changed in this run. JS string `===` is a
// value compare, so any edit yields a different value — including
// same-length ones (overwriting characters, formatting toggles) that
// a length-based tick would miss.
const lastContentRefByTab = new Map<string, string>();
// Suppress the file-watcher reload that fires when we ourselves write the file.
// Maps absolute path -> wall-clock ms after which an event for that path is real again.
const selfWriteUntilByPath = new Map<string, number>();
const SELF_WRITE_GRACE_MS = 400;
const AUTO_SAVE_DEBOUNCE_MS = 1500;
// Cancel a pending auto-save for a tab. Call this only on paths that
// COMMIT to a save or discard outcome — never before showing a modal,
// because if the user picks Cancel, the timer is gone forever and
// background auto-save is silently disabled for that tab until the
// next keystroke.
function cancelPendingAutoSave(tabId: string) {
const t = autoSaveTimers.get(tabId);
if (t) {
clearTimeout(t);
autoSaveTimers.delete(tabId);
}
}
// in-page scroll position history for mouse 4/5 nav
let scrollHistory: number[] = [];
let scrollFuture: number[] = [];
let collapsedHeaders = $state(new Set<string>());
let zoomData = $state<{ src?: string; html?: string } | null>(null);
// derived from tab manager
let activeTab = $derived(tabManager.activeTab);
let isEditing = $derived(activeTab?.isEditing ?? false);
let rawContent = $derived(activeTab?.rawContent ?? '');
let isSplit = $derived(activeTab?.isSplit ?? false);
// derived from tab manager
let currentFile = $derived(tabManager.activeTab?.path ?? '');
const markdownLinkExtensions = ['.md', '.markdown', '.mdown', '.mkd', '.txt'];
function hasMarkdownLinkExtension(path: string) {
const normalizedPath = path.toLowerCase();
return markdownLinkExtensions.some((ext) => normalizedPath.endsWith(ext));
}
let isMarkdown = $derived(hasMarkdownLinkExtension(currentFile));
let editorLanguage = $derived(getLanguage(currentFile));
let htmlContent = $derived(tabManager.activeTab?.content ?? '');
const markdownLinkExtensionPattern = markdownLinkExtensions
.map((ext) => ext.slice(1).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|');
const allowedMarkdownUriPattern = new RegExp(`^(?:(?:[a-z]:[^?#]*\\.(?:${markdownLinkExtensionPattern})(?:[?#].*)?$)|(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|asset|tauri):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))`, 'i');
let sanitizedHtml = $derived(DOMPurify.sanitize(htmlContent, {
ALLOWED_URI_REGEXP: allowedMarkdownUriPattern,
}));
let scrollTop = $derived(tabManager.activeTab?.scrollTop ?? 0);
let isScrolled = $derived(scrollTop > 0);
let windowTitle = $derived(tabManager.activeTab?.title ?? 'Markpad');
let isScrollSynced = $derived(tabManager.activeTab?.isScrollSynced ?? false);
let loadingTabs = $state<string[]>([]);
let isAtBottom = $state(false);
let showHome = $state(false);
let isFullWidth = $state(localStorage.getItem('isFullWidth') === 'true');
let viewerWidth = $state(0);
const TOC_WIDTH = 240;
let isOverhanging = $derived(isFullWidth || (viewerWidth > 0 && TOC_WIDTH > Math.max(50, (viewerWidth - 780) / 2)));
$effect(() => {
localStorage.setItem('isFullWidth', String(isFullWidth));
});
import { parseAndApplyVscodeTheme, clearVscodeTheme } from './utils/theme';
// Theme State
let theme = $state<string>('system');
onMount(() => {
const storedTheme = localStorage.getItem('theme');
if (storedTheme) theme = storedTheme;
// Clear the forced background color from app.html
document.documentElement.style.removeProperty('background-color');
});
$effect(() => {
localStorage.setItem('theme', theme);
invoke('save_theme', { theme }).catch(console.error);
if (theme === 'system' || theme === 'light' || theme === 'dark') {
if (theme === 'system') {
delete document.documentElement.dataset.theme;
delete document.documentElement.dataset.themeType;
} else {
document.documentElement.dataset.theme = theme;
document.documentElement.dataset.themeType = theme;
}
clearVscodeTheme();
const monaco = (window as any).monaco;
if (monaco && monaco.editor) {
const isSystemDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const effectiveTheme = theme === 'system' ? (isSystemDark ? 'dark' : 'light') : theme;
monaco.editor.setTheme(effectiveTheme === 'dark' ? 'vs-dark' : 'vs');
}
} else if (theme.startsWith('vscode:')) {
const name = theme.replace('vscode:', '');
invoke('read_vscode_theme', { name }).then((json: any) => {
parseAndApplyVscodeTheme(json, name);
}).catch(e => {
console.error("Failed to load vscode theme", e);
theme = 'system';
});
}
// Re-initialize mermaid or trigger update if needed
// Note: Mermaid 10+ usually doesn't support dynamic re-init easily but we can try re-rendering rich content
if (markdownBody && !isEditing) renderRichContent();
});
// ui state
let tooltip = $state({ show: false, text: '', shortcut: '', html: '', isFootnote: false, x: 0, y: 0, align: 'top' as 'top' | 'right' | 'left' | 'below' });
let caretEl: HTMLElement;
let caretAbsoluteTop = 0;
let modalState = $state<{
show: boolean;
title: string;
message: string;
kind: 'info' | 'warning' | 'error';
showSave: boolean;
resolve: ((v: 'save' | 'discard' | 'cancel') => void) | null;
}>({
show: false,
title: '',
message: '',
kind: 'info',
showSave: false,
resolve: null,
});
let docContextMenu = $state<{
show: boolean;
x: number;
y: number;
items: ContextMenuItem[];
}>({
show: false,
x: 0,
y: 0,
items: [],
});
function askCustom(message: string, options: { title: string; kind: 'info' | 'warning' | 'error'; showSave?: boolean }): Promise<'save' | 'discard' | 'cancel'> {
return new Promise((resolve) => {
modalState = {
show: true,
title: options.title,
message,
kind: options.kind,
showSave: options.showSave ?? false,
resolve,
};
});
}
function handleModalSave() {
if (modalState.resolve) modalState.resolve('save');
modalState.show = false;
}
function handleModalConfirm() {
if (modalState.resolve) modalState.resolve('discard');
modalState.show = false;
}
function handleModalCancel() {
if (modalState.resolve) modalState.resolve('cancel');
modalState.show = false;
}
function handleSplitterKeyDown(e: KeyboardEvent) {
const activeTab = tabManager.activeTab;
if (!activeTab || !tabManager.activeTabId) return;
if (e.key === 'ArrowLeft') {
tabManager.setSplitRatio(tabManager.activeTabId, Math.max(0.1, activeTab.splitRatio - 0.05));
} else if (e.key === 'ArrowRight') {
tabManager.setSplitRatio(tabManager.activeTabId, Math.min(0.9, activeTab.splitRatio + 0.05));
}
}
let isForceExiting = $state(false);
async function appExit() {
if (settings.restoreStateOnReopen) {
const hasUnsaved = tabManager.tabs.some((t) => t.isDirty || (t.path === '' && t.rawContent.trim() !== ''));
if (hasUnsaved) {
const response = await askCustom(t('modal.areYouSureYouWantToExit', settings.language), {
title: t('modal.confirmExit', settings.language),
kind: 'warning',
showSave: false,
});
if (response !== 'discard') return;
}
localStorage.removeItem('savedTabsData');
isForceExiting = true;
}
appWindow.close();
}
function getLanguage(path: string) {
if (!path) return 'markdown';
const ext = path.split('.').pop()?.toLowerCase();
switch (ext) {
case 'js':
case 'jsx':
return 'javascript';
case 'ts':
case 'tsx':
return 'typescript';
case 'html':
return 'html';
case 'css':
return 'css';
case 'json':
return 'json';
case 'md':
case 'markdown':
case 'mdown':
case 'mkd':
return 'markdown';
default:
return 'plaintext';
}
}
$effect(() => {
const _ = tabManager.activeTabId;
showHome = false;
findOpen = false;
});
function processHighlights(root: Element) {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
acceptNode(node) {
let curr = node.parentElement;
while (curr && curr !== root) {
if (['CODE', 'PRE', 'SCRIPT', 'STYLE'].includes(curr.tagName)) return NodeFilter.FILTER_REJECT;
curr = curr.parentElement;
}
return NodeFilter.FILTER_ACCEPT;
},
});
const toReplace: { node: Text; replaced: string }[] = [];
let node: Node | null;
while ((node = walker.nextNode())) {
const text = (node as Text).nodeValue || '';
if (text.includes('==')) {
const replaced = text.replace(/==([^=\n]+)==/g, '<mark>$1</mark>');
if (replaced !== text) toReplace.push({ node: node as Text, replaced });
}
}
for (const { node, replaced } of toReplace) {
const span = root.ownerDocument!.createElement('span');
span.innerHTML = replaced;
node.parentNode?.replaceChild(span, node);
}
}
function processBlockIds(root: Element, doc: Document) {
// handle pre-emitted block-id spans from rust parser
for (const el of Array.from(root.querySelectorAll('.block-id, [data-block-id]'))) {
const rawId = el.getAttribute('data-block-id') || (el as HTMLElement).textContent?.replace(/^\^/, '').trim() || '';
if (!rawId) continue;
const anchor = doc.createElement('a');
anchor.id = rawId;
anchor.className = 'block-id-anchor';
anchor.setAttribute('data-label', rawId);
anchor.setAttribute('aria-hidden', 'true');
el.replaceWith(anchor);
}
// scan text nodes for trailing ^id pattern (text ^blockid at end of block)
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
acceptNode(node) {
const parent = node.parentElement;
if (!parent) return NodeFilter.FILTER_REJECT;
if (['CODE', 'PRE', 'SCRIPT', 'STYLE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'].includes(parent.tagName)) return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_ACCEPT;
},
});
const blockIdPattern = / \^([a-zA-Z0-9_-]+)\s*$/;
const nodes: { node: Text; id: string }[] = [];
let textNode: Node | null;
while ((textNode = walker.nextNode())) {
const text = (textNode as Text).nodeValue || '';
const match = text.match(blockIdPattern);
if (match) nodes.push({ node: textNode as Text, id: match[1] });
}
for (const { node, id } of nodes) {
const text = node.nodeValue || '';
const cleanText = text.replace(blockIdPattern, '');
const anchor = doc.createElement('a');
anchor.id = id;
anchor.className = 'block-id-anchor';
anchor.setAttribute('data-label', id);
anchor.setAttribute('aria-hidden', 'true');
const parent = node.parentNode;
if (parent) {
const textBefore = doc.createTextNode(cleanText);
parent.replaceChild(anchor, node);
parent.insertBefore(textBefore, anchor);
}
}
}
function processTaskItems(root: Element) {
for (const input of Array.from(root.querySelectorAll('li input[type="checkbox"]'))) {
input.setAttribute('data-task-checkbox', '');
input.removeAttribute('disabled');
(input as HTMLInputElement).style.cursor = 'pointer';
const li = input.closest('li');
if (!li) continue;
// wrap bare text/inline nodes after checkbox in a span for CSS targeting
const nodes = Array.from(li.childNodes);
const inputIdx = nodes.indexOf(input);
const afterInput = nodes.slice(inputIdx + 1);
// we loop until we hit a block child (like a nested UL)
const inlineNodes = [];
for (const n of afterInput) {
if (n.nodeType === 1 && ['P', 'DIV', 'UL', 'OL'].includes((n as Element).tagName)) break;
inlineNodes.push(n);
}
if (inlineNodes.length > 0) {
const wrapper = root.ownerDocument!.createElement('span');
wrapper.className = 'task-text';
for (const n of inlineNodes) wrapper.appendChild(n);
// insert the newly wrapped span after the checkbox
li.insertBefore(wrapper, afterInput[inlineNodes.length] || null);
}
if ((input as HTMLInputElement).checked) {
li.classList.add('task-done');
}
}
}
type LoadMarkdownOptions = {
navigate?: boolean;
skipTabManagement?: boolean;
preserveEditState?: boolean;
resetScrollHistory?: boolean;
};
async function loadMarkdown(filePath: string, options: LoadMarkdownOptions = {}) {
showHome = false;
let existing = null;
try {
if (options.resetScrollHistory || filePath !== currentFile) {
scrollHistory = [];
scrollFuture = [];
}
if (options.navigate && tabManager.activeTab) {
tabManager.navigate(tabManager.activeTab.id, filePath);
} else if (!options.skipTabManagement) {
existing = tabManager.tabs.find((t) => t.path === filePath);
if (existing) {
tabManager.setActive(existing.id);
} else if (tabManager.activeTab && tabManager.activeTab.path === '' && !tabManager.activeTab.isDirty && tabManager.activeTab.rawContent.trim() === '') {
tabManager.updateTabPath(tabManager.activeTab.id, filePath);
} else {
tabManager.addTab(filePath);
}
}
const activeId = tabManager.activeTabId;
if (!activeId) return;
const isMarkdown = hasMarkdownLinkExtension(filePath);
const tab = tabManager.tabs.find((t) => t.id === activeId);
if (isMarkdown) {
// Only set default edit mode if it's a brand new tab or we aren't preserving state
if (tab && !options.preserveEditState && !existing) {
tab.isEditing = settings.startInEditor;
}
const [html, content, isFull] = await invoke('open_markdown_preview', { path: filePath, maxBytes: 50000 }) as [string, string, boolean];
const processedInfo = processMarkdownHtml(html, filePath, collapsedHeaders);
tabManager.updateTabContent(activeId, processedInfo);
tabManager.setTabRawContent(activeId, content);
if (!isFull) {
loadingTabs = [...loadingTabs, activeId];
tick().then(() => {
if (markdownBody) isAtBottom = markdownBody.scrollHeight <= markdownBody.clientHeight + 100;
});
Promise.all([
invoke('open_markdown', { path: filePath }) as Promise<string>,
invoke('read_file_content', { path: filePath }) as Promise<string>
]).then(([fullHtml, fullContent]) => {
const applyFull = () => {
try {
if (isScrolling) {
setTimeout(applyFull, 100);
return;
}
if (tabManager.tabs.find((t) => t.id === activeId)?.path === filePath) {
const fullProcessed = processMarkdownHtml(fullHtml, filePath, collapsedHeaders);
tabManager.updateTabContent(activeId, fullProcessed);
tabManager.setTabRawContent(activeId, fullContent);
loadingTabs = loadingTabs.filter((id) => id !== activeId);
if (tabManager.activeTabId === activeId) {
tick().then(() => {
setTimeout(renderRichContent, 10);
});
}
} else {
loadingTabs = loadingTabs.filter((id) => id !== activeId);
}
} catch (applyErr) {
console.error("applyFull error:", applyErr);
addToast('Error processing full markdown: ' + String(applyErr), 'error');
loadingTabs = loadingTabs.filter((id) => id !== activeId);
}
};
if ('requestIdleCallback' in window) {
(window as any).requestIdleCallback(applyFull, { timeout: 2000 });
} else {
setTimeout(applyFull, 100);
}
}).catch((e) => {
console.error("Promise.all error:", e);
addToast('Backend Error loading full markdown: ' + String(e), 'error');
loadingTabs = loadingTabs.filter((id) => id !== activeId);
});
}
} else {
if (tab) tab.isEditing = true;
const content = (await invoke('read_file_content', { path: filePath })) as string;
tabManager.setTabRawContent(activeId, content);
}
if (liveMode) invoke('watch_file', { path: filePath }).catch(console.error);
await tick();
if (filePath) saveRecentFile(filePath);
} catch (error) {
console.error('Error loading file:', error);
const errStr = String(error);
if (errStr.includes('The system cannot find the file specified') || errStr.includes('No such file or directory')) {
deleteRecentFile(filePath);
if (tabManager.activeTab && tabManager.activeTab.path === filePath) {
tabManager.closeTab(tabManager.activeTab.id);
}
}
}
}
async function renderRichContent() {
if (!markdownBody) return;
if (!hljs || !renderMathInElement || !mermaid) return;
// Initialize Mermaid with theme based on system preference or override
const isSystemDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const datasetThemeType = document.documentElement.dataset.themeType;
const isDark = datasetThemeType === 'dark' || (theme === 'dark') || (theme === 'system' && isSystemDark);
const effectiveTheme = isDark ? 'dark' : 'neutral';
mermaid.initialize({ startOnLoad: false, theme: effectiveTheme });
// Process code blocks
const codeBlocks = Array.from(markdownBody.querySelectorAll('pre code'));
for (const block of codeBlocks) {
const codeEl = block as HTMLElement;
const preEl = codeEl.parentElement as HTMLPreElement;
// Check for Mermaid blocks
if (codeEl.classList.contains('language-mermaid')) {
try {
const mermaidCode = codeEl.textContent || '';
const id = `mermaid-${Date.now()}-${Math.floor(Math.random() * 10000)}`;
// Render the diagram
const { svg } = await mermaid.render(id, mermaidCode);
// Create container and replace the <pre> block
const container = document.createElement('div');
container.className = 'mermaid-diagram';
// Allow foreignObject for Mermaid text rendering
container.innerHTML = DOMPurify.sanitize(svg, {
ADD_TAGS: ['foreignObject'],
ADD_ATTR: ['dominant-baseline', 'text-anchor'],
});
preEl.replaceWith(container);
} catch (error) {
console.error('Failed to render Mermaid diagram:', error);
// Display error in place of diagram
const errorDiv = document.createElement('div');
errorDiv.className = 'mermaid-error';
errorDiv.style.color = 'red';
errorDiv.style.padding = '1em';
errorDiv.textContent = `Error rendering Mermaid diagram: ${error}`;
preEl.replaceWith(errorDiv);
}
continue; // Skip highlight.js for this block
}
// Existing highlight.js logic
// Check if language was explicitly specified BEFORE highlight.js runs
const hasExplicitLang = Array.from(codeEl.classList).some((c) => c.startsWith('language-'));
// Only highlight if explicit language is specified
if (hasExplicitLang) {
hljs.highlightElement(codeEl);
}
const langClass = Array.from(codeEl.classList).find((c) => c.startsWith('language-'));
if (preEl && preEl.tagName === 'PRE') {
preEl.querySelectorAll('.lang-label').forEach((l) => l.remove());
const codeContent = codeEl.textContent || '';
const existingWrapper = preEl.parentElement?.classList.contains('code-block-shell') ? preEl.parentElement as HTMLDivElement : null;
existingWrapper?.querySelectorAll(':scope > .lang-label').forEach((l) => l.remove());
const wrapper = existingWrapper ?? document.createElement('div');
if (!existingWrapper) {
wrapper.className = 'code-block-shell';
preEl.replaceWith(wrapper);
wrapper.appendChild(preEl);
}
const copyCode = () => {
const codeToCopy = codeContent.replace(/\n$/, '');
invoke('clipboard_write_text', { text: codeToCopy }).then(() => {
const originalContent = label.innerHTML;
label.innerHTML = 'Copied!';
label.classList.add('copied');
setTimeout(() => {
label.innerHTML = originalContent;
label.classList.remove('copied');
}, 1500);
}).catch((err) => {
console.error('Failed to copy code:', err);
});
};
const label = document.createElement('button');
label.className = 'lang-label';
label.title = 'Click to copy code';
label.onclick = copyCode;
if (hasExplicitLang && langClass) {
label.textContent = langClass.replace('language-', '');
wrapper.appendChild(label);
} else {
label.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>`;
wrapper.appendChild(label);
}
}
}
// KaTeX math rendering
if (katex) {
const mathElements = markdownBody.querySelectorAll('[data-math]');
for (const el of Array.from(mathElements)) {
const isDisplay = el.getAttribute('data-math') === 'display';
const mathSource = el.getAttribute('data-math-source') || el.textContent || '';
try {
katex.render(mathSource, el as HTMLElement, {
displayMode: isDisplay,
throwOnError: false,
});
} catch (e) {
console.error('KaTeX rendering error:', e);
}
}
}
if (renderMathInElement) {
renderMathInElement(markdownBody, {
delimiters: [
{ left: '$$', right: '$$', display: true },
{ left: '\\(', right: '\\)', display: false },
{ left: '\\[', right: '\\]', display: true },
],
throwOnError: false,
});
}
}
$effect(() => {
if (sanitizedHtml && markdownBody && !isEditing && hljs && renderMathInElement && mermaid) renderRichContent();
});
// Re-apply find highlights after the preview HTML is replaced. The
// `bind:innerHTML={sanitizedHtml}` on the article wipes the DOM on every
// edit/render pass; without this, highlights vanish until the user
// re-types in the find bar.
$effect(() => {
const _ = sanitizedHtml;
if (!findOpen || !findBar) return;
tick().then(() => findBar?.reapply());
});
$effect(() => {
// Depend on the ID and body existence to trigger restore
const id = tabManager.activeTabId;
const body = markdownBody;
if (id && body) {
untrack(() => {
const tab = tabManager.tabs.find((t) => t.id === id);
if (tab) {
let scrolled = false;
if (tab.anchorLine > 0) {
// Interpolated Restore
// Find element containing the anchor line
const children = Array.from(body.children) as HTMLElement[];
for (const el of children) {
const sourcepos = el.dataset.sourcepos;
if (sourcepos) {
const [start, end] = sourcepos.split('-');
const startLine = parseInt(start.split(':')[0]);
const endLine = parseInt(end.split(':')[0]);
if (!isNaN(startLine) && !isNaN(endLine)) {
if (tab.anchorLine >= startLine && tab.anchorLine <= endLine) {
// Found the container
const totalLines = endLine - startLine; // Can be 0 for single line
let ratio = 0;
if (totalLines > 0) {
ratio = (tab.anchorLine - startLine) / totalLines;
}
// Calculate target pixel position
// We want the anchor line to be roughly at offset 60
const targetOffset = el.offsetTop + el.offsetHeight * ratio - 60;
body.scrollTop = Math.max(0, targetOffset);
scrolled = true;
break;
}
}
}
}
}
if (!scrolled) {
if (body.scrollHeight > body.clientHeight && tab.scrollPercentage > 0) {
const targetScroll = tab.scrollPercentage * (body.scrollHeight - body.clientHeight);
body.scrollTop = targetScroll;
} else {
body.scrollTop = tab.scrollTop;
}
}
}
});
}
});
$effect(() => {
if (markdownBody && !isEditing && tabManager.activeTabId) {
tick().then(() => {
markdownBody?.focus({ preventScroll: true });
});
}
});
function scrollToLine(line: number, ratio: number = 0) {
if (!markdownBody) return;
const children = Array.from(markdownBody.children) as HTMLElement[];
for (const el of children) {
const sourcepos = el.dataset.sourcepos;
if (sourcepos) {
const [start, end] = sourcepos.split('-');
const startLine = parseInt(start.split(':')[0]);
const endLine = parseInt(end.split(':')[0]);
if (!isNaN(startLine) && !isNaN(endLine)) {
if (line >= startLine && line <= endLine) {
const totalLines = endLine - startLine;
let lineRatio = 0;
if (totalLines > 0) {
lineRatio = (line - startLine) / totalLines;
}
lineRatio = Math.max(0, Math.min(1, lineRatio));
const elementTop = el.offsetTop + el.offsetHeight * lineRatio;
const viewportHeight = markdownBody.clientHeight;
const targetScroll = elementTop - viewportHeight * ratio;
if (Math.abs(markdownBody.scrollTop - targetScroll) > 5) {
isProgrammaticScroll = true;
markdownBody.scrollTop = Math.max(0, targetScroll);
}
return;
}
}
}
}
}
function handleEditorScrollSync(line: number, ratio: number = 0) {
if (tabManager.activeTab?.isScrollSynced) {
scrollToLine(line, ratio);
}
}
function syncEditorToPreviewScroll(target: HTMLElement) {
if (!tabManager.activeTab?.isScrollSynced || !editorPane) return;
const anchorOffset = target.scrollTop + 60;
const viewportRatio = target.clientHeight > 0 ? Math.min(1, 60 / target.clientHeight) : 0;
const children = Array.from(markdownBody?.children || []);
for (const child of children) {
const el = child as HTMLElement;
if (el.offsetTop <= anchorOffset && el.offsetTop + el.offsetHeight > anchorOffset) {
const sourcepos = el.dataset.sourcepos;
if (!sourcepos) break;
const [start, end] = sourcepos.split('-');
const startLine = parseInt(start.split(':')[0]);
const endLine = parseInt(end.split(':')[0]);
if (!isNaN(startLine) && !isNaN(endLine)) {
const relativeOffset = anchorOffset - el.offsetTop;
const elementRatio = el.offsetHeight > 0 ? relativeOffset / el.offsetHeight : 0;
const totalLines = endLine - startLine;
const estimatedLine = startLine + Math.round(totalLines * elementRatio);
editorPane.syncScrollToLine(estimatedLine, viewportRatio);
}
break;
}
}
}
let isScrolling = $state(false);
let scrollIdleTimer: ReturnType<typeof setTimeout>;
function handleScroll(e: Event) {
const target = e.target as HTMLElement;
isAtBottom = Math.abs(target.scrollHeight - target.scrollTop - target.clientHeight) < 100;
isScrolling = true;
clearTimeout(scrollIdleTimer);
scrollIdleTimer = setTimeout(() => {
isScrolling = false;
}, 300);
if (isProgrammaticScroll) {
isProgrammaticScroll = false;
if (tabManager.activeTabId) {
tabManager.updateTabScroll(tabManager.activeTabId, target.scrollTop);
}
return;
}
if (tabManager.activeTabId) {
// Update raw scroll pos
tabManager.updateTabScroll(tabManager.activeTabId, target.scrollTop);
// Percentage fallback
if (target.scrollHeight > target.clientHeight) {
const percentage = target.scrollTop / (target.scrollHeight - target.clientHeight);
tabManager.updateTabScrollPercentage(tabManager.activeTabId, percentage);
}
// Interpolated Anchor Calculation
const anchorOffset = target.scrollTop + 60;
const children = Array.from(markdownBody?.children || []);
for (const child of children) {
const el = child as HTMLElement;
// Check intersection
if (el.offsetTop <= anchorOffset && el.offsetTop + el.offsetHeight > anchorOffset) {
const sourcepos = el.dataset.sourcepos;
if (sourcepos) {
const [start, end] = sourcepos.split('-');
const startLine = parseInt(start.split(':')[0]);
const endLine = parseInt(end.split(':')[0]);
if (!isNaN(startLine) && !isNaN(endLine)) {
// Calculate relative position within element
const relativeOffset = anchorOffset - el.offsetTop;
const ratio = relativeOffset / el.offsetHeight;
const totalLines = endLine - startLine;
const estimatedLine = startLine + Math.round(totalLines * ratio);
tabManager.updateTabAnchorLine(tabManager.activeTabId, estimatedLine);
}
}
break;
}
}
}
syncEditorToPreviewScroll(target);
}
function toggleFold(key: string) {
const isCurrentlyCollapsed = collapsedHeaders.has(key);
if (isCurrentlyCollapsed) {
const next = new Set(collapsedHeaders);
next.delete(key);
collapsedHeaders = next;
} else {
collapsedHeaders = new Set([...collapsedHeaders, key]);
}
if (!markdownBody) return;
let h = markdownBody.querySelector(`[id="${CSS.escape(key)}"].foldable-header`) as HTMLElement | null;
if (!h) {
const allHeaders = markdownBody.querySelectorAll('.foldable-header');
for (const el of Array.from(allHeaders)) {
if ((el.textContent?.trim() || '') === key) {
h = el as HTMLElement;
break;
}
}
}
if (!h) return;
const wrapId = h.getAttribute('data-fold-target');
const wrapper = wrapId ? document.getElementById(wrapId) : null;
if (!wrapper) return;
h.classList.toggle('is-collapsed', !isCurrentlyCollapsed);
wrapper.classList.toggle('is-collapsed', !isCurrentlyCollapsed);
}
type RelativeMarkdownTarget = {
path: string;
hash: string;
};
function decodeLinkPath(path: string) {
try {
return decodeURIComponent(path);
} catch {
return path;
}
}
function normalizeComparableMarkdownPath(path: string) {
const normalized = path.replace(/\\/g, '/');
const comparable = normalized.startsWith('//')
? `//${normalized.slice(2).replace(/\/+/g, '/')}`
: normalized.replace(/\/+/g, '/');
if (settings.osType === 'windows' || /^[a-z]:/i.test(comparable) || comparable.startsWith('//')) {
return comparable.toLowerCase();
}
return comparable;
}
function isAbsoluteMarkdownPath(path: string) {
return path.startsWith('/') || path.startsWith('\\') || /^[a-z]:/i.test(path);
}
function getRelativeMarkdownTarget(href: string): RelativeMarkdownTarget | null {
const pathWithoutHash = href.split('#')[0].split('?')[0];
const isMarkdownTarget = hasMarkdownLinkExtension(pathWithoutHash);
const isWindowsDrivePath = /^[a-z]:/i.test(href);
const isProtocolRelativeExternal = href.startsWith('//');
const hasScheme = /^[a-z][a-z0-9+.-]*:/i.test(href);
if (!isMarkdownTarget || isProtocolRelativeExternal || (hasScheme && !isWindowsDrivePath)) return null;
const hashIndex = href.indexOf('#');
return {
path: decodeLinkPath(pathWithoutHash),
hash: hashIndex === -1 ? '' : href.slice(hashIndex + 1)