(function(){ var ICON_EDIT = ''; var ICON_VIEW = ''; var ICON_ZOOM = ''; var ICON_UP = ''; var ICON_DOWN = ''; var ICON_CLOSE = ''; 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 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 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 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; // 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; 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 (inEdit()) ed.resize(); } function changeZoom(delta) { applyZoom(zoomPercent + delta, true); } function currentScrollProgress() { var root = document.documentElement; var max = Math.max(root.scrollHeight - window.innerHeight, 0); var y = window.scrollY || root.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) { var token = ++scrollRestoreToken; function restore() { if (token !== scrollRestoreToken) return; var max = Math.max(document.documentElement.scrollHeight - window.innerHeight, 0); window.scrollTo(window.scrollX || 0, 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); } window.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 x = window.scrollX || document.documentElement.scrollLeft || 0; var y = window.scrollY || document.documentElement.scrollTop || 0; ta.style.height = 'auto'; var h = Math.max(ta.scrollHeight, window.innerHeight); ta.style.height = h + 'px'; window.scrollTo(x, 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); } }; } // Edit mode is per tab and owned by Rust; this only paints it. function setEditMode(on) { 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); } ed.resize(); } function enterEdit() { if (document.body.classList.contains('home')) return; var progress = currentScrollProgress(); 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); window.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); 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.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')) { if (inEdit()) return; var seed = (document.body.classList.contains('finding') && document.activeElement === findInput) ? null : selectionSeed(); e.preventDefault(); showFind(seed ? seed.text : '', seed ? seed.top : null); 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; } if (e.key === 'Escape' && inEdit()) { leaveEdit(); } }); // 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) { 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) { 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); window.scrollTo(0, 0); }; window.__setMissing = function(previewHtml) { 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); window.scrollTo(0, 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'); }); }); })();