fix(editor): add find/replace bar and tidy CodeMirror scrolling

This commit is contained in:
2026-11-06 09:00:35 +08:00
parent 715c8068f8
commit a58a94b05f
4 changed files with 237 additions and 14 deletions

View File

@@ -381,7 +381,7 @@ body.editing.cm-active { display: flex; flex-direction: column; height: 100vh; o
body.editing.cm-active .tabbar { flex: none; } body.editing.cm-active .tabbar { flex: none; }
body.editing.cm-active #app { flex: 1; min-height: 0; width: 100%; max-width: none; padding: 0; overflow: hidden; } body.editing.cm-active #app { flex: 1; min-height: 0; width: 100%; max-width: none; padding: 0; overflow: hidden; }
body.editing.cm-active #editor { display: none; } body.editing.cm-active #editor { display: none; }
body.editing.cm-active #cm-editor { display: block; height: 100%; padding: 10px 24px 0 14px; box-sizing: border-box; } body.editing.cm-active #cm-editor { display: block; height: 100%; padding: 10px 0 0 14px; box-sizing: border-box; }
#cm-editor .CodeMirror { height: 100%; background: transparent; color: inherit; font: 14px/1.6 "SF Mono","Menlo","Consolas",monospace; } #cm-editor .CodeMirror { height: 100%; background: transparent; color: inherit; font: 14px/1.6 "SF Mono","Menlo","Consolas",monospace; }
#cm-editor .CodeMirror-gutters { background: transparent; border-right: 1px solid rgba(128,128,128,.18); } #cm-editor .CodeMirror-gutters { background: transparent; border-right: 1px solid rgba(128,128,128,.18); }
#cm-editor .CodeMirror-linenumber { color: #9aa0a6; padding: 0 10px 0 4px; } #cm-editor .CodeMirror-linenumber { color: #9aa0a6; padding: 0 10px 0 4px; }
@@ -405,7 +405,9 @@ body.editing.cm-active #cm-editor { display: block; height: 100%; padding: 10px
#cm-editor .CodeMirror-dialog input { font: inherit; } #cm-editor .CodeMirror-dialog input { font: inherit; }
#cm-editor .CodeMirror-dialog button { color: #1a1a1a; } #cm-editor .CodeMirror-dialog button { color: #1a1a1a; }
#cm-editor .CodeMirror-foldmarker { color: #0550ae; text-shadow: none; background: rgba(9,105,218,.08); border-radius: 3px; padding: 0 .3em; } #cm-editor .CodeMirror-foldmarker { color: #0550ae; text-shadow: none; background: rgba(9,105,218,.08); border-radius: 3px; padding: 0 .3em; }
#cm-editor .CodeMirror-lines { padding: 4px 0 24px; } #cm-editor .CodeMirror-lines { padding: 4px 24px 24px 0; }
#cm-editor .CodeMirror-scroll { overflow-x: hidden !important; }
#cm-editor .CodeMirror-scrollbar-filler { display: none !important; }
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
#cm-editor .CodeMirror { color: #d4d4d4; } #cm-editor .CodeMirror { color: #d4d4d4; }
@@ -429,3 +431,13 @@ body.editing.cm-active #cm-editor { display: block; height: 100%; padding: 10px
@media print { @media print {
#cm-editor { display: none !important; } #cm-editor { display: none !important; }
} }
/* Edit-mode find/replace bar: same look as the preview findbar. */
html.cm-editing { overflow: hidden; scrollbar-gutter: auto; }
#edit-findbar { top: calc(var(--chrome-top) + 8px); z-index: 130; }
body.edit-finding #edit-findbar { display: flex; }
#edit-findbar .edit-replace-group { display: flex; align-items: center; gap: 6px; }
#edit-findbar .edit-replace-group[hidden] { display: none; }
#edit-findbar #edit-replace-input { width: 160px; }
#edit-findbar button.edit-replace-btn { width: auto; min-width: 54px; padding: 0 8px; font-size: 12px; }
#cm-editor .cm-edit-find-hit { background: rgba(255, 213, 0, .38); }

View File

@@ -25,6 +25,18 @@ __MDP_PAGE_CSS__
<button id="find-next" title="Next" aria-label="Next"></button> <button id="find-next" title="Next" aria-label="Next"></button>
<button id="find-close" title="Close" aria-label="Close"></button> <button id="find-close" title="Close" aria-label="Close"></button>
</div> </div>
<div class="findbar" id="edit-findbar" role="search" hidden>
<input id="edit-find-input" type="search" placeholder="__MDP_SEARCH_PLACEHOLDER__" aria-label="__MDP_SEARCH_PLACEHOLDER__">
<span id="edit-find-state"></span>
<button id="edit-find-prev" title="Previous" aria-label="Previous"></button>
<button id="edit-find-next" title="Next" aria-label="Next"></button>
<button id="edit-find-close" title="Close" aria-label="Close"></button>
<span class="edit-replace-group" id="edit-replace-group" hidden>
<input id="edit-replace-input" type="text" placeholder="Replace with" aria-label="Replace with">
<button id="edit-replace-one" class="edit-replace-btn" type="button">Replace</button>
<button id="edit-replace-all" class="edit-replace-btn" type="button">All</button>
</span>
</div>
<div id="app"> <div id="app">
<div id="preview">__MDP_PREVIEW_HTML__</div> <div id="preview">__MDP_PREVIEW_HTML__</div>
<textarea id="editor" spellcheck="false">__MDP_RAW_MD_ESCAPED__</textarea> <textarea id="editor" spellcheck="false">__MDP_RAW_MD_ESCAPED__</textarea>

View File

@@ -20,6 +20,16 @@
var findPrev = document.getElementById('find-prev'); var findPrev = document.getElementById('find-prev');
var findNext = document.getElementById('find-next'); var findNext = document.getElementById('find-next');
var findClose = document.getElementById('find-close'); 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 tabsEl = document.getElementById('tabs');
var docStats = document.getElementById('doc-stats'); var docStats = document.getElementById('doc-stats');
var tabOpen = document.getElementById('tab-open'); var tabOpen = document.getElementById('tab-open');
@@ -49,6 +59,11 @@
// original start-up page. Set to false to keep the tab bar always on. // original start-up page. Set to false to keep the tab bar always on.
var HIDE_SINGLE_HOME_TAB = true; var HIDE_SINGLE_HOME_TAB = true;
var findHits = []; var findHits = [];
var editFinding = false;
var editFindMatches = [];
var editFindIndex = -1;
var editFindOverlay = null;
var editFindTimer = 0;
var currentFindHit = -1; var currentFindHit = -1;
var lastFindQuery = ''; var lastFindQuery = '';
var STAT_WORDS = '__MDP_STAT_WORDS_JS__'; var STAT_WORDS = '__MDP_STAT_WORDS_JS__';
@@ -79,6 +94,9 @@
findPrev.innerHTML = ICON_UP; findPrev.innerHTML = ICON_UP;
findNext.innerHTML = ICON_DOWN; findNext.innerHTML = ICON_DOWN;
findClose.innerHTML = ICON_CLOSE; 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 inEdit() { return document.body.classList.contains('editing'); }
function textSegments(text) { function textSegments(text) {
@@ -131,12 +149,15 @@
function restoreScrollProgress(progress) { function restoreScrollProgress(progress) {
if (cm && inEdit()) { if (cm && inEdit()) {
pendingScrollRatio = progress; pendingScrollRatio = progress;
var cmToken = ++scrollRestoreToken;
var applyCm = function() { var applyCm = function() {
if (cmToken !== scrollRestoreToken) return;
var info = cm.getScrollInfo(); var info = cm.getScrollInfo();
var cmMax = Math.max(info.height - info.clientHeight, 0); var cmMax = Math.max(info.height - info.clientHeight, 0);
cm.scrollTo(null, cmMax * progress); cm.scrollTo(null, cmMax * progress);
}; };
requestAnimationFrame(function() { requestAnimationFrame(function() {
if (cmToken !== scrollRestoreToken) return;
cm.refresh(); cm.refresh();
applyCm(); applyCm();
requestAnimationFrame(applyCm); requestAnimationFrame(applyCm);
@@ -650,9 +671,9 @@
mode: { name: 'markdown', highlightFormatting: true }, mode: { name: 'markdown', highlightFormatting: true },
lineNumbers: true, lineNumbers: true,
lineWrapping: true, lineWrapping: true,
foldGutter: { rangeFinder: markdownFoldRange, minFoldSize: 1 }, foldGutter: { rangeFinder: markdownFoldRange, minFoldSize: 0 },
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'], gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
foldOptions: { rangeFinder: markdownFoldRange, minFoldSize: 1 }, foldOptions: { rangeFinder: markdownFoldRange, minFoldSize: 0 },
indentUnit: 2, indentUnit: 2,
tabSize: 2, tabSize: 2,
indentWithTabs: false, indentWithTabs: false,
@@ -671,13 +692,13 @@
if (removed) instance.replaceRange('', { line: cursor.line, ch: 0 }, { line: cursor.line, ch: removed }); if (removed) instance.replaceRange('', { line: cursor.line, ch: 0 }, { line: cursor.line, ch: removed });
}, },
'Enter': function(instance) { instance.execCommand('newlineAndIndent'); }, 'Enter': function(instance) { instance.execCommand('newlineAndIndent'); },
'Ctrl-F': function(instance) { instance.execCommand('find'); }, 'Ctrl-F': function() { openEditFind(false); },
'Cmd-F': function(instance) { instance.execCommand('find'); }, 'Cmd-F': function() { openEditFind(false); },
'Ctrl-H': function(instance) { instance.execCommand('replace'); }, 'Ctrl-H': function() { openEditFind(true); },
'Cmd-H': function(instance) { instance.execCommand('replace'); }, 'Cmd-H': function() { openEditFind(true); },
'Ctrl-S': function() { save(); }, 'Ctrl-S': function() { save(); },
'Cmd-S': function() { save(); }, 'Cmd-S': function() { save(); },
'Esc': function() { leaveEdit(); } 'Esc': function() { if (editFinding) closeEditFind(); }
} }
}); });
} catch (err) { } catch (err) {
@@ -695,6 +716,7 @@
cm.on('scroll', reportScroll); cm.on('scroll', reportScroll);
updateEditorZoom(); updateEditorZoom();
document.body.classList.toggle('cm-active', inEdit()); document.body.classList.toggle('cm-active', inEdit());
document.documentElement.classList.toggle('cm-editing', inEdit());
if (inEdit()) { if (inEdit()) {
ed.focus(); ed.focus();
restoreScrollProgress(pendingScrollRatio); restoreScrollProgress(pendingScrollRatio);
@@ -774,8 +796,132 @@
if (end <= line) return null; if (end <= line) return null;
return { from: CodeMirror.Pos(line + 1, 0), to: CodeMirror.Pos(end, instance.getLine(end).length) }; return { from: CodeMirror.Pos(line + 1, 0), to: CodeMirror.Pos(end, instance.getLine(end).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. // Edit mode is per tab and owned by Rust; this only paints it.
function setEditMode(on) { function setEditMode(on) {
if (!on && editFinding) closeEditFind();
if (on && !cm && !cmDisabled) requestEditorSource(); if (on && !cm && !cmDisabled) requestEditorSource();
if (on) { if (on) {
document.body.classList.add('editing'); document.body.classList.add('editing');
@@ -790,8 +936,10 @@
} }
if (cm) { if (cm) {
document.body.classList.toggle('cm-active', on); document.body.classList.toggle('cm-active', on);
document.documentElement.classList.toggle('cm-editing', on);
if (on) cm.refresh(); if (on) cm.refresh();
} else { } else {
document.documentElement.classList.remove('cm-editing');
ed.resize(); ed.resize();
} }
} }
@@ -936,6 +1084,22 @@
findPrev.addEventListener('click', function() { runFind(true); }); findPrev.addEventListener('click', function() { runFind(true); });
findNext.addEventListener('click', function() { runFind(false); }); findNext.addEventListener('click', function() { runFind(false); });
findClose.addEventListener('click', hideFind); 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() { btnToggle.addEventListener('click', function() {
window.__mdPreviewToggleEdit(); window.__mdPreviewToggleEdit();
@@ -1007,12 +1171,17 @@
return; return;
} }
if ((e.metaKey || e.ctrlKey) && (e.key === 'f' || e.key === 'F')) { 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(); 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); showFind(seed ? seed.text : '', seed ? seed.top : null);
return; 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')) { if ((e.metaKey || e.ctrlKey) && (e.key === 'e' || e.key === 'E')) {
e.preventDefault(); e.preventDefault();
if (inEdit()) leaveEdit(); else enterEdit(); if (inEdit()) leaveEdit(); else enterEdit();
@@ -1029,7 +1198,6 @@
return; return;
} }
if (e.key === 'Escape' && document.body.classList.contains('finding')) { hideFind(); 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 // Called by Rust after a save (only preview is refreshed) or after an
@@ -1125,6 +1293,7 @@
requestTabAction('activate', tab.getAttribute('data-tab-id')); requestTabAction('activate', tab.getAttribute('data-tab-id'));
}); });
window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid, editing, scrollRatio) { window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid, editing, scrollRatio) {
if (editFinding) closeEditFind();
document.body.classList.remove('home'); document.body.classList.remove('home');
document.body.classList.remove('missing'); document.body.classList.remove('missing');
hideFind(); hideFind();
@@ -1140,6 +1309,7 @@
restoreScrollProgress(typeof scrollRatio === 'number' ? scrollRatio : 0); restoreScrollProgress(typeof scrollRatio === 'number' ? scrollRatio : 0);
}; };
window.__setEmptyPreview = function(previewHtml) { window.__setEmptyPreview = function(previewHtml) {
if (editFinding) closeEditFind();
document.body.classList.add('home'); document.body.classList.add('home');
document.body.classList.remove('missing'); document.body.classList.remove('missing');
setEditMode(false); setEditMode(false);
@@ -1154,6 +1324,7 @@
window.scrollTo(0, 0); window.scrollTo(0, 0);
}; };
window.__setMissing = function(previewHtml) { window.__setMissing = function(previewHtml) {
if (editFinding) closeEditFind();
document.body.classList.remove('home'); document.body.classList.remove('home');
document.body.classList.add('missing'); document.body.classList.add('missing');
setEditMode(false); setEditMode(false);

View File

@@ -250,11 +250,39 @@ mod tests {
assert!(page.contains("CM_MAX_BYTES = 2 * 1024 * 1024")); assert!(page.contains("CM_MAX_BYTES = 2 * 1024 * 1024"));
assert!(page.contains("CodeMirror-linenumbers")); assert!(page.contains("CodeMirror-linenumbers"));
assert!(page.contains("rangeFinder: markdownFoldRange")); assert!(page.contains("rangeFinder: markdownFoldRange"));
assert!(page.contains("instance.execCommand('find')")); assert!(page.contains("openEditFind(false)"));
assert!(page.contains("instance.execCommand('replace')")); assert!(page.contains("openEditFind(true)"));
assert!(!page.contains("CodeMirror.defineMode")); assert!(!page.contains("CodeMirror.defineMode"));
} }
#[test]
fn edit_mode_find_bar_has_clickable_controls_and_no_escape_exit() {
let strings = Strings::english();
let page = build_page(
&md_to_html("# A\n\ntext"),
"# A\n\ntext",
None,
EnhanceFlags::default(),
&strings,
false,
);
assert!(page.contains(r#"id="edit-findbar""#));
assert!(page.contains(r#"id="edit-find-input""#));
assert!(page.contains(r#"id="edit-find-prev""#));
assert!(page.contains(r#"id="edit-find-next""#));
assert!(page.contains(r#"id="edit-replace-input""#));
assert!(page.contains(r#"id="edit-replace-all""#));
assert!(page.contains("function openEditFind(replaceMode)"));
assert!(page.contains("function closeEditFind()"));
assert!(page.contains("cm.getSearchCursor(query"));
assert!(page.contains("document.documentElement.classList.toggle('cm-editing'"));
assert!(page.contains("minFoldSize: 0"));
// Escape closes the find bar; it must not leave edit mode anymore.
assert!(!page.contains("if (e.key === 'Escape' && inEdit()) { leaveEdit(); }"));
assert!(!page.contains("'Esc': function() { leaveEdit(); }"));
}
#[test] #[test]
fn page_expands_multi_column_tables() { fn page_expands_multi_column_tables() {
let strings = Strings::english(); let strings = Strings::english();