chore: baseline md-preview 1.4.2 + agent workspace
This commit is contained in:
1
.gitattributes
vendored
Normal file
1
.gitattributes
vendored
Normal file
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
11
.gitignore
vendored
Normal file
11
.gitignore
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
# 构建产物
|
||||
/target/
|
||||
/MD-Preview-windows-x64.exe
|
||||
|
||||
# 上游源码备份:本地保留,不入 git(用户决定)
|
||||
/backup/
|
||||
|
||||
# 日志与临时文件
|
||||
*.log
|
||||
/agent/tmp/
|
||||
/agent/reports/*.log
|
||||
4379
Cargo.lock
generated
Normal file
4379
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
36
Cargo.toml
Normal file
36
Cargo.toml
Normal file
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "md-preview"
|
||||
version = "1.4.2"
|
||||
edition = "2021"
|
||||
rust-version = "1.89"
|
||||
|
||||
[dependencies]
|
||||
wry = "0.50"
|
||||
tao = "0.33"
|
||||
pulldown-cmark = { version = "0.12", default-features = false, features = ["html"] }
|
||||
rfd = "0.15"
|
||||
notify = "7"
|
||||
open = "5"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "ico"] }
|
||||
sys-locale = "0.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
url = "2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = "0.52"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2 = "0.6.4"
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["NSAlert", "NSApplication", "NSButton", "NSCell", "NSControl", "NSEvent", "NSImage", "NSMenu", "NSMenuItem", "NSResponder", "NSView"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["objc2-core-foundation", "NSString"] }
|
||||
|
||||
[target.'cfg(windows)'.build-dependencies]
|
||||
winresource = "0.1"
|
||||
|
||||
[profile.release]
|
||||
opt-level = "z"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
strip = true
|
||||
panic = "abort"
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 vorojar
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
13
README.md
Normal file
13
README.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# MD Preview(Windows 本地版)
|
||||
|
||||
本地 Markdown 预览/编辑器,离线、无自动更新,产物固定为
|
||||
`D:\Scripts\md-preview\MD-Preview-windows-x64.exe`。
|
||||
|
||||
- 构建与校验:`agent/scripts/build.ps1`
|
||||
- 交接文档:`agent/docs/HANDOFF.md`
|
||||
- 代码扫描:`agent/docs/scan-2026-10-21.md`
|
||||
- 功能计划:`agent/docs/roadmap.md`
|
||||
- Agent 约定:`agent/README.md`
|
||||
|
||||
> 默认 `.md` 打开方式指向上述 exe 路径,**不要改名或移动**。
|
||||
> `backup/` 与成品 exe 不入 git。
|
||||
44
agent/README.md
Normal file
44
agent/README.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# agent/ — MD Preview 维护者工作区
|
||||
|
||||
这里是本项目的“Agent 附属区”:文档、构建/冒烟脚本、测试夹具与验证记录。应用代码仍在 `src/`。
|
||||
|
||||
## 目录
|
||||
|
||||
| 路径 | 用途 |
|
||||
|---|---|
|
||||
| `docs/HANDOFF.md` | 主交接文档(工具链、构建、坑、验收) |
|
||||
| `docs/scan-2026-10-21.md` | 代码扫描:残留、bug、修复建议 |
|
||||
| `docs/roadmap.md` | 功能路线图与验收标准 |
|
||||
| `scripts/build.ps1` | release 构建 → 固定 exe 路径 → 校验 |
|
||||
| `tests/smoke.ps1` | cargo test + 关联检查 + 可选隔离启动 |
|
||||
| `tests/fixtures/` | 手工/冒烟用 Markdown 样例 |
|
||||
| `reports/` | 验证截图与记录(png 入库,日志忽略) |
|
||||
| `notes/` | 草稿 |
|
||||
|
||||
## 不变量
|
||||
|
||||
1. **产物路径固定**:`D:\Scripts\md-preview\MD-Preview-windows-x64.exe`。默认 `.md` 打开方式指向它,不要改名/移动。
|
||||
2. **离线**:不引入联网、自动更新、遥测;外部链接交给系统浏览器。
|
||||
3. **轻量**:不为小功能引入新库;优先原生 JS/CSS 与已有依赖。
|
||||
4. **测试**:`cargo test` 必须保持全绿;UI 行为用 `tests/fixtures` 做手工/冒烟回归。
|
||||
|
||||
## 常用命令
|
||||
|
||||
```powershell
|
||||
# 构建并校验(推荐)
|
||||
.\agent\scripts\build.ps1
|
||||
|
||||
# 只跑测试
|
||||
cargo test
|
||||
|
||||
# 冒烟(含注册表与可选启动)
|
||||
.\agent\tests\smoke.ps1 -Launch
|
||||
```
|
||||
|
||||
## 环境注意
|
||||
|
||||
工作区是 **Medium** 完整性级别。DSH 用 `workspace-write` 打开时进程是 **Low**,会写不动(EPERM / os error 5)。改代码、编译、替换 exe 需要 DSH 以 **danger-full-access** 运行,或在你自己的普通 PowerShell 里执行。详见 `docs/HANDOFF.md` 第 4 节。
|
||||
|
||||
## Git
|
||||
|
||||
仓库由用户自行初始化(私有)。`backup/` 与成品 exe 不入库;`agent/` 全量入库。
|
||||
264
agent/docs/HANDOFF.md
Normal file
264
agent/docs/HANDOFF.md
Normal file
@@ -0,0 +1,264 @@
|
||||
# MD Preview 本地维护交接
|
||||
|
||||
> 最后更新:2026-10-21
|
||||
> 维护范围:仅 Windows 本地构建,目标产物 `MD-Preview-windows-x64.exe`
|
||||
|
||||
## 1. 当前状态
|
||||
|
||||
- 上游版本:`md-preview 1.4.2`(源码来自 `backup/md-preview-master.zip`)
|
||||
- 改造目标:**本地预览器,不联网、不自动更新**;预览/编辑/标签/会话等功能与上游一致
|
||||
- 源码规模:`src/main.rs` 4229 行、`src/session.rs` 247 行、`src/instance.rs` 207 行
|
||||
- 当前产物:`D:\Scripts\md-preview\MD-Preview-windows-x64.exe`
|
||||
- 大小 5,495,296 字节
|
||||
- SHA256 `1931EA5D0062E465AFEED7B0E7BD6D1B598500861101D66AD8ABB93E44EA3A6F`
|
||||
- 测试:`cargo test` → 39 passed, 0 failed
|
||||
- 编译警告:1 个 `dead_code`(macOS 专用事件枚举,Windows 下未构造),可忽略
|
||||
|
||||
## 2. 本机工具链
|
||||
|
||||
| 组件 | 版本 / 路径 |
|
||||
|---|---|
|
||||
| Rust | 1.99.1 (`stable-x86_64-pc-windows-msvc`) |
|
||||
| cargo | 1.99.1 |
|
||||
| MSVC | 14.51.36231(VS 18 Community,C++ 桌面开发) |
|
||||
| Windows SDK | 10.0.26100 / 10.0.28000 |
|
||||
| WebView2 Runtime | 155.x |
|
||||
|
||||
Rust 安装在默认位置:`C:\Users\wucl1\.cargo`、`C:\Users\wucl1\.rustup`。
|
||||
DSH 的 pwsh 可能没有继承 PATH,构建时用完整路径:
|
||||
|
||||
```powershell
|
||||
& "$env:USERPROFILE\.cargo\bin\cargo.exe" build --release
|
||||
```
|
||||
|
||||
## 3. 构建与运行
|
||||
|
||||
```powershell
|
||||
cd D:\Scripts\md-preview
|
||||
cargo build --release
|
||||
copy .\target\release\md-preview.exe .\MD-Preview-windows-x64.exe
|
||||
.\MD-Preview-windows-x64.exe
|
||||
```
|
||||
|
||||
- 增量构建约 15 秒,清理后约 1–2 分钟(16 核,release 开启 LTO + opt-level=z)
|
||||
- 依赖锁定在 `Cargo.lock`(435 个包),**不要随手 `cargo update`**
|
||||
- 调试可 `cargo build`(debug,快),产物在 `target\debug\`
|
||||
|
||||
## 4. ⚠️ 必读:完整性级别与 os error 5
|
||||
|
||||
这是本次维护踩过最大的坑,务必先读:
|
||||
|
||||
- DSH 的 **workspace-write** 模式会把子进程降为 **Low 完整性级别(Low IL)**,并期望工作区文件也是 Low。
|
||||
- 从被标成 Low 的目录编译出的 exe 会继承 Low 标签;启动后写 `%LOCALAPPDATA%\md-preview\instance.lock` 会被 Windows 的 no-write-up 拒绝,弹窗:
|
||||
|
||||
```
|
||||
Could Not Open MD Preview
|
||||
拒绝访问 (os error 5)
|
||||
```
|
||||
|
||||
- 这不是应用 bug。同一个 exe 复制到 `D:\Installer\MD-Preview\` 就能正常运行(目标目录是 Medium)。
|
||||
|
||||
当前仓库状态:工作区已设为 **Medium**,DSH 必须以 **danger-full-access** 运行才能编辑/编译此目录。
|
||||
如果你用 workspace-write 打开本仓库,DSH 进程是 Low,会写不动 Medium 工作区(表现是编辑/编译全部 Access denied)。
|
||||
|
||||
### 如果 exe 又报 os error 5
|
||||
|
||||
```powershell
|
||||
# 方案 1:把工作区(含 target)改回 Medium 后重建
|
||||
icacls D:\Scripts\md-preview /setintegritylevel "(OI)(CI)Medium" /T /C
|
||||
cargo build --release
|
||||
|
||||
# 方案 2:不改标签,直接把 exe 复制到普通目录再运行
|
||||
copy .\target\release\md-preview.exe D:\Installer\MD-Preview\MD-Preview-windows-x64.exe
|
||||
```
|
||||
|
||||
检查标签:
|
||||
|
||||
```powershell
|
||||
icacls .\MD-Preview-windows-x64.exe # 应显示 Medium,不能是 Low
|
||||
```
|
||||
|
||||
### 若坚持用 workspace-write 沙箱
|
||||
|
||||
工作区必须保持 Low,DSH 才能写;构建输出必须放到工作区外(否则 exe 又是 Low):
|
||||
|
||||
1. `icacls D:\Scripts\md-preview /setintegritylevel "(OI)(CI)Low" /T /C`
|
||||
2. 项目内 `.cargo\config.toml`:
|
||||
```toml
|
||||
[build]
|
||||
target-dir = "D:/MD-Preview-build/target"
|
||||
```
|
||||
3. 在**自己的普通 PowerShell**里构建,再把 exe 复制到 `D:\Installer\MD-Preview\`
|
||||
|
||||
## 5. 已删除的联网/更新功能(不要加回来)
|
||||
|
||||
- 工具栏 Update 按钮、`#btn-update`、更新相关 CSS/JS
|
||||
- 启动时自动检查 GitHub Releases(`api.github.com`)
|
||||
- 版本比较、release 选择、SHA256 digest 处理
|
||||
- Windows 自更新:下载 exe → 校验 → 覆盖自身 → 重启(内嵌 PowerShell 脚本)
|
||||
- macOS Sparkle 更新器
|
||||
- macOS 菜单:Website / GitHub / Releases / Check for Updates
|
||||
- IPC:`open-url:`、`check-updates`、`update-check-result`
|
||||
- `assets/enhance/update-check.js`
|
||||
- 3 个 update 相关测试及页面断言
|
||||
|
||||
验证 exe 里已无这些字符串:
|
||||
|
||||
```powershell
|
||||
python -c "d=open(r'MD-Preview-windows-x64.exe','rb').read(); print(d.count(b'api.github'), d.count(b'btn-update'), d.count(b'Check for Updates'), d.lower().count(b'powershell'))"
|
||||
# 期望:0 0 0 0
|
||||
```
|
||||
|
||||
## 6. 保留的功能(回归时必须覆盖)
|
||||
|
||||
- 多标签、会话恢复、最近文件、缺失文件标签与重新定位
|
||||
- Markdown 预览(GFM、表格、任务列表、front matter、GitHub Alerts、高亮)
|
||||
- 源码编辑 + 700ms 防抖自动保存,关闭前 flush
|
||||
- 查找、打印、正文缩放 70%–200%、滚动进度保持
|
||||
- 本地相对图片/文档链接跳转;http/https/mailto 用系统浏览器打开
|
||||
- 外部修改热重载(notify)
|
||||
- 数学公式 KaTeX、Mermaid、highlight.js(离线内嵌)
|
||||
- 单实例:第二个进程把路径转发给第一个
|
||||
- 拖拽打开、`Cmd/Ctrl+O/E/N/F/P`
|
||||
|
||||
## 7. 目录结构
|
||||
|
||||
```
|
||||
D:\Scripts\md-preview
|
||||
├─ Cargo.toml / Cargo.lock / build.rs
|
||||
├─ src/main.rs 界面、页面模板、渲染、事件循环、Windows 集成(4229 行)
|
||||
├─ src/session.rs 标签会话持久化
|
||||
├─ src/instance.rs 单实例锁与本地端口转发
|
||||
├─ assets/ 9 个被 include_str!/include_bytes! 内嵌的资源
|
||||
│ ├─ icon.ico
|
||||
│ ├─ enhance/preview-enhance.js
|
||||
│ ├─ hljs/…
|
||||
│ ├─ katex/…
|
||||
│ └─ mermaid/mermaid.min.js
|
||||
├─ backup/md-preview-master.zip 上游源码备份(3.77 MB,本地保留,不入 git)
|
||||
├─ MD-Preview-windows-x64.exe 构建产物(不入 git;默认打开方式指向此路径)
|
||||
├─ target/ 编译缓存(不入 git,可删)
|
||||
├─ agent/ Agent 文档 / 脚本 / 测试夹具
|
||||
│ ├─ README.md
|
||||
│ ├─ docs/{HANDOFF.md, scan-2026-10-21.md, roadmap.md}
|
||||
│ ├─ scripts/build.ps1
|
||||
│ └─ tests/{smoke.ps1, fixtures/}
|
||||
├─ README.md 入口,指向 agent/docs/HANDOFF.md
|
||||
├─ LICENSE / .gitignore / .gitattributes
|
||||
```
|
||||
|
||||
Git 由用户自行初始化(私有仓库;`backup/` 与成品 exe 不入 git)。`.gitignore` 已忽略 `/target/`、`MD-Preview-windows-x64.exe`、`/backup/` 与临时日志。
|
||||
|
||||
## 8. 运行时数据
|
||||
|
||||
`%LOCALAPPDATA%\md-preview\`:
|
||||
|
||||
- `session.json`:打开的标签与 active tab
|
||||
- `recent-files.txt`:最近文件(最多 8 个)
|
||||
- `window.geom` / `theme.txt`
|
||||
- `instance.lock` / `instance.json`:单实例
|
||||
- `WebView2\`:WebView2 缓存
|
||||
|
||||
测试时如果写入临时标签,收尾记得清掉,避免下次启动出现 missing tab。
|
||||
|
||||
## 9. 已知问题 / 风险
|
||||
|
||||
1. exe **未签名**。本机通过 Explorer 启动未再出现 SmartScreen,Defender 自定义扫描也未报毒;换机器仍可能提示。可选:本地自签名 + 信任,或加 Defender 排除(需管理员)。
|
||||
2. 源码里仍保留 macOS/Linux 分支和 `objc2` 依赖(`cfg` 裁掉,Windows 不编译)。彻底精简可再删约 900 行 + 3 个 target 依赖。
|
||||
3. 删除更新功能后,应用完全离线;外部链接仍会交给系统浏览器(这是保留功能,不是自更新)。
|
||||
4. 单实例依赖本地 TCP 回环端口;如被防火墙/安全软件拦截,会表现为第二实例报错或无法转发。
|
||||
|
||||
## 10. 建议的下一步
|
||||
|
||||
1. 用真实 bug 场景回归:打开大文档、多标签、编辑保存、外部修改、打印。
|
||||
2. 如需彻底 Windows-only:删除 `cfg(target_os = "macos"/"linux")` 代码与 `Cargo.toml` 的 `[target.'cfg(target_os = "macos")'.dependencies]`。
|
||||
3. 如要分发:考虑代码签名;当前 exe 无发布者信息。
|
||||
|
||||
## 11. 验收清单
|
||||
|
||||
```powershell
|
||||
cd D:\Scripts\md-preview
|
||||
cargo test # 39 passed
|
||||
cargo build --release # Finished
|
||||
.\MD-Preview-windows-x64.exe path\to\file.md
|
||||
```
|
||||
|
||||
手工检查:
|
||||
|
||||
- [ ] 窗口标题为 `文件名 — MD Preview`
|
||||
- [ ] 工具栏无 Update 按钮
|
||||
- [ ] 多标签切换、关闭、会话恢复
|
||||
- [ ] 编辑后 700ms 自动保存,关闭前落盘
|
||||
- [ ] 第二个实例打开文件时,第一个实例新增标签、第二个退出
|
||||
- [ ] `icacls MD-Preview-windows-x64.exe` 为 Medium
|
||||
|
||||
## 12. 追加修复(2026-10-21 下午)
|
||||
|
||||
### 12.1 代码块里的 `==` 被吞掉
|
||||
|
||||
症状:C# 代码块中的 `if (m_Profile == null) { ... a == b; }` 渲染成 `if (m_Profile null)`,`==` 消失。
|
||||
|
||||
原因:`add_mark_highlights()` 对**所有** `Event::Text` 做 `==高亮==` 转换,fenced code block 的内容同样是 Text 事件,两个 `==` 被当成一对高亮分隔符消费掉。
|
||||
|
||||
修复:`add_mark_highlights()` 现在跟踪 `Tag::CodeBlock` 的进入/退出,只在代码块外转换;新增测试 `fenced_code_blocks_keep_double_equals_literal`。
|
||||
|
||||
验证:39 个测试通过;截图确认 C# 代码块保留 `==`,正文 `==highlight==` 仍正常高亮。
|
||||
|
||||
### 12.2 “打开方式”指向已删除的 exe
|
||||
|
||||
`HKCU\Software\Classes\MDPreview.md\shell\open\command` 原先指向 `D:\Users\wucl1\Downloads\MD-Preview-windows-x64.exe`(已不存在)。原因是 `.md-preview-registered` 标记存在时 `register_as_default()` 直接返回,路径永不更新。
|
||||
|
||||
修复:每次启动都刷新 ProgID 的 `DefaultIcon` / `shell\open\command` 和 `Applications\<exe名>` 路径,标记只用于一次性的扩展名广告。现在指向:
|
||||
|
||||
```
|
||||
"D:\Scripts\md-preview\MD-Preview-windows-x64.exe" "%1"
|
||||
```
|
||||
|
||||
### 12.3 工作区外残留审计
|
||||
|
||||
- `%LOCALAPPDATA%\md-preview`:只改了应用自己的 `session.json` / `recent-files.txt`,测试标签已清掉;测试用 `probe-ps2.txt` 已删。
|
||||
- 注册表:上述 `MDPreview.md`、`Applications\MD-Preview-windows-x64.exe`、`.md/.markdown/.mdown/.mkd\OpenWithProgids` 均为应用自身注册;无其他键。
|
||||
- `%TEMP%`:`mdp-*`、`md-preview-*` 测试目录/日志已全部删除(计数 0)。
|
||||
- `D:\Installer\MD-Preview`:只保留原安装的旧 exe;测试用 `new-build-copy.exe` 已删。
|
||||
- `C:\Users\wucl1\.cargo`(455 MB)与 `.rustup`(1.33 GB):工具链与 crate 缓存,属正常安装。
|
||||
- 清理前备份 zip 已随临时目录被清掉;被删的上游文件仍可从 `backup/md-preview-master.zip` 恢复。
|
||||
|
||||
## 13. 2026-10-21 交接更新(代码扫描 + 新需求)
|
||||
|
||||
### 13.1 基线复核
|
||||
|
||||
- `cargo test` → 39 passed / 0 failed(本次用 `CARGO_TARGET_DIR=%TEMP%\mdp-scan-target` 执行:workspace-write 是 Low IL,写不动 Medium 的 `target\`)。
|
||||
- `cargo build` 仍是 1 条警告:`CloseActiveTab / ToggleEdit / ShowFind / SetTheme / Quit` 永不构造(只由 macOS 菜单产生)。
|
||||
- 扫描时成品 exe 与 `target\release\md-preview.exe` 的 SHA256 一致(`1931EA5D…A3A6F`);重新构建后哈希可能变化(同源码、同大小,但不是 bit-for-bit 可复现),以 `build.ps1` 输出的 SHA256 为准。
|
||||
- exe 内已无 `api.github` / `btn-update` / `Check for Updates` / `powershell` / `update-check-result` / `open-url`。
|
||||
- 注册表 `HKCU\Software\Classes\MDPreview.md\shell\open\command` → `"D:\Scripts\md-preview\MD-Preview-windows-x64.exe" "%1"`;`.md` 的 `UserChoiceLatest\ProgId = MDPreview.md`,双击可用。
|
||||
|
||||
### 13.2 扫描发现(详见 `agent/docs/scan-2026-10-21.md`)
|
||||
|
||||
1. **`\\?\` 前缀污染**:`fs::canonicalize` 把路径写成 `\\?\D:\...`,Recent 列表和 missing 页直接显示该前缀;`file_url_for_path_dir` 还会生成畸形 base href `file:////%3F/D:/...`(未内嵌的相对图片会加载失败)。
|
||||
修法:`strip_prefix(r"\\?\")` 或改用 `dunce::canonicalize`(依赖树里已有 dunce,无新增编译量)。
|
||||
2. **macOS 侧残留错误**:`show_info_dialog` 未定义(macOS 编译会失败);`mdPreviewQuit:` selector 未注册(Cmd+Q 无效)。Windows 不受影响。
|
||||
3. **右键菜单**:`contextmenu` 在预览模式被全局 `preventDefault()`(main.rs:1489)。本次决定**保持禁用**,缩放改走 Ctrl+滚轮。
|
||||
4. **非 md 本地链接**:pdf/html 链接静默无响应(`local_document_path_from_url` 只接受文档扩展名)。
|
||||
5. **折叠与自动保存冲突**:每次保存都会重设 `#preview.innerHTML`(main.rs:4083),折叠状态必须持久化,否则每 700ms 被重置。
|
||||
|
||||
### 13.3 新需求决策(2026-10-21)
|
||||
|
||||
| 需求 | 决定 | 备注 |
|
||||
|---|---|---|
|
||||
| 右上角 Open / Print 按钮 | 移除 | 保留 `Ctrl+O` / `Ctrl+P` 与空状态 Open 按钮 |
|
||||
| 缩放 | **Ctrl + 鼠标滚轮** | 右键菜单继续禁用;保留 Ctrl +/- 与 Ctrl+0 |
|
||||
| 标题折叠 | 按 `#` 层级折叠/展开 | 状态需按 tab + heading slug 持久化 |
|
||||
| 代码配色 | 换 hljs 主题为 Visual Studio 风格 | 只换 CSS,不加库 |
|
||||
|
||||
### 13.4 目录与 git
|
||||
|
||||
- `HANDOFF.md` 已移入 `agent/docs/`;根目录 `README.md` 作为入口。
|
||||
- `agent/` 归 git 管理:docs / scripts / tests / fixtures / reports。
|
||||
- `backup/` 与成品 exe **不入 git**(用户决定;本地保留)。注意 `git clean -xdf` 会删除这两个被忽略的路径。
|
||||
- 构建脚本:`agent/scripts/build.ps1`(固定输出到 `D:\Scripts\md-preview\MD-Preview-windows-x64.exe`,校验 SHA256、禁用字符串与完整性级别)。
|
||||
- 冒烟脚本:`agent/tests/smoke.ps1`(cargo test + 注册表 + 可选隔离启动)。
|
||||
|
||||
### 13.5 下一步
|
||||
|
||||
按 `agent/docs/roadmap.md` 的顺序做:Bug 修复批 → 删按钮 → 代码配色 → Ctrl+滚轮 → 标题折叠。每步 `cargo test` + `build.ps1` + 手工回归,一步一 commit。
|
||||
96
agent/docs/roadmap.md
Normal file
96
agent/docs/roadmap.md
Normal file
@@ -0,0 +1,96 @@
|
||||
# 功能路线图 — 2026-10-21 决策版
|
||||
|
||||
## 决策(已确认)
|
||||
|
||||
- 缩放:**Ctrl + 鼠标滚轮**;右键菜单保持禁用。
|
||||
- 移除右上角 Open / Print 按钮;保留 `Ctrl+O` / `Ctrl+P` 与空状态 Open。
|
||||
- 按 `#` 层级折叠标题,方便读长文。
|
||||
- 代码配色改为 Visual Studio 风格;只换 hljs CSS,不引入新库。
|
||||
- 整体原则:轻量,不引库,不加联网能力。
|
||||
|
||||
## 顺序与预估
|
||||
|
||||
| 步骤 | 内容 | 预估 | 风险 |
|
||||
|---|---|---|---|
|
||||
| 0 | git + agent 骨架(本次已完成除 git 外的准备) | 0.5–1 h | 低 |
|
||||
| 1 | Bug 修复批:`\\?\` / base href / 非 md 链接 / session 兜底 | 2–3 h | 低 |
|
||||
| 2 | 移除 Open / Print 按钮 | 0.5 h | 低 |
|
||||
| 3 | 代码配色 VS 风格 | 1.5–2.5 h | 低 |
|
||||
| 4 | Ctrl + 滚轮缩放 | 0.5–1 h | 低 |
|
||||
| 5 | 标题折叠 | 6–10 h | 中高 |
|
||||
| 6 | 回归(大文档、多标签、mermaid、打印) | 2–3 h | 中 |
|
||||
|
||||
轻量版约 1 天;稳妥版(折叠完整、含回归)约 2.5–3.5 天。
|
||||
|
||||
## 步骤 2:移除 Open / Print
|
||||
|
||||
改动点:
|
||||
|
||||
- HTML:`src/main.rs:1350`(Open)、`1353`(Print)
|
||||
- CSS:`src/main.rs:1333-1335` 的 `body.editing #btn-open, #btn-search, #btn-print`
|
||||
- JS:`ICON_OPEN` / `ICON_PRINT`、`btnOpen` / `btnPrint`、两个 click 监听
|
||||
- Strings:`btn_print`;`btn_open`(空状态用的是 `open_file`,不再需要)
|
||||
- 测试:`src/main.rs:2293`、`2302`
|
||||
|
||||
保留:`Ctrl+O`、`Ctrl+P`、`window.__mdPreviewOpenFile`(脏标签时 Rust 回调用)。
|
||||
|
||||
验收:工具栏只剩 搜索 / 编辑 / 缩放;`Ctrl+O`、`Ctrl+P`、空状态 Open、Recent 均正常;`cargo test` 全绿。
|
||||
|
||||
## 步骤 3:代码配色(Visual Studio 风格)
|
||||
|
||||
- 新增 `assets/hljs/vs2015.min.css`(深色)与 `vs.min.css` 或 `atom-one-light.min.css`(浅色),替换现有 GitHub 主题。
|
||||
- 同步调整 `#preview pre` 背景:浅色 `#f6f8fa` 或 `#fff`,深色 `#1e1e1e`。
|
||||
- 不改 JS,不加库;仍由 `prefers-color-scheme` 切换。
|
||||
- 用 `tests/fixtures/code-samples.md` 目测 C# / Rust / JS / JSON / YAML / PowerShell / diff 的对比度。
|
||||
|
||||
验收:浅色/深色都不刺眼;字符串、注释、关键字、类型、数字有明显区分;代码块背景与主题一致。
|
||||
|
||||
可选:加“代码配色”独立切换(localStorage),+2–3 h。
|
||||
|
||||
## 步骤 4:Ctrl + 滚轮
|
||||
|
||||
实现要点:
|
||||
|
||||
- `document.addEventListener('wheel', handler, { passive: false })`。
|
||||
- 只有 `e.ctrlKey` 时 `preventDefault()`,避免 WebView2 自己的页面缩放。
|
||||
- 复用 `changeZoom(±ZOOM_STEP)`;建议按 `deltaY` 方向 + 80–120ms 节流,避免一次滚动跳很多级。
|
||||
- 触控板双指捏合在 Chromium 里也表现为 `ctrlKey + wheel`,可顺带支持。
|
||||
- 编辑模式下同样生效(`--content-scale` 已作用于 textarea)。
|
||||
|
||||
验收:预览/编辑都能缩放;范围仍为 70%–200%;Ctrl+0 复位;不触发浏览器缩放;不影响滚动。
|
||||
|
||||
## 步骤 5:标题折叠
|
||||
|
||||
实现要点:
|
||||
|
||||
1. 在 `preview-enhance.js` 里,把 `#preview` 的标题按层级包成嵌套 `<section class="mdp-fold" data-level="n">`。
|
||||
2. 标题左侧加三角按钮(`<button class="mdp-fold-toggle" aria-expanded>`),点击切换 `collapsed`。
|
||||
3. **状态持久化**:`localStorage` 按 `tabKey(文件路径)+ heading id` 存折叠集合;Rust 需把 tab 路径传给页面(`__setContent` 多一个参数,或复用 `__setTabs` 的 active path)。
|
||||
4. 每次 `__setPreview` 重建 DOM 后立即恢复折叠态(在 idle enhance 之前),避免闪烁。
|
||||
5. 查找:命中在折叠区时自动展开祖先(或先展开全部再恢复,二选一,需实测体验)。
|
||||
6. Mermaid:隐藏容器里尺寸为 0,展开后需要重新渲染/触发布局;建议记录源码,展开时重跑。
|
||||
7. 打印:`@media print` 强制展开,避免打印缺失内容。
|
||||
8. 可选:`Alt+点击` 折叠整棵子树;“全部折叠/展开”快捷键。
|
||||
|
||||
验收:
|
||||
|
||||
- 点击 H1/H2/H3 三角可折叠其正文与子标题;
|
||||
- 自动保存 700ms 后折叠状态不丢;
|
||||
- 切换标签后各自的折叠状态正确;
|
||||
- 查找、锚点跳转、打印、mermaid 均正常;
|
||||
- 大文档(>= 1MB)折叠后滚动与展开无明显卡顿。
|
||||
|
||||
## 回归清单(每次发版)
|
||||
|
||||
- [ ] 窗口标题 `文件名 — MD Preview`,脏状态显示 `•`
|
||||
- [ ] 工具栏无 Open / Print
|
||||
- [ ] 多标签、关闭、会话恢复、缺失文件重定位
|
||||
- [ ] 编辑 700ms 自动保存;关闭前落盘
|
||||
- [ ] 外部修改提示与保护
|
||||
- [ ] 查找(含中文输入法组合输入)
|
||||
- [ ] Ctrl+滚轮、Ctrl+0、70%–200%
|
||||
- [ ] 折叠状态与自动保存共存
|
||||
- [ ] 代码配色浅/深
|
||||
- [ ] 打印预览完整
|
||||
- [ ] 单实例转发
|
||||
- [ ] `agent/scripts/build.ps1` 通过,exe 为 Medium
|
||||
125
agent/docs/scan-2026-10-21.md
Normal file
125
agent/docs/scan-2026-10-21.md
Normal file
@@ -0,0 +1,125 @@
|
||||
# 代码扫描记录 — 2026-10-21
|
||||
|
||||
> 基线:`src/main.rs` 4229 行,`cargo test` 39 passed。
|
||||
> 行号均基于该基线,改动后可能偏移。
|
||||
|
||||
## 0. 验证方式
|
||||
|
||||
工作区是 Medium,而 DSH 的 workspace-write 是 Low,直接 `cargo test` 会报:
|
||||
|
||||
```text
|
||||
error: failed to open: D:\Scripts\md-preview\target\debug\.cargo-build-lock
|
||||
拒绝访问。 (os error 5)
|
||||
```
|
||||
|
||||
为了在不提权的情况下完成扫描,本次把编译输出临时放到 TEMP:
|
||||
|
||||
```powershell
|
||||
$env:CARGO_TARGET_DIR = Join-Path $env:TEMP 'mdp-scan-target'
|
||||
cargo test
|
||||
```
|
||||
|
||||
结果:**39 passed / 0 failed**;唯一警告是 5 个 dead variants。
|
||||
(TEMP 里编出来的 exe 是 Low,不能拿来当成品。)
|
||||
|
||||
## 1. 残留
|
||||
|
||||
| # | 位置 | 问题 | 影响 |
|
||||
|---|---|---|---|
|
||||
| 1 | `src/main.rs:3336` | `show_info_dialog(...)` 被调用,但全项目没有定义 | 在 `cfg(target_os = "macos")` 内,Windows 不编译所以没暴露;编 macOS 直接失败 |
|
||||
| 2 | `src/main.rs:2917` | 菜单项 `mdPreviewQuit:` 没有在 ClassBuilder 注册(只注册 8 个 selector) | macOS Cmd+Q 无效 / unrecognized selector |
|
||||
| 3 | `src/main.rs:43` | `CloseActiveTab / ToggleEdit / ShowFind / SetTheme / Quit` 在 Windows 永不构造 | 唯一编译警告 |
|
||||
| 4 | main.rs 全文 | macOS/Linux 分支约 900 行 + Cargo 里 3 个 objc 依赖 | Windows 不编译,属于多平台包袱 |
|
||||
| 5 | `src/main.rs:1947` | `body.classList.add('missing')` 没有对应 CSS | 死状态 |
|
||||
| 6 | `src/main.rs:251` | `theme.txt` / `ThemeChoice` 在 Windows 没有入口 | macOS 菜单配套残留 |
|
||||
| 7 | `HANDOFF.md` | 行数 4218 与实际 4229 不符 | 已顺手更新 |
|
||||
|
||||
## 2. Bug
|
||||
|
||||
### 2.1 `\\?\` 前缀污染(高可见度 / 低风险)
|
||||
|
||||
`session.rs` 的 `normalize_path` 使用 `fs::canonicalize`,Windows 返回 verbatim 路径:
|
||||
|
||||
```text
|
||||
%LOCALAPPDATA%\md-preview\recent-files.txt
|
||||
\\?\D:\Scripts\XFab\Agent\notes\slicer-frontload-migration-2.md
|
||||
...
|
||||
session.json "tabs": ["\\\\?\\D:\\Scripts\\..."]
|
||||
```
|
||||
|
||||
影响:
|
||||
|
||||
- 空状态 Recent 列表的二级路径直接显示 `\\?\D:\...`;
|
||||
- 丢失文件页的路径 `<code>` 也带前缀;
|
||||
- session/recent 跨机器、跨用户失效。
|
||||
|
||||
### 2.2 Base href 畸形(由 2.1 引出)
|
||||
|
||||
`file_url_for_path_dir` 手工拼 `file://`,对 `\\?\D:\Scripts\md-preview` 得到:
|
||||
|
||||
```text
|
||||
file:////%3F/D:/Scripts/md-preview/
|
||||
```
|
||||
|
||||
正确应为 `file:///D:/Scripts/md-preview/`。目前本地图片都 base64 内嵌、链接由 JS 拦截,所以问题不明显;**未内嵌的相对图片**(扩展名不支持/读取失败)会加载失败。
|
||||
|
||||
建议直接用已有依赖 `url`:
|
||||
|
||||
```rust
|
||||
url::Url::from_directory_path(dir).ok().map(|u| u.to_string())
|
||||
```
|
||||
|
||||
### 2.3 右键被全局禁用(本轮保持现状)
|
||||
|
||||
`src/main.rs:1489`:预览模式 `preventDefault()`,编辑模式仅 textarea 放行。
|
||||
本轮决定**继续禁用**右键菜单,缩放改走 Ctrl+滚轮。
|
||||
|
||||
### 2.4 非 md 本地链接静默失败
|
||||
|
||||
`local_document_path_from_url` 只接受 `md/markdown/mdown/mkd/txt`;点 `file:` 的 pdf/html 链接毫无反应,也没有提示。
|
||||
建议:非文档类型交给 `open::that`(仍然离线)。
|
||||
|
||||
### 2.5 折叠状态会被自动保存冲掉(新功能约束)
|
||||
|
||||
`src/main.rs:4083`:每次保存都用新 HTML 重设 `#preview.innerHTML`,而自动保存是 700ms。
|
||||
折叠状态如果只放 DOM,用户打字时每 0.7 秒展开一次。必须按 `tab + heading slug` 持久化。
|
||||
|
||||
### 2.6 其它低风险
|
||||
|
||||
| 问题 | 位置 | 说明 |
|
||||
|---|---|---|
|
||||
| 大文档 IPC 体积 | `src/main.rs:3745` | 启动页已避开 2MB 限制,但保存仍把整篇 md 走 `postMessage`,预览走 `evaluate_script`;3MB 文档没测过 |
|
||||
| 每次保存全量重高亮 | `src/main.rs:1845` | 大文档高频保存会卡,可节流 |
|
||||
| session.json 写入窗口 | `src/session.rs:113` | Windows 上先 `remove_file` 再 `rename`,中间崩溃会丢会话 |
|
||||
| 主题背景覆盖 | `src/main.rs:1079` / `1271` | `#preview pre` 的底色会盖掉 hljs 主题背景,换 VS 配色时必须同步改 |
|
||||
| 删按钮的连带点 | `src/main.rs:1350/1353/1333` | HTML、CSS、JS、Strings、测试共 6 处 |
|
||||
|
||||
## 3. 已确认干净
|
||||
|
||||
- 更新功能无残留:exe 中 `api.github`、`btn-update`、`Check for Updates`、`powershell`、`update-check-result`、`open-url` 计数均为 0。
|
||||
- 扫描时 exe 与 `target\release\md-preview.exe` SHA256 一致:`1931EA5D...A3A6F`;重新构建后哈希可能变化(同源码/同大小,非 bit-for-bit 可复现),以 `build.ps1` 输出为准。
|
||||
- 文件关联:`HKCU\Software\Classes\MDPreview.md\shell\open\command` 指向固定路径;`.md` 的 `UserChoiceLatest\ProgId = MDPreview.md`。
|
||||
- 单实例、会话恢复、外部修改保护、自动保存、查找、缩放、打印逻辑均有测试或明确实现。
|
||||
- `.gitignore` 基本正确(只需补 agent 临时目录)。
|
||||
|
||||
## 4. 修复建议(按优先级)
|
||||
|
||||
1. `\\?\` 去前缀 + base href 改用 `url::Url::from_directory_path`(约 1 h,含测试)。
|
||||
2. 非 md 本地链接交给系统打开(约 0.5 h)。
|
||||
3. session.json 写入加 `.bak` 兜底(约 0.5 h)。
|
||||
4. macOS 两个残留错误:要么修掉,要么把 macOS 分支整体删除(0.5 h / 3–5 h)。
|
||||
5. 补一条 3MB 文档“编辑-保存-切换”冒烟(约 1 h)。
|
||||
|
||||
## 5. 复现命令
|
||||
|
||||
```powershell
|
||||
# 测试
|
||||
$env:CARGO_TARGET_DIR = Join-Path $env:TEMP 'mdp-scan-target'
|
||||
cargo test
|
||||
|
||||
# 产物一致性
|
||||
Get-FileHash .\MD-Preview-windows-x64.exe, .\target\release\md-preview.exe -Algorithm SHA256
|
||||
|
||||
# 关联
|
||||
reg query "HKCU\Software\Classes\MDPreview.md\shell\open\command"
|
||||
```
|
||||
0
agent/notes/.gitkeep
Normal file
0
agent/notes/.gitkeep
Normal file
0
agent/reports/.gitkeep
Normal file
0
agent/reports/.gitkeep
Normal file
90
agent/scripts/build.ps1
Normal file
90
agent/scripts/build.ps1
Normal file
@@ -0,0 +1,90 @@
|
||||
#requires -Version 5.1
|
||||
<#
|
||||
MD Preview 发布构建脚本
|
||||
固定产物:D:\Scripts\md-preview\MD-Preview-windows-x64.exe
|
||||
|
||||
运行环境:普通 PowerShell(Medium),或 DSH 的 danger-full-access。
|
||||
workspace-write 是 Low 完整性级别,写不动本目录(EPERM / os error 5)。
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$OutputPath = 'D:\Scripts\md-preview\MD-Preview-windows-x64.exe',
|
||||
[switch]$SkipTests
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
Set-Location $repoRoot
|
||||
|
||||
$cargo = Join-Path $env:USERPROFILE '.cargo\bin\cargo.exe'
|
||||
if (-not (Test-Path $cargo)) {
|
||||
$cargo = (Get-Command cargo -ErrorAction Stop).Source
|
||||
}
|
||||
|
||||
function Step([string]$text) { Write-Host ('==> ' + $text) -ForegroundColor Cyan }
|
||||
|
||||
function Assert-TargetNotRunning([string]$path) {
|
||||
$ids = @()
|
||||
foreach ($p in (Get-Process -ErrorAction SilentlyContinue)) {
|
||||
$pPath = $null
|
||||
try { $pPath = $p.Path } catch { }
|
||||
if ($pPath -eq $path) { $ids += $p.Id }
|
||||
}
|
||||
if ($ids.Count -gt 0) {
|
||||
throw ('MD Preview 正在运行(PID ' + ($ids -join ', ') + '),请先关闭窗口再构建。')
|
||||
}
|
||||
}
|
||||
|
||||
Assert-TargetNotRunning $OutputPath
|
||||
|
||||
if (-not $SkipTests) {
|
||||
Step 'cargo test'
|
||||
& $cargo test
|
||||
if ($LASTEXITCODE -ne 0) { throw 'cargo test failed' }
|
||||
}
|
||||
|
||||
Step 'cargo build --release'
|
||||
& $cargo build --release
|
||||
if ($LASTEXITCODE -ne 0) { throw 'cargo build failed' }
|
||||
|
||||
$built = Join-Path $repoRoot 'target\release\md-preview.exe'
|
||||
if (-not (Test-Path $built)) { throw ('missing build output: ' + $built) }
|
||||
|
||||
Step ('copy -> ' + $OutputPath)
|
||||
$outDir = Split-Path -Parent $OutputPath
|
||||
if (-not (Test-Path $outDir)) { New-Item -ItemType Directory -Path $outDir | Out-Null }
|
||||
Assert-TargetNotRunning $OutputPath
|
||||
try {
|
||||
Copy-Item $built $OutputPath -Force -ErrorAction Stop
|
||||
} catch {
|
||||
throw ('复制失败(目标可能被占用):' + $_.Exception.Message)
|
||||
}
|
||||
|
||||
$info = Get-Item $OutputPath
|
||||
$hash = (Get-FileHash $OutputPath -Algorithm SHA256).Hash
|
||||
Write-Host ('size : {0:N0} bytes' -f $info.Length)
|
||||
Write-Host ('sha256 : ' + $hash)
|
||||
Write-Host ('version : ' + $info.VersionInfo.FileVersion)
|
||||
|
||||
Step 'check removed update strings'
|
||||
$bytes = [IO.File]::ReadAllBytes($OutputPath)
|
||||
$ascii = [Text.Encoding]::ASCII.GetString($bytes)
|
||||
$forbidden = @('api.github', 'btn-update', 'Check for Updates', 'powershell', 'update-check-result', 'open-url')
|
||||
$bad = @()
|
||||
foreach ($needle in $forbidden) {
|
||||
$count = ([regex]::Matches($ascii, [regex]::Escape($needle), 'IgnoreCase')).Count
|
||||
Write-Host (' {0,-20} {1}' -f $needle, $count)
|
||||
if ($count -ne 0) { $bad += $needle }
|
||||
}
|
||||
if ($bad.Count -gt 0) { throw ('removed features still present: ' + ($bad -join ', ')) }
|
||||
|
||||
Step 'check integrity level'
|
||||
$acl = (icacls $OutputPath | Out-String)
|
||||
if ($acl -match 'Medium Mandatory Level') {
|
||||
Write-Host ' Medium - OK'
|
||||
} else {
|
||||
Write-Warning '不是 Medium:启动时可能报 os error 5,见 agent/docs/HANDOFF.md 第 4 节'
|
||||
}
|
||||
|
||||
Write-Host ''
|
||||
Write-Host ('DONE ' + $OutputPath) -ForegroundColor Green
|
||||
86
agent/tests/fixtures/code-samples.md
vendored
Normal file
86
agent/tests/fixtures/code-samples.md
vendored
Normal file
@@ -0,0 +1,86 @@
|
||||
# 代码配色样例
|
||||
|
||||
用于对比 highlight.js 主题:关键字、字符串、注释、类型、数字、内置函数、diff。
|
||||
|
||||
## C#
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
|
||||
public sealed class Profile
|
||||
{
|
||||
private readonly string _name;
|
||||
|
||||
public Profile(string name) => _name = name;
|
||||
|
||||
// 比较运算符必须保持字面量
|
||||
public bool IsEmpty() => _name == null || _name.Length == 0;
|
||||
|
||||
public override string ToString() => $"Profile({_name})";
|
||||
}
|
||||
```
|
||||
|
||||
## Rust
|
||||
|
||||
```rust
|
||||
#[derive(Debug, Clone)]
|
||||
struct Config {
|
||||
port: u16,
|
||||
retries: usize,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let cfg = Config { port: 8080, retries: 3 };
|
||||
println!("{cfg:?}"); // 调试输出
|
||||
}
|
||||
```
|
||||
|
||||
## JavaScript
|
||||
|
||||
```javascript
|
||||
const items = [1, 2, 3].map((n) => n * 2);
|
||||
function sum(a, b) {
|
||||
return a + b; // 行注释
|
||||
}
|
||||
console.log(sum(1, 2), items);
|
||||
```
|
||||
|
||||
## JSON
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "md-preview",
|
||||
"version": "1.4.2",
|
||||
"offline": true,
|
||||
"count": 39
|
||||
}
|
||||
```
|
||||
|
||||
## YAML
|
||||
|
||||
```yaml
|
||||
version: 1
|
||||
active: 0
|
||||
tabs:
|
||||
- D:\Scripts\md-preview\HANDOFF.md
|
||||
- note.md
|
||||
```
|
||||
|
||||
## PowerShell
|
||||
|
||||
```powershell
|
||||
$env:CARGO_TARGET_DIR = Join-Path $env:TEMP 'mdp-scan-target'
|
||||
Get-ChildItem -File | Where-Object { $_.Length -gt 1MB }
|
||||
```
|
||||
|
||||
## Diff
|
||||
|
||||
```diff
|
||||
- old line
|
||||
+ new line
|
||||
unchanged
|
||||
```
|
||||
|
||||
## 行内代码
|
||||
|
||||
使用 `cargo test` 与 `build.ps1`;正文里的 ==高亮== 仍应生效,而 `==literal==` 不应高亮。
|
||||
51
agent/tests/fixtures/long-headings.md
vendored
Normal file
51
agent/tests/fixtures/long-headings.md
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
---
|
||||
title: 折叠与长文测试
|
||||
tags: [fixture, fold, headings]
|
||||
---
|
||||
|
||||
# 一级标题 A
|
||||
|
||||
这是 A 的引导段落。用来验证一级标题折叠时,它下面的二级、三级内容是否一起收起。
|
||||
|
||||
## 二级 A-1
|
||||
|
||||
A-1 段落。包含 **粗体**、*斜体*、`inline code` 与 ==高亮==。
|
||||
|
||||
### 三级 A-1-1
|
||||
|
||||
- 列表项 1
|
||||
- 列表项 2
|
||||
- 嵌套项
|
||||
|
||||
#### 四级 A-1-1-1
|
||||
|
||||
> 引用块,用于检查折叠后的间距。
|
||||
|
||||
## 二级 A-2
|
||||
|
||||
| 列 1 | 列 2 | 列 3 | 列 4 |
|
||||
|---|---|---|---|
|
||||
| a | b | c | d |
|
||||
|
||||
### 三级 A-2-1
|
||||
|
||||
任务列表:
|
||||
|
||||
- [x] 已完成
|
||||
- [ ] 未完成
|
||||
|
||||
# 一级标题 B
|
||||
|
||||
B 的正文。
|
||||
|
||||
## 二级 B-1
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
println!("hello");
|
||||
}
|
||||
```
|
||||
|
||||
## 二级 B-2
|
||||
|
||||
结尾段落。
|
||||
16
agent/tests/fixtures/math-mermaid.md
vendored
Normal file
16
agent/tests/fixtures/math-mermaid.md
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
# 数学与图表
|
||||
|
||||
行内公式 $E = mc^2$,块级公式:
|
||||
|
||||
$$
|
||||
\int_0^1 x^2 \, dx = \frac{1}{3}
|
||||
$$
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[开始] --> B{判断}
|
||||
B -->|是| C[执行]
|
||||
B -->|否| D[结束]
|
||||
```
|
||||
|
||||
前后各留一段文字,方便检查折叠与滚动。
|
||||
64
agent/tests/smoke.ps1
Normal file
64
agent/tests/smoke.ps1
Normal file
@@ -0,0 +1,64 @@
|
||||
#requires -Version 5.1
|
||||
<#
|
||||
MD Preview 冒烟测试
|
||||
cargo test + 关联检查 + 可选隔离启动(不污染真实 %LOCALAPPDATA%)
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Exe = 'D:\Scripts\md-preview\MD-Preview-windows-x64.exe',
|
||||
[switch]$Launch
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
Set-Location $repoRoot
|
||||
|
||||
$cargo = Join-Path $env:USERPROFILE '.cargo\bin\cargo.exe'
|
||||
if (-not (Test-Path $cargo)) { $cargo = (Get-Command cargo -ErrorAction Stop).Source }
|
||||
|
||||
if (-not (Test-Path $Exe)) { throw ('missing exe: ' + $Exe + ' (先运行 agent/scripts/build.ps1)') }
|
||||
|
||||
Write-Host '==> cargo test' -ForegroundColor Cyan
|
||||
& $cargo test
|
||||
if ($LASTEXITCODE -ne 0) { throw 'cargo test failed' }
|
||||
|
||||
Write-Host '==> --help' -ForegroundColor Cyan
|
||||
$help = (& $Exe --help 2>&1 | Out-String)
|
||||
if ($help -match 'MD Preview') {
|
||||
Write-Host ' OK'
|
||||
} else {
|
||||
Write-Warning '--help 无输出(GUI 子系统在部分终端下不回显,可忽略)'
|
||||
}
|
||||
|
||||
Write-Host '==> registry association' -ForegroundColor Cyan
|
||||
$reg = Get-ItemProperty 'HKCU:\Software\Classes\MDPreview.md\shell\open\command' -ErrorAction SilentlyContinue
|
||||
$expected = '"' + $Exe + '" "%1"'
|
||||
if ($null -eq $reg) {
|
||||
Write-Warning 'ProgID 未注册(先运行一次 exe)'
|
||||
} elseif ($reg.'(default)' -ne $expected) {
|
||||
Write-Warning ('ProgID 指向不一致: ' + $reg.'(default)')
|
||||
} else {
|
||||
Write-Host ' OK'
|
||||
}
|
||||
|
||||
if ($Launch) {
|
||||
Write-Host '==> launch with isolated config' -ForegroundColor Cyan
|
||||
$config = Join-Path $env:TEMP ('mdp-smoke-' + [guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory -Path $config | Out-Null
|
||||
$fixture = Join-Path $PSScriptRoot 'fixtures\long-headings.md'
|
||||
$env:MD_PREVIEW_CONFIG_DIR = $config
|
||||
try {
|
||||
$proc = Start-Process -FilePath $Exe -ArgumentList @($fixture) -PassThru
|
||||
Start-Sleep -Seconds 3
|
||||
if ($proc.HasExited) { throw ('process exited early: ' + $proc.ExitCode) }
|
||||
Write-Host ' running - OK'
|
||||
$proc.CloseMainWindow() | Out-Null
|
||||
if (-not $proc.WaitForExit(5000)) { $proc.Kill() }
|
||||
Write-Host ' exit - OK'
|
||||
} finally {
|
||||
Remove-Item Env:\MD_PREVIEW_CONFIG_DIR -ErrorAction SilentlyContinue
|
||||
Remove-Item -Recurse -Force $config -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host 'SMOKE OK' -ForegroundColor Green
|
||||
431
assets/enhance/preview-enhance.js
Normal file
431
assets/enhance/preview-enhance.js
Normal file
@@ -0,0 +1,431 @@
|
||||
(function() {
|
||||
var flags = window.__mdPreviewFeatureFlags || { math: false, mermaid: false };
|
||||
var mermaidSeq = 0;
|
||||
var anchorNavigationBound = false;
|
||||
|
||||
function idle(fn) {
|
||||
return (window.requestIdleCallback || function(cb) { return setTimeout(cb, 0); })(fn);
|
||||
}
|
||||
|
||||
function setFlags(needsMath, needsMermaid) {
|
||||
flags = { math: !!needsMath, mermaid: !!needsMermaid };
|
||||
window.__mdPreviewFeatureFlags = flags;
|
||||
}
|
||||
|
||||
function hasClassInTree(el, cls) {
|
||||
while (el && el !== document.body) {
|
||||
if (el.classList && el.classList.contains(cls)) return true;
|
||||
el = el.parentElement;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function shouldSkipTextNode(node) {
|
||||
var el = node.parentElement;
|
||||
if (!el) return true;
|
||||
var tag = el.tagName;
|
||||
if (tag === 'CODE' || tag === 'PRE' || tag === 'KBD' || tag === 'SAMP' ||
|
||||
tag === 'SCRIPT' || tag === 'STYLE' || tag === 'TEXTAREA') return true;
|
||||
return hasClassInTree(el, 'katex') ||
|
||||
hasClassInTree(el, 'math') ||
|
||||
hasClassInTree(el, 'mdp-mark') ||
|
||||
hasClassInTree(el, 'mdp-mermaid') ||
|
||||
hasClassInTree(el, 'mdp-mermaid-error');
|
||||
}
|
||||
|
||||
function isEscaped(text, index) {
|
||||
var count = 0;
|
||||
for (var i = index - 1; i >= 0 && text[i] === '\\'; i--) count++;
|
||||
return count % 2 === 1;
|
||||
}
|
||||
|
||||
function findClosing(text, start, delim) {
|
||||
for (var i = start; i < text.length; i++) {
|
||||
if (delim === '$') {
|
||||
if (text[i] === '$' && !isEscaped(text, i) && text[i - 1] && !/\s/.test(text[i - 1])) {
|
||||
return i;
|
||||
}
|
||||
} else if (text.substr(i, delim.length) === delim && !isEscaped(text, i)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function nextDelimiter(text, index) {
|
||||
if (text.substr(index, 2) === '$$' && !isEscaped(text, index)) {
|
||||
return { open: '$$', close: '$$', display: true };
|
||||
}
|
||||
if (text.substr(index, 2) === '\\[' && !isEscaped(text, index)) {
|
||||
return { open: '\\[', close: '\\]', display: true };
|
||||
}
|
||||
if (text.substr(index, 2) === '\\(' && !isEscaped(text, index)) {
|
||||
return { open: '\\(', close: '\\)', display: false };
|
||||
}
|
||||
if (text[index] === '$' && !isEscaped(text, index) && text[index + 1] &&
|
||||
text[index + 1] !== '$' && !/\s/.test(text[index + 1])) {
|
||||
return { open: '$', close: '$', display: false };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function mathParts(text) {
|
||||
var parts = [];
|
||||
var i = 0;
|
||||
var last = 0;
|
||||
while (i < text.length) {
|
||||
var delim = nextDelimiter(text, i);
|
||||
if (!delim) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
var bodyStart = i + delim.open.length;
|
||||
var closeAt = findClosing(text, bodyStart, delim.close);
|
||||
if (closeAt < 0) {
|
||||
i += delim.open.length;
|
||||
continue;
|
||||
}
|
||||
if (i > last) parts.push({ text: text.slice(last, i) });
|
||||
parts.push({
|
||||
math: text.slice(bodyStart, closeAt),
|
||||
display: delim.display
|
||||
});
|
||||
i = closeAt + delim.close.length;
|
||||
last = i;
|
||||
}
|
||||
if (!parts.length) return null;
|
||||
if (last < text.length) parts.push({ text: text.slice(last) });
|
||||
return parts;
|
||||
}
|
||||
|
||||
function enhanceMath(root) {
|
||||
if (!flags.math || !window.katex) return;
|
||||
var mathNodes = root.querySelectorAll('.math.math-inline, .math.math-display');
|
||||
Array.prototype.forEach.call(mathNodes, function(el) {
|
||||
if (el.dataset.mdpMath === '1') return;
|
||||
var source = el.textContent;
|
||||
var display = el.classList.contains('math-display');
|
||||
el.dataset.mdpMath = '1';
|
||||
try {
|
||||
window.katex.render(source, el, {
|
||||
displayMode: display,
|
||||
throwOnError: false,
|
||||
strict: 'warn',
|
||||
trust: false
|
||||
});
|
||||
} catch (err) {
|
||||
el.className = 'mdp-math-error';
|
||||
el.textContent = source;
|
||||
el.title = err && err.message ? err.message : 'KaTeX render error';
|
||||
}
|
||||
});
|
||||
|
||||
var walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
|
||||
acceptNode: function(node) {
|
||||
if (shouldSkipTextNode(node)) return NodeFilter.FILTER_REJECT;
|
||||
return /(\$|\\\(|\\\[)/.test(node.nodeValue) ?
|
||||
NodeFilter.FILTER_ACCEPT :
|
||||
NodeFilter.FILTER_REJECT;
|
||||
}
|
||||
});
|
||||
var nodes = [];
|
||||
while (walker.nextNode()) nodes.push(walker.currentNode);
|
||||
nodes.forEach(function(node) {
|
||||
var parts = mathParts(node.nodeValue);
|
||||
if (!parts) return;
|
||||
var frag = document.createDocumentFragment();
|
||||
parts.forEach(function(part) {
|
||||
if (part.text !== undefined) {
|
||||
frag.appendChild(document.createTextNode(part.text));
|
||||
return;
|
||||
}
|
||||
var span = document.createElement('span');
|
||||
try {
|
||||
window.katex.render(part.math, span, {
|
||||
displayMode: part.display,
|
||||
throwOnError: false,
|
||||
strict: 'warn',
|
||||
trust: false
|
||||
});
|
||||
} catch (err) {
|
||||
span.className = 'mdp-math-error';
|
||||
span.textContent = part.math;
|
||||
span.title = err && err.message ? err.message : 'KaTeX render error';
|
||||
}
|
||||
frag.appendChild(span);
|
||||
});
|
||||
node.parentNode.replaceChild(frag, node);
|
||||
});
|
||||
}
|
||||
|
||||
function currentMermaidTheme() {
|
||||
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ?
|
||||
'dark' :
|
||||
'default';
|
||||
}
|
||||
|
||||
function renderMermaid(container, source) {
|
||||
if (!window.mermaid || !window.mermaid.render) return;
|
||||
var id = 'mdp-mermaid-' + (++mermaidSeq);
|
||||
try {
|
||||
window.mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
securityLevel: 'strict',
|
||||
theme: currentMermaidTheme()
|
||||
});
|
||||
Promise.resolve(window.mermaid.render(id, source)).then(function(result) {
|
||||
container.innerHTML = result.svg || result;
|
||||
}).catch(function(err) {
|
||||
container.className = 'mdp-mermaid-error';
|
||||
container.textContent = source;
|
||||
container.title = err && err.message ? err.message : 'Mermaid render error';
|
||||
});
|
||||
} catch (err) {
|
||||
container.className = 'mdp-mermaid-error';
|
||||
container.textContent = source;
|
||||
container.title = err && err.message ? err.message : 'Mermaid render error';
|
||||
}
|
||||
}
|
||||
|
||||
function enhanceMermaid(root) {
|
||||
if (!flags.mermaid || !window.mermaid) return;
|
||||
var nodes = root.querySelectorAll('pre > code.language-mermaid, pre > code.mermaid');
|
||||
Array.prototype.forEach.call(nodes, function(code) {
|
||||
var pre = code.parentElement;
|
||||
if (!pre || pre.dataset.mdpMermaid === '1') return;
|
||||
pre.dataset.mdpMermaid = '1';
|
||||
var source = code.textContent;
|
||||
var container = document.createElement('div');
|
||||
container.className = 'mdp-mermaid';
|
||||
container.textContent = source;
|
||||
pre.parentNode.replaceChild(container, pre);
|
||||
renderMermaid(container, source);
|
||||
});
|
||||
}
|
||||
|
||||
function enhanceTables(root) {
|
||||
var tables = root.querySelectorAll('table');
|
||||
Array.prototype.forEach.call(tables, function(table) {
|
||||
if (hasClassInTree(table, 'mdp-table-wrap')) return;
|
||||
var firstRow = table.querySelector('tr');
|
||||
var cellCount = firstRow ? firstRow.children.length : 0;
|
||||
if (cellCount < 4) return;
|
||||
|
||||
var wrap = document.createElement('div');
|
||||
wrap.className = 'mdp-table-wrap';
|
||||
table.parentNode.insertBefore(wrap, table);
|
||||
wrap.appendChild(table);
|
||||
});
|
||||
}
|
||||
|
||||
function alertClassFor(value) {
|
||||
var type = String(value || '').toLowerCase();
|
||||
if (type === 'note' || type === 'tip' || type === 'important' ||
|
||||
type === 'warning' || type === 'caution') {
|
||||
return 'markdown-alert-' + type;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function alertTypeFromClass(node) {
|
||||
var match = String(node && node.className || '').match(/\bmarkdown-alert-(note|tip|important|warning|caution)\b/i);
|
||||
return match ? match[1].toLowerCase() : '';
|
||||
}
|
||||
|
||||
function alertLabelFor(type) {
|
||||
var labels = {
|
||||
note: 'Note',
|
||||
tip: 'Tip',
|
||||
important: 'Important',
|
||||
warning: 'Warning',
|
||||
caution: 'Caution'
|
||||
};
|
||||
return labels[type] || '';
|
||||
}
|
||||
|
||||
function ensureAlertTitle(quote, type) {
|
||||
if (!quote || !type) return;
|
||||
var existing = quote.firstElementChild;
|
||||
if (existing && existing.classList && existing.classList.contains('markdown-alert-title')) return;
|
||||
|
||||
var title = document.createElement('p');
|
||||
title.className = 'markdown-alert-title';
|
||||
title.textContent = alertLabelFor(type);
|
||||
quote.insertBefore(title, quote.firstChild);
|
||||
}
|
||||
|
||||
function trimAlertLead(node) {
|
||||
while (node && node.firstChild) {
|
||||
var child = node.firstChild;
|
||||
if (child.nodeType === Node.TEXT_NODE && !child.nodeValue.trim()) {
|
||||
node.removeChild(child);
|
||||
continue;
|
||||
}
|
||||
if (child.nodeName === 'BR') {
|
||||
node.removeChild(child);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function enhanceAlerts(root) {
|
||||
var quotes = root.querySelectorAll('blockquote');
|
||||
Array.prototype.forEach.call(quotes, function(quote) {
|
||||
var type = alertTypeFromClass(quote);
|
||||
var first = quote.firstElementChild || quote;
|
||||
var match = null;
|
||||
|
||||
if (!type && first && first.firstChild && first.firstChild.nodeType === Node.TEXT_NODE) {
|
||||
match = first.firstChild.nodeValue.match(/^\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*/i);
|
||||
if (match) type = String(match[1]).toLowerCase();
|
||||
}
|
||||
|
||||
if (!type) return;
|
||||
|
||||
var cls = alertClassFor(type);
|
||||
if (!cls) return;
|
||||
|
||||
quote.classList.add(cls);
|
||||
if (match) {
|
||||
first.firstChild.nodeValue = first.firstChild.nodeValue.slice(match[0].length);
|
||||
trimAlertLead(first);
|
||||
if (first !== quote && !first.children.length && !first.textContent.trim()) {
|
||||
quote.removeChild(first);
|
||||
}
|
||||
trimAlertLead(quote);
|
||||
}
|
||||
ensureAlertTitle(quote, type);
|
||||
});
|
||||
}
|
||||
|
||||
function markParts(text) {
|
||||
var parts = [];
|
||||
var cursor = 0;
|
||||
while (cursor < text.length) {
|
||||
var open = text.indexOf('==', cursor);
|
||||
if (open < 0) break;
|
||||
var close = text.indexOf('==', open + 2);
|
||||
if (close < 0) break;
|
||||
var body = text.slice(open + 2, close);
|
||||
if (!body.trim()) break;
|
||||
if (open > cursor) parts.push({ text: text.slice(cursor, open) });
|
||||
parts.push({ mark: body });
|
||||
cursor = close + 2;
|
||||
}
|
||||
if (!parts.length) return null;
|
||||
if (cursor < text.length) parts.push({ text: text.slice(cursor) });
|
||||
return parts;
|
||||
}
|
||||
|
||||
function enhanceMarks(root) {
|
||||
var walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
|
||||
acceptNode: function(node) {
|
||||
if (shouldSkipTextNode(node)) return NodeFilter.FILTER_REJECT;
|
||||
return node.nodeValue.indexOf('==') >= 0 ?
|
||||
NodeFilter.FILTER_ACCEPT :
|
||||
NodeFilter.FILTER_REJECT;
|
||||
}
|
||||
});
|
||||
var nodes = [];
|
||||
while (walker.nextNode()) nodes.push(walker.currentNode);
|
||||
nodes.forEach(function(node) {
|
||||
var parts = markParts(node.nodeValue);
|
||||
if (!parts) return;
|
||||
var frag = document.createDocumentFragment();
|
||||
parts.forEach(function(part) {
|
||||
if (part.text !== undefined) {
|
||||
frag.appendChild(document.createTextNode(part.text));
|
||||
return;
|
||||
}
|
||||
var mark = document.createElement('mark');
|
||||
mark.className = 'mdp-mark';
|
||||
mark.textContent = part.mark;
|
||||
frag.appendChild(mark);
|
||||
});
|
||||
node.parentNode.replaceChild(frag, node);
|
||||
});
|
||||
}
|
||||
|
||||
function decodeFragment(value) {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch (_) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function updateHash(fragment) {
|
||||
try {
|
||||
if (window.history && window.history.pushState) {
|
||||
window.history.pushState(null, '', '#' + fragment);
|
||||
return;
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
try {
|
||||
window.location.hash = fragment;
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
function bindAnchorNavigation() {
|
||||
if (anchorNavigationBound) return;
|
||||
anchorNavigationBound = true;
|
||||
|
||||
document.addEventListener('click', function(event) {
|
||||
var link = event.target && event.target.closest ?
|
||||
event.target.closest('#preview a[href]') :
|
||||
null;
|
||||
if (!link) return;
|
||||
|
||||
var href = link.getAttribute('href') || '';
|
||||
if (href.charAt(0) !== '#') {
|
||||
var local = /^file:/i.test(href) || !/^[a-z][a-z0-9+.-]*:/i.test(href);
|
||||
if (local && window.ipc && window.ipc.postMessage) {
|
||||
event.preventDefault();
|
||||
window.ipc.postMessage('open-local-link:' + href);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
var fragment = href.slice(1);
|
||||
if (!fragment) {
|
||||
window.scrollTo(0, 0);
|
||||
updateHash(fragment);
|
||||
return;
|
||||
}
|
||||
|
||||
var decoded = decodeFragment(fragment);
|
||||
var target = document.getElementById(decoded) || document.getElementById(fragment);
|
||||
if (!target) return;
|
||||
|
||||
target.scrollIntoView({ block: 'start' });
|
||||
updateHash(fragment);
|
||||
});
|
||||
}
|
||||
|
||||
window.__setFeatureFlags = setFlags;
|
||||
|
||||
window.__setKatexCss = function(css) {
|
||||
if (document.getElementById('katex-css')) return;
|
||||
var style = document.createElement('style');
|
||||
style.id = 'katex-css';
|
||||
style.textContent = css;
|
||||
document.head.appendChild(style);
|
||||
};
|
||||
|
||||
window.__enhancePreview = function() {
|
||||
var root = document.getElementById('preview');
|
||||
if (!root) return;
|
||||
bindAnchorNavigation();
|
||||
idle(function() {
|
||||
enhanceTables(root);
|
||||
enhanceAlerts(root);
|
||||
enhanceMarks(root);
|
||||
enhanceMath(root);
|
||||
enhanceMermaid(root);
|
||||
});
|
||||
};
|
||||
})();
|
||||
17
assets/hljs/delphi.min.js
vendored
Normal file
17
assets/hljs/delphi.min.js
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
/*! `delphi` grammar compiled for Highlight.js 11.9.0 */
|
||||
(()=>{var e=(()=>{"use strict";return e=>{
|
||||
const r=["exports","register","file","shl","array","record","property","for","mod","while","set","ally","label","uses","raise","not","stored","class","safecall","var","interface","or","private","static","exit","index","inherited","to","else","stdcall","override","shr","asm","far","resourcestring","finalization","packed","virtual","out","and","protected","library","do","xorwrite","goto","near","function","end","div","overload","object","unit","begin","string","on","inline","repeat","until","destructor","write","message","program","with","read","initialization","except","default","nil","if","case","cdecl","in","downto","threadvar","of","try","pascal","const","external","constructor","type","public","then","implementation","finally","published","procedure","absolute","reintroduce","operator","as","is","abstract","alias","assembler","bitpacked","break","continue","cppdecl","cvar","enumerator","experimental","platform","deprecated","unimplemented","dynamic","export","far16","forward","generic","helper","implements","interrupt","iochecks","local","name","nodefault","noreturn","nostackframe","oldfpccall","otherwise","saveregisters","softfloat","specialize","strict","unaligned","varargs"],a=[e.C_LINE_COMMENT_MODE,e.COMMENT(/\{/,/\}/,{
|
||||
relevance:0}),e.COMMENT(/\(\*/,/\*\)/,{relevance:10})],t={className:"meta",
|
||||
variants:[{begin:/\{\$/,end:/\}/},{begin:/\(\*\$/,end:/\*\)/}]},n={
|
||||
className:"string",begin:/'/,end:/'/,contains:[{begin:/''/}]},i={
|
||||
className:"string",begin:/(#\d+)+/},s={begin:e.IDENT_RE+"\\s*=\\s*class\\s*\\(",
|
||||
returnBegin:!0,contains:[e.TITLE_MODE]},c={className:"function",
|
||||
beginKeywords:"function constructor destructor procedure",end:/[:;]/,
|
||||
keywords:"function constructor|10 destructor|10 procedure|10",
|
||||
contains:[e.TITLE_MODE,{className:"params",begin:/\(/,end:/\)/,keywords:r,
|
||||
contains:[n,i,t].concat(a)},t].concat(a)};return{name:"Delphi",
|
||||
aliases:["dpr","dfm","pas","pascal"],case_insensitive:!0,keywords:r,
|
||||
illegal:/"|\$[G-Zg-z]|\/\*|<\/|\|/,contains:[n,i,e.NUMBER_MODE,{
|
||||
className:"number",relevance:0,variants:[{begin:"\\$[0-9A-Fa-f]+"},{
|
||||
begin:"&[0-7]+"},{begin:"%[01]+"}]},s,c,t].concat(a)}}})()
|
||||
;hljs.registerLanguage("delphi",e)})();
|
||||
10
assets/hljs/github-dark.min.css
vendored
Normal file
10
assets/hljs/github-dark.min.css
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!
|
||||
Theme: GitHub Dark
|
||||
Description: Dark theme as seen on github.com
|
||||
Author: github.com
|
||||
Maintainer: @Hirse
|
||||
Updated: 2021-05-15
|
||||
|
||||
Outdated base version: https://github.com/primer/github-syntax-dark
|
||||
Current colors taken from GitHub's CSS
|
||||
*/.hljs{color:#c9d1d9;background:#0d1117}.hljs-doctag,.hljs-keyword,.hljs-meta .hljs-keyword,.hljs-template-tag,.hljs-template-variable,.hljs-type,.hljs-variable.language_{color:#ff7b72}.hljs-title,.hljs-title.class_,.hljs-title.class_.inherited__,.hljs-title.function_{color:#d2a8ff}.hljs-attr,.hljs-attribute,.hljs-literal,.hljs-meta,.hljs-number,.hljs-operator,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-id,.hljs-variable{color:#79c0ff}.hljs-meta .hljs-string,.hljs-regexp,.hljs-string{color:#a5d6ff}.hljs-built_in,.hljs-symbol{color:#ffa657}.hljs-code,.hljs-comment,.hljs-formula{color:#8b949e}.hljs-name,.hljs-quote,.hljs-selector-pseudo,.hljs-selector-tag{color:#7ee787}.hljs-subst{color:#c9d1d9}.hljs-section{color:#1f6feb;font-weight:700}.hljs-bullet{color:#f2cc60}.hljs-emphasis{color:#c9d1d9;font-style:italic}.hljs-strong{color:#c9d1d9;font-weight:700}.hljs-addition{color:#aff5b4;background-color:#033a16}.hljs-deletion{color:#ffdcd7;background-color:#67060c}
|
||||
10
assets/hljs/github.min.css
vendored
Normal file
10
assets/hljs/github.min.css
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!
|
||||
Theme: GitHub
|
||||
Description: Light theme as seen on github.com
|
||||
Author: github.com
|
||||
Maintainer: @Hirse
|
||||
Updated: 2021-05-15
|
||||
|
||||
Outdated base version: https://github.com/primer/github-syntax-light
|
||||
Current colors taken from GitHub's CSS
|
||||
*/.hljs{color:#24292e;background:#fff}.hljs-doctag,.hljs-keyword,.hljs-meta .hljs-keyword,.hljs-template-tag,.hljs-template-variable,.hljs-type,.hljs-variable.language_{color:#d73a49}.hljs-title,.hljs-title.class_,.hljs-title.class_.inherited__,.hljs-title.function_{color:#6f42c1}.hljs-attr,.hljs-attribute,.hljs-literal,.hljs-meta,.hljs-number,.hljs-operator,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-id,.hljs-variable{color:#005cc5}.hljs-meta .hljs-string,.hljs-regexp,.hljs-string{color:#032f62}.hljs-built_in,.hljs-symbol{color:#e36209}.hljs-code,.hljs-comment,.hljs-formula{color:#6a737d}.hljs-name,.hljs-quote,.hljs-selector-pseudo,.hljs-selector-tag{color:#22863a}.hljs-subst{color:#24292e}.hljs-section{color:#005cc5;font-weight:700}.hljs-bullet{color:#735c0f}.hljs-emphasis{color:#24292e;font-style:italic}.hljs-strong{color:#24292e;font-weight:700}.hljs-addition{color:#22863a;background-color:#f0fff4}.hljs-deletion{color:#b31d28;background-color:#ffeef0}
|
||||
1213
assets/hljs/highlight.min.js
vendored
Normal file
1213
assets/hljs/highlight.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
BIN
assets/icon.ico
Normal file
BIN
assets/icon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.9 KiB |
1
assets/katex/katex.inline.css
Normal file
1
assets/katex/katex.inline.css
Normal file
File diff suppressed because one or more lines are too long
1
assets/katex/katex.min.js
vendored
Normal file
1
assets/katex/katex.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
3405
assets/mermaid/mermaid.min.js
vendored
Normal file
3405
assets/mermaid/mermaid.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
17
build.rs
Normal file
17
build.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
#[cfg(target_os = "windows")]
|
||||
fn main() {
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon("assets/icon.ico");
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
let file_version = format!("{version}.0");
|
||||
res.set("CompanyName", "vorojar");
|
||||
res.set("FileDescription", "MD Preview");
|
||||
res.set("FileVersion", &file_version);
|
||||
res.set("LegalCopyright", "Copyright (c) vorojar");
|
||||
res.set("ProductName", "MD Preview");
|
||||
res.set("ProductVersion", version);
|
||||
res.compile().expect("failed to compile Windows resources");
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn main() {}
|
||||
207
src/instance.rs
Normal file
207
src/instance.rs
Normal file
@@ -0,0 +1,207 @@
|
||||
//! Local launch forwarding. The OS file lock owns the endpoint lifetime; a crashed
|
||||
//! process releases it automatically, so stale endpoint data cannot block restart.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Launch {
|
||||
pub paths: Vec<PathBuf>,
|
||||
pub edit: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Endpoint {
|
||||
port: u16,
|
||||
token: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Request {
|
||||
token: String,
|
||||
launch: Launch,
|
||||
}
|
||||
|
||||
pub struct Primary {
|
||||
_lock: File,
|
||||
listener: TcpListener,
|
||||
endpoint: Endpoint,
|
||||
}
|
||||
|
||||
pub fn acquire(directory: &Path, launch: &Launch) -> io::Result<Option<Primary>> {
|
||||
std::fs::create_dir_all(directory)?;
|
||||
let mut options = OpenOptions::new();
|
||||
options.read(true).write(true).create(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let lock = options.open(directory.join("instance.lock"))?;
|
||||
let endpoint_path = directory.join("instance.json");
|
||||
match lock.try_lock() {
|
||||
Ok(()) => {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
|
||||
let token = (0..2)
|
||||
.map(|_| {
|
||||
format!(
|
||||
"{:016x}",
|
||||
std::collections::hash_map::RandomState::new()
|
||||
.build_hasher()
|
||||
.finish()
|
||||
)
|
||||
})
|
||||
.collect::<String>();
|
||||
let endpoint = Endpoint {
|
||||
port: listener.local_addr()?.port(),
|
||||
token,
|
||||
};
|
||||
// Windows file locks can exclude reads, so publish outside the locked file.
|
||||
let mut endpoint_file = options.truncate(true).open(&endpoint_path)?;
|
||||
serde_json::to_writer(&mut endpoint_file, &endpoint)?;
|
||||
endpoint_file.flush()?;
|
||||
Ok(Some(Primary {
|
||||
_lock: lock,
|
||||
listener,
|
||||
endpoint,
|
||||
}))
|
||||
}
|
||||
Err(std::fs::TryLockError::WouldBlock) => {
|
||||
// The winner may still be publishing its endpoint after taking the lock.
|
||||
let mut last_error = io::Error::other("Running instance is not ready");
|
||||
for _ in 0..30 {
|
||||
let endpoint = File::open(&endpoint_path).and_then(|file| {
|
||||
serde_json::from_reader::<_, Endpoint>(file).map_err(io::Error::from)
|
||||
});
|
||||
match endpoint.and_then(|endpoint| forward(&endpoint, launch)) {
|
||||
Ok(()) => return Ok(None),
|
||||
Err(error) => last_error = error,
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
Err(last_error)
|
||||
}
|
||||
Err(std::fs::TryLockError::Error(error)) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn forward(endpoint: &Endpoint, launch: &Launch) -> io::Result<()> {
|
||||
let address = SocketAddr::from((Ipv4Addr::LOCALHOST, endpoint.port));
|
||||
let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(1))?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(3)))?;
|
||||
stream.set_write_timeout(Some(Duration::from_secs(3)))?;
|
||||
serde_json::to_writer(
|
||||
&mut stream,
|
||||
&serde_json::json!({"token": endpoint.token, "launch": launch}),
|
||||
)?;
|
||||
stream.shutdown(std::net::Shutdown::Write)?;
|
||||
let mut ack = [0];
|
||||
stream.read_exact(&mut ack)?;
|
||||
if ack != [1] {
|
||||
return Err(io::Error::other("Launch was not accepted"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Primary {
|
||||
pub fn listen(self, handler: impl Fn(Launch) -> bool + Send + 'static) {
|
||||
std::thread::spawn(move || {
|
||||
// Keep the lock alive alongside the listener.
|
||||
let _lock = self._lock;
|
||||
for stream in self.listener.incoming() {
|
||||
let Ok(mut stream) = stream else { break };
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_secs(1)));
|
||||
let _ = stream.set_write_timeout(Some(Duration::from_secs(1)));
|
||||
let request =
|
||||
serde_json::from_reader::<_, Request>((&mut stream).take(1024 * 1024));
|
||||
if let Ok(request) = request {
|
||||
if request.token == self.endpoint.token && handler(request.launch) {
|
||||
let _ = stream.write_all(&[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn secondary_launch_forwards_paths_and_edit_flag() {
|
||||
let directory = std::env::temp_dir().join(format!("mdp-instance-{}", std::process::id()));
|
||||
let launch = Launch {
|
||||
paths: vec![directory.join("含 空格.md")],
|
||||
edit: true,
|
||||
};
|
||||
let primary = acquire(&directory, &launch).unwrap().unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
primary.listen(move |launch| tx.send(launch).is_ok());
|
||||
assert!(acquire(&directory, &launch).unwrap().is_none());
|
||||
assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap(), launch);
|
||||
let empty = Launch {
|
||||
paths: vec![],
|
||||
edit: false,
|
||||
};
|
||||
assert!(acquire(&directory, &empty).unwrap().is_none());
|
||||
assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap(), empty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_foreign_tokens_and_accepts_concurrent_launches() {
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("mdp-instance-concurrent-{}", std::process::id()));
|
||||
let initial = Launch {
|
||||
paths: vec![],
|
||||
edit: false,
|
||||
};
|
||||
let primary = acquire(&directory, &initial).unwrap().unwrap();
|
||||
let foreign = Endpoint {
|
||||
port: primary.endpoint.port,
|
||||
token: "wrong-token".to_string(),
|
||||
};
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
primary.listen(move |launch| tx.send(launch).is_ok());
|
||||
assert!(forward(&foreign, &initial).is_err());
|
||||
assert!(rx.try_recv().is_err());
|
||||
let threads = (0..8)
|
||||
.map(|index| {
|
||||
let directory = directory.clone();
|
||||
std::thread::spawn(move || {
|
||||
let launch = Launch {
|
||||
paths: vec![directory.join(format!("{index}.md"))],
|
||||
edit: false,
|
||||
};
|
||||
assert!(acquire(&directory, &launch).unwrap().is_none());
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for thread in threads {
|
||||
thread.join().unwrap();
|
||||
}
|
||||
let mut paths = (0..8)
|
||||
.map(|_| rx.recv_timeout(Duration::from_secs(2)).unwrap().paths[0].clone())
|
||||
.collect::<Vec<_>>();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
assert_eq!(paths.len(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn released_lock_allows_restart_with_stale_endpoint() {
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("mdp-instance-restart-{}", std::process::id()));
|
||||
let launch = Launch {
|
||||
paths: vec![],
|
||||
edit: false,
|
||||
};
|
||||
let first = acquire(&directory, &launch).unwrap().unwrap();
|
||||
drop(first);
|
||||
assert!(acquire(&directory, &launch).unwrap().is_some());
|
||||
}
|
||||
}
|
||||
4229
src/main.rs
Normal file
4229
src/main.rs
Normal file
File diff suppressed because it is too large
Load Diff
247
src/session.rs
Normal file
247
src/session.rs
Normal file
@@ -0,0 +1,247 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct DocumentTab {
|
||||
pub id: u64,
|
||||
pub path: PathBuf,
|
||||
pub dirty: bool,
|
||||
pub missing: bool,
|
||||
pub edit_on_open: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct DocumentSession {
|
||||
pub tabs: Vec<DocumentTab>,
|
||||
pub active_id: Option<u64>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct PersistedSession {
|
||||
version: u8,
|
||||
active: Option<usize>,
|
||||
tabs: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl DocumentSession {
|
||||
pub fn load(path: &Path) -> Self {
|
||||
let Ok(raw) = fs::read(path) else {
|
||||
return Self::default();
|
||||
};
|
||||
let Ok(saved) = serde_json::from_slice::<PersistedSession>(&raw) else {
|
||||
return Self::default();
|
||||
};
|
||||
if saved.version != 1 {
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
let mut session = Self::default();
|
||||
for path in saved.tabs {
|
||||
session.open(path, false);
|
||||
}
|
||||
session.active_id = saved
|
||||
.active
|
||||
.and_then(|index| session.tabs.get(index))
|
||||
.map(|tab| tab.id)
|
||||
.or_else(|| session.tabs.last().map(|tab| tab.id));
|
||||
session
|
||||
}
|
||||
|
||||
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();
|
||||
tab.edit_on_open |= edit_on_open;
|
||||
self.active_id = Some(tab.id);
|
||||
return tab.id;
|
||||
}
|
||||
|
||||
self.next_id += 1;
|
||||
let id = self.next_id;
|
||||
self.tabs.push(DocumentTab {
|
||||
id,
|
||||
missing: !path.exists(),
|
||||
path,
|
||||
dirty: false,
|
||||
edit_on_open,
|
||||
});
|
||||
self.active_id = Some(id);
|
||||
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();
|
||||
self.active_id = Some(id);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn close(&mut self, id: u64) -> bool {
|
||||
let Some(index) = self.tabs.iter().position(|tab| tab.id == id) else {
|
||||
return false;
|
||||
};
|
||||
let was_active = self.active_id == Some(id);
|
||||
self.tabs.remove(index);
|
||||
if was_active {
|
||||
self.active_id = self
|
||||
.tabs
|
||||
.get(index)
|
||||
.or_else(|| index.checked_sub(1).and_then(|i| self.tabs.get(i)))
|
||||
.map(|tab| tab.id);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub fn save(&self, path: &Path) -> io::Result<()> {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
let active = self
|
||||
.active_id
|
||||
.and_then(|id| self.tabs.iter().position(|tab| tab.id == id));
|
||||
let saved = PersistedSession {
|
||||
version: 1,
|
||||
active,
|
||||
tabs: self.tabs.iter().map(|tab| tab.path.clone()).collect(),
|
||||
};
|
||||
let body = serde_json::to_vec_pretty(&saved).map_err(io::Error::other)?;
|
||||
let temporary = path.with_extension("json.tmp");
|
||||
fs::write(&temporary, body)?;
|
||||
#[cfg(target_os = "windows")]
|
||||
if path.exists() {
|
||||
fs::remove_file(path)?;
|
||||
}
|
||||
fs::rename(temporary, path)
|
||||
}
|
||||
|
||||
pub fn active(&self) -> Option<&DocumentTab> {
|
||||
let id = self.active_id?;
|
||||
self.tabs.iter().find(|tab| tab.id == id)
|
||||
}
|
||||
|
||||
pub fn active_mut(&mut self) -> Option<&mut DocumentTab> {
|
||||
let id = self.active_id?;
|
||||
self.tabs.iter_mut().find(|tab| tab.id == id)
|
||||
}
|
||||
|
||||
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) {
|
||||
return false;
|
||||
}
|
||||
let Some(tab) = self.get_mut(id) else {
|
||||
return false;
|
||||
};
|
||||
tab.path = path;
|
||||
tab.missing = !tab.path.exists();
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_path(path: PathBuf) -> PathBuf {
|
||||
let absolute = if path.is_absolute() {
|
||||
path
|
||||
} else {
|
||||
std::env::current_dir().unwrap_or_default().join(path)
|
||||
};
|
||||
fs::canonicalize(&absolute).unwrap_or_else(|_| {
|
||||
absolute
|
||||
.parent()
|
||||
.and_then(|parent| fs::canonicalize(parent).ok())
|
||||
.and_then(|parent| absolute.file_name().map(|name| parent.join(name)))
|
||||
.unwrap_or(absolute)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let unique = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"md-preview-session-{name}-{}-{unique}",
|
||||
std::process::id()
|
||||
));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_the_same_path_activates_without_duplicate() {
|
||||
let dir = temp_dir("dedupe");
|
||||
let file = dir.join("note.md");
|
||||
fs::write(&file, "# Note").unwrap();
|
||||
let mut session = DocumentSession::default();
|
||||
|
||||
let first = session.open(file.clone(), false);
|
||||
let second = session.open(file.clone(), true);
|
||||
|
||||
assert_eq!(first, second);
|
||||
assert_eq!(session.tabs.len(), 1);
|
||||
assert_eq!(session.active_id, Some(first));
|
||||
assert!(session.tabs[0].edit_on_open);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_active_tab_selects_the_next_neighbor() {
|
||||
let dir = temp_dir("close");
|
||||
let mut session = DocumentSession::default();
|
||||
let first = session.open(dir.join("one.md"), false);
|
||||
let second = session.open(dir.join("two.md"), false);
|
||||
let third = session.open(dir.join("three.md"), false);
|
||||
assert!(session.activate(second));
|
||||
|
||||
assert!(session.close(second));
|
||||
|
||||
assert_eq!(session.active_id, Some(third));
|
||||
assert_eq!(
|
||||
session.tabs.iter().map(|tab| tab.id).collect::<Vec<_>>(),
|
||||
vec![first, third]
|
||||
);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persisted_session_keeps_missing_tabs_and_active_order() {
|
||||
let dir = temp_dir("roundtrip");
|
||||
let state_path = dir.join("session.json");
|
||||
let existing = dir.join("existing.md");
|
||||
let missing = dir.join("missing.md");
|
||||
fs::write(&existing, "# Existing").unwrap();
|
||||
let mut session = DocumentSession::default();
|
||||
session.open(existing.clone(), false);
|
||||
session.open(missing.clone(), false);
|
||||
|
||||
session.save(&state_path).unwrap();
|
||||
let restored = DocumentSession::load(&state_path);
|
||||
|
||||
assert_eq!(restored.tabs.len(), 2);
|
||||
assert_eq!(restored.tabs[0].path, fs::canonicalize(existing).unwrap());
|
||||
assert_eq!(
|
||||
restored.tabs[1].path,
|
||||
fs::canonicalize(&dir)
|
||||
.unwrap()
|
||||
.join(missing.file_name().unwrap())
|
||||
);
|
||||
assert!(!restored.tabs[0].missing);
|
||||
assert!(restored.tabs[1].missing);
|
||||
assert_eq!(restored.active_id, restored.tabs.get(1).map(|tab| tab.id));
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user