Files
md-preview/assets/page/page.js

1362 lines
52 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(function(){
var ICON_EDIT = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>';
var ICON_VIEW = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>';
var ICON_ZOOM = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/><path d="M8 11h6"/><path d="M11 8v6"/></svg>';
var ICON_UP = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m18 15-6-6-6 6"/></svg>';
var ICON_DOWN = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>';
var ICON_CLOSE = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>';
var L_EDIT = '__MDP_BTN_EDIT__', L_VIEW = '__MDP_BTN_PREVIEW__', L_HOME = '__MDP_HOME_TAB__';
window.__mdPreviewFoldLabel = '__MDP_FOLD_TOGGLE__';
window.__mdPreviewCannotSave = '__MDP_CANNOT_SAVE_JS__';
var btnToggle = document.getElementById('btn-toggle');
var btnZoom = document.getElementById('btn-zoom');
var btnZoomOut = document.getElementById('btn-zoom-out');
var btnZoomReset = document.getElementById('btn-zoom-reset');
var btnZoomIn = document.getElementById('btn-zoom-in');
var zoomControl = document.getElementById('zoom-control');
var findInput = document.getElementById('find-input');
var findState = document.getElementById('find-state');
var findPrev = document.getElementById('find-prev');
var findNext = document.getElementById('find-next');
var findClose = document.getElementById('find-close');
var editFindBar = document.getElementById('edit-findbar');
var editFindInput = document.getElementById('edit-find-input');
var editFindState = document.getElementById('edit-find-state');
var editFindPrev = document.getElementById('edit-find-prev');
var editFindNextBtn = document.getElementById('edit-find-next');
var editFindClose = document.getElementById('edit-find-close');
var editReplaceGroup = document.getElementById('edit-replace-group');
var editReplaceInput = document.getElementById('edit-replace-input');
var editReplaceOne = document.getElementById('edit-replace-one');
var editReplaceAll = document.getElementById('edit-replace-all');
var tabsEl = document.getElementById('tabs');
var docStats = document.getElementById('doc-stats');
var tabOpen = document.getElementById('tab-open');
var tabMenu = document.getElementById('tab-menu');
var tabMenuPath = document.getElementById('tab-menu-path');
var tabMenuReveal = document.getElementById('tab-menu-reveal');
var tabMenuNewWindow = document.getElementById('tab-menu-new-window');
var tabMenuTargetId = 0;
var tabDrag = null;
var suppressTabClickUntil = 0;
var ta = document.getElementById('editor');
var appEl = document.getElementById('app');
var dirty = false;
var activeTabId = 0;
var tabCount = 0;
var pendingAutosaveTimer = 0;
var autosavePaused = false;
var saveBlocked = false;
var AUTOSAVE_DEBOUNCE_MS = 700;
var composingFind = false;
var pendingFindTimer = 0;
var FIND_DEBOUNCE_MS = 300;
// Tab inserts spaces, never a literal tab. Two spaces matches the
// common Markdown/AI-generated document style and keeps list nesting
// compact; change this single constant to switch the width.
var INDENT = ' ';
// The strip stays hidden while the only tab is Home, matching the
// original start-up page. Set to false to keep the tab bar always on.
var HIDE_SINGLE_HOME_TAB = true;
var findHits = [];
var editFinding = false;
var editFindMatches = [];
var editFindIndex = -1;
var editFindOverlay = null;
var editFindTimer = 0;
var currentFindHit = -1;
var lastFindQuery = '';
var STAT_WORDS = '__MDP_STAT_WORDS_JS__';
var STAT_CHARS = '__MDP_STAT_CHARS_JS__';
var ZOOM_SAVE_DEBOUNCE_MS = 400;
var pendingZoomSaveTimer = 0;
var ZOOM_MIN = 50;
var ZOOM_MAX = 300;
var ZOOM_STEP = 5;
var ZOOM_WHEEL_THROTTLE_MS = 90;
var zoomWheelAt = 0;
var zoomPercent = 100;
// CodeMirror is loaded on demand (first edit mode), never at startup.
var CM_MAX_BYTES = 2 * 1024 * 1024;
var CM_MAX_LINES = 20000;
var cm = null;
var cmLoading = false;
var cmDisabled = false;
var applyingRemote = false;
var pendingScrollRatio = 0;
// All source-text access goes through this adapter. The CodeMirror
// implementation replaces the returned object; callers never touch ta.
var ed = createTextareaEditor(ta);
ed.bind();
btnToggle.innerHTML = ICON_EDIT;
btnZoom.innerHTML = ICON_ZOOM;
findPrev.innerHTML = ICON_UP;
findNext.innerHTML = ICON_DOWN;
findClose.innerHTML = ICON_CLOSE;
editFindPrev.innerHTML = ICON_UP;
editFindNextBtn.innerHTML = ICON_DOWN;
editFindClose.innerHTML = ICON_CLOSE;
function inEdit() { return document.body.classList.contains('editing'); }
function textSegments(text) {
if (typeof Intl !== 'undefined' && Intl.Segmenter) {
var segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
return Array.from(segmenter.segment(text), function(item) { return item.segment; });
}
return Array.from(text);
}
function updateDocumentStats(raw) {
var segments = textSegments(String(raw || ''));
var words = segments.reduce(function(total, segment) {
return total + (/^\s+$/u.test(segment) ? 0 : 1);
}, 0);
var number = new Intl.NumberFormat().format;
docStats.textContent =
number(words) + ' ' + STAT_WORDS + ' · ' + number(segments.length) + ' ' + STAT_CHARS;
}
function queueZoomSave() {
if (pendingZoomSaveTimer) clearTimeout(pendingZoomSaveTimer);
pendingZoomSaveTimer = setTimeout(function() {
pendingZoomSaveTimer = 0;
if (window.ipc) window.ipc.postMessage('zoom:' + zoomPercent);
}, ZOOM_SAVE_DEBOUNCE_MS);
}
function applyZoom(percent, persist) {
zoomPercent = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, percent));
document.documentElement.style.setProperty('--content-scale', String(zoomPercent / 100));
btnZoomReset.textContent = zoomPercent + '%';
if (persist) queueZoomSave();
if (cm) updateEditorZoom();
else if (inEdit()) ed.resize();
}
function changeZoom(delta) {
applyZoom(zoomPercent + delta, true);
}
function currentScrollProgress() {
if (cm && inEdit()) {
var info = cm.getScrollInfo();
var cmMax = info.height - info.clientHeight;
if (cmMax <= 0) return 0;
var line = cm.lineAtHeight(info.top, 'local');
var lineTop = cm.heightAtLine(line, 'local');
return Math.min(1, Math.max(0, lineTop / cmMax));
}
var max = Math.max(appEl.scrollHeight - appEl.clientHeight, 0);
var y = appEl.scrollTop || 0;
return max > 0 ? Math.min(1, Math.max(0, y / max)) : 0;
}
// A newer restore supersedes any callback the previous one left behind.
var scrollRestoreToken = 0;
function restoreScrollProgress(progress) {
if (cm && inEdit()) {
pendingScrollRatio = progress;
var cmToken = ++scrollRestoreToken;
var applyCm = function() {
if (cmToken !== scrollRestoreToken) return;
var info = cm.getScrollInfo();
var cmMax = Math.max(info.height - info.clientHeight, 0);
cm.scrollTo(null, cmMax * progress);
// Land on a line boundary so repeated switches do not drift.
var topLine = cm.lineAtHeight(cm.getScrollInfo().top, 'local');
cm.scrollTo(null, cm.heightAtLine(topLine, 'local'));
};
requestAnimationFrame(function() {
if (cmToken !== scrollRestoreToken) return;
cm.refresh();
applyCm();
requestAnimationFrame(applyCm);
});
// Late layout inside CodeMirror can change the scroll height too.
setTimeout(applyCm, 150);
return;
}
var token = ++scrollRestoreToken;
function restore() {
if (token !== scrollRestoreToken) return;
var max = Math.max(appEl.scrollHeight - appEl.clientHeight, 0);
appEl.scrollTop = max * progress;
}
restore();
requestAnimationFrame(function() {
restore();
requestAnimationFrame(restore);
});
// Late layout (tables, math, mermaid) can change the content height.
setTimeout(restore, 150);
}
// Report the viewport so Rust can restore it when the tab comes back. The
// tab id travels with the report: a late scroll must not land on the tab
// that became active in the meantime.
var pendingScrollReport = 0;
function reportScroll() {
if (pendingScrollReport || !activeTabId) return;
pendingScrollReport = setTimeout(function() {
pendingScrollReport = 0;
if (window.ipc && activeTabId) {
window.ipc.postMessage('scroll:' + activeTabId + ':' + currentScrollProgress().toFixed(4));
}
}, 200);
}
appEl.addEventListener('scroll', reportScroll, { passive: true });
applyZoom(100, false);
window.__mdPreviewSetZoom = function(percent) { applyZoom(percent, false); };
updateDocumentStats(ed.value());
function shortenPath(path, max) {
if (!path || path.length <= max) return path || '';
var head = Math.ceil((max - 3) / 2);
var tail = Math.floor((max - 3) / 2);
return path.slice(0, head) + '...' + path.slice(-tail);
}
function suppressTabTooltips() {
Array.prototype.forEach.call(tabsEl.querySelectorAll('.tab[title]'), function(tab) {
tab.setAttribute('data-saved-title', tab.getAttribute('title'));
tab.removeAttribute('title');
});
}
function restoreTabTooltips() {
Array.prototype.forEach.call(tabsEl.querySelectorAll('.tab[data-saved-title]'), function(tab) {
var title = tab.getAttribute('data-saved-title');
tab.removeAttribute('data-saved-title');
if (title) tab.setAttribute('title', title);
});
}
function hideTabMenu() {
if (!tabMenu || tabMenu.hidden) return;
tabMenu.hidden = true;
tabMenuTargetId = 0;
restoreTabTooltips();
}
function showTabMenu(id, x, y) {
if (!tabMenu) return;
if (!tabMenu.hidden) hideTabMenu();
suppressTabTooltips();
tabMenuTargetId = id;
var tabEl = tabsEl.querySelector('.tab[data-tab-id="' + id + '"]');
var isHome = tabEl ? tabEl.classList.contains('home') : false;
var path = tabEl ? (tabEl.getAttribute('data-tab-path') || '') : '';
if (tabMenuPath) {
tabMenuPath.textContent = isHome ? L_HOME : shortenPath(path, 42);
if (!isHome && path) tabMenuPath.setAttribute('title', path);
else tabMenuPath.removeAttribute('title');
}
tabMenu.hidden = false;
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1 || isHome;
if (tabMenuReveal) tabMenuReveal.disabled = isHome || !path;
tabMenu.style.left = '0px';
tabMenu.style.top = '0px';
var rect = tabMenu.getBoundingClientRect();
var left = Math.max(8, Math.min(x, window.innerWidth - rect.width - 8));
var top = Math.max(8, Math.min(y, window.innerHeight - rect.height - 8));
tabMenu.style.left = left + 'px';
tabMenu.style.top = top + 'px';
}
function detachTab(id) {
if (tabCount <= 1) return;
if (saveBlocked) {
window.alert(window.__mdPreviewCannotSave || 'Discard unsaved changes?');
return;
}
requestTabAction('detach', id);
}
document.addEventListener('contextmenu', function(e) {
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
if (tab) {
e.preventDefault();
e.stopPropagation();
showTabMenu(tab.getAttribute('data-tab-id'), e.clientX, e.clientY);
return;
}
hideTabMenu();
if (!inEdit() || !ed.isTarget(e.target)) e.preventDefault();
});
function setDirty(d) {
if (dirty === d) return;
dirty = d;
window.ipc.postMessage(d ? 'dirty:1' : 'dirty:0');
}
function cancelPendingAutosave() {
if (!pendingAutosaveTimer) return;
clearTimeout(pendingAutosaveTimer);
pendingAutosaveTimer = 0;
}
function save() {
cancelPendingAutosave();
if (!dirty) return;
window.ipc.postMessage('save:' + ed.value());
}
function scheduleAutosave() {
cancelPendingAutosave();
if (autosavePaused) return;
pendingAutosaveTimer = setTimeout(function() {
pendingAutosaveTimer = 0;
if (dirty) save();
}, AUTOSAVE_DEBOUNCE_MS);
}
window.__mdPreviewSave = save;
function requestTabAction(action, id) {
cancelPendingAutosave();
var message = 'tab-action:' + action + ':' + id + ':' + currentScrollProgress().toFixed(4);
if (dirty) {
if (saveBlocked) {
if (!window.confirm(window.__mdPreviewCannotSave || 'Discard unsaved changes?')) return;
} else {
message += '\n' + ed.value();
}
}
window.ipc.postMessage(message);
}
function openFile() {
if (inEdit()) leaveEdit();
window.ipc.postMessage('open');
}
window.__mdPreviewOpenFile = openFile;
function newFile() {
if (inEdit()) leaveEdit();
window.ipc.postMessage('new-file');
}
window.__mdPreviewNewFile = newFile;
function newTab() {
// Reuse the close/activate path so a dirty editor is saved before the
// Home tab replaces it.
requestTabAction('new-tab', 0);
}
function selectionSeed() {
var sel = window.getSelection && window.getSelection();
if (!sel || sel.rangeCount === 0) return null;
var anchor = sel.anchorNode;
var element = anchor && (anchor.nodeType === 3 ? anchor.parentElement : anchor);
if (!element || !element.closest || !element.closest('#preview')) return null;
var text = sel.toString();
if (!text) return null;
var top = null;
try {
var rect = sel.getRangeAt(0).getBoundingClientRect();
if (rect && (rect.width || rect.height)) top = rect.top;
} catch (_) {}
var lines = text.split(/\r?\n/);
for (var i = 0; i < lines.length; i += 1) {
var line = lines[i].trim();
if (line) return { text: line, top: top };
}
return null;
}
function showFind(seed, anchorTop) {
if (document.body.classList.contains('home')) return;
if (inEdit()) return;
document.body.classList.add('finding');
if (typeof seed === 'string' && seed) {
findInput.value = seed;
runFindQuery(seed, anchorTop, false);
}
setTimeout(function(){
try { findInput.focus({ preventScroll: true }); } catch (_) { findInput.focus(); }
findInput.select();
}, 0);
}
window.__mdPreviewShowFind = showFind;
function hideFind() {
document.body.classList.remove('finding');
findInput.value = '';
clearFindHits();
if (pendingFindTimer) { clearTimeout(pendingFindTimer); pendingFindTimer = 0; }
var sel = window.getSelection && window.getSelection();
if (sel && sel.removeAllRanges) sel.removeAllRanges();
}
function updateFindState() {
findState.textContent = findHits.length ? (currentFindHit + 1) + '/' + findHits.length : '';
}
function clearFindHits() {
findHits.forEach(function(mark) {
var parent = mark.parentNode;
if (!parent) return;
parent.replaceChild(document.createTextNode(mark.textContent), mark);
parent.normalize();
});
findHits = [];
currentFindHit = -1;
lastFindQuery = '';
updateFindState();
}
function focusFindInput(selectionStart, selectionEnd) {
if (!document.body.classList.contains('finding')) return;
try {
findInput.focus({ preventScroll: true });
} catch (_) {
findInput.focus();
}
if (typeof selectionStart === 'number' && typeof selectionEnd === 'number') {
try { findInput.setSelectionRange(selectionStart, selectionEnd); } catch (_) {}
}
}
function restoreFindInput(selectionStart, selectionEnd) {
setTimeout(function() { focusFindInput(selectionStart, selectionEnd); }, 0);
requestAnimationFrame(function() {
focusFindInput(selectionStart, selectionEnd);
setTimeout(function() { focusFindInput(selectionStart, selectionEnd); }, 80);
});
}
function selectFindHit(index, reveal) {
if (!findHits.length) {
currentFindHit = -1;
updateFindState();
return;
}
if (currentFindHit >= 0 && findHits[currentFindHit]) {
findHits[currentFindHit].classList.remove('current');
}
currentFindHit = (index + findHits.length) % findHits.length;
var hit = findHits[currentFindHit];
hit.classList.add('current');
if (reveal !== false) {
if (window.__mdPreviewExpandFold) window.__mdPreviewExpandFold(hit);
hit.scrollIntoView({ block: 'center', inline: 'nearest' });
}
updateFindState();
}
function findStartIndex(anchorTop) {
if (!findHits.length) return 0;
var startTop = typeof anchorTop === 'number' ? anchorTop : 0;
var lastAbove = -1;
for (var i = 0; i < findHits.length; i += 1) {
var rect = findHits[i].getBoundingClientRect();
if (!rect.width && !rect.height) continue;
if (rect.bottom < startTop) {
lastAbove = i;
continue;
}
return i;
}
return lastAbove >= 0 ? lastAbove : 0;
}
function runFindQuery(query, anchorTop, reveal) {
clearFindHits();
query = String(query || '').trim();
if (!query) return;
lastFindQuery = query;
var needle = query.toLowerCase();
var previewEl = document.getElementById('preview');
var walker = document.createTreeWalker(previewEl, NodeFilter.SHOW_TEXT, {
acceptNode: function(node) {
if (!node.nodeValue || node.nodeValue.toLowerCase().indexOf(needle) < 0) {
return NodeFilter.FILTER_REJECT;
}
var parent = node.parentElement;
if (!parent || parent.closest('script,style,svg,mark.search-hit,.katex,.mdp-mermaid')) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
});
var nodes = [];
while (walker.nextNode()) nodes.push(walker.currentNode);
nodes.forEach(function(node) {
var text = node.nodeValue;
var lower = text.toLowerCase();
var fragment = document.createDocumentFragment();
var start = 0;
var index;
while ((index = lower.indexOf(needle, start)) >= 0) {
if (index > start) fragment.appendChild(document.createTextNode(text.slice(start, index)));
var mark = document.createElement('mark');
mark.className = 'search-hit';
mark.textContent = text.slice(index, index + query.length);
findHits.push(mark);
fragment.appendChild(mark);
start = index + query.length;
}
if (start < text.length) fragment.appendChild(document.createTextNode(text.slice(start)));
node.parentNode.replaceChild(fragment, node);
});
selectFindHit(findStartIndex(anchorTop), reveal);
}
function runFind(backward) {
var q = findInput.value;
if (!q) { clearFindHits(); return; }
var hadFocus = document.activeElement === findInput;
var selectionStart = findInput.selectionStart;
var selectionEnd = findInput.selectionEnd;
var normalized = String(q || '').trim();
if (!normalized) {
clearFindHits();
} else if (normalized !== lastFindQuery) {
runFindQuery(normalized);
} else {
selectFindHit(currentFindHit + (backward ? -1 : 1));
}
if (hadFocus) restoreFindInput(selectionStart, selectionEnd);
}
function scheduleFind() {
if (pendingFindTimer) clearTimeout(pendingFindTimer);
pendingFindTimer = setTimeout(function() {
pendingFindTimer = 0;
if (!composingFind) runFindQuery(findInput.value);
}, FIND_DEBOUNCE_MS);
}
// Grow textarea height to its content so the page (html) owns the sole
// scrollbar; avoids the double-scrollbar you see if textarea keeps its
// own internal scroll.
function autoResize() {
var y = appEl.scrollTop;
ta.style.height = 'auto';
var h = Math.max(ta.scrollHeight, appEl.clientHeight);
ta.style.height = h + 'px';
appEl.scrollTop = y;
}
// ---- Source editor commands -------------------------------------------------
function editorLineStart(value, pos) {
return value.lastIndexOf('\n', Math.max(0, pos - 1)) + 1;
}
function editorLineEnd(value, pos) {
var end = value.indexOf('\n', pos);
return end < 0 ? value.length : end;
}
function replaceEditorRange(text, start, end, selectionStart, selectionEnd) {
try {
ta.focus({ preventScroll: true });
} catch (_) {
ta.focus();
}
ta.setSelectionRange(start, end);
var inserted = false;
try {
if (text === '') {
inserted = document.execCommand('delete', false);
} else {
inserted = document.execCommand('insertText', false, text);
}
} catch (_) {
inserted = false;
}
if (!inserted) {
ta.setRangeText(text, start, end, 'end');
ta.dispatchEvent(new Event('input', { bubbles: true }));
}
if (typeof selectionStart === 'number' && typeof selectionEnd === 'number') {
try { ta.setSelectionRange(selectionStart, selectionEnd); } catch (_) {}
}
setDirty(true);
scheduleAutosave();
autoResize();
updateDocumentStats(ta.value);
}
function transformSelectedEditorLines(transform) {
var value = ta.value;
var start = ta.selectionStart;
var end = ta.selectionEnd;
if (start === end) return false;
var from = editorLineStart(value, start);
var last = end - 1;
if (last > start && value.charAt(last) === '\n') last -= 1;
var to = editorLineEnd(value, last);
var block = value.slice(from, to);
var lines = block.split('\n');
var transformed = lines.map(transform).join('\n');
if (transformed !== block) {
replaceEditorRange(transformed, from, to, from, from + transformed.length);
}
return true;
}
function indentSelectedEditorLines() {
transformSelectedEditorLines(function(line) {
return INDENT + line;
});
}
function outdentSelectedEditorLines() {
transformSelectedEditorLines(function(line) {
if (line.charAt(0) === '\t') return line.slice(1);
var removed = 0;
while (removed < INDENT.length && line.charAt(removed) === ' ') removed += 1;
return line.slice(removed);
});
}
function indentEditor() {
var start = ta.selectionStart;
var end = ta.selectionEnd;
if (start === end) {
replaceEditorRange(INDENT, start, end, start + INDENT.length, start + INDENT.length);
return;
}
indentSelectedEditorLines();
}
function outdentEditor() {
var value = ta.value;
var start = ta.selectionStart;
var end = ta.selectionEnd;
if (start !== end) {
outdentSelectedEditorLines();
return;
}
var from = editorLineStart(value, start);
var line = value.slice(from, editorLineEnd(value, start));
var removed = 0;
if (line.charAt(0) === '\t') {
removed = 1;
} else {
while (removed < INDENT.length && line.charAt(removed) === ' ') removed += 1;
}
if (!removed) return;
var next = Math.max(from, start - removed);
replaceEditorRange('', from, from + removed, next, next);
}
function insertNewlineWithIndent() {
var value = ta.value;
var start = ta.selectionStart;
var end = ta.selectionEnd;
var from = editorLineStart(value, start);
var prefix = value.slice(from, start);
var leading = /^[ \t]*/.exec(prefix)[0];
if (!/\S/.test(prefix)) leading = '';
var text = '\n' + leading;
var next = start + text.length;
replaceEditorRange(text, start, end, next, next);
}
function editorKeydown(e) {
if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Tab' && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
if (e.shiftKey) outdentEditor(); else indentEditor();
return;
}
if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
insertNewlineWithIndent();
}
}
function createTextareaEditor(ta) {
return {
value: function() { return ta.value; },
setValue: function(text) { ta.value = text; },
focus: function() {
try { ta.focus({ preventScroll: true }); } catch (_) { ta.focus(); }
},
selection: function() { return { start: ta.selectionStart, end: ta.selectionEnd }; },
setSelection: function(start, end) { try { ta.setSelectionRange(start, end); } catch (_) {} },
replaceRange: replaceEditorRange,
indent: indentEditor,
outdent: outdentEditor,
newlineWithIndent: insertNewlineWithIndent,
resize: autoResize,
isTarget: function(node) { return node === ta; },
bind: function() {
ta.addEventListener('keydown', editorKeydown);
ta.addEventListener('input', editorInput);
}
};
}
// ---- CodeMirror implementation -------------------------------------------
function updateEditorZoom() {
if (!cm) return;
cm.getWrapperElement().style.fontSize = (14 * zoomPercent / 100) + 'px';
cm.refresh();
}
function editorTooLarge() {
var text = ed.value();
if (text.length > CM_MAX_BYTES) return true;
return text.split('\n').length > CM_MAX_LINES;
}
function requestEditorSource() {
if (cm || cmLoading || cmDisabled) return;
if (editorTooLarge()) { cmDisabled = true; return; }
cmLoading = true;
if (window.ipc) window.ipc.postMessage('need-editor');
}
window.__mdpOnEditorSource = function() {
cmLoading = false;
if (cm || cmDisabled || typeof CodeMirror === 'undefined') return;
createCodeMirror();
};
function createCodeMirror() {
var host = document.getElementById('cm-editor');
if (!host) return;
try {
cm = CodeMirror(host, {
value: ed.value(),
mode: { name: 'markdown', highlightFormatting: true },
lineNumbers: true,
lineWrapping: true,
foldGutter: { rangeFinder: markdownFoldRange, minFoldSize: 0 },
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
foldOptions: { rangeFinder: markdownFoldRange, minFoldSize: 0 },
indentUnit: 2,
tabSize: 2,
indentWithTabs: false,
viewportMargin: 10,
extraKeys: {
'Tab': function(instance) {
if (instance.somethingSelected()) instance.execCommand('indentMore');
else instance.replaceSelection(INDENT, 'end');
},
'Shift-Tab': function(instance) {
if (instance.somethingSelected()) { instance.execCommand('indentLess'); return; }
var cursor = instance.getCursor();
var line = instance.getLine(cursor.line) || '';
var removed = line.charAt(0) === '\t' ? 1 : 0;
while (removed < INDENT.length && line.charAt(removed) === ' ') removed += 1;
if (removed) instance.replaceRange('', { line: cursor.line, ch: 0 }, { line: cursor.line, ch: removed });
},
'Enter': function(instance) { instance.execCommand('newlineAndIndent'); },
'Ctrl-F': function() { openEditFind(false); },
'Cmd-F': function() { openEditFind(false); },
'Ctrl-H': function() { openEditFind(true); },
'Cmd-H': function() { openEditFind(true); },
'Ctrl-S': function() { save(); },
'Cmd-S': function() { save(); },
'Esc': function() { if (editFinding) closeEditFind(); }
}
});
} catch (err) {
cm = null;
cmDisabled = true;
return;
}
ed = createCodeMirrorEditor(cm);
cm.on('change', function() {
if (applyingRemote) return;
setDirty(true);
scheduleAutosave();
updateDocumentStats(ed.value());
});
cm.on('scroll', reportScroll);
updateEditorZoom();
document.body.classList.toggle('cm-active', inEdit());
document.documentElement.classList.toggle('cm-editing', inEdit());
if (inEdit()) {
ed.focus();
restoreScrollProgress(pendingScrollRatio);
}
}
function createCodeMirrorEditor(instance) {
function setValue(text) {
applyingRemote = true;
try { instance.setValue(text); } finally { applyingRemote = false; }
}
return {
value: function() { return instance.getValue(); },
setValue: setValue,
focus: function() { instance.focus(); },
selection: function() {
var ranges = instance.listSelections();
var head = ranges && ranges.length ? ranges[0].head : instance.getCursor();
var anchor = ranges && ranges.length ? ranges[0].anchor : head;
return { start: instance.indexFromPos(anchor), end: instance.indexFromPos(head) };
},
setSelection: function(start, end) {
instance.setSelection(instance.posFromIndex(start), instance.posFromIndex(end));
},
replaceRange: function(text, start, end) {
instance.replaceRange(text, instance.posFromIndex(start), instance.posFromIndex(end));
},
indent: function() { instance.execCommand('indentMore'); },
outdent: function() { instance.execCommand('indentLess'); },
newlineWithIndent: function() { instance.execCommand('newlineAndIndent'); },
resize: function() { updateEditorZoom(); },
isTarget: function(node) { return instance.getWrapperElement().contains(node); },
bind: function() {}
};
}
function markdownFoldRange(instance, line) {
// CodeMirror passes a Pos here; accept a plain line number too.
var lineNo = typeof line === 'number' ? line : line.line;
var text = instance.getLine(lineNo);
if (!text) return null;
var fence = /^\s*(```+|~~~+)/.exec(text);
if (fence) {
var marker = fence[1];
var fenceEnd = -1;
for (var f = lineNo + 1; f <= instance.lastLine(); f += 1) {
var fenceLine = instance.getLine(f) || '';
if (/^\s*(```+|~~~+)\s*$/.test(fenceLine) && fenceLine.indexOf(marker.charAt(0)) >= 0) {
fenceEnd = f;
break;
}
}
if (fenceEnd > lineNo + 1) {
return { from: CodeMirror.Pos(lineNo + 1, 0), to: CodeMirror.Pos(fenceEnd - 1, instance.getLine(fenceEnd - 1).length) };
}
return null;
}
var heading = /^(#{1,6})\s/.exec(text);
var level = heading ? heading[1].length : 0;
if (!heading) {
var underline = instance.getLine(lineNo + 1) || '';
if (text.trim() && /^(=+|-+)\s*$/.test(underline)) {
level = underline.charAt(0) === '=' ? 1 : 2;
}
}
if (!level) return null;
var endLine = lineNo;
for (var i = lineNo + 1; i <= instance.lastLine(); i += 1) {
var bodyLine = instance.getLine(i) || '';
var nextHeading = /^(#{1,6})\s/.exec(bodyLine);
var nextLevel = nextHeading ? nextHeading[1].length : 0;
if (!nextHeading && bodyLine.trim()) {
var nextUnderline = instance.getLine(i + 1) || '';
if (/^(=+|-+)\s*$/.test(nextUnderline)) {
nextLevel = nextUnderline.charAt(0) === '=' ? 1 : 2;
}
}
if (nextLevel && nextLevel <= level) break;
if (bodyLine.trim()) endLine = i;
}
if (endLine <= lineNo) return null;
return { from: CodeMirror.Pos(lineNo + 1, 0), to: CodeMirror.Pos(endLine, instance.getLine(endLine).length) };
}
// ---- Edit-mode find/replace ----------------------------------------------
function editFindOverlayFor(query) {
var escaped = query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
var re = new RegExp(escaped, 'gi');
return { token: function(stream) {
re.lastIndex = stream.pos;
var match = re.exec(stream.string);
if (match && match.index === stream.pos) {
stream.pos += match[0].length || 1;
return 'edit-find-hit';
}
if (match) { stream.pos = match.index; } else { stream.skipToEnd(); }
}};
}
function editFindClearOverlay() {
if (cm && editFindOverlay) cm.removeOverlay(editFindOverlay);
editFindOverlay = null;
}
function editFindVisible(on) {
editFinding = on;
document.body.classList.toggle('edit-finding', on);
editFindBar.hidden = !on;
if (!on) {
if (editFindTimer) { clearTimeout(editFindTimer); editFindTimer = 0; }
editFindClearOverlay();
editFindMatches = [];
editFindIndex = -1;
editFindState.textContent = '';
if (cm && inEdit()) cm.focus();
}
}
function openEditFind(replaceMode) {
if (!cm || !inEdit()) return;
editReplaceGroup.hidden = !replaceMode;
editFindVisible(true);
var selected = cm.getSelection();
if (selected && selected.indexOf('\n') < 0) editFindInput.value = selected;
editFindInput.focus();
editFindInput.select();
editFindRun(true);
}
function closeEditFind() {
editFindVisible(false);
}
function editFindSelect(index) {
if (!editFindMatches.length) {
editFindIndex = -1;
editFindState.textContent = '';
return;
}
editFindIndex = (index + editFindMatches.length) % editFindMatches.length;
var match = editFindMatches[editFindIndex];
editFindState.textContent = (editFindIndex + 1) + '/' + editFindMatches.length;
cm.setSelection(match.from, match.to);
try { cm.scrollIntoView({ from: match.from, to: match.to }, 40); } catch (_) {}
}
function editFindRun(reset) {
if (!cm || !editFinding) return;
var query = editFindInput.value;
editFindClearOverlay();
editFindMatches = [];
editFindIndex = -1;
if (!query) {
editFindState.textContent = '';
return;
}
editFindOverlay = editFindOverlayFor(query);
cm.addOverlay(editFindOverlay);
var cursor = cm.getSearchCursor(query, CodeMirror.Pos(cm.firstLine(), 0), { caseFold: true });
while (cursor.findNext()) {
editFindMatches.push({ from: cursor.from(), to: cursor.to() });
if (editFindMatches.length >= 5000) break;
}
if (!editFindMatches.length) {
editFindState.textContent = '0/0';
return;
}
if (reset) {
var current = cm.getCursor('from');
var start = 0;
for (var i = 0; i < editFindMatches.length; i += 1) {
if (CodeMirror.cmpPos(editFindMatches[i].from, current) >= 0) { start = i; break; }
}
editFindSelect(start);
} else {
editFindSelect(0);
}
}
function editFindStep(backward) {
if (!editFinding) return;
if (!editFindMatches.length) { editFindRun(true); return; }
editFindSelect(editFindIndex + (backward ? -1 : 1));
}
function editFindReplaceOne() {
if (!cm || !editFinding) return;
var query = editFindInput.value;
if (!query) return;
if (!editFindMatches.length) editFindRun(true);
var match = editFindMatches[editFindIndex];
if (!match) return;
var replacement = editReplaceInput.value;
if (cm.getRange(match.from, match.to) !== cm.getSelection()) {
editFindSelect(editFindIndex);
return;
}
cm.replaceRange(replacement, match.from, match.to, '+input');
editFindRun(true);
}
function editFindReplaceAll() {
if (!cm || !editFinding) return;
var query = editFindInput.value;
if (!query) return;
if (!editFindMatches.length) editFindRun(true);
if (!editFindMatches.length) return;
var replacement = editReplaceInput.value;
var matches = editFindMatches.slice();
cm.operation(function() {
for (var i = matches.length - 1; i >= 0; i -= 1) {
cm.replaceRange(replacement, matches[i].from, matches[i].to, '+input');
}
});
editFindRun(true);
}
// Edit mode is per tab and owned by Rust; this only paints it.
function setEditMode(on) {
if (!on && editFinding) closeEditFind();
if (on && !cm && !cmDisabled) requestEditorSource();
if (on) {
document.body.classList.add('editing');
btnToggle.innerHTML = ICON_VIEW;
btnToggle.title = L_VIEW;
btnToggle.setAttribute('aria-label', L_VIEW);
} else {
document.body.classList.remove('editing');
btnToggle.innerHTML = ICON_EDIT;
btnToggle.title = L_EDIT;
btnToggle.setAttribute('aria-label', L_EDIT);
}
if (cm) {
document.body.classList.toggle('cm-active', on);
document.documentElement.classList.toggle('cm-editing', on);
if (on) cm.refresh();
} else {
document.documentElement.classList.remove('cm-editing');
ed.resize();
}
}
function enterEdit() {
if (document.body.classList.contains('home')) return;
var progress = currentScrollProgress();
pendingScrollRatio = progress;
setEditMode(true);
ed.focus();
restoreScrollProgress(progress);
if (window.ipc) window.ipc.postMessage('edit-mode:' + activeTabId + ':1');
}
function leaveEdit() {
var progress = currentScrollProgress();
if (dirty) save();
setEditMode(false);
restoreScrollProgress(progress);
if (window.ipc) window.ipc.postMessage('edit-mode:' + activeTabId + ':0');
}
window.__mdPreviewToggleEdit = function() {
if (inEdit()) leaveEdit(); else enterEdit();
};
window.__mdPreviewCloseActiveTab = function() {
if (activeTabId) requestTabAction('close', activeTabId);
};
tabOpen.addEventListener('click', newTab);
if (tabMenuNewWindow) {
tabMenuNewWindow.addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
var id = tabMenuTargetId;
hideTabMenu();
if (id) detachTab(id);
});
}
if (tabMenuReveal) {
tabMenuReveal.addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
var id = tabMenuTargetId;
hideTabMenu();
if (id) window.ipc.postMessage('reveal-tab:' + id);
});
}
tabsEl.addEventListener('pointerdown', function(e) {
if (e.button !== 0 || tabCount <= 1) return;
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
if (!tab || (e.target.closest && e.target.closest('.tab-close'))) return;
if (tab.classList.contains('home')) return;
hideTabMenu();
tabDrag = { id: tab.getAttribute('data-tab-id'), startY: e.clientY, element: tab, pointerId: e.pointerId, dragged: false };
try { tab.setPointerCapture(e.pointerId); } catch (err) {}
});
tabsEl.addEventListener('pointermove', function(e) {
if (!tabDrag || e.pointerId !== tabDrag.pointerId) return;
if (!tabDrag.dragged && Math.abs(e.clientY - tabDrag.startY) >= 24) {
tabDrag.dragged = true;
tabDrag.element.classList.add('dragging');
}
});
tabsEl.addEventListener('pointerup', function(e) {
if (!tabDrag || e.pointerId !== tabDrag.pointerId) return;
var drag = tabDrag;
tabDrag = null;
drag.element.classList.remove('dragging');
try {
if (drag.element.hasPointerCapture(e.pointerId)) drag.element.releasePointerCapture(e.pointerId);
} catch (err) {}
if (!drag.dragged) return;
suppressTabClickUntil = Date.now() + 350;
if (tabCount > 1) detachTab(drag.id);
});
tabsEl.addEventListener('pointercancel', function(e) {
if (!tabDrag || e.pointerId !== tabDrag.pointerId) return;
var drag = tabDrag;
tabDrag = null;
drag.element.classList.remove('dragging');
});
window.addEventListener('resize', hideTabMenu);
appEl.addEventListener('scroll', hideTabMenu, true);
window.addEventListener('blur', hideTabMenu);
document.addEventListener('click', function(e) {
if (Date.now() < suppressTabClickUntil) {
var suppressedTab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
if (suppressedTab) {
suppressTabClickUntil = 0;
e.preventDefault();
e.stopPropagation();
return;
}
}
if (tabMenu && !tabMenu.hidden) hideTabMenu();
var closeTab = e.target && e.target.closest ? e.target.closest('[data-close-tab]') : null;
if (closeTab) {
e.preventDefault();
e.stopPropagation();
requestTabAction('close', closeTab.getAttribute('data-close-tab'));
return;
}
var locateTab = e.target && e.target.closest ? e.target.closest('[data-locate-tab]') : null;
if (locateTab) {
e.preventDefault();
window.ipc.postMessage('locate-tab:' + locateTab.getAttribute('data-locate-tab'));
return;
}
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
if (tab) {
e.preventDefault();
requestTabAction('activate', tab.getAttribute('data-tab-id'));
return;
}
var newFileBtn = e.target && e.target.closest ? e.target.closest('[data-new-file]') : null;
if (newFileBtn) {
e.preventDefault();
newFile();
return;
}
var openBtn = e.target && e.target.closest ? e.target.closest('[data-open-file]') : null;
if (openBtn) {
e.preventDefault();
openFile();
return;
}
var recentBtn = e.target && e.target.closest ? e.target.closest('[data-recent-index]') : null;
if (recentBtn) {
e.preventDefault();
window.ipc.postMessage('open-recent:' + recentBtn.getAttribute('data-recent-index'));
}
});
findInput.addEventListener('compositionstart', function() { composingFind = true; });
findInput.addEventListener('compositionend', function() { composingFind = false; scheduleFind(); });
findInput.addEventListener('input', function(e) {
if (composingFind || e.isComposing) return;
scheduleFind();
});
findInput.addEventListener('keydown', function(e) {
if (composingFind || e.isComposing) return;
if (e.key === 'Enter') { e.preventDefault(); runFind(e.shiftKey); }
if (e.key === 'Escape') { e.preventDefault(); hideFind(); }
});
findPrev.addEventListener('click', function() { runFind(true); });
findNext.addEventListener('click', function() { runFind(false); });
findClose.addEventListener('click', hideFind);
editFindInput.addEventListener('input', function() {
if (editFindTimer) clearTimeout(editFindTimer);
editFindTimer = setTimeout(function() { editFindTimer = 0; editFindRun(true); }, 120);
});
editFindInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter') { e.preventDefault(); editFindStep(e.shiftKey); }
else if (e.key === 'Escape') { e.preventDefault(); closeEditFind(); }
});
editFindPrev.addEventListener('click', function() { editFindStep(true); });
editFindNextBtn.addEventListener('click', function() { editFindStep(false); });
editFindClose.addEventListener('click', closeEditFind);
editReplaceOne.addEventListener('click', editFindReplaceOne);
editReplaceAll.addEventListener('click', editFindReplaceAll);
editReplaceInput.addEventListener('keydown', function(e) {
if (e.key === 'Escape') { e.preventDefault(); closeEditFind(); }
});
btnToggle.addEventListener('click', function() {
window.__mdPreviewToggleEdit();
});
btnZoom.addEventListener('click', function(e) {
e.stopPropagation();
zoomControl.classList.toggle('open');
});
btnZoomOut.addEventListener('click', function() { changeZoom(-ZOOM_STEP); });
btnZoomReset.addEventListener('click', function() { applyZoom(100, true); });
btnZoomIn.addEventListener('click', function() { changeZoom(ZOOM_STEP); });
function onContentWheel(e) {
if (!e.ctrlKey) return;
e.preventDefault();
if (Math.abs(e.deltaY) < 0.01) return;
var now = Date.now();
if (now - zoomWheelAt < ZOOM_WHEEL_THROTTLE_MS) return;
zoomWheelAt = now;
changeZoom(e.deltaY < 0 ? ZOOM_STEP : -ZOOM_STEP);
}
window.addEventListener('wheel', onContentWheel, { passive: false });
function editorInput() { setDirty(true); scheduleAutosave(); autoResize(); updateDocumentStats(ta.value); }
window.addEventListener('resize', function() { if (inEdit()) ed.resize(); });
document.addEventListener('click', function(e) {
if (!zoomControl.contains(e.target)) zoomControl.classList.remove('open');
});
document.addEventListener('keydown', function(e) {
if (e.defaultPrevented) return;
if (e.key === 'Escape' && tabMenu && !tabMenu.hidden) {
hideTabMenu();
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'w' || e.key === 'W')) {
if (activeTabId) {
e.preventDefault();
requestTabAction('close', activeTabId);
}
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'n' || e.key === 'N')) {
e.preventDefault();
newFile();
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === '+' || e.key === '=' || e.code === 'NumpadAdd')) {
e.preventDefault();
changeZoom(ZOOM_STEP);
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === '-' || e.code === 'NumpadSubtract')) {
e.preventDefault();
changeZoom(-ZOOM_STEP);
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === '0' || e.code === 'Numpad0')) {
e.preventDefault();
applyZoom(100, true);
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'r' || e.key === 'R')) {
e.preventDefault();
if (!inEdit()) window.ipc.postMessage('refresh');
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'o' || e.key === 'O')) {
e.preventDefault();
openFile();
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'f' || e.key === 'F')) {
e.preventDefault();
if (inEdit()) { openEditFind(false); return; }
var seed = (document.body.classList.contains('finding') && document.activeElement === findInput) ? null : selectionSeed();
showFind(seed ? seed.text : '', seed ? seed.top : null);
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'h' || e.key === 'H') && inEdit()) {
e.preventDefault();
openEditFind(true);
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'e' || e.key === 'E')) {
e.preventDefault();
if (inEdit()) leaveEdit(); else enterEdit();
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 's' || e.key === 'S')) {
if (inEdit()) { e.preventDefault(); save(); }
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'p' || e.key === 'P')) {
e.preventDefault();
if (inEdit()) leaveEdit();
setTimeout(function(){ window.ipc.postMessage('print'); }, 0);
return;
}
if (e.key === 'Escape' && document.body.classList.contains('finding')) { hideFind(); return; }
});
// Called by Rust after a save (only preview is refreshed) or after an
// external file change (both preview + textarea are refreshed).
window.__setPreview = function(previewHtml, needsMath, needsMermaid) {
if (arguments.length > 1 && window.__setFeatureFlags) {
window.__setFeatureFlags(needsMath, needsMermaid);
}
document.getElementById('preview').innerHTML = previewHtml;
(window.requestIdleCallback || function(fn){ return setTimeout(fn, 0); })(function() {
if (typeof hljs !== 'undefined') hljs.highlightAll();
if (window.__enhancePreview) window.__enhancePreview();
});
};
window.__setBaseHref = function(baseHref) {
var base = document.getElementById('base-href');
if (!base) {
base = document.createElement('base');
base.id = 'base-href';
document.head.insertBefore(base, document.head.firstChild);
}
if (baseHref) base.setAttribute('href', baseHref);
else base.removeAttribute('href');
};
window.__markSaved = function(savedRaw) {
if (typeof savedRaw === 'string' && ed.value() !== savedRaw) {
window.ipc.postMessage('dirty:1');
return;
}
autosavePaused = false;
saveBlocked = false;
setDirty(false);
};
window.__markSaveBlocked = function() {
saveBlocked = true;
autosavePaused = true;
};
window.__mdPreviewPauseAutosave = function() {
cancelPendingAutosave();
autosavePaused = true;
};
window.__mdPreviewResolveExternalChange = function() {
cancelPendingAutosave();
window.ipc.postMessage('external-change:' + (dirty ? 'dirty' : 'clean'));
};
window.__setTabs = function(tabs) {
hideTabMenu();
tabs = Array.isArray(tabs) ? tabs : [];
tabCount = tabs.length;
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1;
tabsEl.textContent = '';
activeTabId = 0;
var showTabBar = HIDE_SINGLE_HOME_TAB
? (tabs.length > 1 || (tabs.length === 1 && !tabs[0].home))
: tabs.length > 0;
document.body.classList.toggle('has-tabs', showTabBar);
tabs.forEach(function(tab) {
var isHome = !!tab.home;
var item = document.createElement('div');
item.className = 'tab' + (isHome ? ' home' : '') + (tab.active ? ' active' : '') + (tab.missing ? ' missing' : '') + (tab.dirty ? ' dirty' : '');
item.setAttribute('data-tab-id', tab.id);
item.setAttribute('data-tab-path', isHome ? '' : tab.path);
item.setAttribute('role', 'button');
item.setAttribute('tabindex', '0');
item.title = isHome ? L_HOME : tab.path;
if (tab.active) activeTabId = tab.id;
var status = document.createElement('span');
status.className = 'tab-status';
status.textContent = tab.missing ? '!' : '';
var name = document.createElement('span');
name.className = 'tab-name';
name.textContent = isHome ? L_HOME : tab.name;
var close = document.createElement('button');
close.className = 'tab-close';
close.type = 'button';
close.setAttribute('data-close-tab', tab.id);
close.setAttribute('aria-label', 'Close ' + (isHome ? L_HOME : tab.name));
close.textContent = '×';
// A lone Home tab is the start-up page; there is nothing to close.
if (tabCount === 1 && isHome) close.hidden = true;
item.appendChild(status);
item.appendChild(name);
item.appendChild(close);
tabsEl.appendChild(item);
if (tab.active) requestAnimationFrame(function() { item.scrollIntoView({ block: 'nearest', inline: 'nearest' }); });
});
};
tabsEl.addEventListener('keydown', function(e) {
if (e.key !== 'Enter' && e.key !== ' ') return;
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
if (!tab) return;
e.preventDefault();
requestTabAction('activate', tab.getAttribute('data-tab-id'));
});
window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid, editing, scrollRatio) {
if (editFinding) closeEditFind();
document.body.classList.remove('home');
document.body.classList.remove('missing');
hideFind();
window.__setBaseHref(baseHref);
window.__setPreview(previewHtml, needsMath, needsMermaid);
if (!inEdit() || !dirty) {
autosavePaused = false;
ed.setValue(rawMd);
updateDocumentStats(rawMd);
setDirty(false);
}
setEditMode(!!editing);
restoreScrollProgress(typeof scrollRatio === 'number' ? scrollRatio : 0);
};
window.__setEmptyPreview = function(previewHtml) {
if (editFinding) closeEditFind();
document.body.classList.add('home');
document.body.classList.remove('missing');
setEditMode(false);
cancelPendingAutosave();
autosavePaused = false;
hideFind();
window.__setBaseHref('');
document.getElementById('preview').innerHTML = previewHtml;
ed.setValue('');
updateDocumentStats('');
setDirty(false);
appEl.scrollTop = 0;
};
window.__setMissing = function(previewHtml) {
if (editFinding) closeEditFind();
document.body.classList.remove('home');
document.body.classList.add('missing');
setEditMode(false);
cancelPendingAutosave();
autosavePaused = false;
hideFind();
window.__setBaseHref('');
document.getElementById('preview').innerHTML = previewHtml;
ed.setValue('');
updateDocumentStats('');
setDirty(false);
appEl.scrollTop = 0;
};
// Defer hljs parse + initial highlight to idle time.
// hljs itself is NOT inlined in this page — Rust injects it via
// evaluate_script once we tell it we're painted. Until that injection
// runs, typeof hljs === 'undefined' and highlightAll is skipped; once
// it lands, hljs.highlightAll() gets called by the injected bootstrap
// and __setPreview.
// Signal Rust after first paint (triggers hljs inject; bench mode exits).
requestAnimationFrame(function() {
requestAnimationFrame(function() {
if (window.ipc) window.ipc.postMessage('ready');
});
});
})();