feat: add Home as the default tab

- Model Home as a tab without a file path (Option<PathBuf>)
- + creates a Home tab; opening a file from Home reuses that tab
- Add a New File button to the Home page (replaces + for file creation)
- Closing the last file tab falls back to a Home tab
- Hide the tab strip while the only tab is Home
- Keep Home tabs out of detach, reveal, watcher, and duplicate checks
This commit is contained in:
2026-10-28 18:21:53 +08:00
parent abeb426a43
commit 809b7b0299
4 changed files with 449 additions and 119 deletions

View File

@@ -12,7 +12,7 @@
- **双击即开**:单个 exe(约 5.5 MB),不用安装;可设为 `.md` 的默认打开方式。 - **双击即开**:单个 exe(约 5.5 MB),不用安装;可设为 `.md` 的默认打开方式。
- **完全离线**:不联网、不检查更新、无遥测;外部链接交给系统浏览器打开。 - **完全离线**:不联网、不检查更新、无遥测;外部链接交给系统浏览器打开。
- **多标签 + 多窗口**:标签右键可在新窗口打开,也可以上下拖动标签直接移出;同一文件全局只开一次,重复打开只聚焦;不恢复上次标签,启动显示最近文件、缺失文件可重新定位。 - **多标签 + 多窗口**:首页本身就是一个默认标签(Home),标签栏的 `+` 新建一个首页标签;在首页标签里打开文件会直接替换该标签(浏览器语义);关闭最后一个文件标签回到首页,只剩首页标签时标签栏自动隐藏。标签右键可在新窗口打开,也可以上下拖动标签直接移出;同一文件全局只开一次,重复打开只聚焦;不恢复上次标签,启动显示最近文件、缺失文件可重新定位。
- **预览 / 编辑一体**:`Ctrl+E` 切换;编辑时 700ms 自动保存,`Ctrl+S` 立即保存。 - **预览 / 编辑一体**:`Ctrl+E` 切换;编辑时 700ms 自动保存,`Ctrl+S` 立即保存。
- **长文档友好**: - **长文档友好**:
- 鼠标移到标题左侧出现折角箭头,点击即可折叠到下一个同级标题(H1–H6); - 鼠标移到标题左侧出现折角箭头,点击即可折叠到下一个同级标题(H1–H6);
@@ -36,9 +36,11 @@
| 操作 | 方式 | | 操作 | 方式 |
|---|---| |---|---|
| 打开文件 | 双击 `.md`、拖进窗口、`Ctrl+O`、首页“最近文件” | | 打开文件 | 双击 `.md`、拖进窗口、`Ctrl+O`、首页“Open File / 最近文件” |
| 新建文件 | `Ctrl+N` | | 新建文件 | `Ctrl+N` 或首页“新建文件”按钮 |
| 关闭标签 | `Ctrl+W` 或标签上的 ×;非最后窗口关掉最后一个标签会关闭该窗口 | | 新建标签 | 标签栏 `+`(新开一个首页标签) |
| 返回首页 | 点击标签栏的“首页”标签;只剩首页标签时标签栏自动隐藏 |
| 关闭标签 | `Ctrl+W` 或标签上的 ×;关闭最后一个文件标签会回到首页;非最后窗口关掉最后一个标签会关闭该窗口 |
| 在新窗口打开 | 右键标签 → “在新窗口打开”,或按住标签上下拖动超过约 24px(至少两个标签时可用) | | 在新窗口打开 | 右键标签 → “在新窗口打开”,或按住标签上下拖动超过约 24px(至少两个标签时可用) |
| 打开文件所在位置 | 右键标签 → “打开文件所在位置”(文件丢失时打开所在目录) | | 打开文件所在位置 | 右键标签 → “打开文件所在位置”(文件丢失时打开所在目录) |
| 预览 / 编辑切换 | `Ctrl+E` | | 预览 / 编辑切换 | `Ctrl+E` |
@@ -48,6 +50,8 @@
| 缩放 | `Ctrl+滚轮`、`Ctrl++`、`Ctrl+-`、`Ctrl+0` 复位 | | 缩放 | `Ctrl+滚轮`、`Ctrl++`、`Ctrl+-`、`Ctrl+0` 复位 |
| 折叠标题 | 鼠标移到标题左侧,点折角箭头 | | 折叠标题 | 鼠标移到标题左侧,点折角箭头 |
> 首页标签上打开文件会直接替换这个标签(和浏览器新标签页一样),不会额外留下空白标签;想同时保留首页,先按标签栏的 `+` 新建一个首页标签。
设置与最近文件保存在 `%LOCALAPPDATA%\md-preview\`(`recent-files.txt`、`zoom.txt` 等);旧 `session.json` 不再读写。删除 exe 不会自动清掉这些记录。 设置与最近文件保存在 `%LOCALAPPDATA%\md-preview\`(`recent-files.txt`、`zoom.txt` 等);旧 `session.json` 不再读写。删除 exe 不会自动清掉这些记录。
## 和上游 1.4.2 的主要区别 ## 和上游 1.4.2 的主要区别
@@ -65,6 +69,7 @@
| 路径处理 | 修复 Windows `\\?\` 前缀污染 Recent / base URL 的问题 | | 路径处理 | 修复 Windows `\\?\` 前缀污染 Recent / base URL 的问题 |
| 稳定性 | 关闭前落盘、外部修改热重载、单实例转发、缺失文件重定位 | | 稳定性 | 关闭前落盘、外部修改热重载、单实例转发、缺失文件重定位 |
| 多窗口 | 单进程多窗口;标签右键移出到新窗口;同一文件全局唯一;启动只保留最近文件,不恢复标签 | | 多窗口 | 单进程多窗口;标签右键移出到新窗口;同一文件全局唯一;启动只保留最近文件,不恢复标签 |
| 首页 / 新标签 | 首页变成默认标签;`+` 新建首页标签;首页上新增“新建文件”按钮;只剩首页时标签栏隐藏 |
## 从源码构建 ## 从源码构建
@@ -76,7 +81,7 @@
- WebView2 Runtime - WebView2 Runtime
```powershell ```powershell
cargo test # 53 个测试 cargo test # 59 个测试
.\agent\scripts\build.ps1 # release 构建 + 校验 + 复制到固定 exe 路径 .\agent\scripts\build.ps1 # release 构建 + 校验 + 复制到固定 exe 路径
``` ```

View File

@@ -3,7 +3,7 @@
> 最后更新:2026-10-28 > 最后更新:2026-10-28
> 用途:上下文压缩/交接后快速恢复。详细背景见 AGENTS.md、HANDOFF.md、scan-2026-10-21.md、roadmap.md。 > 用途:上下文压缩/交接后快速恢复。详细背景见 AGENTS.md、HANDOFF.md、scan-2026-10-21.md、roadmap.md。
> >
> **当前:单进程多窗口 + 标签拖拽/菜单/多显示器修复完成;固定 exe 已替换为 2026-10-28 本地 release(5,507,584 字节,SHA256 0BFF7302…);Gitea release v1.4.2-local.3 已发布。53 个测试通过。** > **当前:首页标签改造完成(Home 默认标签、`+` 新建标签、首页“新建文件”、单首页隐藏标签栏);59 个测试通过,release 产物已校验(5,511,168 字节,SHA256 B1F86E88…)。固定 exe 尚未替换:收尾时 `MD-Preview-windows-x64.exe` 正在运行且打开了 `WIP.md`,为避免关闭用户窗口/丢修改,按约定停在这里;关闭窗口后运行 `agent\scripts\build.ps1` 即可部署。push / Gitea release 本轮未做。**
## 1. 仓库 ## 1. 仓库
@@ -38,8 +38,9 @@
## 2. 当前构建/部署状态 ## 2. 当前构建/部署状态
- `cargo test`:53 passed / 0 failed(2026-10-28,标签/菜单修复后)。 - `cargo test`:59 passed / 0 failed(2026-10-28,首页标签改造后)。
- 当前固定 exe(2026-10-28 部署): - 2026-10-28 首页标签改造的 release 产物:`target\release\md-preview.exe`,5,511,168 字节,SHA256 `B1F86E88C180DD41A181DDA8FF7DBEFB2C359ACFE2E8D25714046F3A134BF8C8`,完整性 Medium,禁用字符串检查全 0。固定 exe 待用户关闭正在运行的 `WIP.md` 窗口后由 build.ps1 替换。
- 当前固定 exe(2026-10-28 部署,仍为上一版):
- 大小 5,507,584 字节;版本 1.4.2.0 - 大小 5,507,584 字节;版本 1.4.2.0
- SHA256 `0BFF730209CE835B18DC1447740A1F2770EA0645577A91EB969A6215B1C2372E` - SHA256 `0BFF730209CE835B18DC1447740A1F2770EA0645577A91EB969A6215B1C2372E`
- 完整性级别 Medium - OK;禁用字符串检查全 0;PE subsystem=2(GUI,无双击 cmd)。 - 完整性级别 Medium - OK;禁用字符串检查全 0;PE subsystem=2(GUI,无双击 cmd)。
@@ -65,6 +66,7 @@
| 11 | 单进程多窗口:阶段 4 取消 session 恢复 | 完成 `e24733a`;只保留 recent;51 tests | | 11 | 单进程多窗口:阶段 4 取消 session 恢复 | 完成 `e24733a`;只保留 recent;51 tests |
| 12 | 单进程多窗口:阶段 5 标签右键新窗口 | 完成 `5740274`;先保存后移动;源窗口空则关闭;52 tests | | 12 | 单进程多窗口:阶段 5 标签右键新窗口 | 完成 `5740274`;先保存后移动;源窗口空则关闭;52 tests |
| 13 | 新窗口留在源显示器 + 标签拖拽 + 菜单路径/打开所在位置 | 完成 `9ae2c13`;53 tests;固定 exe 已更新 | | 13 | 新窗口留在源显示器 + 标签拖拽 + 菜单路径/打开所在位置 | 完成 `9ae2c13`;53 tests;固定 exe 已更新 |
| 14 | 首页标签:Home 默认标签、`+` 新建标签、首页“新建文件”、单首页隐藏标签栏 | 完成;59 tests;固定 exe/发布待收尾 |
## 4. 已确认的产品决策 ## 4. 已确认的产品决策
@@ -77,7 +79,8 @@
- **单换行按换行显示**(softbreak→`<br>`),空行仍是段落分隔;标题内不转换。这是本工具面向 AI 输出的有意方言,和严格 CommonMark 不同;硬折行的长段落会保留断点。 - **单换行按换行显示**(softbreak→`<br>`),空行仍是段落分隔;标题内不转换。这是本工具面向 AI 输出的有意方言,和严格 CommonMark 不同;硬折行的长段落会保留断点。
- 开启 GFM 脚注与定义列表;UTF-8 BOM 在渲染前忽略。 - 开启 GFM 脚注与定义列表;UTF-8 BOM 在渲染前忽略。
- 编辑模式保留 700ms 自动保存 + `Ctrl+S` 立即保存。 - 编辑模式保留 700ms 自动保存 + `Ctrl+S` 立即保存。
- 多窗口:单进程、每窗口一个 WebView2/DocumentSession;标签右键“在新窗口打开”或上下拖动标签(>24px)为移动语义;同一文件只开一个;不恢复 session,只保留 recent;非最后窗口关闭最后一个标签会关闭窗口,最后窗口保留空窗口;Cmd+Q 仅 macOS。详见 `agent/docs/design-single-process-multi-window.md`。 - 多窗口:单进程、每窗口一个 WebView2/DocumentSession;标签右键“在新窗口打开”或上下拖动标签(>24px)为移动语义;同一文件只开一个;不恢复 session,只保留 recent;非最后窗口关闭最后一个标签会关闭窗口,最后窗口关闭最后一个文件标签会回到首页;Cmd+Q 仅 macOS。详见 `agent/docs/design-single-process-multi-window.md`。
- 首页标签(2026-10-28 确认):Home 是**无路径的普通标签**(可多个,浏览器新标签页语义);`+` 追加并激活首页标签;首页上 Open File / Recent / New File / 拖入文件会复用当前首页标签;关闭最后一个文件标签回到首页;只有首页标签时隐藏标签栏(`HIDE_SINGLE_HOME_TAB = true`,一行可关);首页标签不可拖出/不可新窗口打开、不监听文件、不参与查重;首页 New File 按钮取代原 `+` 的建文件语义,`Ctrl+N` 仍新建文件。
- 新窗口位置:源窗口当前显示器内 +28,+28 偏移并 clamp;不逐窗口恢复位置。 - 新窗口位置:源窗口当前显示器内 +28,+28 偏移并 clamp;不逐窗口恢复位置。
- 标签右键菜单:顶部路径(中间省略,保留开头和文件名),第一项“打开文件所在位置”,第二项“在新窗口打开”;右键时临时移除标签 tooltip。 - 标签右键菜单:顶部路径(中间省略,保留开头和文件名),第一项“打开文件所在位置”,第二项“在新窗口打开”;右键时临时移除标签 tooltip。
@@ -106,7 +109,7 @@
- `OpenPaths` 携带目标 WindowId;拖放/导航/IPC/Ready 不再统一落到 active window;批次 target 固定; - `OpenPaths` 携带目标 WindowId;拖放/导航/IPC/Ready 不再统一落到 active window;批次 target 固定;
- detach 不再在创建新窗口前激活源 session;创建/移除失败不会改写源 active; - detach 不再在创建新窗口前激活源 session;创建/移除失败不会改写源 active;
- `focus_open_tab` 在源 active 或目标标签 dirty 时拒绝切换并提示,不再静默丢焦点; - `focus_open_tab` 在源 active 或目标标签 dirty 时拒绝切换并提示,不再静默丢焦点;
- 非最后窗口关闭最后一个标签会关闭该窗口;最后窗口保留空窗口; - 非最后窗口关闭最后一个标签会关闭该窗口;最后窗口关闭最后一个文件标签会回到首页;
- `RecentChanged` 不再清空有标签窗口; - `RecentChanged` 不再清空有标签窗口;
- 移除了不可达的内部 `new-window` 路径。 - 移除了不可达的内部 `new-window` 路径。
- 用户可见变化:启动不再恢复上次标签;同文件重复打开聚焦已有窗口/标签;标签右键现在有“在新窗口打开”(中文界面为“在新窗口打开”),这是第一个普通用户可操作的多窗口入口。 - 用户可见变化:启动不再恢复上次标签;同文件重复打开聚焦已有窗口/标签;标签右键现在有“在新窗口打开”(中文界面为“在新窗口打开”),这是第一个普通用户可操作的多窗口入口。

View File

@@ -36,6 +36,7 @@ struct SelfWriteRecord {
#[derive(Debug)] #[derive(Debug)]
enum UserEvent { enum UserEvent {
NewFile(WindowId), NewFile(WindowId),
NewTab(WindowId),
OpenFile(WindowId), OpenFile(WindowId),
OpenPaths(Option<WindowId>, Vec<PathBuf>, bool), OpenPaths(Option<WindowId>, Vec<PathBuf>, bool),
ActivateTab(WindowId, u64), ActivateTab(WindowId, u64),
@@ -192,6 +193,9 @@ struct Strings {
drop_hint: &'static str, drop_hint: &'static str,
cannot_read: &'static str, cannot_read: &'static str,
open_file: &'static str, open_file: &'static str,
new_file: &'static str,
new_tab: &'static str,
home_tab: &'static str,
recent_title: &'static str, recent_title: &'static str,
missing_title: &'static str, missing_title: &'static str,
missing_body: &'static str, missing_body: &'static str,
@@ -221,6 +225,9 @@ impl Strings {
drop_hint: "Drop a .md file here or press Cmd/Ctrl+O to open", drop_hint: "Drop a .md file here or press Cmd/Ctrl+O to open",
cannot_read: "无法读取文件", cannot_read: "无法读取文件",
open_file: "Open File", open_file: "Open File",
new_file: "新建文件",
new_tab: "新建标签页",
home_tab: "首页",
recent_title: "Recent", recent_title: "Recent",
missing_title: "文件已移动或删除", missing_title: "文件已移动或删除",
missing_body: "这个标签会继续保留。你可以重新定位文件,或关闭标签。", missing_body: "这个标签会继续保留。你可以重新定位文件,或关闭标签。",
@@ -246,6 +253,9 @@ impl Strings {
drop_hint: "Drop a .md file here or press Cmd/Ctrl+O to open", drop_hint: "Drop a .md file here or press Cmd/Ctrl+O to open",
cannot_read: "Cannot read file", cannot_read: "Cannot read file",
open_file: "Open File", open_file: "Open File",
new_file: "New File",
new_tab: "New Tab",
home_tab: "Home",
recent_title: "Recent", recent_title: "Recent",
missing_title: "File Moved or Deleted", missing_title: "File Moved or Deleted",
missing_body: "This tab is kept. Locate the file again or close the tab.", missing_body: "This tab is kept. Locate the file again or close the tab.",
@@ -865,15 +875,21 @@ fn tabs_json(session: &DocumentSession) -> String {
.tabs .tabs
.iter() .iter()
.map(|tab| { .map(|tab| {
// The page localizes the Home label; rust only flags the kind.
let name = tab let name = tab
.path .file_path()
.file_name() .and_then(|path| path.file_name())
.map(|name| name.to_string_lossy().to_string()) .map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| tab.path.to_string_lossy().to_string()); .unwrap_or_default();
let path = tab
.file_path()
.map(|path| path.to_string_lossy().to_string())
.unwrap_or_default();
serde_json::json!({ serde_json::json!({
"id": tab.id, "id": tab.id,
"name": name, "name": name,
"path": tab.path.to_string_lossy(), "path": path,
"home": tab.is_home(),
"active": session.active_id == Some(tab.id), "active": session.active_id == Some(tab.id),
"missing": tab.missing, "missing": tab.missing,
"dirty": tab.dirty, "dirty": tab.dirty,
@@ -1079,16 +1095,18 @@ fn build_enhancer_bootstrap(flags: EnhanceFlags, loaded: EnhanceFlags) -> Vec<St
scripts scripts
} }
fn empty_preview_html(s: &Strings, recent_files: &[PathBuf]) -> String { fn home_preview_html(s: &Strings, recent_files: &[PathBuf]) -> String {
let empty_class = if recent_files.is_empty() { let empty_class = if recent_files.is_empty() {
"empty" "empty"
} else { } else {
"empty has-recent" "empty has-recent"
}; };
let mut html = format!( let mut html = format!(
r#"<div class="{empty_class}"><div class="icon">#</div><div>{}</div><button class="empty-open" type="button" data-open-file>{}</button>"#, r#"<div class="{empty_class}"><div class="icon">#</div><div>{}</div><div class="empty-actions"><button class="empty-open" type="button" data-open-file>{}</button><button class="empty-open empty-new" type="button" data-new-file title="{}">{}</button></div>"#,
html_escape_text(s.drop_hint), 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() { if !recent_files.is_empty() {
@@ -1124,9 +1142,9 @@ fn build_page(
base_href: Option<&str>, base_href: Option<&str>,
flags: EnhanceFlags, flags: EnhanceFlags,
s: &Strings, s: &Strings,
empty: bool, home: bool,
) -> String { ) -> String {
let body_class = if empty { "empty" } else { "" }; let body_class = if home { "home" } else { "" };
let base_tag = base_href let base_tag = base_href
.map(|href| format!(r#"<base id="base-href" href="{}">"#, html_escape_attr(href))) .map(|href| format!(r#"<base id="base-href" href="{}">"#, html_escape_attr(href)))
.unwrap_or_else(|| r#"<base id="base-href">"#.to_string()); .unwrap_or_else(|| r#"<base id="base-href">"#.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; }} min-height: 60vh; color: #999; font-size: 18px; gap: 12px; text-align: center; }}
.empty.has-recent {{ .empty.has-recent {{
justify-content: flex-start; justify-content: flex-start;
min-height: calc(100vh - 48px); min-height: calc(100vh - var(--chrome-top) - 38px);
padding: clamp(56px, 10vh, 96px) 0 40px; padding: clamp(56px, 10vh, 96px) 0 40px;
box-sizing: border-box; box-sizing: border-box;
}} }}
.empty .icon {{ font-size: 48px; opacity: 0.4; }} .empty .icon {{ font-size: 48px; opacity: 0.4; }}
.empty-actions {{ display: flex; gap: 8px; margin-top: 6px; }}
.empty-open {{ .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; border: 1px solid #ddd; border-radius: 8px; background: #fff;
color: #1a1a1a; font: inherit; font-size: 15px; cursor: pointer; 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; font: 16px/1 -apple-system, BlinkMacSystemFont, sans-serif; opacity: .58;
}} }}
.tab-close:hover {{ opacity: 1; background: rgba(0,0,0,.08); }} .tab-close:hover {{ opacity: 1; background: rgba(0,0,0,.08); }}
.tab-close[hidden] {{ display: none; }}
.tab-menu {{ .tab-menu {{
position: fixed; z-index: 200; min-width: 188px; padding: 4px; position: fixed; z-index: 200; min-width: 188px; padding: 4px;
background: #fff; border: 1px solid #ddd; border-radius: 8px; background: #fff; border: 1px solid #ddd; border-radius: 8px;
@@ -1374,7 +1394,7 @@ body.has-tabs {{ --chrome-top: 50px; }}
transition: opacity 0.18s ease; transition: opacity 0.18s ease;
}} }}
html:hover .toolbar {{ opacity: 1; pointer-events: auto; }} html:hover .toolbar {{ opacity: 1; pointer-events: auto; }}
body.empty .toolbar {{ display: none !important; }} body.home .toolbar {{ display: none !important; }}
.toolbar button {{ .toolbar button {{
width: 34px; height: 34px; padding: 0; width: 34px; height: 34px; padding: 0;
background: rgba(255,255,255,0.8); 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; }} #preview .mdp-fold-toggle {{ display: none !important; }}
}} }}
</style></head><body class="{body_class}"> </style></head><body class="{body_class}">
<div class="tabbar" id="tabbar"><div class="tabs" id="tabs"></div><div class="doc-stats" id="doc-stats" aria-live="polite"></div><button class="tab-open" id="tab-open" type="button" title="{btn_new}" aria-label="{btn_new}">+</button></div> <div class="tabbar" id="tabbar"><div class="tabs" id="tabs"></div><div class="doc-stats" id="doc-stats" aria-live="polite"></div><button class="tab-open" id="tab-open" type="button" title="{new_tab}" aria-label="{new_tab}">+</button></div>
<div class="tab-menu" id="tab-menu" hidden><div class="tab-menu-path" id="tab-menu-path"></div><button type="button" id="tab-menu-reveal">{btn_open_location}</button><button type="button" id="tab-menu-new-window">{btn_new_window}</button></div> <div class="tab-menu" id="tab-menu" hidden><div class="tab-menu-path" id="tab-menu-path"></div><button type="button" id="tab-menu-reveal">{btn_open_location}</button><button type="button" id="tab-menu-new-window">{btn_new_window}</button></div>
<div class="toolbar"> <div class="toolbar">
<button id="btn-toggle" title="{btn_edit}" aria-label="{btn_edit}"></button> <button id="btn-toggle" title="{btn_edit}" aria-label="{btn_edit}"></button>
@@ -1542,7 +1562,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
var ICON_UP = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m18 15-6-6-6 6"/></svg>'; var ICON_UP = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m18 15-6-6-6 6"/></svg>';
var ICON_DOWN = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>'; var ICON_DOWN = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>';
var ICON_CLOSE = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>'; var ICON_CLOSE = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>';
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.__mdPreviewFoldLabel = '{fold_toggle}';
window.__mdPreviewCannotSave = '{cannot_save_js}'; window.__mdPreviewCannotSave = '{cannot_save_js}';
@@ -1578,6 +1598,9 @@ body.editing #app {{ max-width: none; padding: 0; }}
var composingFind = false; var composingFind = false;
var pendingFindTimer = 0; var pendingFindTimer = 0;
var FIND_DEBOUNCE_MS = 300; 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 findHits = [];
var currentFindHit = -1; var currentFindHit = -1;
var lastFindQuery = ''; var lastFindQuery = '';
@@ -1683,15 +1706,16 @@ body.editing #app {{ max-width: none; padding: 0; }}
suppressTabTooltips(); suppressTabTooltips();
tabMenuTargetId = id; tabMenuTargetId = id;
var tabEl = tabsEl.querySelector('.tab[data-tab-id="' + 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') || '') : ''; var path = tabEl ? (tabEl.getAttribute('data-tab-path') || '') : '';
if (tabMenuPath) {{ if (tabMenuPath) {{
tabMenuPath.textContent = shortenPath(path, 42); tabMenuPath.textContent = isHome ? L_HOME : shortenPath(path, 42);
if (path) tabMenuPath.setAttribute('title', path); if (!isHome && path) tabMenuPath.setAttribute('title', path);
else tabMenuPath.removeAttribute('title'); else tabMenuPath.removeAttribute('title');
}} }}
tabMenu.hidden = false; tabMenu.hidden = false;
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1; if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1 || isHome;
if (tabMenuReveal) tabMenuReveal.disabled = !path; if (tabMenuReveal) tabMenuReveal.disabled = isHome || !path;
tabMenu.style.left = '0px'; tabMenu.style.left = '0px';
tabMenu.style.top = '0px'; tabMenu.style.top = '0px';
var rect = tabMenu.getBoundingClientRect(); var rect = tabMenu.getBoundingClientRect();
@@ -1765,8 +1789,13 @@ body.editing #app {{ max-width: none; padding: 0; }}
window.ipc.postMessage('new-file'); window.ipc.postMessage('new-file');
}} }}
window.__mdPreviewNewFile = newFile; 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() {{ function showFind() {{
if (document.body.classList.contains('empty')) return; if (document.body.classList.contains('home')) return;
if (inEdit()) return; if (inEdit()) return;
document.body.classList.add('finding'); document.body.classList.add('finding');
setTimeout(function(){{ findInput.focus(); findInput.select(); }}, 0); setTimeout(function(){{ findInput.focus(); findInput.select(); }}, 0);
@@ -1905,6 +1934,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
window.scrollTo(x, y); window.scrollTo(x, y);
}} }}
function enterEdit() {{ function enterEdit() {{
if (document.body.classList.contains('home')) return;
var progress = currentScrollProgress(); var progress = currentScrollProgress();
document.body.classList.add('editing'); document.body.classList.add('editing');
btnToggle.innerHTML = ICON_VIEW; btnToggle.innerHTML = ICON_VIEW;
@@ -1937,7 +1967,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
if (activeTabId) requestTabAction('close', activeTabId); if (activeTabId) requestTabAction('close', activeTabId);
}}; }};
tabOpen.addEventListener('click', newFile); tabOpen.addEventListener('click', newTab);
if (tabMenuNewWindow) {{ if (tabMenuNewWindow) {{
tabMenuNewWindow.addEventListener('click', function(e) {{ tabMenuNewWindow.addEventListener('click', function(e) {{
e.preventDefault(); e.preventDefault();
@@ -1960,6 +1990,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
if (e.button !== 0 || tabCount <= 1) return; if (e.button !== 0 || tabCount <= 1) return;
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null; 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 || (e.target.closest && e.target.closest('.tab-close'))) return;
if (tab.classList.contains('home')) return;
hideTabMenu(); hideTabMenu();
tabDrag = {{ id: tab.getAttribute('data-tab-id'), startY: e.clientY, element: tab, pointerId: e.pointerId, dragged: false }}; tabDrag = {{ id: tab.getAttribute('data-tab-id'), startY: e.clientY, element: tab, pointerId: e.pointerId, dragged: false }};
try {{ tab.setPointerCapture(e.pointerId); }} catch (err) {{}} 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')); requestTabAction('activate', tab.getAttribute('data-tab-id'));
return; 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; var openBtn = e.target && e.target.closest ? e.target.closest('[data-open-file]') : null;
if (openBtn) {{ if (openBtn) {{
e.preventDefault(); e.preventDefault();
@@ -2192,28 +2229,34 @@ body.editing #app {{ max-width: none; padding: 0; }}
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1; if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1;
tabsEl.textContent = ''; tabsEl.textContent = '';
activeTabId = 0; 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) {{ tabs.forEach(function(tab) {{
var isHome = !!tab.home;
var item = document.createElement('div'); 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-id', tab.id);
item.setAttribute('data-tab-path', tab.path); item.setAttribute('data-tab-path', isHome ? '' : tab.path);
item.setAttribute('role', 'button'); item.setAttribute('role', 'button');
item.setAttribute('tabindex', '0'); item.setAttribute('tabindex', '0');
item.title = tab.path; item.title = isHome ? L_HOME : tab.path;
if (tab.active) activeTabId = tab.id; if (tab.active) activeTabId = tab.id;
var status = document.createElement('span'); var status = document.createElement('span');
status.className = 'tab-status'; status.className = 'tab-status';
status.textContent = tab.missing ? '!' : ''; status.textContent = tab.missing ? '!' : '';
var name = document.createElement('span'); var name = document.createElement('span');
name.className = 'tab-name'; name.className = 'tab-name';
name.textContent = tab.name; name.textContent = isHome ? L_HOME : tab.name;
var close = document.createElement('button'); var close = document.createElement('button');
close.className = 'tab-close'; close.className = 'tab-close';
close.type = 'button'; close.type = 'button';
close.setAttribute('data-close-tab', tab.id); 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 = '×'; 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(status);
item.appendChild(name); item.appendChild(name);
item.appendChild(close); item.appendChild(close);
@@ -2229,7 +2272,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
requestTabAction('activate', tab.getAttribute('data-tab-id')); requestTabAction('activate', tab.getAttribute('data-tab-id'));
}}); }});
window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid) {{ window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid) {{
document.body.classList.remove('empty'); document.body.classList.remove('home');
document.body.classList.remove('missing'); document.body.classList.remove('missing');
hideFind(); hideFind();
window.__setBaseHref(baseHref); window.__setBaseHref(baseHref);
@@ -2243,7 +2286,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
}} }}
}}; }};
window.__setEmptyPreview = function(previewHtml) {{ window.__setEmptyPreview = function(previewHtml) {{
document.body.classList.add('empty'); document.body.classList.add('home');
document.body.classList.remove('missing'); document.body.classList.remove('missing');
document.body.classList.remove('editing'); document.body.classList.remove('editing');
btnToggle.innerHTML = ICON_EDIT; btnToggle.innerHTML = ICON_EDIT;
@@ -2260,7 +2303,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
window.scrollTo(0, 0); window.scrollTo(0, 0);
}}; }};
window.__setMissing = function(previewHtml) {{ window.__setMissing = function(previewHtml) {{
document.body.classList.remove('empty'); document.body.classList.remove('home');
document.body.classList.add('missing'); document.body.classList.add('missing');
document.body.classList.remove('editing'); document.body.classList.remove('editing');
btnToggle.innerHTML = ICON_EDIT; btnToggle.innerHTML = ICON_EDIT;
@@ -2300,7 +2343,8 @@ if(window.__enhancePreview)window.__enhancePreview();
base_tag = base_tag, base_tag = base_tag,
preview_html = preview_html, preview_html = preview_html,
raw_md_escaped = html_escape_ta(raw_md), 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_new_window = s.btn_new_window,
btn_open_location = s.btn_open_location, btn_open_location = s.btn_open_location,
btn_edit = s.btn_edit, btn_edit = s.btn_edit,
@@ -2792,8 +2836,21 @@ mod tests {
); );
assert!(page.contains("window.ipc.postMessage('new-file')")); 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("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("AUTOSAVE_DEBOUNCE_MS = 700"));
assert!(page.contains("pendingAutosaveTimer = setTimeout")); assert!(page.contains("pendingAutosaveTimer = setTimeout"));
assert!(page.contains("window.__markSaved = function(savedRaw)")); assert!(page.contains("window.__markSaved = function(savedRaw)"));
@@ -2904,9 +2961,12 @@ mod tests {
fn empty_state_exposes_open_and_recent_files() { fn empty_state_exposes_open_and_recent_files() {
let strings = Strings::for_lang(Lang::En); let strings = Strings::for_lang(Lang::En);
let recent = vec![PathBuf::from("/tmp/example.md")]; 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("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("Recent"));
assert!(html.contains("example.md")); assert!(html.contains("example.md"));
assert!(html.contains("data-recent-index=\"0\"")); 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"));
assert!(!page.contains(".empty.has-recent .recent { max-height")); assert!(!page.contains(".empty.has-recent .recent { max-height"));
assert!(page.contains("<body class=\"home\">"));
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] #[test]
@@ -3651,11 +3725,11 @@ fn install_file_watcher(
) { ) {
let mut current = holder.lock().unwrap(); let mut current = holder.lock().unwrap();
*current = None; *current = None;
*last_self_write.lock().unwrap() = None;
let Some(path) = path else { let Some(path) = path else {
return; return;
}; };
let mut observed_content = fs::read(&path).ok(); let mut observed_content = fs::read(&path).ok();
*last_self_write.lock().unwrap() = None;
let target_path = path.clone(); let target_path = path.clone();
let callback_path = path.clone(); let callback_path = path.clone();
let proxy = proxy.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()); let normalized = session::normalize_path(path.to_path_buf());
for (window_id, ws) in &app.windows { for (window_id, ws) in &app.windows {
let session = ws.session.lock().unwrap(); 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)); return Some((*window_id, tab.id));
} }
} }
@@ -3908,8 +3986,8 @@ fn focus_open_tab(
.session .session
.lock() .lock()
.unwrap() .unwrap()
.active() .active_path()
.map(|tab| tab.path.clone()); .map(Path::to_path_buf);
install_file_watcher(&ws.watcher, proxy, &ws.last_self_write, window_id, path); install_file_watcher(&ws.watcher, proxy, &ws.last_self_write, window_id, path);
true true
} }
@@ -3920,20 +3998,38 @@ fn update_tabs(webview: &WebView, session: &DocumentSession) {
} }
fn update_window_title(window: &Window, session: &DocumentSession) { fn update_window_title(window: &Window, session: &DocumentSession) {
let title = session let title = match session.active() {
.active() Some(tab) => match tab.file_path() {
.map(|tab| { Some(path) => {
let name = tab let name = path
.path .file_name()
.file_name() .map(|name| name.to_string_lossy().to_string())
.map(|name| name.to_string_lossy().to_string()) .unwrap_or_else(|| path.to_string_lossy().to_string());
.unwrap_or_else(|| tab.path.to_string_lossy().to_string()); format!("{}{} — MD Preview", if tab.dirty { "• " } else { "" }, name)
format!("{}{} — MD Preview", if tab.dirty { "• " } else { "" }, name) }
}) None => "MD Preview".to_string(),
.unwrap_or_else(|| "MD Preview".to_string()); },
None => "MD Preview".to_string(),
};
window.set_title(&title); window.set_title(&title);
} }
fn render_home(
webview: &WebView,
window: &Window,
session: &DocumentSession,
recent_files: &Arc<Mutex<Vec<PathBuf>>>,
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( fn render_active_document(
webview: &WebView, webview: &WebView,
window: &Window, window: &Window,
@@ -3944,24 +4040,23 @@ fn render_active_document(
strings: &Strings, strings: &Strings,
) -> bool { ) -> bool {
let Some(active) = session.active().cloned() else { let Some(active) = session.active().cloned() else {
let html = empty_preview_html(strings, &recent_files.lock().unwrap()); render_home(webview, window, session, recent_files, strings);
let _ = webview.evaluate_script(&format!( return false;
"if(window.__setEmptyPreview)window.__setEmptyPreview('{}');", };
escape_js(&html) // Home tabs carry no file; they render the new-tab page.
)); let Some(path) = active.file_path().map(Path::to_path_buf) else {
update_tabs(webview, session); render_home(webview, window, session, recent_files, strings);
update_window_title(window, session);
return false; return false;
}; };
match fs::read_to_string(&active.path) { match fs::read_to_string(&path) {
Ok(raw) => { Ok(raw) => {
if let Some(tab) = session.get_mut(active.id) { if let Some(tab) = session.get_mut(active.id) {
tab.missing = false; tab.missing = false;
} }
remember_recent_file(recent_files, &active.path); remember_recent_file(recent_files, &path);
let html = md_to_html_with_base(&raw, active.path.parent()); let html = md_to_html_with_base(&raw, path.parent());
let base_href = base_href_for_file(&active.path).unwrap_or_default(); let base_href = base_href_for_file(&path).unwrap_or_default();
let flags = enhance_flags_for(&raw); let flags = enhance_flags_for(&raw);
*enhance_flags.lock().unwrap() = flags; *enhance_flags.lock().unwrap() = flags;
let _ = webview.evaluate_script(&format!( 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.", "The file disappeared while it still has unsaved edits. The editor content has been kept.",
); );
} else { } 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!( let _ = webview.evaluate_script(&format!(
"if(window.__setMissing)window.__setMissing('{}');", "if(window.__setMissing)window.__setMissing('{}');",
escape_js(&html) escape_js(&html)
@@ -4013,7 +4108,7 @@ fn render_active_document(
r#"<div class="missing-file"><h2>{}</h2><p>{}</p><code>{}</code><button type="button" data-open-file>{}</button><button type="button" data-close-tab="{}">{}</button></div>"#, r#"<div class="missing-file"><h2>{}</h2><p>{}</p><code>{}</code><button type="button" data-open-file>{}</button><button type="button" data-close-tab="{}">{}</button></div>"#,
html_escape_text(strings.cannot_read), html_escape_text(strings.cannot_read),
html_escape_text(&error.to_string()), 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), html_escape_text(strings.open_file),
active.id, active.id,
html_escape_text(strings.close_tab), 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. // persisted path data in this page; load the active tab after the ready IPC.
fn build_startup_page(strings: &Strings) -> String { fn build_startup_page(strings: &Strings) -> String {
build_page( build_page(
&empty_preview_html(strings, &[]), &home_preview_html(strings, &[]),
"", "",
None, None,
EnhanceFlags::default(), EnhanceFlags::default(),
@@ -4104,7 +4199,7 @@ fn build_webview(
} }
} }
} else if let Some(url) = body.strip_prefix("open-local-link:") { } 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()) { if let Some(path) = resolve_document_link(url, active_path.as_deref()) {
let _ = proxy_for_ipc.send_event(UserEvent::OpenPaths( let _ = proxy_for_ipc.send_event(UserEvent::OpenPaths(
Some(window_id), Some(window_id),
@@ -4124,7 +4219,7 @@ fn build_webview(
return; return;
}; };
if let Some(content) = pending_content { 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 { let Some(path) = path else {
return; return;
}; };
@@ -4156,6 +4251,9 @@ fn build_webview(
"detach" => { "detach" => {
let _ = proxy_for_ipc.send_event(UserEvent::DetachTab(window_id, id)); 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:") { } else if let Some(id) = body.strip_prefix("locate-tab:") {
@@ -4185,11 +4283,11 @@ fn build_webview(
save_zoom(percent); save_zoom(percent);
} }
} else if body == "refresh" { } 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)); let _ = proxy_for_ipc.send_event(UserEvent::FileChanged(window_id, path));
} }
} else if let Some(content) = body.strip_prefix("save:") { } 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 { if let Some(path) = path {
*last_self_write.lock().unwrap() = Some(SelfWriteRecord { *last_self_write.lock().unwrap() = Some(SelfWriteRecord {
path: path.clone(), 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 = builder.build(target).map_err(|error| error.to_string())?;
let window_id = window.id(); let window_id = window.id();
let page = build_startup_page(&app.strings); 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 session = Arc::new(Mutex::new(initial_session));
let last_self_write = Arc::new(Mutex::new(None)); let last_self_write = Arc::new(Mutex::new(None));
let recent_files = Arc::clone(&app.recent_files); let recent_files = Arc::clone(&app.recent_files);
@@ -4469,6 +4571,9 @@ fn main() {
for path in cli_paths { for path in cli_paths {
initial_session.open(path, edit_from_cli); initial_session.open(path, edit_from_cli);
} }
if initial_session.tabs.is_empty() {
initial_session.open_home();
}
let event_loop: EventLoop<UserEvent> = EventLoopBuilder::with_user_event().build(); let event_loop: EventLoop<UserEvent> = EventLoopBuilder::with_user_event().build();
let proxy = event_loop.create_proxy(); let proxy = event_loop.create_proxy();
@@ -4485,7 +4590,8 @@ fn main() {
let title = initial_session let title = initial_session
.active() .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())) .map(|name| format!("{} — MD Preview", name.to_string_lossy()))
.unwrap_or_else(|| "MD Preview".to_string()); .unwrap_or_else(|| "MD Preview".to_string());
@@ -4622,7 +4728,8 @@ fn main() {
.lock() .lock()
.unwrap() .unwrap()
.active() .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() let mut dialog = rfd::FileDialog::new()
.add_filter("Markdown", &["md", "markdown", "mdown", "mkd"]) .add_filter("Markdown", &["md", "markdown", "mdown", "mkd"])
.set_file_name(strings.new_filename); .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)) => { TaoEvent::UserEvent(UserEvent::OpenPaths(target, paths, edit_on_open)) => {
let target_window = target.unwrap_or(app.active_window); let target_window = target.unwrap_or(app.active_window);
let Some(ws) = app.windows.get_mut(&target_window) else { let Some(ws) = app.windows.get_mut(&target_window) else {
@@ -4719,7 +4836,11 @@ fn main() {
let mut session = ws.session.lock().unwrap(); let mut session = ws.session.lock().unwrap();
let previous_active = session.active_id; let previous_active = session.active_id;
let preserve_active = session.active().map(|tab| tab.dirty).unwrap_or(false); 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 preserve_active {
if let Some(id) = previous_active { if let Some(id) = previous_active {
session.activate(id); session.activate(id);
@@ -4731,7 +4852,7 @@ fn main() {
drop(session); drop(session);
ws.render_active(&recent_files, &strings); 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( install_file_watcher(
&ws.watcher, &ws.watcher,
&proxy, &proxy,
@@ -4749,7 +4870,7 @@ fn main() {
if session.activate(id) { if session.activate(id) {
drop(session); drop(session);
ws.render_active(&recent_files, &strings); 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); install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
} }
} }
@@ -4759,20 +4880,34 @@ fn main() {
return; return;
}; };
let mut session = ws.session.lock().unwrap(); 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 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.close(id) {
if session.tabs.is_empty() { if was_active {
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 {
drop(session); drop(session);
ws.render_active(&recent_files, &strings); 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); install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
} else { } else {
update_tabs(&ws.webview, &session); 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 { let Some(tab) = session.tabs.iter().find(|tab| tab.id == tab_id).cloned() else {
return; return;
}; };
if tab.is_home() {
return;
}
let target_active = session.active_id == Some(tab_id); let target_active = session.active_id == Some(tab_id);
if !target_active && tab.dirty { if !target_active && tab.dirty {
drop(session); drop(session);
@@ -4833,7 +4971,7 @@ fn main() {
if !close_source { if !close_source {
drop(session); drop(session);
ws.render_active(&recent_files, &strings); 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); install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
} }
} }
@@ -4848,7 +4986,8 @@ fn main() {
.tabs .tabs
.iter() .iter()
.find(|tab| tab.id == tab_id) .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 let Some(path) = path {
if !reveal_in_explorer(&path) { if !reveal_in_explorer(&path) {
@@ -4901,7 +5040,7 @@ fn main() {
if session.relocate(id, path) && session.activate(id) { if session.relocate(id, path) && session.activate(id) {
drop(session); drop(session);
ws.render_active(&recent_files, &strings); 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); install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
} else { } else {
show_warning_dialog("Already Open", "That file is already open in another tab."); 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 { let Some(ws) = app.windows.get_mut(&window_id) else {
return; return;
}; };
if ws if ws.session.lock().unwrap().active_path() == Some(path.as_path()) {
.session
.lock()
.unwrap()
.active()
.map(|tab| tab.path.as_path())
== Some(path.as_path())
{
ws.pending_external_change = Some(path); ws.pending_external_change = Some(path);
let _ = ws.webview.evaluate_script( let _ = ws.webview.evaluate_script(
"if(window.__mdPreviewResolveExternalChange)window.__mdPreviewResolveExternalChange();", "if(window.__mdPreviewResolveExternalChange)window.__mdPreviewResolveExternalChange();",
@@ -4937,7 +5069,7 @@ fn main() {
return; return;
} }
let mut session = ws.session.lock().unwrap(); 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); let session_dirty = session.active().map(|tab| tab.dirty).unwrap_or(false);
if should_protect_external_change(webview_dirty, session_dirty) { if should_protect_external_change(webview_dirty, session_dirty) {
if let Some(tab) = session.active_mut() { if let Some(tab) = session.active_mut() {
@@ -4969,8 +5101,12 @@ fn main() {
ws.warned_external_change = None; ws.warned_external_change = None;
} }
let mut session = ws.session.lock().unwrap(); let mut session = ws.session.lock().unwrap();
let active_matches = session.active().map(|tab| tab.path.as_path()) == Some(path.as_path()); let active_matches = session.active_path() == Some(path.as_path());
if let Some(tab) = session.tabs.iter_mut().find(|tab| tab.path == path) { if let Some(tab) = session
.tabs
.iter_mut()
.find(|tab| tab.path.as_deref() == Some(path.as_path()))
{
tab.dirty = false; tab.dirty = false;
tab.missing = false; tab.missing = false;
} }
@@ -5052,13 +5188,13 @@ fn main() {
.evaluate_script("if(window.__mdPreviewShowFind)window.__mdPreviewShowFind();"); .evaluate_script("if(window.__mdPreviewShowFind)window.__mdPreviewShowFind();");
} }
TaoEvent::UserEvent(UserEvent::RecentChanged) => { 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!( let js = format!(
"if(window.__setEmptyPreview)window.__setEmptyPreview('{}');", "if(window.__setEmptyPreview)window.__setEmptyPreview('{}');",
escape_js(&html) escape_js(&html)
); );
for ws in app.windows.values() { 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); let _ = ws.webview.evaluate_script(&js);
} }
} }
@@ -5110,7 +5246,7 @@ fn main() {
if !ws.page_ready { if !ws.page_ready {
ws.page_ready = true; ws.page_ready = true;
ws.render_active(&recent_files, &strings); 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); install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path);
} }
for (paths, edit) in ws.pending_launches.drain(..) { for (paths, edit) in ws.pending_launches.drain(..) {

View File

@@ -1,15 +1,26 @@
use std::fs; use std::fs;
use std::path::PathBuf; use std::path::{Path, PathBuf};
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub struct DocumentTab { pub struct DocumentTab {
pub id: u64, pub id: u64,
pub path: PathBuf, /// `None` marks the built-in Home tab; Home has no file on disk.
pub path: Option<PathBuf>,
pub dirty: bool, pub dirty: bool,
pub missing: bool, pub missing: bool,
pub edit_on_open: 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)] #[derive(Debug, Default)]
pub struct DocumentSession { pub struct DocumentSession {
pub tabs: Vec<DocumentTab>, pub tabs: Vec<DocumentTab>,
@@ -20,8 +31,12 @@ pub struct DocumentSession {
impl DocumentSession { impl DocumentSession {
pub fn open(&mut self, path: PathBuf, edit_on_open: bool) -> u64 { pub fn open(&mut self, path: PathBuf, edit_on_open: bool) -> u64 {
let path = normalize_path(path); let path = normalize_path(path);
if let Some(tab) = self.tabs.iter_mut().find(|tab| tab.path == path) { if let Some(tab) = self
tab.missing = !tab.path.exists(); .tabs
.iter_mut()
.find(|tab| tab.path.as_deref() == Some(path.as_path()))
{
tab.missing = !path.exists();
tab.edit_on_open |= edit_on_open; tab.edit_on_open |= edit_on_open;
self.active_id = Some(tab.id); self.active_id = Some(tab.id);
return tab.id; return tab.id;
@@ -29,22 +44,82 @@ impl DocumentSession {
self.next_id += 1; self.next_id += 1;
let id = self.next_id; let id = self.next_id;
let missing = !path.exists();
self.tabs.push(DocumentTab { self.tabs.push(DocumentTab {
id, id,
missing: !path.exists(), path: Some(path),
path,
dirty: false, dirty: false,
missing,
edit_on_open, edit_on_open,
}); });
self.active_id = Some(id); self.active_id = Some(id);
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 { pub fn activate(&mut self, id: u64) -> bool {
let Some(tab) = self.tabs.iter_mut().find(|tab| tab.id == id) else { let Some(tab) = self.tabs.iter_mut().find(|tab| tab.id == id) else {
return false; return false;
}; };
tab.missing = !tab.path.exists(); if let Some(path) = tab.path.as_deref() {
tab.missing = !path.exists();
}
self.active_id = Some(id); self.active_id = Some(id);
true true
} }
@@ -65,6 +140,17 @@ impl DocumentSession {
true 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 { pub fn with_tab(tab: DocumentTab) -> Self {
let id = tab.id; let id = tab.id;
Self { Self {
@@ -76,6 +162,9 @@ impl DocumentSession {
pub fn detach(&mut self, id: u64) -> Option<DocumentTab> { pub fn detach(&mut self, id: u64) -> Option<DocumentTab> {
let index = self.tabs.iter().position(|tab| tab.id == id)?; 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 was_active = self.active_id == Some(id);
let tab = self.tabs.remove(index); let tab = self.tabs.remove(index);
if was_active { if was_active {
@@ -98,20 +187,36 @@ impl DocumentSession {
self.tabs.iter_mut().find(|tab| tab.id == id) 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> { pub fn get_mut(&mut self, id: u64) -> Option<&mut DocumentTab> {
self.tabs.iter_mut().find(|tab| tab.id == id) self.tabs.iter_mut().find(|tab| tab.id == id)
} }
pub fn relocate(&mut self, id: u64, path: PathBuf) -> bool { pub fn relocate(&mut self, id: u64, path: PathBuf) -> bool {
let path = normalize_path(path); 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; return false;
} }
let missing = !path.exists();
let Some(tab) = self.get_mut(id) else { let Some(tab) = self.get_mut(id) else {
return false; return false;
}; };
tab.path = path; if tab.is_home() {
tab.missing = !tab.path.exists(); return false;
}
tab.path = Some(path);
tab.missing = missing;
true true
} }
} }
@@ -222,6 +327,83 @@ mod tests {
let _ = fs::remove_dir_all(dir); 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")] #[cfg(target_os = "windows")]
#[test] #[test]
fn opened_paths_drop_windows_verbatim_prefix() { fn opened_paths_drop_windows_verbatim_prefix() {
@@ -232,9 +414,13 @@ mod tests {
session.open(file.clone(), false); 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!(!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); let _ = fs::remove_dir_all(dir);
} }
} }