#
{}
"#,
html_escape_text(s.drop_hint),
- html_escape_text(s.open_file)
+ html_escape_text(s.open_file),
+ html_escape_attr(s.btn_new),
+ html_escape_text(s.new_file)
);
if !recent_files.is_empty() {
@@ -1124,9 +1142,9 @@ fn build_page(
base_href: Option<&str>,
flags: EnhanceFlags,
s: &Strings,
- empty: bool,
+ home: bool,
) -> String {
- let body_class = if empty { "empty" } else { "" };
+ let body_class = if home { "home" } else { "" };
let base_tag = base_href
.map(|href| format!(r#"
"#, html_escape_attr(href)))
.unwrap_or_else(|| r#"
"#.to_string());
@@ -1276,13 +1294,14 @@ body.has-tabs {{ --chrome-top: 50px; }}
min-height: 60vh; color: #999; font-size: 18px; gap: 12px; text-align: center; }}
.empty.has-recent {{
justify-content: flex-start;
- min-height: calc(100vh - 48px);
+ min-height: calc(100vh - var(--chrome-top) - 38px);
padding: clamp(56px, 10vh, 96px) 0 40px;
box-sizing: border-box;
}}
.empty .icon {{ font-size: 48px; opacity: 0.4; }}
+ .empty-actions {{ display: flex; gap: 8px; margin-top: 6px; }}
.empty-open {{
- margin-top: 6px; min-height: 40px; padding: 0 16px;
+ min-height: 40px; padding: 0 16px;
border: 1px solid #ddd; border-radius: 8px; background: #fff;
color: #1a1a1a; font: inherit; font-size: 15px; cursor: pointer;
}}
@@ -1328,6 +1347,7 @@ body.has-tabs {{ --chrome-top: 50px; }}
font: 16px/1 -apple-system, BlinkMacSystemFont, sans-serif; opacity: .58;
}}
.tab-close:hover {{ opacity: 1; background: rgba(0,0,0,.08); }}
+ .tab-close[hidden] {{ display: none; }}
.tab-menu {{
position: fixed; z-index: 200; min-width: 188px; padding: 4px;
background: #fff; border: 1px solid #ddd; border-radius: 8px;
@@ -1374,7 +1394,7 @@ body.has-tabs {{ --chrome-top: 50px; }}
transition: opacity 0.18s ease;
}}
html:hover .toolbar {{ opacity: 1; pointer-events: auto; }}
-body.empty .toolbar {{ display: none !important; }}
+body.home .toolbar {{ display: none !important; }}
.toolbar button {{
width: 34px; height: 34px; padding: 0;
background: rgba(255,255,255,0.8);
@@ -1510,7 +1530,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
#preview .mdp-fold-toggle {{ display: none !important; }}
}}
-
+
@@ -1542,7 +1562,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
var ICON_UP = '
';
var ICON_DOWN = '
';
var ICON_CLOSE = '
';
- var L_EDIT = '{btn_edit}', L_VIEW = '{btn_preview}';
+ var L_EDIT = '{btn_edit}', L_VIEW = '{btn_preview}', L_HOME = '{home_tab}';
window.__mdPreviewFoldLabel = '{fold_toggle}';
window.__mdPreviewCannotSave = '{cannot_save_js}';
@@ -1578,6 +1598,9 @@ body.editing #app {{ max-width: none; padding: 0; }}
var composingFind = false;
var pendingFindTimer = 0;
var FIND_DEBOUNCE_MS = 300;
+ // 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 = '';
@@ -1683,15 +1706,16 @@ body.editing #app {{ max-width: none; padding: 0; }}
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 = shortenPath(path, 42);
- if (path) tabMenuPath.setAttribute('title', path);
+ 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;
- if (tabMenuReveal) tabMenuReveal.disabled = !path;
+ 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();
@@ -1765,8 +1789,13 @@ body.editing #app {{ max-width: none; padding: 0; }}
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 showFind() {{
- if (document.body.classList.contains('empty')) return;
+ if (document.body.classList.contains('home')) return;
if (inEdit()) return;
document.body.classList.add('finding');
setTimeout(function(){{ findInput.focus(); findInput.select(); }}, 0);
@@ -1905,6 +1934,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
window.scrollTo(x, y);
}}
function enterEdit() {{
+ if (document.body.classList.contains('home')) return;
var progress = currentScrollProgress();
document.body.classList.add('editing');
btnToggle.innerHTML = ICON_VIEW;
@@ -1937,7 +1967,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
if (activeTabId) requestTabAction('close', activeTabId);
}};
- tabOpen.addEventListener('click', newFile);
+ tabOpen.addEventListener('click', newTab);
if (tabMenuNewWindow) {{
tabMenuNewWindow.addEventListener('click', function(e) {{
e.preventDefault();
@@ -1960,6 +1990,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
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) {{}}
@@ -2022,6 +2053,12 @@ body.editing #app {{ max-width: none; padding: 0; }}
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();
@@ -2192,28 +2229,34 @@ body.editing #app {{ max-width: none; padding: 0; }}
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1;
tabsEl.textContent = '';
activeTabId = 0;
- document.body.classList.toggle('has-tabs', tabs.length > 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' + (tab.active ? ' active' : '') + (tab.missing ? ' missing' : '') + (tab.dirty ? ' dirty' : '');
+ 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', tab.path);
+ item.setAttribute('data-tab-path', isHome ? '' : tab.path);
item.setAttribute('role', 'button');
item.setAttribute('tabindex', '0');
- item.title = tab.path;
+ 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 = 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 ' + tab.name);
+ 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);
@@ -2229,7 +2272,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
requestTabAction('activate', tab.getAttribute('data-tab-id'));
}});
window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid) {{
- document.body.classList.remove('empty');
+ document.body.classList.remove('home');
document.body.classList.remove('missing');
hideFind();
window.__setBaseHref(baseHref);
@@ -2243,7 +2286,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
}}
}};
window.__setEmptyPreview = function(previewHtml) {{
- document.body.classList.add('empty');
+ document.body.classList.add('home');
document.body.classList.remove('missing');
document.body.classList.remove('editing');
btnToggle.innerHTML = ICON_EDIT;
@@ -2260,7 +2303,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
window.scrollTo(0, 0);
}};
window.__setMissing = function(previewHtml) {{
- document.body.classList.remove('empty');
+ document.body.classList.remove('home');
document.body.classList.add('missing');
document.body.classList.remove('editing');
btnToggle.innerHTML = ICON_EDIT;
@@ -2300,7 +2343,8 @@ if(window.__enhancePreview)window.__enhancePreview();
base_tag = base_tag,
preview_html = preview_html,
raw_md_escaped = html_escape_ta(raw_md),
- btn_new = s.btn_new,
+ new_tab = s.new_tab,
+ home_tab = escape_js(s.home_tab),
btn_new_window = s.btn_new_window,
btn_open_location = s.btn_open_location,
btn_edit = s.btn_edit,
@@ -2792,8 +2836,21 @@ mod tests {
);
assert!(page.contains("window.ipc.postMessage('new-file')"));
- assert!(page.contains("tabOpen.addEventListener('click', newFile)"));
+ assert!(page.contains("tabOpen.addEventListener('click', newTab)"));
+ assert!(!page.contains("tabOpen.addEventListener('click', newFile)"));
assert!(!page.contains("tabOpen.addEventListener('click', openFile)"));
+ assert!(page.contains("requestTabAction('new-tab', 0)"));
+ assert!(page.contains("data-new-file"));
+ assert!(page.contains("HIDE_SINGLE_HOME_TAB = true"));
+ assert!(page.contains("tabs.length === 1 && !tabs[0].home"));
+ assert!(page.contains("L_HOME = 'Home'"));
+ assert!(
+ page.matches("if (document.body.classList.contains('home')) return;")
+ .count()
+ >= 2
+ );
+ assert!(page.contains("if (tabCount === 1 && isHome) close.hidden = true"));
+ assert!(page.contains("tabMenuNewWindow.disabled = tabCount <= 1 || isHome"));
assert!(page.contains("AUTOSAVE_DEBOUNCE_MS = 700"));
assert!(page.contains("pendingAutosaveTimer = setTimeout"));
assert!(page.contains("window.__markSaved = function(savedRaw)"));
@@ -2904,9 +2961,12 @@ mod tests {
fn empty_state_exposes_open_and_recent_files() {
let strings = Strings::for_lang(Lang::En);
let recent = vec![PathBuf::from("/tmp/example.md")];
- let html = empty_preview_html(&strings, &recent);
+ let html = home_preview_html(&strings, &recent);
assert!(html.contains("Open File"));
+ assert!(html.contains("New File"));
+ assert!(html.contains("empty-actions"));
+ assert!(html.contains("data-new-file"));
assert!(html.contains("Recent"));
assert!(html.contains("example.md"));
assert!(html.contains("data-recent-index=\"0\""));
@@ -2924,6 +2984,20 @@ mod tests {
);
assert!(page.contains(".empty.has-recent"));
assert!(!page.contains(".empty.has-recent .recent { max-height"));
+ assert!(page.contains(""));
+ assert!(page.contains("body.home .toolbar"));
+ }
+
+ #[test]
+ fn tabs_json_marks_home_tabs_without_a_file_path() {
+ let mut session = DocumentSession::default();
+ let home = session.open_home();
+
+ let json = tabs_json(&session);
+
+ assert!(json.contains(&format!(r#""id":{home}"#)), "{json}");
+ assert!(json.contains(r#""home":true"#), "{json}");
+ assert!(json.contains(r#""path":"""#), "{json}");
}
#[test]
@@ -3651,11 +3725,11 @@ fn install_file_watcher(
) {
let mut current = holder.lock().unwrap();
*current = None;
+ *last_self_write.lock().unwrap() = None;
let Some(path) = path else {
return;
};
let mut observed_content = fs::read(&path).ok();
- *last_self_write.lock().unwrap() = None;
let target_path = path.clone();
let callback_path = path.clone();
let proxy = proxy.clone();
@@ -3861,7 +3935,11 @@ fn find_open_path(app: &AppState, path: &Path) -> Option<(WindowId, u64)> {
let normalized = session::normalize_path(path.to_path_buf());
for (window_id, ws) in &app.windows {
let session = ws.session.lock().unwrap();
- if let Some(tab) = session.tabs.iter().find(|tab| tab.path == normalized) {
+ if let Some(tab) = session
+ .tabs
+ .iter()
+ .find(|tab| tab.path.as_deref() == Some(normalized.as_path()))
+ {
return Some((*window_id, tab.id));
}
}
@@ -3908,8 +3986,8 @@ fn focus_open_tab(
.session
.lock()
.unwrap()
- .active()
- .map(|tab| tab.path.clone());
+ .active_path()
+ .map(Path::to_path_buf);
install_file_watcher(&ws.watcher, proxy, &ws.last_self_write, window_id, path);
true
}
@@ -3920,20 +3998,38 @@ fn update_tabs(webview: &WebView, session: &DocumentSession) {
}
fn update_window_title(window: &Window, session: &DocumentSession) {
- let title = session
- .active()
- .map(|tab| {
- let name = tab
- .path
- .file_name()
- .map(|name| name.to_string_lossy().to_string())
- .unwrap_or_else(|| tab.path.to_string_lossy().to_string());
- format!("{}{} — MD Preview", if tab.dirty { "• " } else { "" }, name)
- })
- .unwrap_or_else(|| "MD Preview".to_string());
+ let title = match session.active() {
+ Some(tab) => match tab.file_path() {
+ Some(path) => {
+ let name = path
+ .file_name()
+ .map(|name| name.to_string_lossy().to_string())
+ .unwrap_or_else(|| path.to_string_lossy().to_string());
+ format!("{}{} — MD Preview", if tab.dirty { "• " } else { "" }, name)
+ }
+ None => "MD Preview".to_string(),
+ },
+ None => "MD Preview".to_string(),
+ };
window.set_title(&title);
}
+fn render_home(
+ webview: &WebView,
+ window: &Window,
+ session: &DocumentSession,
+ recent_files: &Arc
>>,
+ strings: &Strings,
+) {
+ let html = home_preview_html(strings, &recent_files.lock().unwrap());
+ let _ = webview.evaluate_script(&format!(
+ "if(window.__setEmptyPreview)window.__setEmptyPreview('{}');",
+ escape_js(&html)
+ ));
+ update_tabs(webview, session);
+ update_window_title(window, session);
+}
+
fn render_active_document(
webview: &WebView,
window: &Window,
@@ -3944,24 +4040,23 @@ fn render_active_document(
strings: &Strings,
) -> bool {
let Some(active) = session.active().cloned() else {
- let html = empty_preview_html(strings, &recent_files.lock().unwrap());
- let _ = webview.evaluate_script(&format!(
- "if(window.__setEmptyPreview)window.__setEmptyPreview('{}');",
- escape_js(&html)
- ));
- update_tabs(webview, session);
- update_window_title(window, session);
+ render_home(webview, window, session, recent_files, strings);
+ return false;
+ };
+ // Home tabs carry no file; they render the new-tab page.
+ let Some(path) = active.file_path().map(Path::to_path_buf) else {
+ render_home(webview, window, session, recent_files, strings);
return false;
};
- match fs::read_to_string(&active.path) {
+ match fs::read_to_string(&path) {
Ok(raw) => {
if let Some(tab) = session.get_mut(active.id) {
tab.missing = false;
}
- remember_recent_file(recent_files, &active.path);
- let html = md_to_html_with_base(&raw, active.path.parent());
- let base_href = base_href_for_file(&active.path).unwrap_or_default();
+ remember_recent_file(recent_files, &path);
+ let html = md_to_html_with_base(&raw, path.parent());
+ let base_href = base_href_for_file(&path).unwrap_or_default();
let flags = enhance_flags_for(&raw);
*enhance_flags.lock().unwrap() = flags;
let _ = webview.evaluate_script(&format!(
@@ -3996,7 +4091,7 @@ fn render_active_document(
"The file disappeared while it still has unsaved edits. The editor content has been kept.",
);
} else {
- let html = missing_preview_html(active.id, &active.path, strings);
+ let html = missing_preview_html(active.id, &path, strings);
let _ = webview.evaluate_script(&format!(
"if(window.__setMissing)window.__setMissing('{}');",
escape_js(&html)
@@ -4013,7 +4108,7 @@ fn render_active_document(
r#""#,
html_escape_text(strings.cannot_read),
html_escape_text(&error.to_string()),
- html_escape_text(&active.path.to_string_lossy()),
+ html_escape_text(&path.to_string_lossy()),
html_escape_text(strings.open_file),
active.id,
html_escape_text(strings.close_tab),
@@ -4036,7 +4131,7 @@ fn render_active_document(
// persisted path data in this page; load the active tab after the ready IPC.
fn build_startup_page(strings: &Strings) -> String {
build_page(
- &empty_preview_html(strings, &[]),
+ &home_preview_html(strings, &[]),
"",
None,
EnhanceFlags::default(),
@@ -4104,7 +4199,7 @@ fn build_webview(
}
}
} else if let Some(url) = body.strip_prefix("open-local-link:") {
- let active_path = session.lock().unwrap().active().map(|tab| tab.path.clone());
+ let active_path = session.lock().unwrap().active_path().map(Path::to_path_buf);
if let Some(path) = resolve_document_link(url, active_path.as_deref()) {
let _ = proxy_for_ipc.send_event(UserEvent::OpenPaths(
Some(window_id),
@@ -4124,7 +4219,7 @@ fn build_webview(
return;
};
if let Some(content) = pending_content {
- let path = session.lock().unwrap().active().map(|tab| tab.path.clone());
+ let path = session.lock().unwrap().active_path().map(Path::to_path_buf);
let Some(path) = path else {
return;
};
@@ -4156,6 +4251,9 @@ fn build_webview(
"detach" => {
let _ = proxy_for_ipc.send_event(UserEvent::DetachTab(window_id, id));
}
+ "new-tab" => {
+ let _ = proxy_for_ipc.send_event(UserEvent::NewTab(window_id));
+ }
_ => {}
}
} else if let Some(id) = body.strip_prefix("locate-tab:") {
@@ -4185,11 +4283,11 @@ fn build_webview(
save_zoom(percent);
}
} else if body == "refresh" {
- if let Some(path) = session.lock().unwrap().active().map(|tab| tab.path.clone()) {
+ if let Some(path) = session.lock().unwrap().active_path().map(Path::to_path_buf) {
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().map(|tab| tab.path.clone());
+ 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(),
@@ -4325,6 +4423,10 @@ fn create_window_with_session(
let window = builder.build(target).map_err(|error| error.to_string())?;
let window_id = window.id();
let page = build_startup_page(&app.strings);
+ let mut initial_session = initial_session;
+ if initial_session.tabs.is_empty() {
+ initial_session.open_home();
+ }
let session = Arc::new(Mutex::new(initial_session));
let last_self_write = Arc::new(Mutex::new(None));
let recent_files = Arc::clone(&app.recent_files);
@@ -4469,6 +4571,9 @@ fn main() {
for path in cli_paths {
initial_session.open(path, edit_from_cli);
}
+ if initial_session.tabs.is_empty() {
+ initial_session.open_home();
+ }
let event_loop: EventLoop = EventLoopBuilder::with_user_event().build();
let proxy = event_loop.create_proxy();
@@ -4485,7 +4590,8 @@ fn main() {
let title = initial_session
.active()
- .and_then(|tab| tab.path.file_name())
+ .and_then(|tab| tab.file_path())
+ .and_then(|path| path.file_name())
.map(|name| format!("{} — MD Preview", name.to_string_lossy()))
.unwrap_or_else(|| "MD Preview".to_string());
@@ -4622,7 +4728,8 @@ fn main() {
.lock()
.unwrap()
.active()
- .and_then(|tab| tab.path.parent().map(Path::to_path_buf));
+ .and_then(|tab| tab.file_path())
+ .and_then(|path| path.parent().map(Path::to_path_buf));
let mut dialog = rfd::FileDialog::new()
.add_filter("Markdown", &["md", "markdown", "mdown", "mkd"])
.set_file_name(strings.new_filename);
@@ -4673,6 +4780,16 @@ fn main() {
));
}
}
+ TaoEvent::UserEvent(UserEvent::NewTab(window_id)) => {
+ let Some(ws) = app.windows.get_mut(&window_id) else {
+ return;
+ };
+ let mut session = ws.session.lock().unwrap();
+ session.open_home();
+ drop(session);
+ ws.render_active(&recent_files, &strings);
+ install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, None);
+ }
TaoEvent::UserEvent(UserEvent::OpenPaths(target, paths, edit_on_open)) => {
let target_window = target.unwrap_or(app.active_window);
let Some(ws) = app.windows.get_mut(&target_window) else {
@@ -4719,7 +4836,11 @@ fn main() {
let mut session = ws.session.lock().unwrap();
let previous_active = session.active_id;
let preserve_active = session.active().map(|tab| tab.dirty).unwrap_or(false);
- session.open(path, edit_on_open);
+ if !preserve_active && session.active_is_home() {
+ session.open_reusing_home(path, edit_on_open);
+ } else {
+ session.open(path, edit_on_open);
+ }
if preserve_active {
if let Some(id) = previous_active {
session.activate(id);
@@ -4731,7 +4852,7 @@ fn main() {
drop(session);
ws.render_active(&recent_files, &strings);
}
- let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
+ let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf);
install_file_watcher(
&ws.watcher,
&proxy,
@@ -4749,7 +4870,7 @@ fn main() {
if session.activate(id) {
drop(session);
ws.render_active(&recent_files, &strings);
- let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
+ let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf);
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
}
}
@@ -4759,20 +4880,34 @@ fn main() {
return;
};
let mut session = ws.session.lock().unwrap();
+ let Some(target) = session.tabs.iter().find(|tab| tab.id == id) else {
+ return;
+ };
let was_active = session.active_id == Some(id);
+ let sole_tab = session.tabs.len() == 1;
+ let closing_home = target.is_home();
+ if sole_tab {
+ if multiple_windows {
+ drop(session);
+ close_window(&mut app, window_id, control_flow);
+ return;
+ }
+ if closing_home {
+ // The last window always keeps one Home tab.
+ return;
+ }
+ // Closing the last file tab returns to the Home tab.
+ session.close_with_home_fallback(id);
+ drop(session);
+ ws.render_active(&recent_files, &strings);
+ install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, None);
+ return;
+ }
if session.close(id) {
- if session.tabs.is_empty() {
- if multiple_windows {
- drop(session);
- close_window(&mut app, window_id, control_flow);
- } else {
- drop(session);
- ws.render_active(&recent_files, &strings);
- }
- } else if was_active {
+ if was_active {
drop(session);
ws.render_active(&recent_files, &strings);
- let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
+ let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf);
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
} else {
update_tabs(&ws.webview, &session);
@@ -4787,6 +4922,9 @@ fn main() {
let Some(tab) = session.tabs.iter().find(|tab| tab.id == tab_id).cloned() else {
return;
};
+ if tab.is_home() {
+ return;
+ }
let target_active = session.active_id == Some(tab_id);
if !target_active && tab.dirty {
drop(session);
@@ -4833,7 +4971,7 @@ fn main() {
if !close_source {
drop(session);
ws.render_active(&recent_files, &strings);
- let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
+ let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf);
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
}
}
@@ -4848,7 +4986,8 @@ fn main() {
.tabs
.iter()
.find(|tab| tab.id == tab_id)
- .map(|tab| tab.path.clone())
+ .and_then(|tab| tab.file_path())
+ .map(Path::to_path_buf)
});
if let Some(path) = path {
if !reveal_in_explorer(&path) {
@@ -4901,7 +5040,7 @@ fn main() {
if session.relocate(id, path) && session.activate(id) {
drop(session);
ws.render_active(&recent_files, &strings);
- let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
+ let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf);
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
} else {
show_warning_dialog("Already Open", "That file is already open in another tab.");
@@ -4912,14 +5051,7 @@ fn main() {
let Some(ws) = app.windows.get_mut(&window_id) else {
return;
};
- if ws
- .session
- .lock()
- .unwrap()
- .active()
- .map(|tab| tab.path.as_path())
- == Some(path.as_path())
- {
+ if ws.session.lock().unwrap().active_path() == Some(path.as_path()) {
ws.pending_external_change = Some(path);
let _ = ws.webview.evaluate_script(
"if(window.__mdPreviewResolveExternalChange)window.__mdPreviewResolveExternalChange();",
@@ -4937,7 +5069,7 @@ fn main() {
return;
}
let mut session = ws.session.lock().unwrap();
- if session.active().map(|tab| tab.path.as_path()) == Some(path.as_path()) {
+ if session.active_path() == Some(path.as_path()) {
let session_dirty = session.active().map(|tab| tab.dirty).unwrap_or(false);
if should_protect_external_change(webview_dirty, session_dirty) {
if let Some(tab) = session.active_mut() {
@@ -4969,8 +5101,12 @@ fn main() {
ws.warned_external_change = None;
}
let mut session = ws.session.lock().unwrap();
- let active_matches = session.active().map(|tab| tab.path.as_path()) == Some(path.as_path());
- if let Some(tab) = session.tabs.iter_mut().find(|tab| tab.path == path) {
+ let active_matches = session.active_path() == Some(path.as_path());
+ if let Some(tab) = session
+ .tabs
+ .iter_mut()
+ .find(|tab| tab.path.as_deref() == Some(path.as_path()))
+ {
tab.dirty = false;
tab.missing = false;
}
@@ -5052,13 +5188,13 @@ fn main() {
.evaluate_script("if(window.__mdPreviewShowFind)window.__mdPreviewShowFind();");
}
TaoEvent::UserEvent(UserEvent::RecentChanged) => {
- let html = empty_preview_html(&strings, &recent_files.lock().unwrap());
+ let html = home_preview_html(&strings, &recent_files.lock().unwrap());
let js = format!(
"if(window.__setEmptyPreview)window.__setEmptyPreview('{}');",
escape_js(&html)
);
for ws in app.windows.values() {
- if ws.session.lock().unwrap().tabs.is_empty() {
+ if ws.session.lock().unwrap().active_is_home() {
let _ = ws.webview.evaluate_script(&js);
}
}
@@ -5110,7 +5246,7 @@ fn main() {
if !ws.page_ready {
ws.page_ready = true;
ws.render_active(&recent_files, &strings);
- let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
+ let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf);
install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
}
for (paths, edit) in ws.pending_launches.drain(..) {
diff --git a/src/session.rs b/src/session.rs
index 022f292..f366e2a 100644
--- a/src/session.rs
+++ b/src/session.rs
@@ -1,15 +1,26 @@
use std::fs;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DocumentTab {
pub id: u64,
- pub path: PathBuf,
+ /// `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,
}
+impl DocumentTab {
+ pub fn is_home(&self) -> bool {
+ self.path.is_none()
+ }
+
+ pub fn file_path(&self) -> Option<&Path> {
+ self.path.as_deref()
+ }
+}
+
#[derive(Debug, Default)]
pub struct DocumentSession {
pub tabs: Vec,
@@ -20,8 +31,12 @@ pub struct DocumentSession {
impl DocumentSession {
pub fn open(&mut self, path: PathBuf, edit_on_open: bool) -> u64 {
let path = normalize_path(path);
- if let Some(tab) = self.tabs.iter_mut().find(|tab| tab.path == path) {
- tab.missing = !tab.path.exists();
+ if let Some(tab) = self
+ .tabs
+ .iter_mut()
+ .find(|tab| tab.path.as_deref() == Some(path.as_path()))
+ {
+ tab.missing = !path.exists();
tab.edit_on_open |= edit_on_open;
self.active_id = Some(tab.id);
return tab.id;
@@ -29,22 +44,82 @@ impl DocumentSession {
self.next_id += 1;
let id = self.next_id;
+ let missing = !path.exists();
self.tabs.push(DocumentTab {
id,
- missing: !path.exists(),
- path,
+ path: Some(path),
dirty: false,
+ missing,
edit_on_open,
});
self.active_id = Some(id);
id
}
+ /// Append and activate a Home tab (the in-app "new tab page").
+ pub fn open_home(&mut self) -> u64 {
+ self.next_id += 1;
+ let id = self.next_id;
+ self.tabs.push(DocumentTab {
+ id,
+ path: None,
+ dirty: false,
+ missing: false,
+ edit_on_open: false,
+ });
+ self.active_id = Some(id);
+ id
+ }
+
+ /// Open `path`, turning the active Home tab into the document when possible
+ /// (browser-style navigation). Falls back to appending a tab otherwise.
+ pub fn open_reusing_home(&mut self, path: PathBuf, edit_on_open: bool) -> u64 {
+ let Some(active_id) = self.active_id else {
+ return self.open(path, edit_on_open);
+ };
+ if !self
+ .tabs
+ .iter()
+ .any(|tab| tab.id == active_id && tab.is_home())
+ {
+ return self.open(path, edit_on_open);
+ }
+
+ let path = normalize_path(path);
+ if let Some(existing) = self
+ .tabs
+ .iter_mut()
+ .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;
+ 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);
+ self.active_id = Some(existing_id);
+ return existing_id;
+ }
+
+ let missing = !path.exists();
+ let tab = self
+ .tabs
+ .iter_mut()
+ .find(|tab| tab.id == active_id)
+ .expect("active tab disappeared");
+ tab.path = Some(path);
+ tab.missing = missing;
+ tab.dirty = false;
+ tab.edit_on_open = edit_on_open;
+ active_id
+ }
+
pub fn activate(&mut self, id: u64) -> bool {
let Some(tab) = self.tabs.iter_mut().find(|tab| tab.id == id) else {
return false;
};
- tab.missing = !tab.path.exists();
+ if let Some(path) = tab.path.as_deref() {
+ tab.missing = !path.exists();
+ }
self.active_id = Some(id);
true
}
@@ -65,6 +140,17 @@ impl DocumentSession {
true
}
+ /// Close a tab and leave a fresh Home tab behind when it was the last one.
+ pub fn close_with_home_fallback(&mut self, id: u64) -> bool {
+ if !self.close(id) {
+ return false;
+ }
+ if self.tabs.is_empty() {
+ self.open_home();
+ }
+ true
+ }
+
pub fn with_tab(tab: DocumentTab) -> Self {
let id = tab.id;
Self {
@@ -76,6 +162,9 @@ impl DocumentSession {
pub fn detach(&mut self, id: u64) -> Option {
let index = self.tabs.iter().position(|tab| tab.id == id)?;
+ if self.tabs[index].is_home() {
+ return None;
+ }
let was_active = self.active_id == Some(id);
let tab = self.tabs.remove(index);
if was_active {
@@ -98,20 +187,36 @@ impl DocumentSession {
self.tabs.iter_mut().find(|tab| tab.id == id)
}
+ pub fn active_path(&self) -> Option<&Path> {
+ self.active().and_then(DocumentTab::file_path)
+ }
+
+ pub fn active_is_home(&self) -> bool {
+ self.active().is_some_and(DocumentTab::is_home)
+ }
+
pub fn get_mut(&mut self, id: u64) -> Option<&mut DocumentTab> {
self.tabs.iter_mut().find(|tab| tab.id == id)
}
pub fn relocate(&mut self, id: u64, path: PathBuf) -> bool {
let path = normalize_path(path);
- if self.tabs.iter().any(|tab| tab.id != id && tab.path == path) {
+ if self
+ .tabs
+ .iter()
+ .any(|tab| tab.id != id && tab.path.as_deref() == Some(path.as_path()))
+ {
return false;
}
+ let missing = !path.exists();
let Some(tab) = self.get_mut(id) else {
return false;
};
- tab.path = path;
- tab.missing = !tab.path.exists();
+ if tab.is_home() {
+ return false;
+ }
+ tab.path = Some(path);
+ tab.missing = missing;
true
}
}
@@ -222,6 +327,83 @@ mod tests {
let _ = fs::remove_dir_all(dir);
}
+ #[test]
+ fn home_tab_is_a_tab_without_a_file_path() {
+ let mut session = DocumentSession::default();
+
+ let home = session.open_home();
+
+ assert_eq!(session.active_id, Some(home));
+ assert_eq!(session.tabs.len(), 1);
+ assert!(session.tabs[0].is_home());
+ assert_eq!(session.active_path(), None);
+ assert!(session.active_is_home());
+ }
+
+ #[test]
+ fn opening_a_file_from_home_reuses_the_home_tab() {
+ let dir = temp_dir("home-reuse");
+ let file = dir.join("note.md");
+ fs::write(&file, "# Note").unwrap();
+ let mut session = DocumentSession::default();
+ let home = session.open_home();
+
+ let opened = session.open_reusing_home(file.clone(), true);
+
+ assert_eq!(opened, home);
+ 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);
+ let _ = fs::remove_dir_all(dir);
+ }
+
+ #[test]
+ fn opening_an_already_open_file_from_home_drops_the_blank_tab() {
+ let dir = temp_dir("home-dedupe");
+ let first = dir.join("one.md");
+ fs::write(&first, "one").unwrap();
+ let mut session = DocumentSession::default();
+ let first_id = session.open(first.clone(), false);
+ let home = session.open_home();
+
+ let opened = session.open_reusing_home(first, false);
+
+ assert_eq!(opened, first_id);
+ assert_eq!(session.tabs.len(), 1);
+ assert_eq!(session.active_id, Some(first_id));
+ assert!(!session.tabs.iter().any(|tab| tab.id == home));
+ let _ = fs::remove_dir_all(dir);
+ }
+
+ #[test]
+ fn home_tab_cannot_be_detached_or_relocated() {
+ let dir = temp_dir("home-guard");
+ let mut session = DocumentSession::default();
+ let home = session.open_home();
+
+ assert!(session.detach(home).is_none());
+ assert!(!session.relocate(home, dir.join("note.md")));
+ assert_eq!(session.tabs.len(), 1);
+ let _ = fs::remove_dir_all(dir);
+ }
+
+ #[test]
+ fn closing_the_last_file_leaves_a_home_tab() {
+ let dir = temp_dir("close-home");
+ let file = dir.join("note.md");
+ fs::write(&file, "").unwrap();
+ let mut session = DocumentSession::default();
+ let file_id = session.open(file, false);
+
+ assert!(session.close_with_home_fallback(file_id));
+
+ assert_eq!(session.tabs.len(), 1);
+ assert!(session.active().unwrap().is_home());
+ assert_eq!(session.active_id, Some(session.tabs[0].id));
+ let _ = fs::remove_dir_all(dir);
+ }
+
#[cfg(target_os = "windows")]
#[test]
fn opened_paths_drop_windows_verbatim_prefix() {
@@ -232,9 +414,13 @@ mod tests {
session.open(file.clone(), false);
- let stored = session.tabs[0].path.to_string_lossy().to_string();
+ let stored = session.tabs[0]
+ .file_path()
+ .unwrap()
+ .to_string_lossy()
+ .to_string();
assert!(!stored.starts_with(r"\\?\"), "verbatim prefix leaked: {stored}");
- assert!(session.tabs[0].path.ends_with("note.md"));
+ assert!(session.tabs[0].file_path().unwrap().ends_with("note.md"));
let _ = fs::remove_dir_all(dir);
}
}