diff --git a/src/main.rs b/src/main.rs
index 6c3eb14..cbeaca4 100644
--- a/src/main.rs
+++ b/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#"
#
"#));
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(""));
@@ -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>,
+ last_self_write: &Arc>>,
+ proxy: &EventLoopProxy,
+ 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::().ok());
+ // The page reports where the tab it is leaving was scrolled to.
+ let scroll_ratio = parts.next().and_then(|value| value.parse::().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::(), ratio.parse::()) {
+ 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::() {
+ 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,
diff --git a/src/session.rs b/src/session.rs
index f366e2a..0a0924b 100644
--- a/src/session.rs
+++ b/src/session.rs
@@ -1,14 +1,19 @@
use std::fs;
use std::path::{Path, PathBuf};
-#[derive(Clone, Debug, PartialEq, Eq)]
+#[derive(Clone, Debug, PartialEq)]
pub struct DocumentTab {
pub id: u64,
/// `None` marks the built-in Home tab; Home has no file on disk.
pub path: Option,
pub dirty: bool,
pub missing: bool,
- pub edit_on_open: bool,
+ /// Edit mode belongs to the tab, so switching tabs restores the mode the
+ /// tab was left in instead of carrying one global mode across documents.
+ pub editing: bool,
+ /// Viewport position as a 0.0 (top) ..= 1.0 (bottom) fraction. Stores a
+ /// ratio rather than pixels so zoom and reflow do not move the reader.
+ pub scroll_ratio: f32,
}
impl DocumentTab {
@@ -37,7 +42,7 @@ impl DocumentSession {
.find(|tab| tab.path.as_deref() == Some(path.as_path()))
{
tab.missing = !path.exists();
- tab.edit_on_open |= edit_on_open;
+ tab.editing |= edit_on_open;
self.active_id = Some(tab.id);
return tab.id;
}
@@ -50,7 +55,8 @@ impl DocumentSession {
path: Some(path),
dirty: false,
missing,
- edit_on_open,
+ editing: edit_on_open,
+ scroll_ratio: 0.0,
});
self.active_id = Some(id);
id
@@ -65,7 +71,8 @@ impl DocumentSession {
path: None,
dirty: false,
missing: false,
- edit_on_open: false,
+ editing: false,
+ scroll_ratio: 0.0,
});
self.active_id = Some(id);
id
@@ -92,7 +99,7 @@ impl DocumentSession {
.find(|tab| tab.id != active_id && tab.path.as_deref() == Some(path.as_path()))
{
existing.missing = !path.exists();
- existing.edit_on_open |= edit_on_open;
+ existing.editing |= edit_on_open;
let existing_id = existing.id;
// The blank tab did its job; drop it the way a browser would.
self.tabs.retain(|tab| tab.id != active_id);
@@ -109,7 +116,8 @@ impl DocumentSession {
tab.path = Some(path);
tab.missing = missing;
tab.dirty = false;
- tab.edit_on_open = edit_on_open;
+ tab.editing = edit_on_open;
+ tab.scroll_ratio = 0.0;
active_id
}
@@ -195,6 +203,33 @@ impl DocumentSession {
self.active().is_some_and(DocumentTab::is_home)
}
+ /// Remember the viewport of the active tab (0.0 top .. 1.0 bottom).
+ pub fn set_active_scroll_ratio(&mut self, ratio: f32) {
+ if !ratio.is_finite() {
+ return;
+ }
+ if let Some(tab) = self.active_mut() {
+ tab.scroll_ratio = ratio.clamp(0.0, 1.0);
+ }
+ }
+
+ /// Store the viewport by tab id; late scroll reports must not land on a tab
+ /// that was activated in the meantime.
+ pub fn set_tab_scroll_ratio(&mut self, id: u64, ratio: f32) {
+ if !ratio.is_finite() {
+ return;
+ }
+ if let Some(tab) = self.get_mut(id) {
+ tab.scroll_ratio = ratio.clamp(0.0, 1.0);
+ }
+ }
+
+ pub fn set_tab_editing(&mut self, id: u64, editing: bool) {
+ if let Some(tab) = self.get_mut(id) {
+ tab.editing = editing;
+ }
+ }
+
pub fn get_mut(&mut self, id: u64) -> Option<&mut DocumentTab> {
self.tabs.iter_mut().find(|tab| tab.id == id)
}
@@ -285,7 +320,7 @@ mod tests {
assert_eq!(first, second);
assert_eq!(session.tabs.len(), 1);
assert_eq!(session.active_id, Some(first));
- assert!(session.tabs[0].edit_on_open);
+ assert!(session.tabs[0].editing);
let _ = fs::remove_dir_all(dir);
}
@@ -354,7 +389,7 @@ mod tests {
assert_eq!(session.tabs.len(), 1);
assert!(!session.tabs[0].is_home());
assert_eq!(session.tabs[0].file_path(), Some(file.as_path()));
- assert!(session.tabs[0].edit_on_open);
+ assert!(session.tabs[0].editing);
let _ = fs::remove_dir_all(dir);
}
@@ -404,6 +439,30 @@ mod tests {
let _ = fs::remove_dir_all(dir);
}
+ #[test]
+ fn edit_mode_and_scroll_position_are_remembered_per_tab() {
+ let dir = temp_dir("per-tab-view");
+ let mut session = DocumentSession::default();
+ let first = session.open(dir.join("one.md"), true);
+ session.set_active_scroll_ratio(0.75);
+ let second = session.open(dir.join("two.md"), false);
+
+ assert_ne!(first, second);
+ assert!(!session.active().unwrap().editing);
+ assert_eq!(session.active().unwrap().scroll_ratio, 0.0);
+
+ assert!(session.activate(first));
+ assert!(session.active().unwrap().editing);
+ assert_eq!(session.active().unwrap().scroll_ratio, 0.75);
+
+ // Late reports address the tab by id, not by whichever tab is active.
+ session.set_tab_scroll_ratio(second, 0.4);
+ assert!(session.activate(second));
+ assert_eq!(session.active().unwrap().scroll_ratio, 0.4);
+ assert!(!session.active().unwrap().editing);
+ let _ = fs::remove_dir_all(dir);
+ }
+
#[cfg(target_os = "windows")]
#[test]
fn opened_paths_drop_windows_verbatim_prefix() {
@@ -419,7 +478,10 @@ mod tests {
.unwrap()
.to_string_lossy()
.to_string();
- assert!(!stored.starts_with(r"\\?\"), "verbatim prefix leaked: {stored}");
+ assert!(
+ !stored.starts_with(r"\\?\"),
+ "verbatim prefix leaked: {stored}"
+ );
assert!(session.tabs[0].file_path().unwrap().ends_with("note.md"));
let _ = fs::remove_dir_all(dir);
}