fix: remember edit mode and scroll position per tab
Edit mode used to live on the window, so switching tabs carried the mode across documents, and the viewport stayed at whatever pixel the previous document had scrolled to. - DocumentTab now owns editing and scroll_ratio. - The page reports edit-mode and scroll changes by tab id; Rust restores them when the tab is activated. Reports carry the id so a late report cannot land on the tab that just became active. - Detaching a tab keeps its edit mode instead of forcing preview.
This commit is contained in:
218
src/main.rs
218
src/main.rs
@@ -1619,8 +1619,12 @@ body.editing #app {{ max-width: none; padding: 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);
|
||||
}}
|
||||
@@ -1629,7 +1633,23 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
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(ta.value);
|
||||
@@ -1727,7 +1747,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
window.__mdPreviewSave = save;
|
||||
function requestTabAction(action, id) {{
|
||||
cancelPendingAutosave();
|
||||
var message = 'tab-action:' + action + ':' + id;
|
||||
var message = 'tab-action:' + action + ':' + id + ':' + currentScrollProgress().toFixed(4);
|
||||
if (dirty) {{
|
||||
if (saveBlocked) {{
|
||||
if (!window.confirm(window.__mdPreviewCannotSave || 'Discard unsaved changes?')) return;
|
||||
@@ -2055,36 +2075,43 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
insertNewlineWithIndent();
|
||||
}}
|
||||
}});
|
||||
// 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);
|
||||
}}
|
||||
autoResize();
|
||||
}}
|
||||
function enterEdit() {{
|
||||
if (document.body.classList.contains('home')) return;
|
||||
var progress = currentScrollProgress();
|
||||
document.body.classList.add('editing');
|
||||
btnToggle.innerHTML = ICON_VIEW;
|
||||
btnToggle.title = L_VIEW;
|
||||
btnToggle.setAttribute('aria-label', L_VIEW);
|
||||
autoResize();
|
||||
setEditMode(true);
|
||||
try {{
|
||||
ta.focus({{ preventScroll: true }});
|
||||
}} catch (_) {{
|
||||
ta.focus();
|
||||
}}
|
||||
restoreScrollProgress(progress);
|
||||
if (window.ipc) window.ipc.postMessage('edit-mode:' + activeTabId + ':1');
|
||||
}}
|
||||
function leaveEdit() {{
|
||||
var progress = currentScrollProgress();
|
||||
if (dirty) save();
|
||||
document.body.classList.remove('editing');
|
||||
btnToggle.innerHTML = ICON_EDIT;
|
||||
btnToggle.title = L_EDIT;
|
||||
btnToggle.setAttribute('aria-label', L_EDIT);
|
||||
setEditMode(false);
|
||||
restoreScrollProgress(progress);
|
||||
if (window.ipc) window.ipc.postMessage('edit-mode:' + activeTabId + ':0');
|
||||
}}
|
||||
window.__mdPreviewToggleEdit = function() {{
|
||||
if (inEdit()) leaveEdit(); else enterEdit();
|
||||
}};
|
||||
window.__mdPreviewEnterEdit = function() {{
|
||||
if (!inEdit()) enterEdit();
|
||||
}};
|
||||
window.__mdPreviewCloseActiveTab = function() {{
|
||||
if (activeTabId) requestTabAction('close', activeTabId);
|
||||
}};
|
||||
@@ -2394,7 +2421,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
e.preventDefault();
|
||||
requestTabAction('activate', tab.getAttribute('data-tab-id'));
|
||||
}});
|
||||
window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid) {{
|
||||
window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid, editing, scrollRatio) {{
|
||||
document.body.classList.remove('home');
|
||||
document.body.classList.remove('missing');
|
||||
hideFind();
|
||||
@@ -2405,16 +2432,14 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
ta.value = rawMd;
|
||||
updateDocumentStats(rawMd);
|
||||
setDirty(false);
|
||||
if (inEdit()) autoResize();
|
||||
}}
|
||||
setEditMode(!!editing);
|
||||
restoreScrollProgress(typeof scrollRatio === 'number' ? scrollRatio : 0);
|
||||
}};
|
||||
window.__setEmptyPreview = function(previewHtml) {{
|
||||
document.body.classList.add('home');
|
||||
document.body.classList.remove('missing');
|
||||
document.body.classList.remove('editing');
|
||||
btnToggle.innerHTML = ICON_EDIT;
|
||||
btnToggle.title = L_EDIT;
|
||||
btnToggle.setAttribute('aria-label', L_EDIT);
|
||||
setEditMode(false);
|
||||
cancelPendingAutosave();
|
||||
autosavePaused = false;
|
||||
hideFind();
|
||||
@@ -2428,10 +2453,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
|
||||
window.__setMissing = function(previewHtml) {{
|
||||
document.body.classList.remove('home');
|
||||
document.body.classList.add('missing');
|
||||
document.body.classList.remove('editing');
|
||||
btnToggle.innerHTML = ICON_EDIT;
|
||||
btnToggle.title = L_EDIT;
|
||||
btnToggle.setAttribute('aria-label', L_EDIT);
|
||||
setEditMode(false);
|
||||
cancelPendingAutosave();
|
||||
autosavePaused = false;
|
||||
hideFind();
|
||||
@@ -2552,7 +2574,7 @@ mod tests {
|
||||
"startup HTML has {} bytes",
|
||||
page.len()
|
||||
);
|
||||
assert!(session.active().unwrap().edit_on_open);
|
||||
assert!(session.active().unwrap().editing);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
@@ -2682,9 +2704,18 @@ mod tests {
|
||||
fn fenced_code_blocks_keep_double_equals_literal() {
|
||||
let html = md_to_html("```csharp\nif (m_Profile == null) {\n return a == b;\n}\n```");
|
||||
|
||||
assert!(html.contains("m_Profile == null"), "comparison must stay literal");
|
||||
assert!(html.contains("a == b"), "every comparison must be preserved");
|
||||
assert!(!html.contains("mdp-mark"), "code blocks must not get highlight markup");
|
||||
assert!(
|
||||
html.contains("m_Profile == null"),
|
||||
"comparison must stay literal"
|
||||
);
|
||||
assert!(
|
||||
html.contains("a == b"),
|
||||
"every comparison must be preserved"
|
||||
);
|
||||
assert!(
|
||||
!html.contains("mdp-mark"),
|
||||
"code blocks must not get highlight markup"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3003,6 +3034,9 @@ mod tests {
|
||||
assert!(page.contains("tabMenuNewWindow.disabled = tabCount <= 1"));
|
||||
assert!(page.contains("updateDocumentStats"));
|
||||
assert!(page.contains("restoreScrollProgress"));
|
||||
assert!(page.contains("postMessage('scroll:' + activeTabId"));
|
||||
assert!(page.contains("setEditMode(!!editing)"));
|
||||
assert!(page.contains("postMessage('edit-mode:' + activeTabId"));
|
||||
assert!(page.contains("postMessage('zoom:' + zoomPercent)"));
|
||||
assert!(page.contains("window.__mdPreviewSetZoom"));
|
||||
assert!(page.contains("id=\"btn-zoom-in\""));
|
||||
@@ -3013,7 +3047,9 @@ mod tests {
|
||||
assert!(page.contains("var ZOOM_STEP = 5"));
|
||||
assert!(page.contains("ZOOM_WHEEL_THROTTLE_MS = 90"));
|
||||
assert!(page.contains("if (!e.ctrlKey) return;"));
|
||||
assert!(page.contains("window.addEventListener('wheel', onContentWheel, { passive: false })"));
|
||||
assert!(
|
||||
page.contains("window.addEventListener('wheel', onContentWheel, { passive: false })")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3051,8 +3087,8 @@ mod tests {
|
||||
let missing_start = page.find("window.__setMissing = function").unwrap();
|
||||
let empty_handler = &page[empty_start..missing_start];
|
||||
|
||||
assert!(empty_handler.contains("document.body.classList.remove('editing')"));
|
||||
assert!(empty_handler.contains("btnToggle.innerHTML = ICON_EDIT"));
|
||||
assert!(empty_handler.contains("document.body.classList.add('home')"));
|
||||
assert!(empty_handler.contains("setEditMode(false)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3105,14 +3141,7 @@ mod tests {
|
||||
assert!(html.contains(r#"<div class="icon">#</div>"#));
|
||||
assert!(!html.contains("empty-mark"));
|
||||
|
||||
let page = build_page(
|
||||
&html,
|
||||
"",
|
||||
None,
|
||||
EnhanceFlags::default(),
|
||||
&strings,
|
||||
true,
|
||||
);
|
||||
let page = build_page(&html, "", None, EnhanceFlags::default(), &strings, true);
|
||||
assert!(page.contains(".empty.has-recent"));
|
||||
assert!(!page.contains(".empty.has-recent .recent { max-height"));
|
||||
assert!(page.contains("<body class=\"home\">"));
|
||||
@@ -4123,6 +4152,35 @@ fn focus_open_tab(
|
||||
true
|
||||
}
|
||||
|
||||
/// Write the active tab's file and remember the write as our own so the file
|
||||
/// watcher does not treat it as an external change. Returns false when nothing
|
||||
/// was written (no active file, or the write failed and SaveFailed was sent).
|
||||
fn save_active_file(
|
||||
session: &Arc<Mutex<DocumentSession>>,
|
||||
last_self_write: &Arc<Mutex<Option<SelfWriteRecord>>>,
|
||||
proxy: &EventLoopProxy<UserEvent>,
|
||||
window_id: WindowId,
|
||||
content: &str,
|
||||
) -> bool {
|
||||
let Some(path) = session.lock().unwrap().active_path().map(Path::to_path_buf) else {
|
||||
return false;
|
||||
};
|
||||
*last_self_write.lock().unwrap() = Some(SelfWriteRecord {
|
||||
path: path.clone(),
|
||||
content: content.to_string(),
|
||||
});
|
||||
match fs::write(&path, content) {
|
||||
Ok(()) => {
|
||||
let _ = proxy.send_event(UserEvent::FileSaved(window_id, path));
|
||||
true
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = proxy.send_event(UserEvent::SaveFailed(window_id, path, error.to_string()));
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn update_tabs(webview: &WebView, session: &DocumentSession) {
|
||||
let state = tabs_json(session);
|
||||
let _ = webview.evaluate_script(&format!("if(window.__setTabs)window.__setTabs({state});"));
|
||||
@@ -4191,26 +4249,21 @@ fn render_active_document(
|
||||
let flags = enhance_flags_for(&raw);
|
||||
*enhance_flags.lock().unwrap() = flags;
|
||||
let _ = webview.evaluate_script(&format!(
|
||||
"if(window.__setContent)window.__setContent('{}', '{}', '{}', {}, {});",
|
||||
"if(window.__setContent)window.__setContent({}, '{}', '{}', '{}', {}, {}, {}, {});",
|
||||
active.id,
|
||||
escape_js(&html),
|
||||
escape_js(&raw),
|
||||
escape_js(&base_href),
|
||||
flags.math,
|
||||
flags.mermaid
|
||||
flags.mermaid,
|
||||
active.editing,
|
||||
active.scroll_ratio
|
||||
));
|
||||
for script in build_enhancer_bootstrap(flags, *loaded_enhancers) {
|
||||
let _ = webview.evaluate_script(&script);
|
||||
}
|
||||
loaded_enhancers.math |= flags.math;
|
||||
loaded_enhancers.mermaid |= flags.mermaid;
|
||||
if active.edit_on_open {
|
||||
if let Some(tab) = session.get_mut(active.id) {
|
||||
tab.edit_on_open = false;
|
||||
}
|
||||
let _ = webview.evaluate_script(
|
||||
"if(window.__mdPreviewEnterEdit)window.__mdPreviewEnterEdit();",
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
if let Some(tab) = session.get_mut(active.id) {
|
||||
@@ -4343,33 +4396,27 @@ fn build_webview(
|
||||
.split_once('\n')
|
||||
.map(|(header, content)| (header, Some(content)))
|
||||
.unwrap_or((rest, None));
|
||||
let mut parts = header.splitn(2, ':');
|
||||
let mut parts = header.splitn(3, ':');
|
||||
let action = parts.next().unwrap_or("");
|
||||
let id = parts.next().and_then(|value| value.parse::<u64>().ok());
|
||||
// The page reports where the tab it is leaving was scrolled to.
|
||||
let scroll_ratio = parts.next().and_then(|value| value.parse::<f32>().ok());
|
||||
let Some(id) = id else {
|
||||
return;
|
||||
};
|
||||
if let Some(ratio) = scroll_ratio {
|
||||
session.lock().unwrap().set_active_scroll_ratio(ratio);
|
||||
}
|
||||
if let Some(content) = pending_content {
|
||||
let path = session.lock().unwrap().active_path().map(Path::to_path_buf);
|
||||
let Some(path) = path else {
|
||||
// A tab action is only safe once the pending edit is written.
|
||||
if !save_active_file(
|
||||
&session,
|
||||
&last_self_write,
|
||||
&proxy_for_ipc,
|
||||
window_id,
|
||||
content,
|
||||
) {
|
||||
return;
|
||||
};
|
||||
*last_self_write.lock().unwrap() = Some(SelfWriteRecord {
|
||||
path: path.clone(),
|
||||
content: content.to_string(),
|
||||
});
|
||||
match fs::write(&path, content) {
|
||||
Ok(()) => {
|
||||
let _ = proxy_for_ipc.send_event(UserEvent::FileSaved(window_id, path));
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = proxy_for_ipc.send_event(UserEvent::SaveFailed(
|
||||
window_id,
|
||||
path.clone(),
|
||||
error.to_string(),
|
||||
));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
match action {
|
||||
@@ -4418,23 +4465,23 @@ fn build_webview(
|
||||
let _ = proxy_for_ipc.send_event(UserEvent::FileChanged(window_id, path));
|
||||
}
|
||||
} else if let Some(content) = body.strip_prefix("save:") {
|
||||
let path = session.lock().unwrap().active_path().map(Path::to_path_buf);
|
||||
if let Some(path) = path {
|
||||
*last_self_write.lock().unwrap() = Some(SelfWriteRecord {
|
||||
path: path.clone(),
|
||||
content: content.to_string(),
|
||||
});
|
||||
match fs::write(&path, content) {
|
||||
Ok(()) => {
|
||||
let _ = proxy_for_ipc.send_event(UserEvent::FileSaved(window_id, path));
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = proxy_for_ipc.send_event(UserEvent::SaveFailed(
|
||||
window_id,
|
||||
path.clone(),
|
||||
error.to_string(),
|
||||
));
|
||||
}
|
||||
save_active_file(
|
||||
&session,
|
||||
&last_self_write,
|
||||
&proxy_for_ipc,
|
||||
window_id,
|
||||
content,
|
||||
);
|
||||
} else if let Some(rest) = body.strip_prefix("scroll:") {
|
||||
if let Some((id, ratio)) = rest.split_once(':') {
|
||||
if let (Ok(id), Ok(ratio)) = (id.parse::<u64>(), ratio.parse::<f32>()) {
|
||||
session.lock().unwrap().set_tab_scroll_ratio(id, ratio);
|
||||
}
|
||||
}
|
||||
} else if let Some(rest) = body.strip_prefix("edit-mode:") {
|
||||
if let Some((id, mode)) = rest.split_once(':') {
|
||||
if let Ok(id) = id.parse::<u64>() {
|
||||
session.lock().unwrap().set_tab_editing(id, mode == "1");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5069,7 +5116,6 @@ fn main() {
|
||||
let mut moved = tab;
|
||||
moved.dirty = false;
|
||||
moved.missing = false;
|
||||
moved.edit_on_open = false;
|
||||
let new_session = DocumentSession::with_tab(moved);
|
||||
let new_window_id = match create_window_with_session(
|
||||
target,
|
||||
|
||||
Reference in New Issue
Block a user