-
-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathbridge.js
More file actions
1353 lines (1222 loc) · 47.8 KB
/
bridge.js
File metadata and controls
1353 lines (1222 loc) · 47.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* PostMessage bridge between Phoenix parent window and mdviewr iframe.
* Handles bidirectional communication for content sync, theme, locale, and edit mode.
* Integrates with doc-cache for instant file switching.
*/
import { on, emit } from "./core/events.js";
import { getState, setState } from "./core/state.js";
import { setLocale } from "./core/i18n.js";
import { marked } from "marked";
import * as docCache from "./core/doc-cache.js";
import { broadcastSelectionStateSync } from "./components/editor.js";
let _syncId = 0;
let _lastReceivedSyncId = -1;
let _suppressContentChange = false;
let _scrollFromCM = false;
let _scrollFromViewer = false;
let _suppressScrollToLine = false;
let _baseURL = "";
let _cursorPosBeforeEdit = null; // cursor position before current edit batch
let _cursorPosDirty = false; // true after content changes, reset when emitted
let _pendingReloadScroll = null; // { filePath, scrollSourceLine } for scroll restore after reload
/**
* Check if a URL is absolute (not relative to the document).
*/
function _isAbsoluteURL(href) {
return /^(?:https?:\/\/|data:|\/\/|#|mailto:|tel:)/.test(href);
}
/**
* Resolve a relative URL against the current base URL.
*/
function _resolveURL(href) {
if (!href || !_baseURL || _isAbsoluteURL(href)) {
return href;
}
try {
return new URL(href, _baseURL).href;
} catch {
return href;
}
}
/**
* Annotate top-level tokens with their source line numbers.
* This allows mapping rendered HTML elements back to markdown source lines.
*/
function _annotateTokenLines(tokens) {
let line = 1;
for (const token of tokens) {
if (token.type !== "space") {
token._sourceLine = line;
}
// Recursively annotate children with their source lines
_annotateTokenChildren(token, line);
if (token.raw) {
line += (token.raw.match(/\n/g) || []).length;
}
}
}
function _annotateTokenChildren(token, startLine) {
// List items
if (token.type === "list" && token.items) {
let itemLine = startLine;
for (const item of token.items) {
item._sourceLine = itemLine;
if (item.tokens) {
_annotateNestedTokens(item.tokens, itemLine);
}
if (item.raw) {
itemLine += (item.raw.match(/\n/g) || []).length;
}
}
}
// Blockquote children
if (token.type === "blockquote" && token.tokens) {
_annotateNestedTokens(token.tokens, startLine);
}
// Table rows
if (token.type === "table") {
if (token.header) {
for (const cell of token.header) {
cell._sourceLine = startLine;
}
}
if (token.rows) {
let rowLine = startLine + 2;
for (const row of token.rows) {
for (const cell of row) {
cell._sourceLine = rowLine;
}
rowLine++;
}
}
}
}
function _annotateNestedTokens(tokens, startLine) {
let line = startLine;
for (const token of tokens) {
if (token.type !== "space") {
token._sourceLine = line;
}
// Recurse into nested lists
if (token.type === "list" && token.items) {
let itemLine = line;
for (const item of token.items) {
item._sourceLine = itemLine;
if (item.tokens) {
_annotateNestedTokens(item.tokens, itemLine);
}
if (item.raw) {
itemLine += (item.raw.match(/\n/g) || []).length;
}
}
}
// Recurse into blockquote children
if (token.type === "blockquote" && token.tokens) {
_annotateNestedTokens(token.tokens, line);
}
// Annotate table rows
if (token.type === "table") {
// Header row
if (token.header) {
for (const cell of token.header) {
cell._sourceLine = line;
}
}
// Body rows: each row is one line after header + separator (2 lines)
if (token.rows) {
let rowLine = line + 2; // skip header + separator lines
for (const row of token.rows) {
for (const cell of row) {
cell._sourceLine = rowLine;
}
rowLine++;
}
}
}
if (token.raw) {
line += (token.raw.match(/\n/g) || []).length;
}
}
}
// Custom renderer that injects data-source-line attributes into block-level elements.
const _proto = marked.Renderer.prototype;
function _withSourceLine(protoFn, tagRegex) {
return function (token) {
const html = protoFn.call(this, token);
if (token._sourceLine != null) {
return html.replace(tagRegex, `$& data-source-line="${token._sourceLine}"`);
}
return html;
};
}
marked.use({
renderer: {
heading: _withSourceLine(_proto.heading, /^<h[1-6]/),
paragraph: _withSourceLine(_proto.paragraph, /^<p/),
list: _withSourceLine(_proto.list, /^<[ou]l/),
listitem: _withSourceLine(_proto.listitem, /^<li/),
table: _withSourceLine(_proto.table, /^<table/),
tablecell: _withSourceLine(_proto.tablecell, /^<t[dh]/),
blockquote: _withSourceLine(_proto.blockquote, /^<blockquote/),
code: _withSourceLine(_proto.code, /^<pre/),
hr: _withSourceLine(_proto.hr, /^<hr/)
}
});
/**
* Parse markdown to HTML with mermaid detection and source line annotations.
*/
export function parseMarkdownToHTML(markdown) {
const has_mermaid = /```mermaid/i.test(markdown);
const tokens = marked.lexer(markdown);
_annotateTokenLines(tokens);
marked.walkTokens(tokens, (token) => {
if (token.type === "image" && token.href) {
token.href = _resolveURL(token.href);
} else if (token.type === "link" && token.href) {
token.href = _resolveURL(token.href);
}
});
const html = marked.parser(tokens);
return { html, has_mermaid };
}
const _isMac = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
/**
* Initialize the postMessage bridge.
*/
export function initBridge() {
docCache.initDocCache();
// Expose helpers for test access (test iframes have no sandbox)
window.__getActiveFilePath = docCache.getActiveFilePath;
window.__getCurrentContent = function () {
return getState().currentContent;
};
window.__setEditModeForTest = function (editMode) {
setState({ editMode });
};
window.__isSuppressingContentChange = function () {
return _suppressContentChange;
};
window.__getCacheKeys = function () {
return docCache._getCacheKeysForTest();
};
window.__getWorkingSetPaths = function () {
return docCache._getWorkingSetPathsForTest();
};
window.__resetCacheForTest = function () {
docCache.clearAll();
};
window.__toggleSearchForTest = function () {
emit("action:toggle-search");
};
window.__broadcastSelectionStateForTest = function () {
broadcastSelectionStateSync();
};
window.__triggerContentSync = function () {
const content = document.getElementById("viewer-content");
if (content) {
content.dispatchEvent(new Event("input", { bubbles: true }));
}
};
window.__clickCheckboxForTest = function (index) {
const content = document.getElementById("viewer-content");
if (!content) { return false; }
const checkboxes = content.querySelectorAll('input[type="checkbox"]');
if (index >= checkboxes.length) { return false; }
checkboxes[index].click();
return checkboxes[index].checked;
};
// Listen for messages from Phoenix parent
window.addEventListener("message", (event) => {
const data = event.data;
if (!data || !data.type) return;
switch (data.type) {
case "MDVIEWR_SET_CONTENT":
handleSetContent(data);
break;
case "MDVIEWR_UPDATE_CONTENT":
handleUpdateContent(data);
break;
case "MDVIEWR_SWITCH_FILE":
handleSwitchFile(data);
break;
case "MDVIEWR_CLEAR_CACHE":
handleClearCache();
break;
case "MDVIEWR_WORKING_SET_CHANGED":
handleWorkingSetChanged(data);
break;
case "MDVIEWR_CLOSE_FILE":
handleCloseFile(data);
break;
case "MDVIEWR_RELOAD_FILE":
handleReloadFile(data);
break;
case "MDVIEWR_SET_THEME":
handleSetTheme(data);
break;
case "MDVIEWR_SET_EDIT_MODE":
handleSetEditMode(data);
break;
case "MDVIEWR_SET_LOCALE":
handleSetLocale(data);
break;
case "MDVIEWR_SCROLL_TO_LINE":
handleScrollToLine(data);
break;
case "MDVIEWR_HIGHLIGHT_SELECTION":
handleHighlightSelection(data);
break;
case "MDVIEWR_RERENDER_CONTENT":
handleRerenderContent(data);
break;
case "MDVIEWR_SOURCE_LINES":
emit("editor:source-lines", data.markdown);
break;
case "MDVIEWR_TOOLBAR_STATE":
if (data.state) {
emit("editor:selection-state", data.state);
}
break;
case "MDVIEWR_IMAGE_UPLOAD_RESULT":
_handleImageUploadResult(data);
break;
case "_TEST_FOCUS_CLICK":
document.body.click();
break;
case "_TEST_SELECT_TEXT_AND_CLICK": {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(document.body);
selection.removeAllRanges();
selection.addRange(range);
document.body.click();
break;
}
case "_TEST_UNSELECT_TEXT_AND_CLICK":
window.getSelection().removeAllRanges();
document.body.click();
break;
}
});
// Intercept keyboard shortcuts in capture phase before the mdviewr editor handles them.
// Undo/redo is routed through CM5's undo stack so both editors stay in sync.
// Unhandled modifier shortcuts are forwarded to Phoenix's keybinding manager.
const _mdEditorHandledKeys = new Set(["b", "i", "k", "u", "z", "y", "a", "c", "v", "x"]); // Ctrl/Cmd + key
const _mdEditorHandledShiftKeys = new Set(["x", "X", "z", "Z"]); // Ctrl/Cmd + Shift + key
document.addEventListener("keydown", (e) => {
// Don't intercept shortcuts when focus is in any input/textarea (except Escape)
// This covers dialog inputs, search bar input, link popover input, etc.
const activeEl = document.activeElement;
if (e.key !== "Escape" && activeEl &&
(activeEl.tagName === "INPUT" || activeEl.tagName === "TEXTAREA") &&
!activeEl.closest("#viewer-content")) {
return;
}
if (e.key === "Escape") {
// Don't forward Escape to Phoenix if any popup/overlay is open
const popupSelectors = [
"#search-bar.open",
"#slash-menu-anchor.visible",
"#lang-picker.visible",
"#link-popover.visible"
];
const hasOpenPopup = popupSelectors.some(sel => document.querySelector(sel));
if (hasOpenPopup) {
// Let the popup handle Escape, then refocus editor
setTimeout(() => {
const content = document.getElementById("viewer-content");
if (content && getState().editMode) {
content.focus({ preventScroll: true });
}
}, 0);
return;
}
sendToParent("embeddedEscapeKeyPressed", {});
return;
}
// Forward function keys to Phoenix
if (e.key.startsWith("F") && e.key.length >= 2 && !isNaN(e.key.slice(1))) {
e.preventDefault();
e.stopImmediatePropagation();
sendToParent("mdviewrKeyboardShortcut", {
key: e.key,
code: e.code,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
shiftKey: e.shiftKey,
altKey: e.altKey
});
return;
}
const isMod = _isMac ? e.metaKey : e.ctrlKey;
if (!isMod) return;
if ((e.key === "z" || e.key === "Z") && !e.shiftKey) {
e.preventDefault();
e.stopImmediatePropagation();
sendToParent("mdviewrUndo", {});
return;
}
if (((e.key === "z" || e.key === "Z") && e.shiftKey) || e.key === "y") {
e.preventDefault();
e.stopImmediatePropagation();
sendToParent("mdviewrRedo", {});
return;
}
// Ctrl/Cmd+F — open in-document search
if (e.key === "f" && !e.shiftKey) {
e.preventDefault();
e.stopImmediatePropagation();
emit("action:toggle-search");
return;
}
// Forward unhandled modifier shortcuts to Phoenix keybinding manager
if (getState().editMode) {
const isHandled = e.shiftKey
? _mdEditorHandledShiftKeys.has(e.key)
: _mdEditorHandledKeys.has(e.key);
if (!isHandled) {
e.preventDefault();
e.stopImmediatePropagation();
sendToParent("mdviewrKeyboardShortcut", {
key: e.key,
code: e.code,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
shiftKey: e.shiftKey,
altKey: e.altKey
});
// Refocus md editor after Phoenix handles the shortcut
// (some commands like Save focus the CM editor)
setTimeout(() => {
const content = document.getElementById("viewer-content");
if (content && getState().editMode) {
content.focus({ preventScroll: true });
}
}, 100);
}
}
}, true);
// Detect source line from data-source-line attributes for scroll sync.
// In read mode, also refocus CM5 unless the user has a text selection.
// Disabled in preview mode (no cursor sync).
document.addEventListener("click", (e) => {
const sourceLine = _getSourceLineFromElement(e.target);
if (getState().editMode) {
if (sourceLine != null) {
_scrollFromViewer = true;
setTimeout(() => { _scrollFromViewer = false; }, 500);
sendToParent("mdviewrScrollSync", { sourceLine });
}
return;
}
const selection = window.getSelection();
if (!selection || selection.toString().length === 0) {
sendToParent("embeddedIframeFocusEditor", { sourceLine });
}
}, true);
// Scroll sync: when viewer scrolls, send first visible source line to CM
let _viewerScrollRAF = null;
const appViewer = document.getElementById("app-viewer");
if (appViewer) {
appViewer.addEventListener("scroll", () => {
if (_scrollFromCM) return;
if (_viewerScrollRAF) { cancelAnimationFrame(_viewerScrollRAF); }
_viewerScrollRAF = requestAnimationFrame(() => {
_viewerScrollRAF = null;
const viewer = document.getElementById("viewer-content");
if (!viewer) return;
const viewerRect = appViewer.getBoundingClientRect();
const elements = viewer.querySelectorAll("[data-source-line]");
let bestEl = null;
let bestDist = Infinity;
for (const el of elements) {
const rect = el.getBoundingClientRect();
const dist = Math.abs(rect.top - viewerRect.top);
if (dist < bestDist) {
bestDist = dist;
bestEl = el;
}
}
if (bestEl) {
const sourceLine = parseInt(bestEl.getAttribute("data-source-line"), 10);
sendToParent("mdviewrScrollSync", { sourceLine, fromScroll: true });
}
});
});
}
// Listen for selection changes to sync selection back to CM
// Also track cursor position for undo/redo restore
document.addEventListener("selectionchange", () => {
if (!getState().editMode) {
return;
}
// Only update cursor position if we're not mid-edit
// (once content changes, freeze position until emitted)
if (!_cursorPosDirty) {
_cursorPosBeforeEdit = _getCursorPosition();
}
// Fast path: send just the source line for instant CM highlight
_sendCursorLineToParent();
// Full selection sync (debounced)
_sendSelectionToParent();
});
// Freeze cursor position on first input (before debounce fires)
document.addEventListener("input", () => {
if (getState().editMode) {
_cursorPosDirty = true;
}
}, true);
// Listen for content changes from editor (debounced by editor.js)
on("bridge:contentChanged", ({ markdown }) => {
if (_suppressContentChange) return;
_syncId++;
// Keep state.currentContent in sync so edit→reader re-render has latest content
setState({ currentContent: markdown });
// Update the cache entry's mdSrc so it stays in sync
const activePath = docCache.getActiveFilePath();
if (activePath) {
const entry = docCache.getEntry(activePath);
if (entry) {
entry.mdSrc = markdown;
}
}
// Send cursor position BEFORE the edit for undo restore
sendToParent("mdviewrContentChanged", { markdown, _syncId, cursorPos: _cursorPosBeforeEdit });
_cursorPosDirty = false; // allow cursor tracking again
});
// Listen for edit mode changes from toolbar
on("state:editMode", (editMode) => {
sendToParent("mdviewrEditModeChanged", { editMode });
});
// Edit mode request — ask Phoenix for permission (entitlement check)
on("request:editMode", () => {
sendToParent("mdviewrRequestEditMode", {});
});
// Forward image upload request from editor to Phoenix
on("bridge:uploadImage", async ({ blob, filename, uploadId }) => {
const arrayBuffer = await blob.arrayBuffer();
sendToParent("mdviewrImageUploadRequest", {
arrayBuffer,
mimeType: blob.type,
filename,
uploadId
});
});
// Cursor sync toggle
on("toggle:cursorSync", ({ enabled }) => {
// Clear any existing highlights when cursor sync is disabled
if (!enabled) {
const viewer = document.getElementById("viewer-content");
if (viewer) {
_removeCursorHighlight(viewer);
}
_lastHighlightSourceLine = null;
_lastHighlightTargetLine = null;
}
sendToParent("mdviewrCursorSyncToggle", { enabled });
});
// Toggle selection color class based on iframe focus
// (::selection + :focus doesn't work in WebKit)
window.addEventListener("focus", () => {
const content = document.getElementById("viewer-content");
if (content) content.classList.add("content-focused");
});
window.addEventListener("blur", () => {
const content = document.getElementById("viewer-content");
if (content) content.classList.remove("content-focused");
});
// Notify parent that iframe is ready
sendToParent("mdviewrReady", {});
}
// --- Content handlers ---
function handleSetContent(data) {
const { markdown, baseURL, filePath } = data;
// Reset sync tracking — Phoenix resets its counter on activate
_lastReceivedSyncId = -1;
if (baseURL) {
_baseURL = baseURL;
}
_suppressContentChange = true;
const parseResult = parseMarkdownToHTML(markdown);
if (filePath) {
// Cache-aware: create/update entry and switch to it
const existing = docCache.getEntry(filePath);
if (existing) {
docCache.updateEntry(filePath, markdown, parseResult);
} else {
docCache.createEntry(filePath, markdown, parseResult);
}
docCache.switchTo(filePath);
}
setState({
currentContent: markdown,
parseResult: parseResult
});
// file:rendered triggers viewer.js handler which does morphdom + renderAfterHTML
emit("file:rendered", parseResult);
_suppressContentChange = false;
}
function handleUpdateContent(data) {
const { markdown, _syncId: remoteSyncId, filePath } = data;
if (remoteSyncId !== undefined && remoteSyncId <= _lastReceivedSyncId) {
return;
}
if (remoteSyncId !== undefined) {
_lastReceivedSyncId = remoteSyncId;
}
_suppressContentChange = true;
// If update is for a background (non-active) file, just update cache
const activePath = docCache.getActiveFilePath();
if (filePath && activePath && filePath !== activePath) {
const parseResult = parseMarkdownToHTML(markdown);
docCache.updateEntry(filePath, markdown, parseResult);
_suppressContentChange = false;
return;
}
const parseResult = parseMarkdownToHTML(markdown);
if (filePath) {
const entry = docCache.getEntry(filePath);
if (entry) {
entry.mdSrc = markdown;
entry.parseResult = parseResult;
}
}
setState({
currentContent: markdown,
parseResult: parseResult
});
emit("file:rendered", parseResult);
// Restore cursor on undo/redo using source line + offset within block
if (data.cursorPos && getState().editMode) {
const content = document.getElementById("viewer-content");
if (content) {
_restoreCursorPosition(content, data.cursorPos);
}
}
_suppressContentChange = false;
}
/**
* Cache-aware file switch. This is the core optimization:
* - Cache hit + same content → just show cached DOM (instant)
* - Cache hit + changed content → re-render in place
* - Cache miss → parse, create entry, render
*/
function handleSwitchFile(data) {
const { filePath, markdown, baseURL } = data;
// Reset sync tracking — Phoenix resets its counter on activate
_lastReceivedSyncId = -1;
_syncId = 0;
if (baseURL) {
_baseURL = baseURL;
}
_suppressContentChange = true;
// Suppress scroll-to-line from CM during file switch — the doc cache
// restores the correct scroll position; CM cursor activity would override it.
_suppressScrollToLine = true;
setTimeout(() => { _suppressScrollToLine = false; }, 500);
// Edit mode is global for the md editor frame — preserve it across file switches
const wasEditMode = getState().editMode;
// Save state for outgoing document
const outgoingPath = docCache.getActiveFilePath();
if (outgoingPath) {
docCache.saveActiveScrollPos();
}
// Exit edit mode before switching DOM to detach handlers from outgoing element
if (wasEditMode) {
emit("doc:beforeSwitch", { fromPath: outgoingPath, toPath: filePath });
setState({ editMode: false });
}
const existing = docCache.getEntry(filePath);
if (existing && existing.mdSrc === markdown) {
// Cache hit, content unchanged — instant switch
docCache.switchTo(filePath);
setState({
currentContent: markdown,
parseResult: existing.parseResult
});
emit("file:switched", { filePath });
} else if (existing) {
// Cache hit, content changed — re-render in place
const parseResult = parseMarkdownToHTML(markdown);
docCache.updateEntry(filePath, markdown, parseResult);
docCache.switchTo(filePath);
setState({
currentContent: markdown,
parseResult: parseResult
});
emit("file:rendered", parseResult);
} else {
// Cache miss — create new entry
const parseResult = parseMarkdownToHTML(markdown);
docCache.createEntry(filePath, markdown, parseResult);
docCache.switchTo(filePath);
// Restore scroll position and edit mode from reload if applicable
if (_pendingReloadScroll && _pendingReloadScroll.filePath === filePath) {
const entry = docCache.getEntry(filePath);
if (entry) {
entry._scrollSourceLine = _pendingReloadScroll.scrollSourceLine;
}
const restoreEditMode = _pendingReloadScroll.editMode;
_pendingReloadScroll = null;
setState({
currentContent: markdown,
parseResult: parseResult
});
emit("file:rendered", parseResult);
// Scroll to source line element after render
if (entry && entry._scrollSourceLine) {
requestAnimationFrame(() => {
const els = entry.dom.querySelectorAll("[data-source-line]");
for (const el of els) {
if (parseInt(el.getAttribute("data-source-line"), 10) === entry._scrollSourceLine) {
el.scrollIntoView({ behavior: "instant", block: "start" });
break;
}
}
});
}
if (restoreEditMode) {
setState({ editMode: true });
}
} else {
setState({
currentContent: markdown,
parseResult: parseResult
});
emit("file:rendered", parseResult);
}
}
// Re-enter edit mode on the new DOM if the frame was in edit mode
if (wasEditMode) {
setState({ editMode: true });
}
_suppressContentChange = false;
}
function handleClearCache() {
docCache.clearAll();
}
function handleWorkingSetChanged(data) {
const { paths } = data;
if (Array.isArray(paths)) {
docCache.setWorkingSet(paths);
}
}
function handleCloseFile(data) {
const { filePath } = data;
if (filePath) {
docCache.removeEntry(filePath);
}
}
/**
* Reload a specific file: save scroll position, clear its cache entry,
* so the next SWITCH_FILE will re-render from scratch.
*/
function handleReloadFile(data) {
const { filePath } = data;
if (!filePath) {
return;
}
const entry = docCache.getEntry(filePath);
// If this is the active file, save current scroll
if (docCache.getActiveFilePath() === filePath) {
docCache.saveActiveScrollPos();
const activeEntry = docCache.getEntry(filePath);
if (activeEntry) {
const scrollSourceLine = activeEntry._scrollSourceLine;
const wasEditMode = getState().editMode;
if (wasEditMode) {
setState({ editMode: false });
}
docCache.removeEntry(filePath);
_pendingReloadScroll = { filePath, scrollSourceLine, editMode: wasEditMode };
}
} else {
docCache.removeEntry(filePath);
}
}
// --- Theme, edit mode, locale ---
function handleSetTheme(data) {
const { theme } = data;
const newScheme = theme === "dark" ? "dark" : "light";
// Skip if already applied to avoid reflows that can reset scroll position
if (document.documentElement.getAttribute("data-theme") === theme &&
document.documentElement.style.colorScheme === newScheme) {
return;
}
document.documentElement.setAttribute("data-theme", theme);
document.documentElement.style.colorScheme = newScheme;
setState({ theme });
}
function handleSetEditMode(data) {
const { editMode } = data;
setState({ editMode });
}
/**
* Re-render content from CM's authoritative markdown.
* Called when switching edit→reader so data-source-line attributes are accurate.
*/
function handleRerenderContent(data) {
const { markdown } = data;
if (!markdown) return;
const parseResult = parseMarkdownToHTML(markdown);
setState({ currentContent: markdown, parseResult });
emit("file:rendered", parseResult);
}
function _handleImageUploadResult(data) {
const { uploadId, embedURL, error } = data;
const content = document.getElementById("viewer-content");
if (!content || !uploadId) return;
const placeholder = content.querySelector(`img[data-upload-id="${uploadId}"]`);
if (!placeholder) return;
if (embedURL) {
placeholder.src = embedURL;
placeholder.alt = placeholder.alt === "Uploading..." ? "" : placeholder.alt;
placeholder.removeAttribute("data-upload-id");
} else {
placeholder.remove();
}
content.dispatchEvent(new Event("input", { bubbles: true }));
}
function handleSetLocale(data) {
const { locale } = data;
if (locale) {
setLocale(locale);
}
}
// --- Scroll sync ---
/**
* Get the cursor position as { sourceLine, offsetInBlock }.
* sourceLine: the data-source-line of the containing block (stable across re-renders)
* offsetInBlock: character offset within that block (precise within a small element)
*/
function _getCursorPosition() {
const sel = window.getSelection();
if (!sel || !sel.rangeCount) return null;
const range = sel.getRangeAt(0);
// Find the source-line block element
let blockEl = sel.anchorNode;
if (blockEl && blockEl.nodeType === Node.TEXT_NODE) blockEl = blockEl.parentElement;
while (blockEl && !blockEl.getAttribute?.("data-source-line")) {
blockEl = blockEl.parentElement;
}
if (!blockEl) return null;
const sourceLine = parseInt(blockEl.getAttribute("data-source-line"), 10);
// Calculate character offset within this block
const pre = document.createRange();
pre.setStart(blockEl, 0);
pre.setEnd(range.startContainer, range.startOffset);
const offsetInBlock = pre.toString().length;
return { sourceLine, offsetInBlock };
}
/**
* Restore cursor to a position defined by { sourceLine, offsetInBlock }.
*/
function _restoreCursorPosition(contentEl, pos) {
if (!pos || !pos.sourceLine) return;
// Find the block element matching the source line
const elements = contentEl.querySelectorAll("[data-source-line]");
let bestEl = null;
let bestLine = -1;
for (const el of elements) {
const srcLine = parseInt(el.getAttribute("data-source-line"), 10);
if (srcLine <= pos.sourceLine && srcLine > bestLine) {
bestLine = srcLine;
bestEl = el;
}
}
if (!bestEl) return;
// Walk text nodes within the block to find the exact offset
const offset = pos.offsetInBlock || 0;
const walker = document.createTreeWalker(bestEl, NodeFilter.SHOW_TEXT);
let remaining = offset;
let node;
while ((node = walker.nextNode())) {
if (remaining <= node.textContent.length) {
const range = document.createRange();
range.setStart(node, remaining);
range.collapse(true);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
return;
}
remaining -= node.textContent.length;
}
// Fallback: place at start of element
const range = document.createRange();
range.selectNodeContents(bestEl);
range.collapse(true);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
function _getSourceLineFromElement(el) {
// Use the current selection to determine exact position within <br> paragraphs
const sel = window.getSelection();
const cursorNode = sel && sel.rangeCount ? sel.getRangeAt(0).startContainer : null;
while (el && el !== document.body) {
const attr = el.getAttribute && el.getAttribute("data-source-line");
if (attr != null) {
let line = parseInt(attr, 10);
if (cursorNode) {
// For paragraphs with <br> (soft line breaks), count <br>
// elements before the cursor for the exact CM line.
if (el.tagName === "P" && el.querySelector("br")) {
const brs = el.querySelectorAll("br");
for (const br of brs) {
const pos = br.compareDocumentPosition(cursorNode);
if (pos & Node.DOCUMENT_POSITION_FOLLOWING || pos & Node.DOCUMENT_POSITION_CONTAINED_BY) {
line++;
}
}
}
// For code blocks, count \n before cursor in textContent.
// data-source-line on <pre> points to the ``` fence line,
// so first code line = line + 1, each \n increments.
if (el.tagName === "PRE") {
const code = el.querySelector("code") || el;
try {
const range = document.createRange();
range.setStart(code, 0);
range.setEnd(sel.getRangeAt(0).startContainer, sel.getRangeAt(0).startOffset);
const textBefore = range.toString();
const newlines = (textBefore.match(/\n/g) || []).length;
line += 1 + newlines; // +1 for the ``` fence line
} catch (_e) {
line += 1; // fallback: first code line
}
}
}
return line;
}
el = el.parentElement;
}
return null;
}
function handleScrollToLine(data) {
const { line, fromScroll, tableCol } = data;
if (line == null) return;
// Suppress during file switch — doc cache restores the correct scroll
if (_suppressScrollToLine) return;