Compare commits
24 Commits
v1.4.2-loc
...
0bb804e4df
| Author | SHA1 | Date | |
|---|---|---|---|
| 0bb804e4df | |||
| 6c0bb8253b | |||
| a5c0b0801d | |||
| 3ecf96fb04 | |||
| fb10fc5de0 | |||
| 1208386452 | |||
| d78d1aa722 | |||
| 1ad4a265c3 | |||
| a4616d0228 | |||
| 9a568774d8 | |||
| 2fc3f740ca | |||
| 590a9a016c | |||
| 0b97bcb6dc | |||
| fadba614a8 | |||
| d0e374a02c | |||
| d5ba2495ba | |||
| 1115052762 | |||
| 44fe93ec20 | |||
| 8221eb5908 | |||
| c783a6dc56 | |||
| dfe38890e0 | |||
| 8d98b5e7a9 | |||
| d2b1630a35 | |||
| 301e042bec |
3
.gitattributes
vendored
3
.gitattributes
vendored
@@ -1 +1,4 @@
|
|||||||
* text=auto eol=lf
|
* text=auto eol=lf
|
||||||
|
# cmd.exe wants CRLF; keep it stable in the working tree.
|
||||||
|
*.cmd text eol=crlf
|
||||||
|
*.bat text eol=crlf
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -5,6 +5,9 @@
|
|||||||
# 上游源码备份:本地保留,不入 git(用户决定)
|
# 上游源码备份:本地保留,不入 git(用户决定)
|
||||||
/backup/
|
/backup/
|
||||||
|
|
||||||
|
# 本机草稿目录(不属于仓库)
|
||||||
|
/test/
|
||||||
|
|
||||||
# 日志与临时文件
|
# 日志与临时文件
|
||||||
*.log
|
*.log
|
||||||
/agent/tmp/
|
/agent/tmp/
|
||||||
|
|||||||
80
Cargo.lock
generated
80
Cargo.lock
generated
@@ -1676,9 +1676,6 @@ version = "1.4.2"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"image",
|
"image",
|
||||||
"notify",
|
"notify",
|
||||||
"objc2",
|
|
||||||
"objc2-app-kit",
|
|
||||||
"objc2-foundation",
|
|
||||||
"open",
|
"open",
|
||||||
"pulldown-cmark",
|
"pulldown-cmark",
|
||||||
"rfd",
|
"rfd",
|
||||||
@@ -1686,7 +1683,6 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"tao",
|
"tao",
|
||||||
"url",
|
"url",
|
||||||
"winreg",
|
|
||||||
"winresource",
|
"winresource",
|
||||||
"wry",
|
"wry",
|
||||||
]
|
]
|
||||||
@@ -3725,15 +3721,6 @@ dependencies = [
|
|||||||
"windows-targets 0.42.2",
|
"windows-targets 0.42.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows-sys"
|
|
||||||
version = "0.48.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
|
|
||||||
dependencies = [
|
|
||||||
"windows-targets 0.48.5",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-sys"
|
name = "windows-sys"
|
||||||
version = "0.52.0"
|
version = "0.52.0"
|
||||||
@@ -3776,21 +3763,6 @@ dependencies = [
|
|||||||
"windows_x86_64_msvc 0.42.2",
|
"windows_x86_64_msvc 0.42.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows-targets"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
|
|
||||||
dependencies = [
|
|
||||||
"windows_aarch64_gnullvm 0.48.5",
|
|
||||||
"windows_aarch64_msvc 0.48.5",
|
|
||||||
"windows_i686_gnu 0.48.5",
|
|
||||||
"windows_i686_msvc 0.48.5",
|
|
||||||
"windows_x86_64_gnu 0.48.5",
|
|
||||||
"windows_x86_64_gnullvm 0.48.5",
|
|
||||||
"windows_x86_64_msvc 0.48.5",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-targets"
|
name = "windows-targets"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
@@ -3831,12 +3803,6 @@ version = "0.42.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
|
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_aarch64_gnullvm"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_aarch64_gnullvm"
|
name = "windows_aarch64_gnullvm"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
@@ -3849,12 +3815,6 @@ version = "0.42.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
|
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_aarch64_msvc"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_aarch64_msvc"
|
name = "windows_aarch64_msvc"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
@@ -3867,12 +3827,6 @@ version = "0.42.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
|
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_i686_gnu"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_i686_gnu"
|
name = "windows_i686_gnu"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
@@ -3891,12 +3845,6 @@ version = "0.42.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
|
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_i686_msvc"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_i686_msvc"
|
name = "windows_i686_msvc"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
@@ -3909,12 +3857,6 @@ version = "0.42.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
|
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_gnu"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_x86_64_gnu"
|
name = "windows_x86_64_gnu"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
@@ -3927,12 +3869,6 @@ version = "0.42.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
|
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_gnullvm"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_x86_64_gnullvm"
|
name = "windows_x86_64_gnullvm"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
@@ -3945,12 +3881,6 @@ version = "0.42.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
|
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_msvc"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_x86_64_msvc"
|
name = "windows_x86_64_msvc"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
@@ -3984,16 +3914,6 @@ dependencies = [
|
|||||||
"memchr",
|
"memchr",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "winreg"
|
|
||||||
version = "0.52.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"windows-sys 0.48.0",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winresource"
|
name = "winresource"
|
||||||
version = "0.1.31"
|
version = "0.1.31"
|
||||||
|
|||||||
@@ -16,14 +16,6 @@ serde = { version = "1", features = ["derive"] }
|
|||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
url = "2"
|
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]
|
[target.'cfg(windows)'.build-dependencies]
|
||||||
winresource = "0.1"
|
winresource = "0.1"
|
||||||
|
|
||||||
|
|||||||
29
README.md
29
README.md
@@ -14,7 +14,7 @@
|
|||||||
- **完全离线**:不联网、不检查更新、无遥测;外部链接交给系统浏览器打开。
|
- **完全离线**:不联网、不检查更新、无遥测;外部链接交给系统浏览器打开。
|
||||||
- **多标签 + 多窗口**:新标签页(New Tab)本身就是一个默认标签,标签栏的 `+` 新建一个 New Tab;在 New Tab 里打开文件会直接替换该标签(浏览器语义);关闭最后一个文件标签回到 New Tab,只剩 New Tab 时标签栏自动隐藏。标签右键可在新窗口打开,也可以上下拖动标签直接移出;同一文件全局只开一次,重复打开只聚焦;不恢复上次标签,启动显示最近文件、缺失文件可重新定位。
|
- **多标签 + 多窗口**:新标签页(New Tab)本身就是一个默认标签,标签栏的 `+` 新建一个 New Tab;在 New Tab 里打开文件会直接替换该标签(浏览器语义);关闭最后一个文件标签回到 New Tab,只剩 New Tab 时标签栏自动隐藏。标签右键可在新窗口打开,也可以上下拖动标签直接移出;同一文件全局只开一次,重复打开只聚焦;不恢复上次标签,启动显示最近文件、缺失文件可重新定位。
|
||||||
- **英文界面**:界面文案统一为英文,不随系统语言切换,避免中英文混排。
|
- **英文界面**:界面文案统一为英文,不随系统语言切换,避免中英文混排。
|
||||||
- **预览 / 编辑一体**:`Ctrl+E` 切换;编辑时 700ms 自动保存,`Ctrl+S` 立即保存。
|
- **预览 / 编辑一体**:`Ctrl+E` 切换;编辑模式与滚动位置按标签记忆,切回时恢复;编辑时 700ms 自动保存,`Ctrl+S` 立即保存。
|
||||||
- **编辑更顺手**:Tab 插入 2 个空格、Shift+Tab 反缩进,多行选区整体缩进;Enter 自动跟随上一行缩进;保留原生撤销。
|
- **编辑更顺手**:Tab 插入 2 个空格、Shift+Tab 反缩进,多行选区整体缩进;Enter 自动跟随上一行缩进;保留原生撤销。
|
||||||
- **长文档友好**:
|
- **长文档友好**:
|
||||||
- 鼠标移到标题左侧出现折角箭头,点击即可折叠到下一个同级标题(H1–H6);
|
- 鼠标移到标题左侧出现折角箭头,点击即可折叠到下一个同级标题(H1–H6);
|
||||||
@@ -27,8 +27,8 @@
|
|||||||
## 下载与运行
|
## 下载与运行
|
||||||
|
|
||||||
1. 在 [Releases](https://git.wucl12.cn/wucl12/md-preview/releases) 页下载 `MD-Preview-windows-x64.exe`(当前发布版本 `v1.4.2-local.5`,2026-10-30);
|
1. 在 [Releases](https://git.wucl12.cn/wucl12/md-preview/releases) 页下载 `MD-Preview-windows-x64.exe`(当前发布版本 `v1.4.2-local.5`,2026-10-30);
|
||||||
2. 放到一个固定目录(例如 `D:\Scripts\md-preview\`),不要随意改名/移动;
|
2. 放到一个固定目录(例如 `C:\Tools\md-preview\`),不要随意改名/移动;
|
||||||
3. 双击运行,或在任意 `.md` 上右键 → 打开方式 → 选择该 exe 并设为默认;
|
3. 双击运行,或在任意 `.md` 上右键 → 打开方式 → 选择该 exe 并设为默认(程序本身不再写注册表;首次需要在“打开方式 → 选择其他应用”里选一次);
|
||||||
4. Windows 10/11 一般自带 WebView2 Runtime;若提示缺失,安装微软的 Evergreen Runtime 即可。
|
4. Windows 10/11 一般自带 WebView2 Runtime;若提示缺失,安装微软的 Evergreen Runtime 即可。
|
||||||
|
|
||||||
> exe 未做代码签名,SmartScreen 可能提示“未知发布者”,选择“更多信息 → 仍要运行”即可。
|
> exe 未做代码签名,SmartScreen 可能提示“未知发布者”,选择“更多信息 → 仍要运行”即可。
|
||||||
@@ -84,34 +84,39 @@
|
|||||||
- WebView2 Runtime
|
- WebView2 Runtime
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
cargo test # 59 个测试
|
cargo test
|
||||||
.\agent\scripts\build.ps1 # release 构建 + 校验 + 复制到固定 exe 路径
|
.\agent\scripts\build.ps1 # release 构建 + 校验(产物留在 target\release\)
|
||||||
|
.\agent\tests\ui-smoke.cmd # 发布前 UI 冒烟(普通桌面 PowerShell + Node 21+)
|
||||||
|
.\agent\scripts\publish.ps1 # 发布到 Nutstore(用户手动,普通 PowerShell)
|
||||||
```
|
```
|
||||||
|
|
||||||
构建脚本会打印 exe 的 SHA256、检查已移除功能的字符串,并确认文件完整性级别为 Medium。
|
构建脚本会打印 exe 的 SHA256、检查已移除功能的字符串,并报告完整性级别;开发构建是 Low,`publish.ps1` 会把它升到 Medium 并复制到 Nutstore。
|
||||||
更细的维护说明(工具链、完整性级别坑、验收清单)见 [`agent/docs/HANDOFF.md`](agent/docs/HANDOFF.md)。
|
更细的维护说明(工具链、完整性级别坑、验收清单)见 [`agent/docs/HANDOFF.md`](agent/docs/HANDOFF.md)。
|
||||||
|
|
||||||
## 目录
|
## 目录
|
||||||
|
|
||||||
```text
|
```text
|
||||||
src/ Rust 源码(main.rs 界面/渲染/事件循环,session.rs 会话,instance.rs 单实例)
|
src/ Rust 源码(main.rs 启动/事件循环,app 逻辑仍在 main.rs;markdown.rs md→html,
|
||||||
assets/ 全部内嵌资源:highlight.js、KaTeX、Mermaid、图标、暗色代码主题
|
page.rs 页面组装,config.rs 路径/zoom/窗口状态,session.rs 会话,instance.rs 单实例)
|
||||||
agent/ 维护者文档、构建/冒烟脚本、测试夹具
|
assets/ 全部内嵌资源:page/ 页面 HTML+CSS+JS、highlight.js、KaTeX、Mermaid、图标、暗色代码主题
|
||||||
docs/ HANDOFF、STATUS、roadmap、扫描记录
|
agent/ 维护者文档、构建/冒烟/发布脚本、测试夹具
|
||||||
scripts/build.ps1 release 构建与校验
|
docs/ HANDOFF、STATUS、roadmap、migration、扫描记录
|
||||||
|
scripts/build.ps1 开发构建(release + 校验)
|
||||||
|
scripts/publish.ps1 发布到 Nutstore(用户手动)
|
||||||
tests/ 冒烟脚本与 Markdown 样例
|
tests/ 冒烟脚本与 Markdown 样例
|
||||||
backup/ 上游源码备份(本地保留,不入 git)
|
backup/ 上游源码备份(本地保留,不入 git)
|
||||||
```
|
```
|
||||||
|
|
||||||
## 已知限制
|
## 已知限制
|
||||||
|
|
||||||
- 仅面向 Windows;源码里仍有未维护的 macOS 分支。
|
- 仅面向 Windows;macOS/Linux 分支已于 2026-11-03 删除。
|
||||||
- exe 未签名,首次运行可能被 SmartScreen 拦截。
|
- exe 未签名,首次运行可能被 SmartScreen 拦截。
|
||||||
- 按设计不自动更新,升级方式是手动替换 exe。
|
- 按设计不自动更新,升级方式是手动替换 exe。
|
||||||
- 折叠状态不持久化,每次打开都是全部展开。
|
- 折叠状态不持久化,每次打开都是全部展开。
|
||||||
- 拖拽标签只用于移出到新窗口;不支持拖回、窗口合并或跨窗口同步编辑。
|
- 拖拽标签只用于移出到新窗口;不支持拖回、窗口合并或跨窗口同步编辑。
|
||||||
- 单换行按换行显示;如果源文件是按固定列硬折行的长段落,预览会保留这些断点,不随窗口宽度重排。
|
- 单换行按换行显示;如果源文件是按固定列硬折行的长段落,预览会保留这些断点,不随窗口宽度重排。
|
||||||
- 只读文件可以看、可以改,但保存会被拒绝(会明确提示,不会卡死)。
|
- 只读文件可以看、可以改,但保存会被拒绝(会明确提示,不会卡死)。
|
||||||
|
- 只识别 Markdown 扩展名(`.md` / `.markdown` / `.mdown` / `.mkd`);`.txt` 不再作为文档打开。
|
||||||
|
|
||||||
## 许可
|
## 许可
|
||||||
|
|
||||||
|
|||||||
@@ -4,54 +4,72 @@
|
|||||||
|
|
||||||
## 0. 工作区边界(最重要)
|
## 0. 工作区边界(最重要)
|
||||||
|
|
||||||
1. **只在工作区 `D:\Scripts\md-preview` 内创建、修改、删除文件。**
|
1. **仓库根**:`D:\Scripts\md-preview\AgentLowWorking`(2026-11-02 迁移后)。只在这个目录内创建、修改、删除文件。
|
||||||
2. **任何工作区外的修改都必须先停下询问用户**,包括但不限于:
|
- DSH 工作区是父目录 `D:\Scripts\md-preview`;代码仓库在其下的 `AgentLowWorking`。改代码/跑 git 前先 `cd AgentLowWorking`(或 `git -C AgentLowWorking`)。
|
||||||
|
- 父目录只放用户指定的小文件(发布启动器、AGENTS 指针);不要放源码/构建产物。
|
||||||
|
- 仓库内**新增文件不需要事先询问**:按职责拆模块、抽资源、加测试是正常的代码组织手段。
|
||||||
|
2. **任何仓库外的修改都必须先停下询问用户**,包括但不限于:
|
||||||
- `%TEMP%` / `%LOCALAPPDATA%` / 用户目录 / 其它磁盘;
|
- `%TEMP%` / `%LOCALAPPDATA%` / 用户目录 / 其它磁盘;
|
||||||
- 注册表、计划任务、服务、环境变量;
|
- 注册表、计划任务、服务、环境变量;
|
||||||
- 删除或移动任何不是本次刚在工作区内生成的文件。
|
- 删除或移动任何不是本次刚在仓库内生成的文件。
|
||||||
询问时要给出:完整路径、要做的操作、原因、影响范围;得到明确同意后才执行。
|
询问时要给出:完整路径、要做的操作、原因、影响范围;得到明确同意后才执行。
|
||||||
3. 不允许为了省事把构建/测试的临时文件写到工作区外。本仓库约定临时目录放在
|
3. 构建/测试的临时文件留在 `target\tmp`、`target\test-tmp`(已忽略),不写 `%TEMP%`。
|
||||||
`target\test-tmp`、`target\tmp` 下(均被 `.gitignore` 忽略)。
|
4. 每次收尾前自查:`git status` 是否只剩预期改动;本次是否在仓库外留下文件;
|
||||||
4. 每次收尾前自查:`git status` 是否只剩预期改动;本次是否在工作区外留下文件;
|
|
||||||
若发现历史残留,只报告并询问,不擅自删除。
|
若发现历史残留,只报告并询问,不擅自删除。
|
||||||
5. DSH 当前以 **danger-full-access** 运行,没有文件系统护栏——这条规则是唯一防线,不得绕过。
|
5. DSH 以 **workspace-write(Low 完整性)** 运行;仓库整棵树是 Low,因此可以正常改代码、编译、commit。**不要**把仓库改回 Medium,**不要**申请 danger-full-access 来改代码。
|
||||||
6. 截图、录屏等二进制验证产物**不入库**:放 `agent/tmp/`(已忽略)或 `target/tmp/`,看完即删;`agent/reports/` 只保留文本记录。
|
6. 截图、录屏等二进制验证产物**不入库**:放 `agent/tmp/`(已忽略)或 `target/tmp/`,看完即删;`agent/reports/` 只保留文本记录。
|
||||||
|
7. `test/` 是本机草稿目录,已 gitignore;不要提交,不要当作仓库内容。
|
||||||
|
|
||||||
## 1. 不变量
|
## 1. 不变量
|
||||||
|
|
||||||
- 产物路径固定:`D:\Scripts\md-preview\MD-Preview-windows-x64.exe`,默认 `.md` 打开方式指向它,不改名、不移动。
|
- **仓库根**:`D:\Scripts\md-preview\AgentLowWorking`。
|
||||||
|
- **发布产物**:`C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`(Medium);默认 `.md` 打开方式指向它。
|
||||||
|
- 仓库内**不放成品 exe**;旧的 `D:\Scripts\md-preview\MD-Preview-windows-x64.exe` 已删除,不要再生成。
|
||||||
|
- Agent 编译出的 `target\release\md-preview.exe` 是 **Low**,不能直接双击运行(会 os error 5);冒烟必须把 `MD_PREVIEW_CONFIG_DIR` 指到仓库内目录。
|
||||||
- 离线:不引入联网、自动更新、遥测;外部链接交给系统浏览器。
|
- 离线:不引入联网、自动更新、遥测;外部链接交给系统浏览器。
|
||||||
- 轻量:不为小功能引入新库;优先原生 JS/CSS 与已有依赖。
|
- 轻量是硬约束:exe 体积以 `build.ps1` 输出为准(2026-11 约 5.5 MB)。不为小功能引入新库,优先原生 JS/CSS 与已有依赖;要 vendor 新的离线资源(>200 KB)先说明并确认。
|
||||||
|
- 可读性优先:单文件按职责拆分,不为“少几个文件”把逻辑堆进 `main.rs`;模块边界以“改一个功能只需动一两个文件”为准。
|
||||||
- 右键菜单保持禁用;缩放只用 Ctrl + 滚轮与工具栏/快捷键。
|
- 右键菜单保持禁用;缩放只用 Ctrl + 滚轮与工具栏/快捷键。
|
||||||
- 工作区完整性级别是 **Medium**;不要把工作区改成 Low。
|
|
||||||
|
|
||||||
## 2. 改动流程
|
## 2. 改动流程
|
||||||
|
|
||||||
1. 一次只做一个功能;**加功能前先给方案,用户确认后再写代码**。
|
1. 一次只做一件事;**用户可感知的功能/行为变化先给方案,用户确认后再写代码**。
|
||||||
2. 改动超出已确认范围(新增文件、改公共接口、动构建脚本、碰工作区外)时,立即停下询问。
|
2. bug 修复、纯重构、测试、文档、格式与静态检查可以直接处理:每项独立提交,`cargo test` 全绿,提交信息写清行为变化。
|
||||||
3. 写完先 `cargo test` 全绿,再部署验收;部署要替换固定 exe 并校验 SHA256/完整性级别。
|
3. 代码级决策(拆模块、新增文件、内部接口、命名)由 agent 自行决定,不需要逐项询问。
|
||||||
4. 每个功能一个 conventional commit,推送到 `origin main`。
|
4. 只有这些要先停下询问:仓库外的文件/注册表/环境变量;发布;新增第三方库或 >200 KB 的 vendored 资源;改变不变量(离线、轻量、右键禁用、只支持 Windows 等)。
|
||||||
|
5. 写完先 `cargo test` 全绿(含新增测试);改动页面 JS 时额外做一次语法检查。
|
||||||
|
6. 每个改动一个 conventional commit,推送到 `origin main`。
|
||||||
|
7. **发布只能由用户手动执行**:用户在普通 PowerShell(Medium)运行 `agent\scripts\publish.ps1`。Agent 不运行发布脚本、不改注册表、不碰 Nutstore。
|
||||||
|
|
||||||
## 3. 构建与测试
|
## 3. 构建与测试
|
||||||
|
|
||||||
- 测试时把临时目录指到工作区内,避免 `%TEMP%` 残留:
|
- 测试/构建前把临时目录指到仓库内:
|
||||||
|
|
||||||
```powershell
|
~~~powershell
|
||||||
$env:TEMP = "$PWD\target\test-tmp"; $env:TMP = $env:TEMP
|
$env:TEMP = "$PWD\target\tmp"; $env:TMP = $env:TEMP
|
||||||
New-Item -ItemType Directory -Force $env:TEMP | Out-Null
|
New-Item -ItemType Directory -Force $env:TEMP | Out-Null
|
||||||
cargo test
|
~~~
|
||||||
```
|
|
||||||
|
|
||||||
- 正式构建用 `agent\scripts\build.ps1`(先关闭正在运行的 MD Preview)。
|
- 开发构建:`.\agent\scripts\build.ps1`(cargo test + build --release + 字符串校验;产物留在 `target\release\`)。
|
||||||
- `git clean -xdf` 会删除被忽略的 `backup/` 与成品 exe,禁止使用。
|
- DSH 的 pwsh 执行策略可能阻止未签名脚本;先运行 `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force`。
|
||||||
|
- 开发冒烟:`$env:MD_PREVIEW_CONFIG_DIR="$PWD\target\smoke"; .\target\release\md-preview.exe <file>`。
|
||||||
|
- **UI/GUI 验证只能由用户执行**:DSH 沙箱禁止命名管道,WebView2/Chromium 起不来(窗口白屏、`msedgewebview2.exe` 立即退出;这不是应用 bug)。
|
||||||
|
- 请用户在自己的桌面 PowerShell 运行 `.\agent\tests\ui-smoke.cmd`(`.ps1` 在 AllSigned 策略下会被拒;`.cmd` 内部用 `-ExecutionPolicy Bypass`),然后读 `target\ui-test\ui-smoke.json` 与 `ui-smoke.png` 判断。
|
||||||
|
- 发布前必跑;改页面 HTML/CSS/JS 或 Rust→JS 调用后必跑。细节见 `docs/HANDOFF.md` §4.1。
|
||||||
|
- **Rust → JS 调用没有编译器检查**:改参数列表时同步改页面函数签名,并保留“精确输出 + 页面签名”测试(`set_content_script_matches_the_page_signature`)。
|
||||||
|
- 不要把 `target\release\md-preview.exe` 复制到任何固定路径,也不要覆盖 Nutstore。
|
||||||
|
- `git clean -xdf` 会删除被忽略的 `backup/`,禁止使用。
|
||||||
|
|
||||||
## 4. 发布镜像(用户已授权)
|
## 4. 发布(用户手动)
|
||||||
|
|
||||||
- release 构建成功并发布到 Gitea 后,可以将固定 exe 复制到 Nutstore 镜像:`C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`,并用 SHA256 校验一致。
|
- 用户在**普通 PowerShell**(Medium)运行 `agent\scripts\publish.ps1`。
|
||||||
- 仅限该路径;其他工作区外修改仍需先询问用户。
|
- 脚本流程:复制 `target\release\md-preview.exe` → Nutstore → 设 Medium → 校验 SHA256 → 刷新 `.md` 关联 → 删除旧 exe。
|
||||||
|
- 发布前必须关闭正在运行的 MD Preview。
|
||||||
|
- 仅 Nutstore 这一个仓库外目标;其他仓库外修改仍需先询问用户。
|
||||||
|
|
||||||
## 5. 参考
|
## 5. 参考
|
||||||
|
|
||||||
- `docs/HANDOFF.md`:工具链、构建、完整性级别坑、验收。
|
- `docs/HANDOFF.md`:工具链、构建、完整性级别、验收。
|
||||||
- `docs/STATUS.md`:当前进度、已确认决策、下一步。
|
- `docs/STATUS.md`:当前进度、已确认决策、下一步。
|
||||||
|
- `docs/migration-2026-11-02.md`:Low 工作区迁移与目录移动步骤。
|
||||||
- `docs/roadmap.md`:功能方案与验收标准。
|
- `docs/roadmap.md`:功能方案与验收标准。
|
||||||
|
|||||||
@@ -1,49 +1,58 @@
|
|||||||
# agent/ — MD Preview 维护者工作区
|
# agent/ — MD Preview 维护者工作区
|
||||||
|
|
||||||
这里是本项目的“Agent 附属区”:文档、构建/冒烟脚本、测试夹具与验证记录。应用代码仍在 `src/`。
|
这里是本项目的“Agent 附属区”:文档、构建/冒烟/发布脚本、测试夹具与验证记录。应用代码仍在 `src/`。
|
||||||
|
|
||||||
## 规则
|
## 规则
|
||||||
|
|
||||||
维护本仓库前先读 [`AGENTS.md`](AGENTS.md):**最高优先级是工作区边界——任何工作区外的文件修改都必须先停下询问用户。**
|
维护本仓库前先读 [`AGENTS.md`](AGENTS.md):**最高优先级是仓库边界——任何仓库外的文件修改都必须先停下询问用户。**
|
||||||
|
|
||||||
## 目录
|
## 目录
|
||||||
|
|
||||||
| 路径 | 用途 |
|
| 路径 | 用途 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `AGENTS.md` | Agent 运行规则(工作区边界、改动流程) |
|
| `AGENTS.md` | Agent 运行规则(仓库边界、改动流程) |
|
||||||
| `docs/HANDOFF.md` | 主交接文档(工具链、构建、坑、验收) |
|
| `docs/HANDOFF.md` | 主交接文档(工具链、构建、完整性级别、验收) |
|
||||||
|
| `docs/migration-2026-11-02.md` | Low 工作区迁移与目录移动步骤 |
|
||||||
| `docs/scan-2026-10-21.md` | 代码扫描:残留、bug、修复建议 |
|
| `docs/scan-2026-10-21.md` | 代码扫描:残留、bug、修复建议 |
|
||||||
| `docs/roadmap.md` | 功能路线图与验收标准 |
|
| `docs/roadmap.md` | 功能路线图与验收标准 |
|
||||||
| `scripts/build.ps1` | release 构建 → 固定 exe 路径 → 校验 |
|
| `scripts/build.ps1` | 开发构建(cargo test + build --release + 校验) |
|
||||||
|
| `scripts/publish.ps1` | 用户手动发布到 Nutstore(Medium) |
|
||||||
| `tests/smoke.ps1` | cargo test + 关联检查 + 可选隔离启动 |
|
| `tests/smoke.ps1` | cargo test + 关联检查 + 可选隔离启动 |
|
||||||
|
| `tests/ui-smoke.cmd` / `ui-smoke.ps1` + `ui-smoke.mjs` | 发布前 UI 冒烟:CDP 断言页面渲染、截图、JSON 报告(需普通桌面 PowerShell + Node 21+;`.cmd` 内部用 Bypass,适合 AllSigned 策略) |
|
||||||
| `tests/fixtures/` | 手工/冒烟用 Markdown 样例 |
|
| `tests/fixtures/` | 手工/冒烟用 Markdown 样例 |
|
||||||
| `reports/` | 验证记录(文本;截图放 `agent/tmp/`,不入库) |
|
| `reports/` | 验证记录(文本;截图放 `agent/tmp/`,不入库) |
|
||||||
| `notes/` | 草稿 |
|
| `notes/` | 草稿 |
|
||||||
|
|
||||||
## 不变量
|
## 不变量
|
||||||
|
|
||||||
1. **产物路径固定**:`D:\Scripts\md-preview\MD-Preview-windows-x64.exe`。默认 `.md` 打开方式指向它,不要改名/移动。
|
1. **仓库根**:`D:\Scripts\md-preview\AgentLowWorking`。默认 `.md` 打开方式指向 `C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`。
|
||||||
2. **离线**:不引入联网、自动更新、遥测;外部链接交给系统浏览器。
|
2. **离线**:不引入联网、自动更新、遥测;外部链接交给系统浏览器。
|
||||||
3. **轻量**:不为小功能引入新库;优先原生 JS/CSS 与已有依赖。
|
3. **轻量**:不为小功能引入新库;优先原生 JS/CSS 与已有依赖。
|
||||||
4. **测试**:`cargo test` 必须保持全绿;UI 行为用 `tests/fixtures` 做手工/冒烟回归。
|
4. **测试**:`cargo test` 必须保持全绿;UI 行为用 `tests/fixtures` 做手工/冒烟回归。
|
||||||
|
|
||||||
## 常用命令
|
## 常用命令
|
||||||
|
|
||||||
```powershell
|
~~~powershell
|
||||||
# 构建并校验(推荐)
|
# 开发构建(DSH workspace-write 可运行)
|
||||||
.\agent\scripts\build.ps1
|
.\agent\scripts\build.ps1
|
||||||
|
|
||||||
# 只跑测试
|
# 只跑测试
|
||||||
cargo test
|
cargo test
|
||||||
|
|
||||||
# 冒烟(含注册表与可选启动)
|
# 冒烟(发布后;含注册表与可选启动)
|
||||||
.\agent\tests\smoke.ps1 -Launch
|
.\agent\tests\smoke.ps1 -Launch
|
||||||
```
|
|
||||||
|
# 发布前 UI 冒烟(用户桌面;CDP + 截图)
|
||||||
|
.\agent\tests\ui-smoke.cmd
|
||||||
|
|
||||||
|
# 发布(必须由用户在自己的普通 PowerShell 运行)
|
||||||
|
.\agent\scripts\publish.ps1
|
||||||
|
~~~
|
||||||
|
|
||||||
## 环境注意
|
## 环境注意
|
||||||
|
|
||||||
工作区是 **Medium** 完整性级别。DSH 用 `workspace-write` 打开时进程是 **Low**,会写不动(EPERM / os error 5)。改代码、编译、替换 exe 需要 DSH 以 **danger-full-access** 运行,或在你自己的普通 PowerShell 里执行。详见 `docs/HANDOFF.md` 第 4 节。
|
仓库整棵树是 **Low** 完整性级别,DSH 以 `workspace-write` 运行即可改代码/编译。构建产物 `target\release\md-preview.exe` 也是 Low,不能直接双击;开发冒烟用 `MD_PREVIEW_CONFIG_DIR` 指到仓库内目录。发布由用户手动运行 `publish.ps1` 升到 Medium 并复制到 Nutstore。详见 `docs/migration-2026-11-02.md`。
|
||||||
|
|
||||||
## Git
|
## Git
|
||||||
|
|
||||||
仓库由用户自行初始化(私有)。`backup/` 与成品 exe 不入库;`agent/` 全量入库。
|
仓库由用户自行初始化(私有)。`backup/`、成品 exe、`test/` 不入库;`agent/` 全量入库(`agent/tmp/` 与日志/截图除外)。
|
||||||
|
|||||||
@@ -1,20 +1,27 @@
|
|||||||
# MD Preview 本地维护交接
|
# MD Preview 本地维护交接
|
||||||
|
|
||||||
> 最后更新:2026-10-21
|
> 最后更新:2026-11-06
|
||||||
> 维护范围:仅 Windows 本地构建,目标产物 `MD-Preview-windows-x64.exe`
|
> 维护范围:仅 Windows 本地构建,目标产物 `MD-Preview-windows-x64.exe`
|
||||||
>
|
>
|
||||||
> **Agent 必须先读 `agent/AGENTS.md`**:最高优先级是工作区边界,任何工作区外的文件修改都要先停下询问用户。
|
> **Agent 必须先读 `agent/AGENTS.md`**:最高优先级是工作区边界,任何工作区外的文件修改都要先停下询问用户。
|
||||||
|
|
||||||
|
> **2026-11-02 迁移(重要)**:代码仓库移到 `D:\Scripts\md-preview\AgentLowWorking`;DSH 工作区仍是父目录 `D:\Scripts\md-preview`;
|
||||||
|
> 仓库整棵树为 **Low**,DSH 用 **workspace-write** 即可改代码/编译;
|
||||||
|
> 成品只发布到 `C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`(Medium),仓库内不再放 exe。
|
||||||
|
> 本文第 4 节等处的 “Medium / danger-full-access” 是旧模型;以 `agent/docs/migration-2026-11-02.md` 和 `AGENTS.md` 为准。
|
||||||
|
>
|
||||||
|
> **2026-11-06**:功能不变的重构继续拆出 `src/files.rs` 与 `src/app.rs`;`main.rs` 只剩入口(`app::run()`);测试各随模块,60 tests 全绿。剩余项见 `agent/docs/next-2026-11-03.md` §3。
|
||||||
|
|
||||||
## 1. 当前状态
|
## 1. 当前状态
|
||||||
|
|
||||||
- 上游版本:`md-preview 1.4.2`(源码来自 `backup/md-preview-master.zip`)
|
- 上游版本:`md-preview 1.4.2`(源码来自 `backup/md-preview-master.zip`)
|
||||||
- 改造目标:**本地预览器,不联网、不自动更新**;预览/编辑/标签/会话等功能与上游一致
|
- 改造目标:**本地预览器,不联网、不自动更新**;预览/编辑/标签/会话等功能与上游一致
|
||||||
- 源码规模:`src/main.rs` 4354 行、`src/session.rs` 281 行、`src/instance.rs` 207 行
|
- 源码规模(2026-11-06):`src/main.rs` 18 行(入口)、`src/app.rs` 1934 行(CLI/启动/状态/渲染/事件循环)、`src/markdown.rs` 628 行、`src/session.rs` 488 行、`src/files.rs` 458 行、`src/page.rs` 260 行、`src/config.rs` 235 行、`src/instance.rs` 207 行、`src/escape.rs` 25 行;页面资源在 `assets/page/`
|
||||||
- 当前产物:`D:\Scripts\md-preview\MD-Preview-windows-x64.exe`
|
- 当前产物(2026-11-02 起):`C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`
|
||||||
- 大小 5,501,440 字节
|
- 当前发布版见 `STATUS.md` 第 2 节(v1.4.2-local.5,5,505,024 字节)
|
||||||
- SHA256 `F76BC3963BA13BBFC8259BC2B4E3D24468C34E3C9E26491D364D5D364BEDE96C`
|
- 仓库内不再放成品 exe;旧 `D:\Scripts\md-preview\MD-Preview-windows-x64.exe` 由 `publish.ps1` 删除
|
||||||
- 测试:`cargo test` → 43 passed, 0 failed
|
- 测试:`cargo test` → 60 passed, 0 failed(2026-11-06)
|
||||||
- 编译警告:1 个 `dead_code`(macOS 专用事件枚举,Windows 下未构造),可忽略
|
- 编译警告:0;`cargo clippy --all-targets` 0 warning,`cargo fmt -- --check` 通过
|
||||||
- 2026-10-21 的全部功能需求已完成并部署,细节与实现要点见第 14 节。
|
- 2026-10-21 的全部功能需求已完成并部署,细节与实现要点见第 14 节。
|
||||||
|
|
||||||
## 2. 本机工具链
|
## 2. 本机工具链
|
||||||
@@ -36,63 +43,51 @@ DSH 的 pwsh 可能没有继承 PATH,构建时用完整路径:
|
|||||||
|
|
||||||
## 3. 构建与运行
|
## 3. 构建与运行
|
||||||
|
|
||||||
```powershell
|
~~~powershell
|
||||||
cd D:\Scripts\md-preview
|
cd D:\Scripts\md-preview\AgentLowWorking
|
||||||
cargo build --release
|
.\agent\scripts\build.ps1 # 开发构建(cargo test + build --release)
|
||||||
copy .\target\release\md-preview.exe .\MD-Preview-windows-x64.exe
|
# 发布由用户在自己的普通 PowerShell 运行:
|
||||||
.\MD-Preview-windows-x64.exe
|
.\agent\scripts\publish.ps1
|
||||||
```
|
~~~
|
||||||
|
|
||||||
- 增量构建约 15 秒,清理后约 1–2 分钟(16 核,release 开启 LTO + opt-level=z)
|
- 增量构建约 15 秒,清理后约 1–2 分钟(16 核,release 开启 LTO + opt-level=z)
|
||||||
- 依赖锁定在 `Cargo.lock`(435 个包),**不要随手 `cargo update`**
|
- 依赖锁定在 `Cargo.lock`(435 个包),**不要随手 `cargo update`**
|
||||||
- 调试可 `cargo build`(debug,快),产物在 `target\debug\`
|
- 调试可 `cargo build`(debug,快),产物在 `target\debug\`
|
||||||
|
|
||||||
## 4. ⚠️ 必读:完整性级别与 os error 5
|
## 4. ⚠️ 必读:Low 工作区与发布(2026-11-02 起)
|
||||||
|
|
||||||
这是本次维护踩过最大的坑,务必先读:
|
- 仓库根 `D:\Scripts\md-preview\AgentLowWorking` 整棵树是 **Low** 完整性级别;DSH 以 **workspace-write** 运行即可改代码、编译、commit。
|
||||||
|
- 从 Low 工作区编译出的 exe 也是 Low:启动后写 `%LOCALAPPDATA%\md-preview\instance.lock` 会被 no-write-up 拒绝(os error 5)。这不是应用 bug。
|
||||||
|
- 开发冒烟不要双击 `target\release\md-preview.exe`,用隔离配置目录:
|
||||||
|
|
||||||
- DSH 的 **workspace-write** 模式会把子进程降为 **Low 完整性级别(Low IL)**,并期望工作区文件也是 Low。
|
~~~powershell
|
||||||
- 从被标成 Low 的目录编译出的 exe 会继承 Low 标签;启动后写 `%LOCALAPPDATA%\md-preview\instance.lock` 会被 Windows 的 no-write-up 拒绝,弹窗:
|
$env:MD_PREVIEW_CONFIG_DIR="$PWD\target\smoke"
|
||||||
|
.\target\release\md-preview.exe path\to\file.md
|
||||||
|
~~~
|
||||||
|
|
||||||
```
|
- 发布:用户在**普通 PowerShell(Medium)**运行 `agent\scripts\publish.ps1`。脚本会复制到 Nutstore、设 Medium、校验 SHA256、刷新 `.md` 关联,最后删除旧 exe。
|
||||||
Could Not Open MD Preview
|
- 如果发布后仍报 os error 5:`icacls <Nutstore exe> | Select-String 'Mandatory Label'` 应为 Medium;确认不是从 Low 目录直接启动。
|
||||||
拒绝访问 (os error 5)
|
- 不要再把仓库改回 Medium,也不要为了改代码申请 danger-full-access。
|
||||||
```
|
|
||||||
|
|
||||||
- 这不是应用 bug。同一个 exe 复制到 `D:\Installer\MD-Preview\` 就能正常运行(目标目录是 Medium)。
|
### 4.1 UI 验证:只能由用户执行(2026-11-04 起)
|
||||||
|
|
||||||
当前仓库状态:工作区已设为 **Medium**,DSH 必须以 **danger-full-access** 运行才能编辑/编译此目录。
|
**DSH 沙箱禁止命名管道**,Chromium/WebView2 的 Mojo IPC 起不来:应用窗口会出现,但 `msedgewebview2.exe` 立即退出、页面白屏;Edge headless 也会报 `FATAL: mojo platform_channel ... 拒绝访问 (0x5)`。这是环境限制,不是应用 bug,也不要用沙箱里的白屏判断页面好坏。
|
||||||
如果你用 workspace-write 打开本仓库,DSH 进程是 Low,会写不动 Medium 工作区(表现是编辑/编译全部 Access denied)。
|
|
||||||
|
|
||||||
### 如果 exe 又报 os error 5
|
因此 GUI/UI 验证统一走这条链路:
|
||||||
|
|
||||||
```powershell
|
1. 用户在自己桌面 PowerShell 运行 `.\agent\tests\ui-smoke.cmd`(默认跑 `target\release\md-preview.exe`,独立配置目录 `target\ui-test\config`)。
|
||||||
# 方案 1:把工作区(含 target)改回 Medium 后重建
|
- 机器执行策略是 AllSigned,未签名 `.ps1` 会被拒;`.cmd` 内部用 `-ExecutionPolicy Bypass`,不改系统策略。
|
||||||
icacls D:\Scripts\md-preview /setintegritylevel "(OI)(CI)Medium" /T /C
|
- 需要 Node 21+(本机 `C:\Program Files\nodejs` 的 24.x);脚本会自己找,也可 `-Node <path>`。
|
||||||
cargo build --release
|
- 用 `-Exe <path>` 测发布版;`-KeepOpen` 失败时留窗口。
|
||||||
|
2. 脚本流程:启动应用 → 等 `http://127.0.0.1:9333/json/list` 就绪 → `ui-smoke.mjs` 通过 CDP 断言页面(加载完成、`#preview` 有内容、`window.ipc`、页面 API、标题/折叠按钮/代码高亮/正文长度)→ 截图 → 关闭应用。
|
||||||
|
3. 产物:`target\ui-test\ui-smoke.json`(checks/snapshot/errors)、`ui-smoke.png`、`app.stdout.log` / `app.stderr.log`。Agent 直接读 JSON 和截图判断。
|
||||||
|
4. 何时跑:每次发布前;改页面 HTML/CSS/JS 后;改 Rust→JS 调用后。2026-11-04 的“白屏 + 数字 1234”就是发布前没跑它。
|
||||||
|
|
||||||
# 方案 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\`
|
|
||||||
|
|
||||||
|
- 就绪判断必须用 `/json/list` 真的返回,不能只看 TCP 端口——WebView2 的端口可能只开一瞬间。
|
||||||
|
- Node 解析要用 `Get-Command` 结果的 `.Path`(或常见安装目录),不要拿命令对象直接喂 `Test-Path`。
|
||||||
|
- **Rust → JS 调用没有编译器检查**:改 `__setContent` / `__setPreview` 等参数列表时必须同步页面签名,并用 `set_content_script_matches_the_page_signature` 这类“精确输出 + 页面签名”测试锁住;白屏就是多传了一个 `active.id`,标签 id 被当 HTML 渲染。
|
||||||
## 5. 已删除的联网/更新功能(不要加回来)
|
## 5. 已删除的联网/更新功能(不要加回来)
|
||||||
|
|
||||||
- 工具栏 Update 按钮、`#btn-update`、更新相关 CSS/JS
|
- 工具栏 Update 按钮、`#btn-update`、更新相关 CSS/JS
|
||||||
@@ -114,8 +109,10 @@ python -c "d=open(r'MD-Preview-windows-x64.exe','rb').read(); print(d.count(b'ap
|
|||||||
|
|
||||||
## 6. 保留的功能(回归时必须覆盖)
|
## 6. 保留的功能(回归时必须覆盖)
|
||||||
|
|
||||||
- 多标签、会话恢复、最近文件、缺失文件标签与重新定位
|
- 多标签、最近文件、缺失文件标签与重新定位
|
||||||
|
- 编辑模式与滚动位置按标签记忆:切回标签恢复离开时的模式与位置(2026-11-03)
|
||||||
- Markdown 预览(GFM、表格、任务列表、front matter、GitHub Alerts、高亮)
|
- Markdown 预览(GFM、表格、任务列表、front matter、GitHub Alerts、高亮)
|
||||||
|
- 文档类型只认 `.md/.markdown/.mdown/.mkd`(2026-11-03 起不再打开 `.txt`)
|
||||||
- 源码编辑 + 700ms 防抖自动保存,关闭前 flush
|
- 源码编辑 + 700ms 防抖自动保存,关闭前 flush
|
||||||
- 查找(`Ctrl+F`;工具栏的 Find 按钮已移除)、打印、正文缩放 50%–300%(Ctrl+滚轮 / Ctrl± / Ctrl+0)、滚动进度保持
|
- 查找(`Ctrl+F`;工具栏的 Find 按钮已移除)、打印、正文缩放 50%–300%(Ctrl+滚轮 / Ctrl± / Ctrl+0)、滚动进度保持
|
||||||
- 标题 hover 折叠(H1–H6;点 H2 折到下一个 H2、点 H3 折到下一个 H3;查找自动展开;打印全展开;不持久化)
|
- 标题 hover 折叠(H1–H6;点 H2 折到下一个 H2、点 H3 折到下一个 H3;查找自动展开;打印全展开;不持久化)
|
||||||
@@ -129,30 +126,23 @@ python -c "d=open(r'MD-Preview-windows-x64.exe','rb').read(); print(d.count(b'ap
|
|||||||
|
|
||||||
## 7. 目录结构
|
## 7. 目录结构
|
||||||
|
|
||||||
```
|
~~~
|
||||||
D:\Scripts\md-preview
|
D:\Scripts\md-preview\
|
||||||
├─ Cargo.toml / Cargo.lock / build.rs
|
├─ AgentLowWorking\ ← 仓库根(整棵树 Low)
|
||||||
├─ src/main.rs 界面、页面模板、渲染、事件循环、Windows 集成(4354 行)
|
│ ├─ Cargo.toml / Cargo.lock / build.rs
|
||||||
├─ src/session.rs 标签会话持久化
|
│ ├─ src/ 应用源码
|
||||||
├─ src/instance.rs 单实例锁与本地端口转发
|
│ ├─ assets/ 内嵌资源
|
||||||
├─ assets/ 8 个被 include_str!/include_bytes! 内嵌的资源
|
│ ├─ backup/ 上游源码备份(不入 git)
|
||||||
│ ├─ icon.ico
|
│ ├─ target/ 编译缓存(不入 git,可删)
|
||||||
│ ├─ enhance/preview-enhance.js
|
│ ├─ agent/ Agent 文档 / 脚本 / 测试夹具
|
||||||
│ ├─ hljs/(highlight.min.js、delphi、vs-dark.css)
|
│ │ ├─ AGENTS.md
|
||||||
│ ├─ katex/…
|
│ │ ├─ docs/{HANDOFF.md, STATUS.md, migration-2026-11-02.md, ...}
|
||||||
│ └─ mermaid/mermaid.min.js
|
│ │ ├─ scripts/{build.ps1, publish.ps1}
|
||||||
├─ backup/md-preview-master.zip 上游源码备份(3.77 MB,本地保留,不入 git)
|
│ │ └─ tests/{smoke.ps1, fixtures/}
|
||||||
├─ MD-Preview-windows-x64.exe 构建产物(不入 git;默认打开方式指向此路径)
|
│ ├─ README.md / LICENSE / .gitignore / .gitattributes
|
||||||
├─ target/ 编译缓存(不入 git,可删)
|
│ └─ test/ 本机草稿(已忽略)
|
||||||
├─ agent/ Agent 文档 / 脚本 / 测试夹具
|
└─ MD-Preview-windows-x64.exe 旧产物;publish.ps1 成功后删除
|
||||||
│ ├─ AGENTS.md Agent 运行规则(最高优先级)
|
~~~
|
||||||
│ ├─ README.md
|
|
||||||
│ ├─ docs/{HANDOFF.md, STATUS.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/` 与临时日志。
|
Git 由用户自行初始化(私有仓库;`backup/` 与成品 exe 不入 git)。`.gitignore` 已忽略 `/target/`、`MD-Preview-windows-x64.exe`、`/backup/` 与临时日志。
|
||||||
|
|
||||||
@@ -160,7 +150,7 @@ Git 由用户自行初始化(私有仓库;`backup/` 与成品 exe 不入 git
|
|||||||
|
|
||||||
`%LOCALAPPDATA%\md-preview\`:
|
`%LOCALAPPDATA%\md-preview\`:
|
||||||
|
|
||||||
- `session.json`:打开的标签与 active tab
|
- 旧 `session.json`:已停用,不读不写(可手动删除)
|
||||||
- `recent-files.txt`:最近文件(最多 8 个)
|
- `recent-files.txt`:最近文件(最多 8 个)
|
||||||
- `window.geom` / `theme.txt` / `zoom.txt`(正文缩放,50–300)
|
- `window.geom` / `theme.txt` / `zoom.txt`(正文缩放,50–300)
|
||||||
- `instance.lock` / `instance.json`:单实例
|
- `instance.lock` / `instance.json`:单实例
|
||||||
@@ -171,7 +161,7 @@ Git 由用户自行初始化(私有仓库;`backup/` 与成品 exe 不入 git
|
|||||||
## 9. 已知问题 / 风险
|
## 9. 已知问题 / 风险
|
||||||
|
|
||||||
1. exe **未签名**。本机通过 Explorer 启动未再出现 SmartScreen,Defender 自定义扫描也未报毒;换机器仍可能提示。可选:本地自签名 + 信任,或加 Defender 排除(需管理员)。
|
1. exe **未签名**。本机通过 Explorer 启动未再出现 SmartScreen,Defender 自定义扫描也未报毒;换机器仍可能提示。可选:本地自签名 + 信任,或加 Defender 排除(需管理员)。
|
||||||
2. 源码里仍保留 macOS/Linux 分支和 `objc2` 依赖(`cfg` 裁掉,Windows 不编译)。彻底精简可再删约 900 行 + 3 个 target 依赖。
|
2. macOS/Linux 分支、Finder 扩展和 `objc2` 依赖已于 2026-11-03 删除;仓库现在只能在 Windows 上编译。
|
||||||
3. 删除更新功能后,应用完全离线;外部链接仍会交给系统浏览器(这是保留功能,不是自更新)。
|
3. 删除更新功能后,应用完全离线;外部链接仍会交给系统浏览器(这是保留功能,不是自更新)。
|
||||||
4. 单实例依赖本地 TCP 回环端口;如被防火墙/安全软件拦截,会表现为第二实例报错或无法转发。
|
4. 单实例依赖本地 TCP 回环端口;如被防火墙/安全软件拦截,会表现为第二实例报错或无法转发。
|
||||||
|
|
||||||
@@ -183,21 +173,25 @@ Git 由用户自行初始化(私有仓库;`backup/` 与成品 exe 不入 git
|
|||||||
|
|
||||||
## 11. 验收清单
|
## 11. 验收清单
|
||||||
|
|
||||||
```powershell
|
~~~powershell
|
||||||
cd D:\Scripts\md-preview
|
cd D:\Scripts\md-preview\AgentLowWorking
|
||||||
cargo test # 43 passed
|
cargo test
|
||||||
cargo build --release # Finished
|
.\agent\scripts\build.ps1
|
||||||
.\MD-Preview-windows-x64.exe path\to\file.md
|
# 发布前 UI 冒烟(普通桌面 PowerShell / Node 21+):
|
||||||
```
|
.\agent\tests\ui-smoke.cmd
|
||||||
|
# 发布由用户在自己的普通 PowerShell 运行:
|
||||||
|
.\agent\scripts\publish.ps1
|
||||||
|
~~~
|
||||||
|
|
||||||
手工检查:
|
手工检查:
|
||||||
|
|
||||||
|
- [ ] `ui-smoke.cmd` 输出 `OK: N checks`,截图里能看到正文、标题和代码高亮
|
||||||
- [ ] 窗口标题为 `文件名 — MD Preview`
|
- [ ] 窗口标题为 `文件名 — MD Preview`
|
||||||
- [ ] 工具栏只有 编辑 / 缩放(无 Update / Open / Print / Find)
|
- [ ] 工具栏只有 编辑 / 缩放(无 Update / Open / Print / Find)
|
||||||
- [ ] 多标签切换、关闭、会话恢复
|
- [ ] 多标签切换、关闭;切回标签仍保持编辑模式和滚动位置
|
||||||
- [ ] 编辑后 700ms 自动保存,关闭前落盘
|
- [ ] 编辑后 700ms 自动保存,关闭前落盘
|
||||||
- [ ] 第二个实例打开文件时,第一个实例新增标签、第二个退出
|
- [ ] 第二个实例打开文件时,第一个实例新增标签、第二个退出
|
||||||
- [ ] `icacls MD-Preview-windows-x64.exe` 为 Medium
|
- [ ] `icacls "C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe"` 为 Medium
|
||||||
|
|
||||||
## 12. 追加修复(2026-10-21 下午)
|
## 12. 追加修复(2026-10-21 下午)
|
||||||
|
|
||||||
@@ -296,7 +290,7 @@ cargo build --release # Finished
|
|||||||
### 14.3 验证配方
|
### 14.3 验证配方
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
cargo test # 43 passed
|
cargo test # 59 passed
|
||||||
.\agent\scripts\build.ps1 # 先关闭正在运行的实例;会打印 SHA256 并校验 Medium
|
.\agent\scripts\build.ps1 # 先关闭正在运行的实例;会打印 SHA256 并校验 Medium
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -317,7 +311,7 @@ cargo test # 43 passed
|
|||||||
|
|
||||||
- Gitea Release `v1.4.2-local.1`:https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.1
|
- Gitea Release `v1.4.2-local.1`:https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.1
|
||||||
- 附件 `MD-Preview-windows-x64.exe`(5,501,440 字节,SHA256 `F76BC396…BEDE96C`),发布说明见 `agent/docs/release-notes-v1.4.2-local.1.md`。
|
- 附件 `MD-Preview-windows-x64.exe`(5,501,440 字节,SHA256 `F76BC396…BEDE96C`),发布说明见 `agent/docs/release-notes-v1.4.2-local.1.md`。
|
||||||
- 发版流程:改版本 / 写 release notes → `build.ps1` → 推 tag 或用 Gitea API 建 release 并上传 exe。API 需要 `write:repository` scope 的 token,用完即删。
|
- 发版流程:改版本 / 写 release notes → `build.ps1` → 用户在普通 PowerShell 运行 `publish.ps1` → 推 tag / 用 Gitea API 建 release 并上传 Nutstore 那份 exe。API 需要 `write:repository` scope 的 token,用完即删。
|
||||||
|
|
||||||
### 14.6 下一次开工检查
|
### 14.6 下一次开工检查
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
# 项目状态(滚动更新)
|
# 项目状态(滚动更新)
|
||||||
|
|
||||||
> 最后更新:2026-10-30
|
> 最后更新:2026-11-03
|
||||||
> 用途:上下文压缩/交接后快速恢复。详细背景见 AGENTS.md、HANDOFF.md、scan-2026-10-21.md、roadmap.md。
|
> 用途:上下文压缩/交接后快速恢复。详细背景见 AGENTS.md、HANDOFF.md、scan-2026-10-21.md、roadmap.md。
|
||||||
>
|
>
|
||||||
> **当前:编辑 Tab/自动缩进 + 阅读 Find 选区填入/零滚动完成;59 个测试通过;固定 exe 已更新为 2026-10-30 build(5,505,024 字节,SHA256 A632EF03…);Gitea release v1.4.2-local.5 待发布;发布后同步 Nutstore。**
|
> **当前(2026-11-03):仓库根 `D:\Scripts\md-preview\AgentLowWorking`,整棵树 Low、DSH workspace-write 可编译;成品只发布到 Nutstore;仓库内 exe 已删除。功能基线 v1.4.2-local.5 + 本地未发布修复(59 tests);仓库已是 Windows-only。**
|
||||||
|
>
|
||||||
|
> 2026-11-03 已做:编辑模式与滚动位置按标签记忆;不再把 `.txt` 当文档;clippy 清零、`cargo fmt` 通过;AGENTS 允许拆模块/新增文件;功能不变地拆出 page/markdown/escape/config 模块并删除 macOS/Linux 死代码。未做功能与下一步见 `docs/next-2026-11-03.md`。
|
||||||
|
|
||||||
## 1. 仓库
|
## 1. 仓库
|
||||||
|
|
||||||
@@ -37,20 +39,26 @@
|
|||||||
- `8644966` feat: 编辑 Tab/Shift+Tab 缩进 + 回车跟随缩进
|
- `8644966` feat: 编辑 Tab/Shift+Tab 缩进 + 回车跟随缩进
|
||||||
- `618ac47` feat: 阅读 Find 选区填入、选区锚点、零滚动打开
|
- `618ac47` feat: 阅读 Find 选区填入、选区锚点、零滚动打开
|
||||||
- 若干 docs 提交(状态/路线图/HANDOFF、local.3/local.4/local.5 release notes)
|
- 若干 docs 提交(状态/路线图/HANDOFF、local.3/local.4/local.5 release notes)
|
||||||
|
- `d2b1630` chore: switch to Low workspace and Nutstore-only publish
|
||||||
|
- `8d98b5e` fix: add UTF-8 BOM to PowerShell scripts
|
||||||
|
- `dfe3889` fix: remember edit mode and scroll position per tab
|
||||||
|
- `c783a6d` fix: stop treating .txt as a supported document
|
||||||
|
- `8221eb5` chore: clear clippy warnings and tighten the build guard
|
||||||
- 忽略:`/target/`、`/MD-Preview-windows-x64.exe`、`/backup/`、`/agent/reports/*.png`
|
- 忽略:`/target/`、`/MD-Preview-windows-x64.exe`、`/backup/`、`/agent/reports/*.png`
|
||||||
- **不变量**:exe 固定为 `D:\Scripts\md-preview\MD-Preview-windows-x64.exe`,默认 .md 打开方式指向它,不要改名/移动。
|
- **不变量(2026-11-02 起)**:仓库根 `D:\Scripts\md-preview\AgentLowWorking`;成品固定为 `C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`(Medium),默认 .md 打开方式指向它;仓库内不再放 exe。
|
||||||
|
|
||||||
## 2. 当前构建/部署状态
|
## 2. 当前构建/部署状态
|
||||||
|
|
||||||
- `cargo test`:59 passed / 0 failed(2026-10-30,编辑缩进 + Find 选区)。
|
- `cargo test`:59 passed / 0 failed(2026-11-03;删除死代码时移除了 3 个平台专用测试)。
|
||||||
- 当前固定 exe(2026-10-30 部署,待发布):
|
- `cargo clippy --all-targets`:0 warning;`cargo fmt -- --check`:通过(2026-11-03)。
|
||||||
|
- 当前固定 exe(2026-10-30 部署):
|
||||||
- 大小 5,505,024 字节;版本 1.4.2.0
|
- 大小 5,505,024 字节;版本 1.4.2.0
|
||||||
- SHA256 `A632EF0363D04CE6F72B9779BA742681868AC31D36A7FE57E4F6D44E7BEAD988`
|
- SHA256 `A632EF0363D04CE6F72B9779BA742681868AC31D36A7FE57E4F6D44E7BEAD988`
|
||||||
- 完整性级别 Medium - OK;禁用字符串检查全 0;PE subsystem=2(GUI,无双击 cmd)。
|
- 完整性级别 Medium - OK;禁用字符串检查全 0;PE subsystem=2(GUI,无双击 cmd)。
|
||||||
- 构建方式:`cargo build --release` + `Copy-Item` + 同等校验。本机 DSH pwsh 下 `build.ps1` 会被 cargo 的 stderr 警告触发 `$ErrorActionPreference='Stop'`;脚本逻辑未改。
|
- 构建方式:`cargo build --release`(build.ps1 已改为 Low 工作区版,不再复制到固定路径;cargo stderr 不会再触发 Stop)。
|
||||||
- 上一版(v1.4.2-local.4):5,499,392 字节;SHA256 `7134BBC68423605BE220E19DAA1D6CB679AFBB9153C526E717F50388C1A0841D`。
|
- 上一版(v1.4.2-local.4):5,499,392 字节;SHA256 `7134BBC68423605BE220E19DAA1D6CB679AFBB9153C526E717F50388C1A0841D`。
|
||||||
- 上一版部署(v1.4.2-local.3):5,507,584 字节;SHA256 `0BFF730209CE835B18DC1447740A1F2770EA0645577A91EB969A6215B1C2372E`。
|
- 上一版部署(v1.4.2-local.3):5,507,584 字节;SHA256 `0BFF730209CE835B18DC1447740A1F2770EA0645577A91EB969A6215B1C2372E`。
|
||||||
- Nutstore 镜像:工作区外的 `C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe` 当前仍为 v1.4.2-local.4;发布 local.5 后按授权同步并校验。
|
- Nutstore 镜像:工作区外的 `C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe` 已同步为 v1.4.2-local.5(5,505,024 字节,SHA256 `A632EF03…`)。
|
||||||
- CDP 复核(2026-10-30):WIP 文档 8 个“为什么”逐个选区 Ctrl+F,滚动变化均为 0px,序号 1/8–8/8 正确;4/8 按 Enter 到 5/8 正常滚动;Tab/Shift+Tab/Enter/撤销均通过。
|
- CDP 复核(2026-10-30):WIP 文档 8 个“为什么”逐个选区 Ctrl+F,滚动变化均为 0px,序号 1/8–8/8 正确;4/8 按 Enter 到 5/8 正常滚动;Tab/Shift+Tab/Enter/撤销均通过。
|
||||||
- CDP 复核(2026-10-28,release):New Tab 标签名、Open File / New File 按钮、单 New Tab 隐藏标签栏、`+` 新建 New Tab、首页打开文件复用标签、关闭最后文件回 New Tab、脏内容先保存;界面无中文、无 JS 异常。
|
- CDP 复核(2026-10-28,release):New Tab 标签名、Open File / New File 按钮、单 New Tab 隐藏标签栏、`+` 新建 New Tab、首页打开文件复用标签、关闭最后文件回 New Tab、脏内容先保存;界面无中文、无 JS 异常。
|
||||||
- CDP 复核(旧):折叠按钮 30×30,位于内容左侧 `-34px`(H2 实测 left=14,heading left=48),垂直居中;hover `opacity .6`;两个 SVG 折角箭头按 `collapsed` 切换。
|
- CDP 复核(旧):折叠按钮 30×30,位于内容左侧 `-34px`(H2 实测 left=14,heading left=48),垂直居中;hover `opacity .6`;两个 SVG 折角箭头按 `collapsed` 切换。
|
||||||
@@ -150,15 +158,17 @@
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
cargo test
|
cargo test
|
||||||
.\agent\scripts\build.ps1 # 需要先关闭正在运行的 MD Preview
|
.\agent\scripts\build.ps1 # 开发构建;产物在 target\release\
|
||||||
.\agent\tests\smoke.ps1 -Launch
|
.\agent\tests\smoke.ps1 -Launch # 发布后冒烟(Nutstore exe)
|
||||||
|
.\agent\scripts\publish.ps1 # 发布:用户在自己的普通 PowerShell 运行
|
||||||
```
|
```
|
||||||
|
|
||||||
## 8. 环境与规则
|
## 8. 环境与规则
|
||||||
|
|
||||||
- **最高优先级**:`agent/AGENTS.md` —— 只在工作区内改文件;工作区外的任何修改先停下询问用户。
|
- **最高优先级**:`agent/AGENTS.md` —— 只在仓库内改文件;仓库外的任何修改先停下询问用户。
|
||||||
- 工作区是 Medium 完整性级别;DSH 需 danger-full-access 才能改/编译(workspace-write 会 EPERM / os error 5)。
|
- 仓库根 `D:\Scripts\md-preview\AgentLowWorking` 整棵树是 **Low**;DSH 用 **workspace-write** 即可改/编译。
|
||||||
- 不要把工作区改成 Low。
|
- 构建产物是 Low,不能直接双击;冒烟用 `MD_PREVIEW_CONFIG_DIR` 指到仓库内。
|
||||||
|
- 发布由用户手动运行 `publish.ps1`(Medium);Agent 不运行发布脚本、不改注册表。
|
||||||
- `git clean -xdf` 会删除被忽略的 backup 与 exe。
|
- `git clean -xdf` 会删除被忽略的 backup 与 exe。
|
||||||
- 截图/录屏等二进制验证产物**不入库**:放 `agent/tmp/` 或 `target/tmp/`,看完即删;`agent/reports/` 只留文本。
|
- 截图/录屏等二进制验证产物**不入库**:放 `agent/tmp/` 或 `target/tmp/`,看完即删;`agent/reports/` 只留文本。
|
||||||
- `%TEMP%` 历史测试残留已于 2026-10-21 16:38 经用户同意清理;之后的测试/构建把 TEMP/TMP 指向 `target\tmp` 与 `target\test-tmp`。
|
- `%TEMP%` 历史测试残留已于 2026-10-21 16:38 经用户同意清理;之后的测试/构建把 TEMP/TMP 指向 `target\tmp` 与 `target\test-tmp`。
|
||||||
@@ -166,9 +176,9 @@ cargo test
|
|||||||
## 9. 发布(Gitea)
|
## 9. 发布(Gitea)
|
||||||
|
|
||||||
- 实例 Gitea 24.5.4,仓库私有。
|
- 实例 Gitea 24.5.4,仓库私有。
|
||||||
- Release `v1.4.2-local.5`(最新,2026-10-30,待发布):
|
- Release `v1.4.2-local.5`(最新,2026-10-30):https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.5
|
||||||
- 附件 `MD-Preview-windows-x64.exe`,5,505,024 字节
|
- 附件 `MD-Preview-windows-x64.exe`,5,505,024 字节
|
||||||
- SHA256 `A632EF0363D04CE6F72B9779BA742681868AC31D36A7FE57E4F6D44E7BEAD988`
|
- SHA256 `A632EF0363D04CE6F72B9779BA742681868AC31D36A7FE57E4F6D44E7BEAD988`(已下载复核一致)
|
||||||
- 正文来源:`agent/docs/release-notes-v1.4.2-local.5.md`
|
- 正文来源:`agent/docs/release-notes-v1.4.2-local.5.md`
|
||||||
- Release `v1.4.2-local.4`(上一版,2026-10-28):https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.4
|
- Release `v1.4.2-local.4`(上一版,2026-10-28):https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.4
|
||||||
- 附件 5,499,392 字节;SHA256 `7134BBC68423605BE220E19DAA1D6CB679AFBB9153C526E717F50388C1A0841D`(已下载复核一致)
|
- 附件 5,499,392 字节;SHA256 `7134BBC68423605BE220E19DAA1D6CB679AFBB9153C526E717F50388C1A0841D`(已下载复核一致)
|
||||||
@@ -182,3 +192,43 @@ cargo test
|
|||||||
- 仓库描述与 topics 已通过 API 设置(topics:windows, markdown, markdown-preview, rust, webview2, offline, desktop-app)。
|
- 仓库描述与 topics 已通过 API 设置(topics:windows, markdown, markdown-preview, rust, webview2, offline, desktop-app)。
|
||||||
- **Gitea token 位置**:`C:\Users\wucl1\.gitea-token`(工作区外;保留,不要提交/删除;读取后不要打印内容)。
|
- **Gitea token 位置**:`C:\Users\wucl1\.gitea-token`(工作区外;保留,不要提交/删除;读取后不要打印内容)。
|
||||||
- 工作区内的 `.gitea-token` 旧路径已 gitignore;以后优先使用上面的用户目录文件。
|
- 工作区内的 `.gitea-token` 旧路径已 gitignore;以后优先使用上面的用户目录文件。
|
||||||
|
|
||||||
|
## 10. 2026-11-02 迁移(Low 工作区)
|
||||||
|
|
||||||
|
- 仓库根:`D:\Scripts\md-preview\AgentLowWorking`(整棵树 Low)。
|
||||||
|
- DSH 工作区仍是父目录 `D:\Scripts\md-preview`;代码在子目录 `AgentLowWorking`。
|
||||||
|
- DSH 以 `workspace-write` 运行;不再需要 danger-full-access。
|
||||||
|
- 开发构建:`.\agent\scripts\build.ps1`(产物 `target\release\md-preview.exe` 是 Low)。
|
||||||
|
- 开发冒烟:`$env:MD_PREVIEW_CONFIG_DIR="$PWD\target\smoke"; .\target\release\md-preview.exe <file>`。
|
||||||
|
- 发布:用户在自己的普通 PowerShell(Medium)运行 `.\agent\scripts\publish.ps1`;脚本复制到 Nutstore、设 Medium、校验 SHA256、刷新 `.md` 关联、删除旧 exe。
|
||||||
|
- 仓库内不再放成品 exe;默认打开指向 Nutstore。
|
||||||
|
- 迁移步骤与回滚见 `agent/docs/migration-2026-11-02.md`。
|
||||||
|
|
||||||
|
## 11. 2026-11-03 维护与待决策
|
||||||
|
|
||||||
|
- 已确认并实现(未发布):
|
||||||
|
- 编辑模式按标签记忆(原先属于窗口);切换标签恢复该标签离开时的编辑/阅读状态;detach 保留编辑状态。
|
||||||
|
- 滚动位置按标签记忆(相对比例,抗缩放/回流);标签动作携带比例,滚动回报带标签 id,避免迟到回报落到新标签;编辑/阅读切换仍保持滚动。
|
||||||
|
- `.txt` 不再作为文档类型:打开、重新定位、本地链接、命令行都只认 `md/markdown/mdown/mkd`。
|
||||||
|
- 非 md 本地链接(pdf/png/html)仍无反应,仅记录,不处理。
|
||||||
|
- 代码整理:`cargo fmt` 通过;clippy 7 条清零;保存写盘合并为 `save_active_file()`;`build.ps1` 的禁止字符串不再包含泛化的 `powershell`。
|
||||||
|
- 架构拆分阶段 1(功能不变,`1115052`):`assets/page/{page.html,page.css,page.js}` 存页面;新增 `src/markdown.rs`(md→html 管线)、`src/page.rs`(页面组装,只填 `__MDP_*__` 占位符)、`src/escape.rs`(JS/HTML 转义)。`main.rs` 5535 → 3709 行;页面输出用 home/doc/startup 三组快照做 sha256 对比,逐字节一致。
|
||||||
|
- 架构拆分阶段 2(功能不变,2026-11-03 晚):新增 `src/config.rs`(路径/zoom/窗口几何/对话框);删除 macOS/Linux/Finder 扩展代码、非 Windows 分支和 `objc2` 依赖(仓库现在只能在 Windows 编译);测试模块移到文件末尾;`main.rs` 3709 → 2822 行。59 tests(删除死代码时移除 3 个平台专用测试)。
|
||||||
|
- 架构拆分阶段 3(功能不变,2026-11-06,`1208386`):新增 `src/files.rs`(最近文件、保存写盘、文件监听、扩展名、本地链接、Explorer)与 `src/testutil.rs`;对应测试随模块搬迁。`main.rs` 2822 → 2365 行。
|
||||||
|
- 架构拆分阶段 4(功能不变,2026-11-06,`fb10fc5`):新增 `src/app.rs`(`UserEvent`/`WindowState`/`AppState`、渲染、`build_webview`、窗口创建/关闭、`run_event_loop`);`main.rs` 只留 CLI、启动装配、`main()` 和测试(2365 → 804 行)。60 tests 全绿,clippy/fmt 干净,release 仍是 5,502,464 字节。
|
||||||
|
- 架构拆分阶段 5(功能不变,2026-11-06,`a5c0b08`):测试全部随模块迁移(app 7、markdown 23、page 5、config 2、files 10、session 10、instance 3,共 60),共享 `testutil::temp_dir`;启动装配与 CLI 移入 `app::run()`,`main.rs` 18 行(仅模块声明 + `app::run()`)。
|
||||||
|
- HKCU 关联:应用启动时不再写注册表(`register_as_default` 及 `winreg` 依赖已删除);`publish.ps1` 维持现状(继续写 ProgID/关联)。首次使用需在 Windows“打开方式 → 选择其他应用”里选一次。
|
||||||
|
- 白屏 bug(2026-11-04 修复):`render_active_document` 给 `window.__setContent` 传了 8 个参数,页面签名只有 7 个(多传了 `active.id`),标签 id 被当成 `previewHtml` 渲染——窗口白屏、打开标签依次显示 1/2/3/4。修复:抽出 `set_content_script()`(单一参数源),新增精确输出 + 页面签名对照测试 `set_content_script_matches_the_page_signature`(60 tests)。教训:Rust→JS 这条边界没有编译器检查。
|
||||||
|
- 发布前 UI 冒烟:`agent/tests/ui-smoke.cmd`(普通桌面 PowerShell;启动 CDP、断言页面渲染、截图、写 `target/ui-test/ui-smoke.json`)。DSH 沙箱禁止命名管道,WebView2/Chromium 在沙箱内无法启动(窗口白屏、`msedgewebview2.exe` 立即退出),所以这一项只能由用户手动跑。**2026-11-04 已在本机跑通:8/8 checks,截图确认页面正常渲染**(`target/ui-test/ui-smoke.png`,不入库)。
|
||||||
|
- 规则调整(`agent/AGENTS.md`):仓库内新增文件/拆模块不需要事先询问;bug 修复、重构、测试、文档可直接做(每项独立提交);只有仓库外修改、发布、新第三方库(>200 KB vendored 资源)和不变量变化需要先问。
|
||||||
|
- 编辑区样式化(2026-11-06 决定,未开工):**改用内嵌 CodeMirror 5**(MIT、离线 vendored,core + markdown/xml mode + search/fold/lineNumbers 约 +270–320 KB,vendor 时附 LICENSE)。
|
||||||
|
- 理由:行号、**编辑区折叠**、替换已确认近期要做;透明叠加层(方案 A)只能做同字号着色,覆盖不了这三项。自研 contenteditable(方案 B)不做。
|
||||||
|
- 集成前先在 page.js 立**编辑器适配层**(`getValue/setValue/focus/getScrollRatio/setScrollRatio/onChange/setEditable`),textarea 与 CM5 共用同一套 autosave/标签状态/注入逻辑。
|
||||||
|
- 集成要点:编辑模式改为 CM 内部滚动(编辑时隐藏页面滚动条),按标签分别记录编辑/阅读滚动比例;标记保持显示(markdown mode 的 `cm-formatting` 标记 + `cm-strong` 内容加粗);autosave 仍 700ms;替换用 search 插件,阅读模式的既有 find 不动。
|
||||||
|
|
||||||
|
## 12. 测试与验证(2026-11-04 起)
|
||||||
|
|
||||||
|
- 代码级:`cargo test`(当前 60)、`cargo clippy --all-targets`、`cargo fmt -- --check`、`agent\scripts\build.ps1`。
|
||||||
|
- UI 级:**只能由用户**在桌面 PowerShell 运行 `agent\tests\ui-smoke.cmd`;Agent 读 `target\ui-test\ui-smoke.json` + `ui-smoke.png`。原因与流程见 `HANDOFF.md` §4.1(DSH 沙箱禁止命名管道,WebView2 无法启动)。
|
||||||
|
- 边界:Rust→JS 调用没有编译器检查;改参数必须同步页面签名,并保留 `set_content_script_matches_the_page_signature` 这类测试。
|
||||||
|
- 已验证(2026-11-04):ui-smoke 8/8 checks,截图确认页面正常渲染。
|
||||||
|
|||||||
101
agent/docs/migration-2026-11-02.md
Normal file
101
agent/docs/migration-2026-11-02.md
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
# 2026-11-02 迁移:Low 工作区 + Nutstore 单一发布
|
||||||
|
|
||||||
|
> 目标:DSH 以 **workspace-write(Low)** 运行就能改代码、编译、测试;成品只通过用户手动运行的 `publish.ps1` 发布到 Nutstore。
|
||||||
|
> 执行前先读 `agent/AGENTS.md`。
|
||||||
|
|
||||||
|
## 1. 最终结构
|
||||||
|
|
||||||
|
~~~
|
||||||
|
D:\Scripts\md-preview\
|
||||||
|
├─ AgentLowWorking\ ← 仓库根(整棵树 Low,含 .git)
|
||||||
|
│ ├─ src / assets / agent / target / Cargo.* / README.md ...
|
||||||
|
│ └─ test\ 本机草稿(已 gitignore)
|
||||||
|
└─ MD-Preview-windows-x64.exe 旧产物(Medium);publish.ps1 成功后删除
|
||||||
|
~~~
|
||||||
|
|
||||||
|
- 仓库根:`D:\Scripts\md-preview\AgentLowWorking`
|
||||||
|
- 发布产物:`C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`(Medium)
|
||||||
|
- 默认 `.md` 打开方式:由 `publish.ps1` 指向 Nutstore
|
||||||
|
- 仓库内不再放 exe
|
||||||
|
|
||||||
|
## 2. 一次性移动(用户执行)
|
||||||
|
|
||||||
|
DSH 工作区保持在父目录 `D:\Scripts\md-preview`,所以**不需要关 DSH**;只要没有编辑器/进程占用仓库文件即可。如果 `Move-Item` 报“文件被占用”,再关掉 DSH/编辑器重试。
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
$old = 'D:\Scripts\md-preview'
|
||||||
|
$new = Join-Path $old 'AgentLowWorking'
|
||||||
|
|
||||||
|
# 1) 创建新仓库根(继承 Low)
|
||||||
|
New-Item -ItemType Directory -Path $new -Force | Out-Null
|
||||||
|
|
||||||
|
# 2) 移动除旧 exe 和新目录以外的全部内容(含 .git、target、backup、test)
|
||||||
|
Get-ChildItem -LiteralPath $old -Force |
|
||||||
|
Where-Object { $_.Name -notin @('AgentLowWorking', 'MD-Preview-windows-x64.exe') } |
|
||||||
|
Move-Item -Destination $new -Force
|
||||||
|
|
||||||
|
# 3) 整棵树 relabel 成 Low(对目录用 /T,顶层文件也会覆盖)
|
||||||
|
icacls $new /setintegritylevel "(OI)(CI)Low" /T /C
|
||||||
|
|
||||||
|
# 4) 校验:前三项 Low,最后一项 Medium
|
||||||
|
icacls (Join-Path $new 'src\main.rs') | Select-String 'Mandatory Label'
|
||||||
|
icacls (Join-Path $new 'Cargo.toml') | Select-String 'Mandatory Label'
|
||||||
|
icacls (Join-Path $new '.git') | Select-String 'Mandatory Label'
|
||||||
|
icacls (Join-Path $old 'MD-Preview-windows-x64.exe') | Select-String 'Mandatory Label'
|
||||||
|
~~~
|
||||||
|
|
||||||
|
移动是同卷 rename,`.git` 一起走:历史、分支、远程都不受影响,**不需要任何 rename 提交**。
|
||||||
|
|
||||||
|
## 3. 移动后继续
|
||||||
|
|
||||||
|
不需要重开 DSH;在 DSH 里 `cd AgentLowWorking`(或所有命令用绝对路径)。验证:
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
# 在 DSH 的 pwsh 里应能写
|
||||||
|
Set-Content "$PWD\target\tmp\probe.txt" 'ok'; Get-Content "$PWD\target\tmp\probe.txt"; Remove-Item "$PWD\target\tmp\probe.txt"
|
||||||
|
cargo test
|
||||||
|
~~~
|
||||||
|
|
||||||
|
## 4. 开发循环
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
.\agent\scripts\build.ps1
|
||||||
|
# 产物 target\release\md-preview.exe 是 Low,不能直接双击
|
||||||
|
$env:MD_PREVIEW_CONFIG_DIR="$PWD\target\smoke"
|
||||||
|
.\target\release\md-preview.exe path\to\file.md
|
||||||
|
~~~
|
||||||
|
|
||||||
|
## 5. 发布(用户手动,普通 PowerShell)
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
cd D:\Scripts\md-preview\AgentLowWorking
|
||||||
|
.\agent\scripts\publish.ps1
|
||||||
|
~~~
|
||||||
|
|
||||||
|
脚本会:检查 Medium 权限和进程占用 → 复制到 Nutstore → 设 Medium → 校验 SHA256 → 刷新 `.md` 关联 → 删除 `D:\Scripts\md-preview\MD-Preview-windows-x64.exe`。
|
||||||
|
|
||||||
|
## 6. 回滚
|
||||||
|
|
||||||
|
如果新模型不可用:
|
||||||
|
|
||||||
|
1. 关掉 DSH。
|
||||||
|
2. 把 `AgentLowWorking` 里的内容移回 `D:\Scripts\md-preview`(同样排除 `AgentLowWorking`)。
|
||||||
|
3. `icacls D:\Scripts\md-preview /setintegritylevel "(OI)(CI)Medium" /T /C`(旧模型)。
|
||||||
|
4. 旧 exe 若已被删除,从 Nutstore 复制回来或重新发布。
|
||||||
|
5. DSH 改回 danger-full-access。
|
||||||
|
|
||||||
|
## 7. 注意
|
||||||
|
|
||||||
|
- `publish.ps1` 只应在**普通 / Medium** PowerShell 里运行;DSH 的 Low shell 会被脚本拒绝。
|
||||||
|
- 发布前关闭 MD Preview;Nutstore 同步也可能短暂锁文件。
|
||||||
|
- 开发版写不了 HKCU,不会抢默认打开;不要用 Medium 的旧 exe 启动,否则关联会被改回旧路径。
|
||||||
|
- `test/` 已 gitignore,移动后仍不提交。
|
||||||
|
|
||||||
|
## 8. 迁移后待办
|
||||||
|
|
||||||
|
- 在 DSH 里确认可写、`cargo test` 全绿。
|
||||||
|
- 父目录可选:`publish.ps1` 启动器 + `AGENTS.md` 指针(让新会话在父目录也能找到仓库规则)。
|
||||||
|
- 给 `.gitignore` 加 `/test/`(本机草稿目录)。
|
||||||
|
- 更新根 `README.md` 的目录树/构建命令。
|
||||||
|
- 提交:`git add -A && git commit -m "chore: move to Low workspace and Nutstore-only publish"`(不要提交 `test/`)。
|
||||||
|
- 需要切换默认打开并删除旧 exe 时,运行 `publish.ps1`。
|
||||||
107
agent/docs/next-2026-11-03.md
Normal file
107
agent/docs/next-2026-11-03.md
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
# 下一步交接(2026-11-03)
|
||||||
|
|
||||||
|
> 用途:这一轮只做了“功能不变”的架构整理。功能改动(HKCU、编辑区样式化)**一个都没做**,下次从这里继续。
|
||||||
|
> 先读 `agent/AGENTS.md`;发布仍由用户手动运行 `agent\scripts\publish.ps1`。
|
||||||
|
|
||||||
|
## 1. 基线
|
||||||
|
|
||||||
|
- 仓库根:`D:\Scripts\md-preview\AgentLowWorking`;Windows-only(macOS/Linux 代码已在 `1115052` 之后的提交里删除)。
|
||||||
|
- `cargo test` 59 passed;`cargo clippy --all-targets` 0 warning;`cargo fmt -- --check` 通过。
|
||||||
|
- 源码:`main.rs` 约 2820 行、`config.rs` 212、`markdown.rs` 405、`session.rs` 488、`instance.rs` 207、`page.rs` 65、`escape.rs` 25。
|
||||||
|
- 页面资源:`assets/page/{page.html,page.css,page.js}`。
|
||||||
|
- 未发布:Nutstore 上的 exe 仍是 v1.4.2-local.5;这一轮的构建只在 `target\release\`(Low)。
|
||||||
|
|
||||||
|
## 2. 已完成(本轮,均未改变 Windows 行为)
|
||||||
|
|
||||||
|
1. 页面 HTML/CSS/JS 搬出 `format!`,`build_page` 只填 `__MDP_*__` 占位符。
|
||||||
|
2. 拆出 `src/markdown.rs`(md→html)、`src/page.rs`、`src/escape.rs`、`src/config.rs`(路径/zoom/窗口几何/对话框)。
|
||||||
|
3. 删除 macOS/Linux 死代码、Finder 扩展、非 Windows 分支与 `objc2` 依赖;`Cargo.toml` 只剩 Windows 依赖。
|
||||||
|
4. 测试模块移到文件末尾(clippy items_after_test_module)。
|
||||||
|
|
||||||
|
## 3. 剩余重构(仍不改行为,建议顺序)
|
||||||
|
|
||||||
|
1. ✅ `src/files.rs`(2026-11-06,`1208386`):最近文件、保存写盘、文件监听、支持的扩展名、本地链接解析、Explorer 定位;附带 `src/testutil.rs`。
|
||||||
|
2. ✅ `src/app.rs`(2026-11-06,`fb10fc5`):`UserEvent`/`WindowState`/`AppState`、find/focus、`render_*`、`build_webview`、窗口创建/关闭、`run_event_loop`。
|
||||||
|
3. ✅ `main.rs` 只留 `main()`、CLI、启动装配和测试(事件 match 仍在 `app::run_event_loop` 里,可按需再拆处理函数)。
|
||||||
|
4. ✅ 测试已随模块走(2026-11-06,`a5c0b08`):app 7、markdown 23、page 5、config 2、files 10、session 10、instance 3;共享 `testutil::temp_dir`。启动装配与 CLI 也移入 `app::run()`,`main.rs` 只剩 18 行。
|
||||||
|
5. 遗留:`UserEvent` 里 5 个未构造变体(`CloseActiveTab/ToggleEdit/ShowFind/Quit/SetTheme`)要么接键盘路径,要么删除。
|
||||||
|
|
||||||
|
## 4. 待做功能(都需要先讨论/确认)
|
||||||
|
|
||||||
|
### 4.1 移除应用自身的 HKCU 写入(2026-11-04 已完成)
|
||||||
|
|
||||||
|
- 已删除 `main()` 里的 `register_as_default()` 调用、该函数以及 `winreg` 依赖;应用不再写注册表。
|
||||||
|
- **`publish.ps1` 维持现状**(继续写 ProgID/关联),这是用户明确决定。
|
||||||
|
- 影响:新机器上应用不再自动出现在“打开方式”;首次在 Windows“打开方式 → 选择其他应用”里选一次;exe 移动后由发布脚本刷新关联。
|
||||||
|
- README 第 3 步、STATUS §11 已同步。
|
||||||
|
|
||||||
|
### 4.2 编辑区样式化(2026-11-06 决定:内嵌 CodeMirror 5)
|
||||||
|
|
||||||
|
需求:编辑模式里 `**加粗**` 显示为粗体、`# 标题` 整行加粗加大、行内代码换字体。**标记保持显示**。用户已确认行号、编辑区折叠、替换近期一定会做。
|
||||||
|
|
||||||
|
**决策(2026-11-06)**:
|
||||||
|
|
||||||
|
- 采用 **CodeMirror 5**(单文件 UMD、离线 vendored,MIT;core + markdown/xml mode + search + fold + lineNumbers 约 +270–320 KB,exe 约 5.50 → 5.8 MB)。用户已确认这项 >200 KB vendored 资源。
|
||||||
|
- 弃用透明叠加层(方案 A):只能同字号着色,覆盖不了行号/折叠/替换。
|
||||||
|
- 不选自研 contenteditable(方案 B)。
|
||||||
|
|
||||||
|
**实现顺序**:
|
||||||
|
|
||||||
|
1. 先在 page.js 抽出编辑器适配层(`getValue/setValue/focus/getScrollRatio/setScrollRatio/onChange/setEditable`);textarea 作为默认实现,行为不变。
|
||||||
|
2. vendor CM5 到 `assets/codemirror/`(附 LICENSE),由 page 注入;保持离线、单 exe。
|
||||||
|
3. CM5 适配器:markdown/xml mode、lineNumbers、foldGutter + 按标题计算折叠区间、search(find/replace);样式沿用现有配色,`cm-strong` 加粗、标题行加粗/着色,标记不隐藏。
|
||||||
|
4. 滚动模型:编辑模式由 CM 内部滚动(隐藏页面滚动条),编辑/阅读各自记住比例,切换时近似同步;按标签独立(`DocumentTab` 可能需要两个比例字段)。
|
||||||
|
5. autosave 仍 700ms,接 `onChange`;`__setContent`/标签切换/缩放/暗色主题都要重新验证;超大文档保护(>2 MB 或 >2 万行)可保留。
|
||||||
|
6. 阅读模式既有 find 与折叠不动;编辑模式 find/replace 由 CM search 提供,UI 统一是后续小工作。
|
||||||
|
|
||||||
|
**验证**:用户跑 `agent/tests/ui-smoke.cmd` + 手动冒烟(编辑/保存/切标签/折叠/替换/IME/滚动切换)。
|
||||||
|
|
||||||
|
## 5. 验证配方
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
$env:TEMP = "$PWD\target\tmp"; $env:TMP = $env:TEMP
|
||||||
|
cargo test
|
||||||
|
cargo clippy --all-targets
|
||||||
|
cargo fmt -- --check
|
||||||
|
.\agent\scripts\build.ps1 # release 构建 + 字符串校验 + 大小/SHA
|
||||||
|
~~~
|
||||||
|
|
||||||
|
页面输出逐字节对比(重构时用):
|
||||||
|
|
||||||
|
1. 临时加一个 `#[test]`,用 `build_page`/build_startup_page 把 home、含公式/mermaid 的文档、启动页写到 `$env:MDP_DUMP_DIR`;
|
||||||
|
2. 重构前后各跑一次,`Get-FileHash` 对比 sha256;
|
||||||
|
3. 用完删除该测试。
|
||||||
|
|
||||||
|
手动冒烟(无自动化):多标签切换、编辑/阅读、Ctrl+F、Ctrl+P、折叠、拖拽打开、外部修改提示、只读保存失败。
|
||||||
|
|
||||||
|
## 5.1 发布前 UI 冒烟(必须由用户在普通 PowerShell 跑)
|
||||||
|
|
||||||
|
**为什么不能由 Agent 跑**:DSH 的 Windows 沙箱禁止命名管道,Chromium/WebView2 的 Mojo IPC 起不来。
|
||||||
|
实测:md-preview 能启动、窗口出现,但 `msedgewebview2.exe` 立刻退出(数据目录只建了一半),页面白屏;Edge headless 报
|
||||||
|
`FATAL:mojo\public\cpp\platform\platform_channel.cc Check failed: 拒绝访问 (0x5)`。
|
||||||
|
这是沙箱限制,不是应用 bug;同时开发 exe 是 Low 完整性,从这里 `icacls /setintegritylevel Medium` 会被拒绝(无 write-up)。
|
||||||
|
|
||||||
|
**用法**(普通 PowerShell,Node 21+;本机 `C:\Program Files\nodejs\node.exe` 是 24.x):
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
cd D:\Scripts\md-preview\AgentLowWorking
|
||||||
|
.\agent\tests\ui-smoke.cmd # 推荐:双击或从 cmd 运行,脚本内部用 Bypass
|
||||||
|
.\agent\tests\ui-smoke.ps1 # 若执行策略允许 .ps1
|
||||||
|
powershell -NoProfile -ExecutionPolicy Bypass -File .\agent\tests\ui-smoke.ps1
|
||||||
|
~~~
|
||||||
|
|
||||||
|
> 本机执行策略可能是 AllSigned:直接跑未签名 .ps1 会被拒绝,所以提供了 `.cmd` 包装(内部 `-ExecutionPolicy Bypass`,不修改系统策略)。
|
||||||
|
|
||||||
|
- 脚本用独立配置目录(`target\ui-test\config`)启动 exe,设置 `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333`,等端口起来后调用 `agent/tests/ui-smoke.mjs`。
|
||||||
|
- mjs 通过 CDP 读取页面快照、断言(页面加载、`#preview` 有内容、`window.ipc` 桥、页面 API、标题/折叠按钮/代码高亮),再截图,写 `target/ui-test/ui-smoke.json` 与 `ui-smoke.png`。
|
||||||
|
- Agent 可以直接读这两个文件定位问题;失败时把 report 里的 checks 贴出来即可。
|
||||||
|
- 已知边界:只验证“页面真的渲染了 + 基础 API 在”,不覆盖标签切换、保存、外部修改等 Rust 侧流程(那些靠单元测试和人工点)。
|
||||||
|
- 2026-11-04 起应用启动不再写注册表,所以用发布版做冒烟也不会改 .md 关联;默认的开发构建仍是 Low,配置目录隔离在 `target/ui-test`。
|
||||||
|
|
||||||
|
## 6. 注意
|
||||||
|
|
||||||
|
- 本仓库现在**只能在 Windows 上编译**;`cargo test` 里仍有 `cfg(target_os = "windows")` 的 Windows 专用测试。
|
||||||
|
- `main.rs` 顶部的 `windows_subsystem` 只对 release 生效;debug 构建带控制台,属正常。
|
||||||
|
- 页面 JS 改动后建议做一次语法检查(临时测试把页面写到文件,再 `node --check`)。
|
||||||
|
- **Rust → JS 调用没有编译器检查**:改 `__setContent` / `__setPreview` 等参数列表时,必须同步改页面的函数签名,并用 `set_content_script_matches_the_page_signature` 这类“精确输出 + 页面签名”测试锁住。2026-11-04 的白屏就是这么来的(多传了一个 `active.id`,标签 id 被当 HTML 渲染)。
|
||||||
|
- 构建/测试临时文件放 `target\tmp`;不要写 `%TEMP%`。
|
||||||
@@ -101,7 +101,7 @@
|
|||||||
|
|
||||||
- [ ] 窗口标题 `文件名 — MD Preview`,脏状态显示 `•`
|
- [ ] 窗口标题 `文件名 — MD Preview`,脏状态显示 `•`
|
||||||
- [ ] 工具栏无 Open / Print / Find
|
- [ ] 工具栏无 Open / Print / Find
|
||||||
- [ ] 多标签、关闭、会话恢复、缺失文件重定位
|
- [ ] 多标签、关闭、缺失文件重定位;切回标签保持编辑模式与滚动位置
|
||||||
- [ ] 编辑 700ms 自动保存;关闭前落盘
|
- [ ] 编辑 700ms 自动保存;关闭前落盘
|
||||||
- [ ] 外部修改提示与保护
|
- [ ] 外部修改提示与保护
|
||||||
- [ ] 查找(含中文输入法组合输入)
|
- [ ] 查找(含中文输入法组合输入)
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
#requires -Version 5.1
|
#requires -Version 5.1
|
||||||
<#
|
<#
|
||||||
MD Preview 发布构建脚本
|
MD Preview 开发构建(DSH workspace-write / Low 完整性可运行)
|
||||||
固定产物:D:\Scripts\md-preview\MD-Preview-windows-x64.exe
|
- cargo test + cargo build --release
|
||||||
|
- 只做校验,不复制到任何固定 exe 路径
|
||||||
运行环境:普通 PowerShell(Medium),或 DSH 的 danger-full-access。
|
- 产物:target\release\md-preview.exe(Low)
|
||||||
workspace-write 是 Low 完整性级别,写不动本目录(EPERM / os error 5)。
|
- 发布:用户在自己的普通 PowerShell 里运行 agent\scripts\publish.ps1
|
||||||
#>
|
#>
|
||||||
[CmdletBinding()]
|
[CmdletBinding()]
|
||||||
param(
|
param(
|
||||||
[string]$OutputPath = 'D:\Scripts\md-preview\MD-Preview-windows-x64.exe',
|
|
||||||
[switch]$SkipTests
|
[switch]$SkipTests
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -16,7 +15,7 @@ $ErrorActionPreference = 'Stop'
|
|||||||
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||||
Set-Location $repoRoot
|
Set-Location $repoRoot
|
||||||
|
|
||||||
# 工作区规则(agent/AGENTS.md):构建/测试的临时文件也留在 target\ 下,不污染 %TEMP%。
|
# 工作区规则(agent/AGENTS.md):临时文件留在 target\ 下,不污染 %TEMP%。
|
||||||
$tmpRoot = Join-Path $repoRoot 'target\tmp'
|
$tmpRoot = Join-Path $repoRoot 'target\tmp'
|
||||||
New-Item -ItemType Directory -Force $tmpRoot | Out-Null
|
New-Item -ItemType Directory -Force $tmpRoot | Out-Null
|
||||||
$env:TEMP = $tmpRoot
|
$env:TEMP = $tmpRoot
|
||||||
@@ -29,53 +28,53 @@ if (-not (Test-Path $cargo)) {
|
|||||||
|
|
||||||
function Step([string]$text) { Write-Host ('==> ' + $text) -ForegroundColor Cyan }
|
function Step([string]$text) { Write-Host ('==> ' + $text) -ForegroundColor Cyan }
|
||||||
|
|
||||||
function Assert-TargetNotRunning([string]$path) {
|
function Invoke-Cargo([string[]]$arguments) {
|
||||||
$ids = @()
|
$previous = $ErrorActionPreference
|
||||||
foreach ($p in (Get-Process -ErrorAction SilentlyContinue)) {
|
$code = 0
|
||||||
$pPath = $null
|
try {
|
||||||
try { $pPath = $p.Path } catch { }
|
# cargo 把进度/警告写到 stderr;Stop 会把它们当成终止错误
|
||||||
if ($pPath -eq $path) { $ids += $p.Id }
|
$ErrorActionPreference = 'Continue'
|
||||||
|
& $cargo @arguments
|
||||||
|
$code = $LASTEXITCODE
|
||||||
|
} finally {
|
||||||
|
$ErrorActionPreference = $previous
|
||||||
}
|
}
|
||||||
if ($ids.Count -gt 0) {
|
if ($code -ne 0) {
|
||||||
throw ('MD Preview 正在运行(PID ' + ($ids -join ', ') + '),请先关闭窗口再构建。')
|
throw ('cargo ' + ($arguments -join ' ') + ' failed with exit code ' + $code)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Assert-TargetNotRunning $OutputPath
|
$built = Join-Path $repoRoot 'target\release\md-preview.exe'
|
||||||
|
|
||||||
|
$running = @()
|
||||||
|
foreach ($process in (Get-Process -ErrorAction SilentlyContinue)) {
|
||||||
|
$path = $null
|
||||||
|
try { $path = $process.Path } catch { }
|
||||||
|
if ($path -eq $built) { $running += [string]$process.Id }
|
||||||
|
}
|
||||||
|
if ($running.Count -gt 0) {
|
||||||
|
throw ('开发版 MD Preview 正在运行(PID ' + ($running -join ', ') + '),请先关闭。')
|
||||||
|
}
|
||||||
|
|
||||||
if (-not $SkipTests) {
|
if (-not $SkipTests) {
|
||||||
Step 'cargo test'
|
Step 'cargo test'
|
||||||
& $cargo test
|
Invoke-Cargo @('test')
|
||||||
if ($LASTEXITCODE -ne 0) { throw 'cargo test failed' }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Step 'cargo build --release'
|
Step 'cargo build --release'
|
||||||
& $cargo build --release
|
Invoke-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) }
|
if (-not (Test-Path $built)) { throw ('missing build output: ' + $built) }
|
||||||
|
|
||||||
Step ('copy -> ' + $OutputPath)
|
$info = Get-Item $built
|
||||||
$outDir = Split-Path -Parent $OutputPath
|
$hash = (Get-FileHash $built -Algorithm SHA256).Hash
|
||||||
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'
|
Step 'check removed update strings'
|
||||||
$bytes = [IO.File]::ReadAllBytes($OutputPath)
|
$bytes = [IO.File]::ReadAllBytes($built)
|
||||||
$ascii = [Text.Encoding]::ASCII.GetString($bytes)
|
$ascii = [Text.Encoding]::ASCII.GetString($bytes)
|
||||||
$forbidden = @('api.github', 'btn-update', 'Check for Updates', 'powershell', 'update-check-result', 'open-url')
|
# Guard the removed updater. 'powershell' used to be on this list, but that word
|
||||||
|
# can legitimately show up in user-facing text; the updater itself needs these.
|
||||||
|
$forbidden = @('api.github', 'btn-update', 'Check for Updates', 'Start-Process', 'Invoke-WebRequest', 'update-check-result', 'open-url')
|
||||||
$bad = @()
|
$bad = @()
|
||||||
foreach ($needle in $forbidden) {
|
foreach ($needle in $forbidden) {
|
||||||
$count = ([regex]::Matches($ascii, [regex]::Escape($needle), 'IgnoreCase')).Count
|
$count = ([regex]::Matches($ascii, [regex]::Escape($needle), 'IgnoreCase')).Count
|
||||||
@@ -84,13 +83,14 @@ foreach ($needle in $forbidden) {
|
|||||||
}
|
}
|
||||||
if ($bad.Count -gt 0) { throw ('removed features still present: ' + ($bad -join ', ')) }
|
if ($bad.Count -gt 0) { throw ('removed features still present: ' + ($bad -join ', ')) }
|
||||||
|
|
||||||
Step 'check integrity level'
|
Step 'report'
|
||||||
$acl = (icacls $OutputPath | Out-String)
|
$acl = (icacls $built | Out-String)
|
||||||
if ($acl -match 'Medium Mandatory Level') {
|
$integrity = 'Unknown'
|
||||||
Write-Host ' Medium - OK'
|
if ($acl -match 'Mandatory Label\\(Low|Medium|High) Mandatory Level') { $integrity = $Matches[1] }
|
||||||
} else {
|
Write-Host ('output : ' + $built)
|
||||||
Write-Warning '不是 Medium:启动时可能报 os error 5,见 agent/docs/HANDOFF.md 第 4 节'
|
Write-Host ('size : {0:N0} bytes' -f $info.Length)
|
||||||
}
|
Write-Host ('sha256 : ' + $hash)
|
||||||
|
Write-Host ('version : ' + $info.VersionInfo.FileVersion)
|
||||||
|
Write-Host ('integrity : ' + $integrity + ' (workspace-write builds are Low)')
|
||||||
Write-Host ''
|
Write-Host ''
|
||||||
Write-Host ('DONE ' + $OutputPath) -ForegroundColor Green
|
Write-Host 'DONE (build only). Publish: .\agent\scripts\publish.ps1 (normal PowerShell, Medium)' -ForegroundColor Green
|
||||||
|
|||||||
114
agent/scripts/publish.ps1
Normal file
114
agent/scripts/publish.ps1
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
#requires -Version 5.1
|
||||||
|
<#
|
||||||
|
MD Preview 发布(必须由用户在自己的普通 PowerShell / Medium 运行)
|
||||||
|
- 源:target\release\md-preview.exe(Low)
|
||||||
|
- 目标:C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe(Medium)
|
||||||
|
- 校验 SHA256 + Medium,刷新 .md 关联,最后删除旧 exe
|
||||||
|
- 不要从 DSH 的 workspace-write shell 运行
|
||||||
|
#>
|
||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[string]$Source = '',
|
||||||
|
[string]$NutstorePath = 'C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe',
|
||||||
|
[string]$OldExe = 'D:\Scripts\md-preview\MD-Preview-windows-x64.exe',
|
||||||
|
[switch]$KeepOldExe
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||||
|
Set-Location $repoRoot
|
||||||
|
if (-not $Source) { $Source = Join-Path $repoRoot 'target\release\md-preview.exe' }
|
||||||
|
|
||||||
|
function Step([string]$text) { Write-Host ('==> ' + $text) -ForegroundColor Cyan }
|
||||||
|
|
||||||
|
function Assert-Medium {
|
||||||
|
$groups = (whoami /groups | Out-String)
|
||||||
|
if ($groups -match 'Low Mandatory Level') {
|
||||||
|
throw '当前是 Low 完整性(DSH 沙箱)。请在自己的普通 PowerShell(Medium)里运行本脚本。'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Assert-NotRunning([string[]]$paths) {
|
||||||
|
$running = @()
|
||||||
|
foreach ($process in (Get-Process -ErrorAction SilentlyContinue)) {
|
||||||
|
$path = $null
|
||||||
|
try { $path = $process.Path } catch { }
|
||||||
|
if ($path -and ($paths -contains $path)) {
|
||||||
|
$running += ($process.ProcessName + ' (PID ' + $process.Id + '): ' + $path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($running.Count -gt 0) {
|
||||||
|
throw ('请先关闭 MD Preview:' + [Environment]::NewLine + ($running -join [Environment]::NewLine))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-Integrity([string]$path) {
|
||||||
|
$out = (icacls $path | Out-String)
|
||||||
|
if ($out -match 'Mandatory Label\\(Low|Medium|High) Mandatory Level') { return $Matches[1] }
|
||||||
|
return 'Unknown'
|
||||||
|
}
|
||||||
|
|
||||||
|
function Set-RegistryDefault([string]$path, [string]$value) {
|
||||||
|
if (-not (Test-Path $path)) { New-Item -Path $path -Force | Out-Null }
|
||||||
|
Set-ItemProperty -Path $path -Name '(default)' -Value $value
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert-Medium
|
||||||
|
if (-not (Test-Path -LiteralPath $Source)) {
|
||||||
|
throw ('找不到构建产物:' + $Source + ';先运行 agent\scripts\build.ps1')
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert-NotRunning @($Source, $NutstorePath, $OldExe)
|
||||||
|
|
||||||
|
$sourceHash = (Get-FileHash -LiteralPath $Source -Algorithm SHA256).Hash
|
||||||
|
|
||||||
|
Step ('copy -> ' + $NutstorePath)
|
||||||
|
$nutstoreDir = Split-Path -Parent $NutstorePath
|
||||||
|
if (-not (Test-Path $nutstoreDir)) { New-Item -ItemType Directory -Path $nutstoreDir -Force | Out-Null }
|
||||||
|
Copy-Item -LiteralPath $Source -Destination $NutstorePath -Force -ErrorAction Stop
|
||||||
|
|
||||||
|
Step 'set Nutstore exe integrity -> Medium'
|
||||||
|
$previous = $ErrorActionPreference
|
||||||
|
$ErrorActionPreference = 'Continue'
|
||||||
|
icacls $NutstorePath /setintegritylevel Medium | Out-Null
|
||||||
|
$icaclsCode = $LASTEXITCODE
|
||||||
|
$ErrorActionPreference = $previous
|
||||||
|
if ($icaclsCode -ne 0) { throw ('icacls failed with exit code ' + $icaclsCode) }
|
||||||
|
|
||||||
|
$integrity = Get-Integrity $NutstorePath
|
||||||
|
if ($integrity -ne 'Medium') { throw ('完整性级别不是 Medium:' + $integrity) }
|
||||||
|
|
||||||
|
$targetHash = (Get-FileHash -LiteralPath $NutstorePath -Algorithm SHA256).Hash
|
||||||
|
if ($sourceHash -ne $targetHash) {
|
||||||
|
throw ('SHA256 不一致:source=' + $sourceHash + ' target=' + $targetHash)
|
||||||
|
}
|
||||||
|
|
||||||
|
Step 'refresh .md association -> Nutstore'
|
||||||
|
$progid = 'MDPreview.md'
|
||||||
|
$command = '"' + $NutstorePath + '" "%1"'
|
||||||
|
Set-RegistryDefault ('HKCU:\Software\Classes\' + $progid + '\shell\open\command') $command
|
||||||
|
Set-RegistryDefault ('HKCU:\Software\Classes\' + $progid + '\DefaultIcon') ('"' + $NutstorePath + '",0')
|
||||||
|
Set-RegistryDefault ('HKCU:\Software\Classes\Applications\MD-Preview-windows-x64.exe\shell\open\command') $command
|
||||||
|
|
||||||
|
$actual = (Get-ItemProperty ('HKCU:\Software\Classes\' + $progid + '\shell\open\command')).'(default)'
|
||||||
|
if ($actual -ne $command) { throw ('关联写入失败:' + $actual) }
|
||||||
|
|
||||||
|
$userChoiceKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.md\UserChoiceLatest\ProgId'
|
||||||
|
$userChoice = $null
|
||||||
|
if (Test-Path $userChoiceKey) { $userChoice = (Get-ItemProperty $userChoiceKey).ProgId }
|
||||||
|
if ($userChoice -ne $progid) {
|
||||||
|
Write-Warning ('.md 的 UserChoice ProgId 是 ' + $userChoice + ',不是 ' + $progid + ';请在 设置 -> 默认应用 里选择一次 MD Preview。')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not $KeepOldExe -and (Test-Path -LiteralPath $OldExe)) {
|
||||||
|
Step ('delete old exe -> ' + $OldExe)
|
||||||
|
Remove-Item -LiteralPath $OldExe -Force -ErrorAction Stop
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host ('size : {0:N0} bytes' -f (Get-Item -LiteralPath $NutstorePath).Length)
|
||||||
|
Write-Host ('sha256 : ' + $targetHash)
|
||||||
|
Write-Host ('integrity : ' + $integrity)
|
||||||
|
Write-Host ('default : ' + $actual)
|
||||||
|
Write-Host ('old exe : ' + $OldExe)
|
||||||
|
Write-Host 'DONE' -ForegroundColor Green
|
||||||
@@ -2,25 +2,46 @@
|
|||||||
<#
|
<#
|
||||||
MD Preview 冒烟测试
|
MD Preview 冒烟测试
|
||||||
cargo test + 关联检查 + 可选隔离启动(不污染真实 %LOCALAPPDATA%)
|
cargo test + 关联检查 + 可选隔离启动(不污染真实 %LOCALAPPDATA%)
|
||||||
|
默认测试 Nutstore 发布版;-Dev 测试 target\release 开发版
|
||||||
#>
|
#>
|
||||||
[CmdletBinding()]
|
[CmdletBinding()]
|
||||||
param(
|
param(
|
||||||
[string]$Exe = 'D:\Scripts\md-preview\MD-Preview-windows-x64.exe',
|
[string]$Exe = 'C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe',
|
||||||
[switch]$Launch
|
[switch]$Launch,
|
||||||
|
[switch]$Dev
|
||||||
)
|
)
|
||||||
|
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||||
Set-Location $repoRoot
|
Set-Location $repoRoot
|
||||||
|
|
||||||
|
$tmpRoot = Join-Path $repoRoot 'target\tmp'
|
||||||
|
New-Item -ItemType Directory -Force $tmpRoot | Out-Null
|
||||||
|
$env:TEMP = $tmpRoot
|
||||||
|
$env:TMP = $tmpRoot
|
||||||
|
|
||||||
$cargo = Join-Path $env:USERPROFILE '.cargo\bin\cargo.exe'
|
$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 $cargo)) { $cargo = (Get-Command cargo -ErrorAction Stop).Source }
|
||||||
|
|
||||||
if (-not (Test-Path $Exe)) { throw ('missing exe: ' + $Exe + ' (先运行 agent/scripts/build.ps1)') }
|
if ($Dev) {
|
||||||
|
$Exe = Join-Path $repoRoot 'target\release\md-preview.exe'
|
||||||
|
if (-not $env:MD_PREVIEW_CONFIG_DIR) {
|
||||||
|
$env:MD_PREVIEW_CONFIG_DIR = Join-Path $repoRoot 'target\smoke'
|
||||||
|
New-Item -ItemType Directory -Force $env:MD_PREVIEW_CONFIG_DIR | Out-Null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not (Test-Path $Exe)) {
|
||||||
|
throw ('missing exe: ' + $Exe + '(先运行 agent/scripts/build.ps1,或先发布)')
|
||||||
|
}
|
||||||
|
|
||||||
Write-Host '==> cargo test' -ForegroundColor Cyan
|
Write-Host '==> cargo test' -ForegroundColor Cyan
|
||||||
|
$previous = $ErrorActionPreference
|
||||||
|
$ErrorActionPreference = 'Continue'
|
||||||
& $cargo test
|
& $cargo test
|
||||||
if ($LASTEXITCODE -ne 0) { throw 'cargo test failed' }
|
$code = $LASTEXITCODE
|
||||||
|
$ErrorActionPreference = $previous
|
||||||
|
if ($code -ne 0) { throw 'cargo test failed' }
|
||||||
|
|
||||||
Write-Host '==> --help' -ForegroundColor Cyan
|
Write-Host '==> --help' -ForegroundColor Cyan
|
||||||
$help = (& $Exe --help 2>&1 | Out-String)
|
$help = (& $Exe --help 2>&1 | Out-String)
|
||||||
@@ -30,20 +51,24 @@ if ($help -match 'MD Preview') {
|
|||||||
Write-Warning '--help 无输出(GUI 子系统在部分终端下不回显,可忽略)'
|
Write-Warning '--help 无输出(GUI 子系统在部分终端下不回显,可忽略)'
|
||||||
}
|
}
|
||||||
|
|
||||||
Write-Host '==> registry association' -ForegroundColor Cyan
|
if ($Dev) {
|
||||||
$reg = Get-ItemProperty 'HKCU:\Software\Classes\MDPreview.md\shell\open\command' -ErrorAction SilentlyContinue
|
Write-Host '==> registry association (skipped: Low build cannot write HKCU)' -ForegroundColor Cyan
|
||||||
$expected = '"' + $Exe + '" "%1"'
|
|
||||||
if ($null -eq $reg) {
|
|
||||||
Write-Warning 'ProgID 未注册(先运行一次 exe)'
|
|
||||||
} elseif ($reg.'(default)' -ne $expected) {
|
|
||||||
Write-Warning ('ProgID 指向不一致: ' + $reg.'(default)')
|
|
||||||
} else {
|
} else {
|
||||||
|
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'
|
Write-Host ' OK'
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($Launch) {
|
if ($Launch) {
|
||||||
Write-Host '==> launch with isolated config' -ForegroundColor Cyan
|
Write-Host '==> launch with isolated config' -ForegroundColor Cyan
|
||||||
$config = Join-Path $env:TEMP ('mdp-smoke-' + [guid]::NewGuid().ToString('N'))
|
$config = Join-Path $tmpRoot ('mdp-smoke-' + [guid]::NewGuid().ToString('N'))
|
||||||
New-Item -ItemType Directory -Path $config | Out-Null
|
New-Item -ItemType Directory -Path $config | Out-Null
|
||||||
$fixture = Join-Path $PSScriptRoot 'fixtures\long-headings.md'
|
$fixture = Join-Path $PSScriptRoot 'fixtures\long-headings.md'
|
||||||
$env:MD_PREVIEW_CONFIG_DIR = $config
|
$env:MD_PREVIEW_CONFIG_DIR = $config
|
||||||
|
|||||||
11
agent/tests/ui-smoke.cmd
Normal file
11
agent/tests/ui-smoke.cmd
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal
|
||||||
|
rem Double-clickable wrapper: Windows PowerShell may refuse unsigned .ps1 files
|
||||||
|
rem (AllSigned policy). This runs the script with a process-scoped Bypass.
|
||||||
|
set "SCRIPT=%~dp0ui-smoke.ps1"
|
||||||
|
"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File "%SCRIPT%" %*
|
||||||
|
set "CODE=%ERRORLEVEL%"
|
||||||
|
if not "%CODE%"=="0" echo.&echo UI smoke exited with code %CODE%.
|
||||||
|
rem Keep the window open when launched without arguments (double-click).
|
||||||
|
if "%~1"=="" pause
|
||||||
|
exit /b %CODE%
|
||||||
206
agent/tests/ui-smoke.mjs
Normal file
206
agent/tests/ui-smoke.mjs
Normal file
@@ -0,0 +1,206 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Pre-release UI check for MD Preview.
|
||||||
|
//
|
||||||
|
// The DSH sandbox blocks named pipes, so Chromium/WebView2 cannot start inside
|
||||||
|
// it. Run this from a normal desktop shell via ui-smoke.ps1: it talks to the
|
||||||
|
// already-running app over the DevTools protocol and writes a JSON report plus
|
||||||
|
// a screenshot under --out.
|
||||||
|
//
|
||||||
|
// Usage: node ui-smoke.mjs --port 9333 --out target/ui-test [--expect home|doc]
|
||||||
|
|
||||||
|
import { mkdirSync, writeFileSync } from "node:fs";
|
||||||
|
import { argv, exit } from "node:process";
|
||||||
|
import { pathToFileURL } from "node:url";
|
||||||
|
|
||||||
|
function parseArgs(list) {
|
||||||
|
const args = {};
|
||||||
|
for (let i = 0; i < list.length; i++) {
|
||||||
|
const item = list[i];
|
||||||
|
if (!item.startsWith("--")) continue;
|
||||||
|
const key = item.slice(2);
|
||||||
|
const next = list[i + 1];
|
||||||
|
if (next === undefined || next.startsWith("--")) args[key] = true;
|
||||||
|
else { args[key] = next; i++; }
|
||||||
|
}
|
||||||
|
return args;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); }
|
||||||
|
|
||||||
|
async function findPageTarget(port, timeoutMs) {
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
let lastError = "no targets";
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(2000) });
|
||||||
|
const targets = await response.json();
|
||||||
|
const page = targets.find((t) => t.type === "page" && t.webSocketDebuggerUrl);
|
||||||
|
if (page) return page;
|
||||||
|
lastError = `${targets.length} target(s), none is a page`;
|
||||||
|
} catch (error) {
|
||||||
|
lastError = String(error && error.message ? error.message : error);
|
||||||
|
}
|
||||||
|
await sleep(250);
|
||||||
|
}
|
||||||
|
throw new Error(`no page target on port ${port}: ${lastError}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
class Cdp {
|
||||||
|
constructor(url) {
|
||||||
|
this.url = url;
|
||||||
|
this.nextId = 1;
|
||||||
|
this.pending = new Map();
|
||||||
|
this.socket = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async connect(timeoutMs) {
|
||||||
|
const socket = new WebSocket(this.url);
|
||||||
|
this.socket = socket;
|
||||||
|
socket.addEventListener("message", (event) => {
|
||||||
|
let message;
|
||||||
|
try { message = JSON.parse(String(event.data)); } catch { return; }
|
||||||
|
if (message.id && this.pending.has(message.id)) {
|
||||||
|
const { resolve, reject } = this.pending.get(message.id);
|
||||||
|
this.pending.delete(message.id);
|
||||||
|
if (message.error) reject(new Error(`${message.error.code}: ${message.error.message}`));
|
||||||
|
else resolve(message.result);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
const timer = setTimeout(() => reject(new Error("CDP connect timed out")), timeoutMs);
|
||||||
|
socket.addEventListener("open", () => { clearTimeout(timer); resolve(); });
|
||||||
|
socket.addEventListener("error", () => { clearTimeout(timer); reject(new Error("CDP socket error")); });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
send(method, params = {}, timeoutMs = 10000) {
|
||||||
|
const id = this.nextId++;
|
||||||
|
const payload = JSON.stringify({ id, method, params });
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
this.pending.delete(id);
|
||||||
|
reject(new Error(`CDP timeout: ${method}`));
|
||||||
|
}, timeoutMs);
|
||||||
|
this.pending.set(id, {
|
||||||
|
resolve: (value) => { clearTimeout(timer); resolve(value); },
|
||||||
|
reject: (error) => { clearTimeout(timer); reject(error); },
|
||||||
|
});
|
||||||
|
this.socket.send(payload);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async evaluate(expression, timeoutMs = 10000) {
|
||||||
|
const result = await this.send("Runtime.evaluate", {
|
||||||
|
expression,
|
||||||
|
returnByValue: true,
|
||||||
|
awaitPromise: true,
|
||||||
|
userGesture: true,
|
||||||
|
}, timeoutMs);
|
||||||
|
if (result.exceptionDetails) {
|
||||||
|
throw new Error(`page exception: ${result.exceptionDetails.text || "unknown"}`);
|
||||||
|
}
|
||||||
|
return result.result ? result.result.value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
close() {
|
||||||
|
try { this.socket.close(); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const SNAPSHOT = `(() => {
|
||||||
|
const preview = document.getElementById('preview');
|
||||||
|
const style = getComputedStyle(document.documentElement);
|
||||||
|
return {
|
||||||
|
readyState: document.readyState,
|
||||||
|
bodyClass: document.body.className,
|
||||||
|
previewChildren: preview ? preview.children.length : -1,
|
||||||
|
previewTextLength: preview ? preview.innerText.length : -1,
|
||||||
|
firstHeading: (document.querySelector('#preview h1, #preview h2, #preview h3') || {}).textContent || '',
|
||||||
|
headings: document.querySelectorAll('#preview h1, #preview h2, #preview h3, #preview h4, #preview h5, #preview h6').length,
|
||||||
|
foldToggles: document.querySelectorAll('.mdp-fold-toggle').length,
|
||||||
|
codeBlocks: document.querySelectorAll('#preview pre code').length,
|
||||||
|
highlighted: document.querySelectorAll('#preview pre code.hljs').length,
|
||||||
|
hasIpc: !!(window.ipc && typeof window.ipc.postMessage === 'function'),
|
||||||
|
hasApi: ['__setContent', '__setTabs', '__setPreview', '__setEmptyPreview', '__markSaved']
|
||||||
|
.every((name) => typeof window[name] === 'function'),
|
||||||
|
zoom: style.getPropertyValue('--content-scale').trim(),
|
||||||
|
tabs: document.querySelectorAll('#tabs .tab').length,
|
||||||
|
tabBarVisible: document.body.classList.contains('has-tabs'),
|
||||||
|
findApi: typeof window.__mdPreviewShowFind === 'function',
|
||||||
|
};
|
||||||
|
})()`;
|
||||||
|
|
||||||
|
export async function run(options) {
|
||||||
|
const { port, outDir, expect } = options;
|
||||||
|
const report = {
|
||||||
|
startedAt: new Date().toISOString(),
|
||||||
|
port,
|
||||||
|
expect,
|
||||||
|
checks: [],
|
||||||
|
errors: [],
|
||||||
|
screenshot: null,
|
||||||
|
snapshot: null,
|
||||||
|
};
|
||||||
|
const check = (name, pass, detail) => report.checks.push({ name, pass: !!pass, detail });
|
||||||
|
|
||||||
|
mkdirSync(outDir, { recursive: true });
|
||||||
|
|
||||||
|
let cdp;
|
||||||
|
try {
|
||||||
|
const target = await findPageTarget(port, options.waitMs ?? 15000);
|
||||||
|
report.targetUrl = target.url;
|
||||||
|
cdp = new Cdp(target.webSocketDebuggerUrl);
|
||||||
|
await cdp.connect(5000);
|
||||||
|
await cdp.send("Runtime.enable");
|
||||||
|
await cdp.send("Page.enable");
|
||||||
|
|
||||||
|
// Let hljs / katex / mermaid / folding settle after the first paint.
|
||||||
|
await sleep(900);
|
||||||
|
const snapshot = await cdp.evaluate(SNAPSHOT);
|
||||||
|
report.snapshot = snapshot;
|
||||||
|
|
||||||
|
check("page loaded", snapshot && snapshot.readyState === "complete", snapshot && snapshot.readyState);
|
||||||
|
check("preview has content", snapshot && snapshot.previewChildren > 0, snapshot && `${snapshot.previewChildren} child nodes`);
|
||||||
|
check("webview IPC bridge", snapshot && snapshot.hasIpc, "window.ipc.postMessage");
|
||||||
|
check("page API installed", snapshot && snapshot.hasApi, "setContent/setTabs/setPreview");
|
||||||
|
|
||||||
|
if (expect === "doc") {
|
||||||
|
check("headings rendered", snapshot && snapshot.headings > 0, snapshot && `${snapshot.headings} headings`);
|
||||||
|
check("heading fold toggles", snapshot && snapshot.foldToggles > 0, snapshot && `${snapshot.foldToggles} toggles`);
|
||||||
|
check("code blocks highlighted", snapshot && snapshot.codeBlocks > 0 && snapshot.highlighted > 0, snapshot && `${snapshot.highlighted}/${snapshot.codeBlocks} highlighted`);
|
||||||
|
check("preview text is not empty", snapshot && snapshot.previewTextLength > 20, snapshot && `${snapshot.previewTextLength} chars`);
|
||||||
|
} else {
|
||||||
|
check("home page body", snapshot && snapshot.bodyClass.includes("home"), snapshot && snapshot.bodyClass);
|
||||||
|
}
|
||||||
|
|
||||||
|
const shot = await cdp.send("Page.captureScreenshot", { format: "png" }, 15000);
|
||||||
|
if (shot && shot.data) {
|
||||||
|
const file = `${outDir}/ui-smoke.png`;
|
||||||
|
writeFileSync(file, Buffer.from(shot.data, "base64"));
|
||||||
|
report.screenshot = file;
|
||||||
|
} else {
|
||||||
|
report.errors.push("captureScreenshot returned no data");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
report.errors.push(String(error && error.message ? error.message : error));
|
||||||
|
} finally {
|
||||||
|
if (cdp) cdp.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
const failed = report.checks.filter((item) => !item.pass);
|
||||||
|
const ok = failed.length === 0 && report.errors.length === 0;
|
||||||
|
const reportPath = `${outDir}/ui-smoke.json`;
|
||||||
|
writeFileSync(reportPath, JSON.stringify({ ...report, ok }, null, 2));
|
||||||
|
console.log(JSON.stringify({ ok, failed: failed.length, errors: report.errors, report: reportPath, screenshot: report.screenshot }, null, 2));
|
||||||
|
return { ok, report, reportPath };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (import.meta.url === pathToFileURL(argv[1] ?? "").href) {
|
||||||
|
const args = parseArgs(argv.slice(2));
|
||||||
|
const port = Number(args.port ?? 9333);
|
||||||
|
const outDir = args.out ?? "target/ui-test";
|
||||||
|
const expect = args.expect ?? "doc";
|
||||||
|
run({ port, outDir, expect })
|
||||||
|
.then(({ ok }) => exit(ok ? 0 : 1))
|
||||||
|
.catch((error) => { console.error(error); exit(2); });
|
||||||
|
}
|
||||||
151
agent/tests/ui-smoke.ps1
Normal file
151
agent/tests/ui-smoke.ps1
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
<#
|
||||||
|
MD Preview 发布前 UI 冒烟(需要普通桌面 PowerShell)
|
||||||
|
- 通过 WebView2 的 CDP 端口检查页面是否真的渲染,并截图
|
||||||
|
- 默认使用仓库里的开发构建(Low 完整性,启动时写不了 HKCU,安全)
|
||||||
|
- 不要在 DSH 沙箱里跑:沙箱禁止命名管道,Chromium/WebView2 起不来
|
||||||
|
#>
|
||||||
|
#requires -Version 5.1
|
||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[string]$Exe = '',
|
||||||
|
[string]$Fixture = '',
|
||||||
|
[int]$Port = 9333,
|
||||||
|
[ValidateSet('doc', 'home')]
|
||||||
|
[string]$Expect = 'doc',
|
||||||
|
[string]$OutDir = '',
|
||||||
|
[string]$Node = '',
|
||||||
|
[switch]$KeepOpen
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||||
|
Set-Location $repoRoot
|
||||||
|
|
||||||
|
if (-not $Exe) { $Exe = Join-Path $repoRoot 'target\release\md-preview.exe' }
|
||||||
|
if (-not $Fixture) { $Fixture = Join-Path $repoRoot 'agent\tests\fixtures\code-samples.md' }
|
||||||
|
if (-not $OutDir) { $OutDir = Join-Path $repoRoot 'target\ui-test' }
|
||||||
|
|
||||||
|
if (-not (Test-Path -LiteralPath $Exe)) { throw ('missing exe: ' + $Exe + '(先运行 agent\scripts\build.ps1)') }
|
||||||
|
if (-not (Test-Path -LiteralPath $Fixture)) { throw ('missing fixture: ' + $Fixture) }
|
||||||
|
function Resolve-Node {
|
||||||
|
$command = Get-Command node -ErrorAction SilentlyContinue
|
||||||
|
if ($command) {
|
||||||
|
if ($command.Path) { return $command.Path }
|
||||||
|
if ($command.Source) { return $command.Source }
|
||||||
|
}
|
||||||
|
$candidates = @()
|
||||||
|
if ($env:ProgramFiles) { $candidates += (Join-Path $env:ProgramFiles 'nodejs\node.exe') }
|
||||||
|
if (${env:ProgramFiles(x86)}) { $candidates += (Join-Path ${env:ProgramFiles(x86)} 'nodejs\node.exe') }
|
||||||
|
if ($env:LOCALAPPDATA) { $candidates += (Join-Path $env:LOCALAPPDATA 'Programs\nodejs\node.exe') }
|
||||||
|
foreach ($candidate in $candidates) {
|
||||||
|
if ($candidate -and (Test-Path -LiteralPath $candidate)) { return $candidate }
|
||||||
|
}
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($Node) { $node = $Node } else { $node = Resolve-Node }
|
||||||
|
if (-not $node) {
|
||||||
|
throw 'Node.js 未找到(需要 Node 21+)。用 -Node 指定路径,或安装 Node 后重试。'
|
||||||
|
}
|
||||||
|
if (-not (Test-Path -LiteralPath $node)) { throw ('Node 路径无效:' + $node) }
|
||||||
|
& $node -e "process.exit(('WebSocket' in globalThis) ? 0 : 1)" 2>$null
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw ('Node 版本太旧:需要 Node 21+ 的内置 WebSocket(当前 ' + (& $node --version) + ')') }
|
||||||
|
|
||||||
|
New-Item -ItemType Directory -Force $OutDir | Out-Null
|
||||||
|
$configDir = Join-Path $OutDir 'config'
|
||||||
|
$logOut = Join-Path $OutDir 'app.stdout.log'
|
||||||
|
$logErr = Join-Path $OutDir 'app.stderr.log'
|
||||||
|
$reportPath = Join-Path $OutDir 'ui-smoke.json'
|
||||||
|
Remove-Item -Recurse -Force $configDir -ErrorAction SilentlyContinue
|
||||||
|
Remove-Item -Force $logOut, $logErr, $reportPath, (Join-Path $OutDir 'ui-smoke.png') -ErrorAction SilentlyContinue
|
||||||
|
|
||||||
|
# 单实例:如果目标 exe 已经在跑,新的启动会被转发出去,CDP 端口就不会出现。
|
||||||
|
$exePath = (Resolve-Path -LiteralPath $Exe).Path
|
||||||
|
$running = @()
|
||||||
|
foreach ($process in (Get-Process -ErrorAction SilentlyContinue)) {
|
||||||
|
$path = $null
|
||||||
|
try { $path = $process.Path } catch { }
|
||||||
|
if ($path -and ($path -ieq $exePath)) { $running += [string]$process.Id }
|
||||||
|
}
|
||||||
|
if ($running.Count -gt 0) {
|
||||||
|
throw ('目标 exe 已在运行(PID ' + ($running -join ', ') + '),请先关闭它;否则启动会被单实例转发。')
|
||||||
|
}
|
||||||
|
|
||||||
|
# CDP 就绪探测:TCP 端口可能只开一瞬间(WebView2 起来后立刻退出),
|
||||||
|
# 所以以 /json/list 真正能返回为准。
|
||||||
|
function Test-Cdp([int]$port) {
|
||||||
|
try {
|
||||||
|
$response = Invoke-WebRequest -UseBasicParsing -Uri ('http://127.0.0.1:' + $port + '/json/list') -TimeoutSec 2
|
||||||
|
return ($response.StatusCode -eq 200)
|
||||||
|
} catch {
|
||||||
|
return $false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$previousConfig = $env:MD_PREVIEW_CONFIG_DIR
|
||||||
|
$previousArgs = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
|
||||||
|
$proc = $null
|
||||||
|
$exitCode = 1
|
||||||
|
try {
|
||||||
|
$env:MD_PREVIEW_CONFIG_DIR = $configDir
|
||||||
|
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = '--remote-debugging-port=' + $Port
|
||||||
|
|
||||||
|
Write-Host ('==> launching ' + $exePath) -ForegroundColor Cyan
|
||||||
|
$proc = Start-Process -FilePath $exePath -ArgumentList @('"' + $Fixture + '"') -PassThru -RedirectStandardOutput $logOut -RedirectStandardError $logErr
|
||||||
|
|
||||||
|
$deadline = (Get-Date).AddSeconds(25)
|
||||||
|
$up = $false
|
||||||
|
while ((Get-Date) -lt $deadline) {
|
||||||
|
if ($proc.HasExited) { break }
|
||||||
|
if (Test-Cdp $Port) { $up = $true; break }
|
||||||
|
Start-Sleep -Milliseconds 300
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not $up) {
|
||||||
|
Write-Host 'ERROR: CDP 端口没有起来。' -ForegroundColor Red
|
||||||
|
Write-Host ' - 不要在 DSH 沙箱里运行本脚本:沙箱禁止命名管道,Chromium/WebView2 无法启动。'
|
||||||
|
Write-Host ' - 确认没有其它 MD Preview 实例占用同一个配置目录。'
|
||||||
|
if (Test-Path -LiteralPath $logErr) {
|
||||||
|
$err = Get-Content -LiteralPath $logErr -ErrorAction SilentlyContinue | Select-Object -Last 10
|
||||||
|
if ($err) { Write-Host ' app.stderr:'; $err | ForEach-Object { Write-Host (' ' + $_) } }
|
||||||
|
}
|
||||||
|
if ($proc.HasExited) { Write-Host (' app 已退出,exit code ' + $proc.ExitCode) }
|
||||||
|
throw 'CDP port did not open'
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ('==> node agent\tests\ui-smoke.mjs --port ' + $Port + ' --expect ' + $Expect) -ForegroundColor Cyan
|
||||||
|
& $node (Join-Path $repoRoot 'agent\tests\ui-smoke.mjs') --port $Port --out $OutDir --expect $Expect
|
||||||
|
$exitCode = $LASTEXITCODE
|
||||||
|
|
||||||
|
if (Test-Path -LiteralPath $reportPath) {
|
||||||
|
$report = Get-Content -LiteralPath $reportPath -Raw | ConvertFrom-Json
|
||||||
|
$failed = @($report.checks | Where-Object { -not $_.pass })
|
||||||
|
if ($report.ok) {
|
||||||
|
Write-Host ('OK: ' + @($report.checks).Count + ' checks') -ForegroundColor Green
|
||||||
|
} else {
|
||||||
|
if ($failed.Count -gt 0) {
|
||||||
|
Write-Host 'FAILED checks:' -ForegroundColor Red
|
||||||
|
$failed | ForEach-Object { Write-Host (' - ' + $_.name + ': ' + $_.detail) -ForegroundColor Red }
|
||||||
|
}
|
||||||
|
if ($report.errors) {
|
||||||
|
Write-Host 'errors:' -ForegroundColor Red
|
||||||
|
$report.errors | ForEach-Object { Write-Host (' - ' + $_) -ForegroundColor Red }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($report.screenshot) { Write-Host ('screenshot: ' + $report.screenshot) }
|
||||||
|
Write-Host ('report : ' + $reportPath)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if ($proc -and -not $KeepOpen) {
|
||||||
|
try {
|
||||||
|
if (-not $proc.HasExited) {
|
||||||
|
$proc.CloseMainWindow() | Out-Null
|
||||||
|
if (-not $proc.WaitForExit(5000)) { $proc.Kill() }
|
||||||
|
}
|
||||||
|
} catch { }
|
||||||
|
}
|
||||||
|
if ($null -eq $previousConfig) { Remove-Item Env:\MD_PREVIEW_CONFIG_DIR -ErrorAction SilentlyContinue } else { $env:MD_PREVIEW_CONFIG_DIR = $previousConfig }
|
||||||
|
if ($null -eq $previousArgs) { Remove-Item Env:\WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS -ErrorAction SilentlyContinue } else { $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $previousArgs }
|
||||||
|
}
|
||||||
|
|
||||||
|
exit $exitCode
|
||||||
376
assets/page/page.css
Normal file
376
assets/page/page.css
Normal file
@@ -0,0 +1,376 @@
|
|||||||
|
:root { color-scheme: light dark; --chrome-top: 10px; --content-scale: 1; }
|
||||||
|
/* Reserve scrollbar space permanently so the fixed toolbar doesn't shift
|
||||||
|
between modes (one with scrollbar, one without). */
|
||||||
|
html { overflow-y: scroll; scrollbar-gutter: stable; }
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
|
||||||
|
margin: 0; padding: 0;
|
||||||
|
line-height: 1.6; font-size: 15px;
|
||||||
|
color: #1a1a1a; background: #fff;
|
||||||
|
}
|
||||||
|
body.has-tabs { --chrome-top: 50px; }
|
||||||
|
#app { width: 100%; box-sizing: border-box; margin: 0 auto; padding: 24px 48px; }
|
||||||
|
#preview { font-size: calc(15px * var(--content-scale)); }
|
||||||
|
#preview .front-matter {
|
||||||
|
margin: 0 0 1.5em;
|
||||||
|
padding: .85em 0;
|
||||||
|
border-top: 1px solid #e1e4e8;
|
||||||
|
border-bottom: 1px solid #e1e4e8;
|
||||||
|
color: #59636e;
|
||||||
|
}
|
||||||
|
#preview .front-matter pre {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
border-radius: 0;
|
||||||
|
overflow: visible;
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
font: inherit;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
#preview h1,#preview h2,#preview h3,#preview h4 { margin-top: 1.4em; }
|
||||||
|
#preview h1 { border-bottom: 1px solid #e1e4e8; padding-bottom: .3em; }
|
||||||
|
#preview h2 { border-bottom: 1px solid #e1e4e8; padding-bottom: .2em; }
|
||||||
|
/* Heading folding: triangle shows on heading hover; the body collapses down to
|
||||||
|
the next heading of the same or higher level. State is per-render only. */
|
||||||
|
#preview .mdp-fold > h1,
|
||||||
|
#preview .mdp-fold > h2,
|
||||||
|
#preview .mdp-fold > h3,
|
||||||
|
#preview .mdp-fold > h4,
|
||||||
|
#preview .mdp-fold > h5,
|
||||||
|
#preview .mdp-fold > h6 { position: relative; }
|
||||||
|
/* Fixed 90%-of-H2 size for every heading level. */
|
||||||
|
#preview .mdp-fold-toggle {
|
||||||
|
position: absolute; left: -34px; top: 50%;
|
||||||
|
width: 30px; height: 30px; padding: 0; border: 0; border-radius: 50%;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
display: grid; place-items: center;
|
||||||
|
background: transparent; color: #999; cursor: pointer;
|
||||||
|
opacity: 0; transition: opacity .12s ease, background .12s ease;
|
||||||
|
}
|
||||||
|
#preview .mdp-fold-toggle svg { grid-area: 1 / 1; overflow: visible; }
|
||||||
|
#preview .mdp-fold-toggle .mdp-fold-i-right { display: none; width: 13.5px; height: 20px; }
|
||||||
|
#preview .mdp-fold-toggle .mdp-fold-i-down { display: block; width: 20px; height: 13.5px; }
|
||||||
|
#preview h1:hover > .mdp-fold-toggle,
|
||||||
|
#preview h2:hover > .mdp-fold-toggle,
|
||||||
|
#preview h3:hover > .mdp-fold-toggle,
|
||||||
|
#preview h4:hover > .mdp-fold-toggle,
|
||||||
|
#preview h5:hover > .mdp-fold-toggle,
|
||||||
|
#preview h6:hover > .mdp-fold-toggle,
|
||||||
|
#preview .mdp-fold-toggle:focus-visible { opacity: .6; }
|
||||||
|
#preview .mdp-fold-toggle:hover { opacity: 1; background: rgba(0,0,0,.07); }
|
||||||
|
#preview .mdp-fold.collapsed > :is(h1, h2, h3, h4, h5, h6) > .mdp-fold-toggle .mdp-fold-i-right { display: block; }
|
||||||
|
#preview .mdp-fold.collapsed > :is(h1, h2, h3, h4, h5, h6) > .mdp-fold-toggle .mdp-fold-i-down { display: none; }
|
||||||
|
#preview .mdp-fold.collapsed > .mdp-fold-body { display: none; }
|
||||||
|
#preview code { background: #f0f0f0; padding: 2px 6px; border-radius: 4px; font-size: 90%; }
|
||||||
|
/* Code blocks stay dark (VS Dark) even in the light app theme. */
|
||||||
|
#preview pre { background: #1e1e1e; color: #d4d4d4; padding: 16px; border-radius: 8px; overflow-x: auto; }
|
||||||
|
#preview pre code { background: none; padding: 0; font-size: 14px; }
|
||||||
|
#preview blockquote { border-left: 4px solid #ddd; margin: 0; padding: 0 1em; color: #666; }
|
||||||
|
#preview .markdown-alert-note,
|
||||||
|
#preview .markdown-alert-tip,
|
||||||
|
#preview .markdown-alert-important,
|
||||||
|
#preview .markdown-alert-warning,
|
||||||
|
#preview .markdown-alert-caution {
|
||||||
|
margin: 1em 0;
|
||||||
|
padding: 0.75em 1em;
|
||||||
|
border-radius: 6px;
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
#preview .markdown-alert-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: .35em;
|
||||||
|
margin: 0 0 .45em;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
#preview .markdown-alert-title + p { margin-top: 0; }
|
||||||
|
#preview .markdown-alert-note { border-color: #0969da; background: #ddf4ff; }
|
||||||
|
#preview .markdown-alert-tip { border-color: #1a7f37; background: #dafbe1; }
|
||||||
|
#preview .markdown-alert-important { border-color: #8250df; background: #fbefff; }
|
||||||
|
#preview .markdown-alert-warning { border-color: #9a6700; background: #fff8c5; }
|
||||||
|
#preview .markdown-alert-caution { border-color: #cf222e; background: #ffebe9; }
|
||||||
|
#preview .markdown-alert-note .markdown-alert-title { color: #0969da; }
|
||||||
|
#preview .markdown-alert-tip .markdown-alert-title { color: #1a7f37; }
|
||||||
|
#preview .markdown-alert-important .markdown-alert-title { color: #8250df; }
|
||||||
|
#preview .markdown-alert-warning .markdown-alert-title { color: #9a6700; }
|
||||||
|
#preview .markdown-alert-caution .markdown-alert-title { color: #cf222e; }
|
||||||
|
#preview .mdp-mark { border-radius: 3px; padding: 0 0.12em; background: #fff2a8; color: inherit; }
|
||||||
|
#preview mark.search-hit { border-radius: 3px; padding: 0 0.12em; background: #fff2a8; color: inherit; }
|
||||||
|
#preview mark.search-hit.current { background: #ffcc4d; color: #1a1a1a; }
|
||||||
|
#preview table { border-collapse: collapse; width: 100%; }
|
||||||
|
#preview .mdp-table-wrap {
|
||||||
|
width: min(calc(100vw - 64px), 1280px);
|
||||||
|
margin: 1em 0 1em 50%;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
overflow-x: auto;
|
||||||
|
-webkit-overflow-scrolling: touch;
|
||||||
|
}
|
||||||
|
#preview .mdp-table-wrap table { width: max-content; min-width: 100%; }
|
||||||
|
#preview table th, #preview table td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
|
||||||
|
#preview table th { background: #f6f8fa; font-weight: 600; color: #1a1a1a; white-space: nowrap; }
|
||||||
|
#preview table td { min-width: 64px; max-width: 360px; vertical-align: top; overflow-wrap: break-word; }
|
||||||
|
#preview img { max-width: 100%; }
|
||||||
|
#preview .katex-display { overflow-x: auto; overflow-y: hidden; padding: 0.15em 0; }
|
||||||
|
#preview .mdp-mermaid { margin: 1.2em 0; overflow-x: auto; text-align: center; }
|
||||||
|
/* Compensate zoom's percentage width so window-fitted diagrams can grow and scroll. */
|
||||||
|
#preview .mdp-mermaid svg { max-width: 100%; height: auto; display: block; margin: 0 auto; width: calc(100% * var(--content-scale)); zoom: var(--content-scale); }
|
||||||
|
#preview .mdp-mermaid-error, #preview .mdp-math-error { color: #b42318; }
|
||||||
|
#preview hr { border: none; border-top: 1px solid #e1e4e8; margin: 2em 0; }
|
||||||
|
#preview a { color: #0969da; text-decoration: none; }
|
||||||
|
#preview a:hover { text-decoration: underline; }
|
||||||
|
#preview ul, #preview ol { padding-left: 2em; }
|
||||||
|
#preview input[type="checkbox"] { margin-right: 6px; }
|
||||||
|
#preview dl { margin: 1em 0; }
|
||||||
|
#preview dt { font-weight: 600; }
|
||||||
|
#preview dd { margin: 0 0 .6em 1.5em; }
|
||||||
|
#preview .footnote-reference { font-size: .75em; }
|
||||||
|
#preview .footnote-definition {
|
||||||
|
margin-top: 1.5em;
|
||||||
|
padding-top: .75em;
|
||||||
|
border-top: 1px solid #e1e4e8;
|
||||||
|
color: #59636e;
|
||||||
|
font-size: .9em;
|
||||||
|
}
|
||||||
|
#preview .footnote-definition-label { margin-right: .35em; font-weight: 600; }
|
||||||
|
.empty { display: flex; flex-direction: column; align-items: center; justify-content: center;
|
||||||
|
min-height: 60vh; color: #999; font-size: 18px; gap: 12px; text-align: center; }
|
||||||
|
.empty.has-recent {
|
||||||
|
justify-content: flex-start;
|
||||||
|
min-height: calc(100vh - var(--chrome-top) - 38px);
|
||||||
|
padding: clamp(56px, 10vh, 96px) 0 40px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
.empty .icon { font-size: 48px; opacity: 0.4; }
|
||||||
|
.empty-actions { display: flex; gap: 8px; margin-top: 6px; }
|
||||||
|
.empty-open {
|
||||||
|
min-height: 40px; padding: 0 16px;
|
||||||
|
border: 1px solid #ddd; border-radius: 8px; background: #fff;
|
||||||
|
color: #1a1a1a; font: inherit; font-size: 15px; cursor: pointer;
|
||||||
|
}
|
||||||
|
.empty-open:hover { background: #f5f5f5; color: #000; }
|
||||||
|
.recent { width: min(480px, 100%); margin-top: 16px; text-align: left; }
|
||||||
|
.recent-title { margin: 0 0 8px; padding: 0; border: 0; font-size: 11px; font-weight: 600; letter-spacing: 0; color: #b6b6b6; text-transform: uppercase; }
|
||||||
|
.recent-list { display: grid; gap: 6px; }
|
||||||
|
.recent-item {
|
||||||
|
width: 100%; min-height: 44px; padding: 7px 10px; border: 1px solid #eee;
|
||||||
|
border-radius: 8px; background: #fff; color: inherit; text-align: left; cursor: pointer;
|
||||||
|
display: grid; gap: 1px;
|
||||||
|
}
|
||||||
|
.recent-item:hover { background: #f7f7f7; }
|
||||||
|
.recent-name { color: #555; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.recent-path { color: #aaa; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.tabbar {
|
||||||
|
display: none; position: sticky; top: 0; z-index: 110; height: 40px;
|
||||||
|
box-sizing: border-box; align-items: stretch; gap: 4px; padding: 4px 8px;
|
||||||
|
border-bottom: 1px solid #e6e6e6; background: rgba(248,248,248,0.96);
|
||||||
|
backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
|
||||||
|
}
|
||||||
|
body.has-tabs .tabbar { display: flex; }
|
||||||
|
.tabs { display: flex; flex: 1; min-width: 0; gap: 4px; overflow-x: auto; scrollbar-width: none; }
|
||||||
|
.tabs::-webkit-scrollbar { display: none; }
|
||||||
|
.tab {
|
||||||
|
flex: 0 1 180px; min-width: 96px; max-width: 200px; height: 31px;
|
||||||
|
display: flex; align-items: center; gap: 7px; padding: 0 8px 0 10px;
|
||||||
|
box-sizing: border-box; border: 1px solid transparent; border-radius: 7px;
|
||||||
|
color: #6b6b6b; background: transparent; cursor: default; user-select: none;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.tab:hover { background: rgba(0,0,0,0.045); }
|
||||||
|
.tab.dragging { opacity: .55; cursor: grabbing; }
|
||||||
|
.tab.active { color: #202020; background: #fff; border-color: #ddd; box-shadow: 0 1px 2px rgba(0,0,0,.04); }
|
||||||
|
.tab.missing { color: #a15c00; }
|
||||||
|
.tab-status { width: 7px; height: 7px; flex: 0 0 auto; border-radius: 50%; background: transparent; }
|
||||||
|
.tab.dirty .tab-status { background: #2979c9; }
|
||||||
|
.tab.missing .tab-status { width: auto; height: auto; background: none; border-radius: 0; font-weight: 700; }
|
||||||
|
.tab-name { min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.tab-close {
|
||||||
|
width: 20px; height: 20px; flex: 0 0 auto; padding: 0; border: 0; border-radius: 5px;
|
||||||
|
display: grid; place-items: center; color: inherit; background: transparent; cursor: pointer;
|
||||||
|
font: 16px/1 -apple-system, BlinkMacSystemFont, sans-serif; opacity: .58;
|
||||||
|
}
|
||||||
|
.tab-close:hover { opacity: 1; background: rgba(0,0,0,.08); }
|
||||||
|
.tab-close[hidden] { display: none; }
|
||||||
|
.tab-menu {
|
||||||
|
position: fixed; z-index: 200; min-width: 188px; padding: 4px;
|
||||||
|
background: #fff; border: 1px solid #ddd; border-radius: 8px;
|
||||||
|
box-shadow: 0 8px 24px rgba(0,0,0,.16);
|
||||||
|
}
|
||||||
|
.tab-menu[hidden] { display: none; }
|
||||||
|
.tab-menu-path {
|
||||||
|
max-width: 280px; padding: 3px 8px 5px; overflow: hidden;
|
||||||
|
color: #8a8a8a; font-size: 11px; line-height: 1.3;
|
||||||
|
white-space: nowrap; text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
.tab-menu button {
|
||||||
|
display: block; width: 100%; padding: 5px 8px; border: 0; border-radius: 5px;
|
||||||
|
background: transparent; color: #222; text-align: left; font: inherit;
|
||||||
|
font-size: 13px; cursor: pointer;
|
||||||
|
}
|
||||||
|
.tab-menu button:hover { background: #f2f2f2; }
|
||||||
|
.tab-menu button:disabled { opacity: .42; cursor: default; }
|
||||||
|
.tab-menu button:disabled:hover { background: transparent; }
|
||||||
|
.tab-open {
|
||||||
|
width: 31px; height: 31px; flex: 0 0 auto; padding: 0; border: 0; border-radius: 7px;
|
||||||
|
color: #666; background: transparent; cursor: pointer; font: 20px/1 -apple-system, sans-serif;
|
||||||
|
}
|
||||||
|
.tab-open:hover { color: #111; background: rgba(0,0,0,.06); }
|
||||||
|
.doc-stats {
|
||||||
|
flex: 0 0 auto; align-self: center; padding: 0 6px;
|
||||||
|
color: #8b8b8b; font-size: 11px; white-space: nowrap; user-select: none;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
.missing-file { min-height: 55vh; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; text-align: center; }
|
||||||
|
.missing-file h2, .missing-file p { margin: 0; }
|
||||||
|
.missing-file p { color: #777; }
|
||||||
|
.missing-file code { max-width: min(620px, 90vw); overflow-wrap: anywhere; color: #8a5a12; }
|
||||||
|
.missing-mark { width: 38px; height: 38px; border: 2px solid #c98322; border-radius: 50%; display: grid; place-items: center; color: #a15c00; font-weight: 700; font-size: 22px; }
|
||||||
|
.missing-actions { display: flex; gap: 8px; margin-top: 8px; }
|
||||||
|
.missing-actions button { min-height: 36px; padding: 0 13px; border: 1px solid #d8d8d8; border-radius: 7px; background: #fff; color: #333; cursor: pointer; font: inherit; }
|
||||||
|
.missing-actions button:hover { background: #f4f4f4; }
|
||||||
|
|
||||||
|
/* Floating toolbar (top-right) — hover-reveal, hidden in empty state */
|
||||||
|
.toolbar {
|
||||||
|
position: fixed; top: var(--chrome-top); right: 12px;
|
||||||
|
display: flex; gap: 6px; z-index: 100;
|
||||||
|
opacity: 0; pointer-events: none;
|
||||||
|
transition: opacity 0.18s ease;
|
||||||
|
}
|
||||||
|
html:hover .toolbar { opacity: 1; pointer-events: auto; }
|
||||||
|
body.home .toolbar { display: none !important; }
|
||||||
|
.toolbar button {
|
||||||
|
width: 34px; height: 34px; padding: 0;
|
||||||
|
background: rgba(255,255,255,0.8);
|
||||||
|
backdrop-filter: blur(6px);
|
||||||
|
-webkit-backdrop-filter: blur(6px);
|
||||||
|
border: 1px solid rgba(0,0,0,0.08);
|
||||||
|
border-radius: 8px;
|
||||||
|
display: grid; place-items: center;
|
||||||
|
cursor: pointer; color: #555;
|
||||||
|
transition: color 0.15s, background 0.15s;
|
||||||
|
}
|
||||||
|
.toolbar button:hover { color: #000; background: rgba(255,255,255,1); }
|
||||||
|
.toolbar button[hidden] { display: none !important; }
|
||||||
|
.zoom-control { position: relative; }
|
||||||
|
.zoom-popover {
|
||||||
|
position: absolute; top: 40px; right: 0;
|
||||||
|
display: none; align-items: center; gap: 2px; padding: 4px;
|
||||||
|
border: 1px solid rgba(0,0,0,.1); border-radius: 8px;
|
||||||
|
background: rgba(255,255,255,.96); box-shadow: 0 6px 20px rgba(0,0,0,.12);
|
||||||
|
backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
|
||||||
|
}
|
||||||
|
.zoom-control.open .zoom-popover { display: flex; }
|
||||||
|
.toolbar .zoom-popover button { width: 30px; height: 30px; border: 0; background: transparent; }
|
||||||
|
.toolbar .zoom-popover button:hover { background: rgba(0,0,0,.06); }
|
||||||
|
.toolbar .zoom-popover .zoom-reset {
|
||||||
|
width: 52px; font-size: 11px; font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
.findbar {
|
||||||
|
position: fixed; top: var(--chrome-top); left: 50%; transform: translateX(-50%);
|
||||||
|
display: none; align-items: center; gap: 6px; z-index: 101;
|
||||||
|
padding: 6px; border: 1px solid rgba(0,0,0,0.08); border-radius: 10px;
|
||||||
|
background: rgba(255,255,255,0.96); box-shadow: 0 8px 24px rgba(0,0,0,0.12);
|
||||||
|
backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
|
||||||
|
}
|
||||||
|
body.finding .findbar { display: flex; }
|
||||||
|
.findbar input {
|
||||||
|
width: min(42vw, 320px); height: 30px; box-sizing: border-box; border: 0;
|
||||||
|
outline: none; background: transparent; color: inherit; font: inherit;
|
||||||
|
}
|
||||||
|
.findbar span { min-width: 14px; color: #8c959f; text-align: center; }
|
||||||
|
.findbar button {
|
||||||
|
width: 30px; height: 30px; padding: 0; border: 0; border-radius: 7px;
|
||||||
|
display: grid; place-items: center; color: #555; background: transparent; cursor: pointer;
|
||||||
|
}
|
||||||
|
.findbar button:hover { background: #f0f0f0; color: #111; }
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
body { color: #d4d4d4; background: #1e1e1e; }
|
||||||
|
#preview a { color: #6cb6ff; }
|
||||||
|
#preview h1, #preview h2 { border-color: #333; }
|
||||||
|
#preview .mdp-fold-toggle { color: #aaa; }
|
||||||
|
#preview .mdp-fold-toggle:hover { background: rgba(255,255,255,.1); }
|
||||||
|
#preview .front-matter { border-color: #333; color: #a9b1ba; }
|
||||||
|
#preview .front-matter pre { background: transparent !important; }
|
||||||
|
#preview code:not(pre code) { background: #2d2d2d; }
|
||||||
|
#preview blockquote { border-color: #444; color: #aaa; }
|
||||||
|
#preview .footnote-definition { border-color: #444; color: #aaa; }
|
||||||
|
#preview .markdown-alert-note,
|
||||||
|
#preview .markdown-alert-tip,
|
||||||
|
#preview .markdown-alert-important,
|
||||||
|
#preview .markdown-alert-warning,
|
||||||
|
#preview .markdown-alert-caution { background: #161b22; color: #d4d4d4; }
|
||||||
|
#preview .markdown-alert-note { border-color: #2f81f7; }
|
||||||
|
#preview .markdown-alert-tip { border-color: #3fb950; }
|
||||||
|
#preview .markdown-alert-important { border-color: #a371f7; }
|
||||||
|
#preview .markdown-alert-warning { border-color: #d29922; }
|
||||||
|
#preview .markdown-alert-caution { border-color: #f85149; }
|
||||||
|
#preview .markdown-alert-note .markdown-alert-title { color: #2f81f7; }
|
||||||
|
#preview .markdown-alert-tip .markdown-alert-title { color: #3fb950; }
|
||||||
|
#preview .markdown-alert-important .markdown-alert-title { color: #a371f7; }
|
||||||
|
#preview .markdown-alert-warning .markdown-alert-title { color: #d29922; }
|
||||||
|
#preview .markdown-alert-caution .markdown-alert-title { color: #f85149; }
|
||||||
|
#preview table th { background: #2d2d2d; color: #f0f0f0; }
|
||||||
|
#preview table td, #preview table th { border-color: #444; }
|
||||||
|
#preview hr { border-color: #333; }
|
||||||
|
.toolbar button {
|
||||||
|
background: rgba(40,40,40,0.8);
|
||||||
|
border-color: rgba(255,255,255,0.1);
|
||||||
|
color: #bbb;
|
||||||
|
}
|
||||||
|
.toolbar button:hover { color: #fff; background: rgba(55,55,55,1); }
|
||||||
|
.zoom-popover { background: rgba(34,34,34,.96); border-color: rgba(255,255,255,.12); }
|
||||||
|
.toolbar .zoom-popover button:hover { background: rgba(255,255,255,.1); }
|
||||||
|
.empty-open { background: #242424; border-color: #444; color: #ddd; }
|
||||||
|
.empty-open:hover { background: #2d2d2d; color: #fff; }
|
||||||
|
.recent-name { color: #ddd; }
|
||||||
|
.recent-item { background: #242424; border-color: #333; }
|
||||||
|
.recent-item:hover { background: #2d2d2d; }
|
||||||
|
.findbar { background: rgba(34,34,34,0.96); border-color: rgba(255,255,255,0.1); }
|
||||||
|
.findbar button:hover { background: #333; color: #fff; }
|
||||||
|
.tabbar { background: rgba(28,28,28,.96); border-color: #363636; }
|
||||||
|
.tab { color: #aaa; }
|
||||||
|
.tab:hover { background: rgba(255,255,255,.07); }
|
||||||
|
.tab.active { color: #eee; background: #2c2c2c; border-color: #444; }
|
||||||
|
.tab.missing { color: #e3a04b; }
|
||||||
|
.tab-close:hover, .tab-open:hover { background: rgba(255,255,255,.1); color: #fff; }
|
||||||
|
.tab-menu { background: #2a2a2a; border-color: #444; box-shadow: 0 8px 24px rgba(0,0,0,.45); }
|
||||||
|
.tab-menu-path { color: #999; }
|
||||||
|
.tab-menu button { color: #ddd; }
|
||||||
|
.tab-menu button:hover { background: rgba(255,255,255,.08); }
|
||||||
|
.tab-menu button:disabled:hover { background: transparent; }
|
||||||
|
.missing-file p { color: #aaa; }
|
||||||
|
.missing-actions button { background: #292929; border-color: #444; color: #ddd; }
|
||||||
|
.missing-actions button:hover { background: #333; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Source editor textarea — height is auto-grown by JS to match content,
|
||||||
|
so the page (html) owns the only vertical scrollbar. */
|
||||||
|
#editor {
|
||||||
|
display: none;
|
||||||
|
width: 100%;
|
||||||
|
box-sizing: border-box;
|
||||||
|
border: none; outline: none; resize: none;
|
||||||
|
overflow: hidden;
|
||||||
|
font: calc(14px * var(--content-scale))/1.6 "SF Mono","Menlo","Consolas",monospace;
|
||||||
|
background: transparent; color: inherit;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
body.editing #preview { display: none; }
|
||||||
|
body.editing #editor { display: block; padding: 16px 48px; }
|
||||||
|
body.editing #app { max-width: none; padding: 0; }
|
||||||
|
|
||||||
|
@page {
|
||||||
|
margin: 12mm;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
.toolbar, .tabbar, #editor { display: none !important; }
|
||||||
|
#preview { display: block !important; }
|
||||||
|
#app { max-width: none; padding: 0; }
|
||||||
|
#preview .mdp-table-wrap { width: auto; margin: 1em 0; transform: none; overflow: visible; }
|
||||||
|
#preview pre { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
||||||
|
#preview .mdp-fold-body { display: block !important; }
|
||||||
|
#preview .mdp-fold-toggle { display: none !important; }
|
||||||
|
}
|
||||||
37
assets/page/page.html
Normal file
37
assets/page/page.html
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
<!DOCTYPE html><html><head><meta charset="utf-8">
|
||||||
|
__MDP_BASE_TAG__
|
||||||
|
<style id="hljs-code">__MDP_CSS_CODE__</style>
|
||||||
|
<style>
|
||||||
|
__MDP_PAGE_CSS__
|
||||||
|
</style></head><body class="__MDP_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="__MDP_NEW_TAB__" aria-label="__MDP_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">__MDP_BTN_OPEN_LOCATION__</button><button type="button" id="tab-menu-new-window">__MDP_BTN_NEW_WINDOW__</button></div>
|
||||||
|
<div class="toolbar">
|
||||||
|
<button id="btn-toggle" title="__MDP_BTN_EDIT__" aria-label="__MDP_BTN_EDIT__"></button>
|
||||||
|
<div class="zoom-control" id="zoom-control">
|
||||||
|
<button id="btn-zoom" title="__MDP_BTN_ZOOM__" aria-label="__MDP_BTN_ZOOM__"></button>
|
||||||
|
<div class="zoom-popover">
|
||||||
|
<button id="btn-zoom-out" title="__MDP_BTN_ZOOM_OUT__" aria-label="__MDP_BTN_ZOOM_OUT__">−</button>
|
||||||
|
<button id="btn-zoom-reset" class="zoom-reset" title="__MDP_BTN_ZOOM_RESET__" aria-label="__MDP_BTN_ZOOM_RESET__">100%</button>
|
||||||
|
<button id="btn-zoom-in" title="__MDP_BTN_ZOOM_IN__" aria-label="__MDP_BTN_ZOOM_IN__">+</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="findbar" role="search">
|
||||||
|
<input id="find-input" type="search" placeholder="__MDP_SEARCH_PLACEHOLDER__" aria-label="__MDP_SEARCH_PLACEHOLDER__">
|
||||||
|
<span id="find-state"></span>
|
||||||
|
<button id="find-prev" title="Previous" aria-label="Previous"></button>
|
||||||
|
<button id="find-next" title="Next" aria-label="Next"></button>
|
||||||
|
<button id="find-close" title="Close" aria-label="Close"></button>
|
||||||
|
</div>
|
||||||
|
<div id="app">
|
||||||
|
<div id="preview">__MDP_PREVIEW_HTML__</div>
|
||||||
|
<textarea id="editor" spellcheck="false">__MDP_RAW_MD_ESCAPED__</textarea>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
__MDP_PAGE_JS__
|
||||||
|
window.__mdPreviewFeatureFlags = { math: __MDP_NEEDS_MATH__, mermaid: __MDP_NEEDS_MERMAID__ };
|
||||||
|
__MDP_PREVIEW_ENHANCE_JS__
|
||||||
|
if(window.__enhancePreview)window.__enhancePreview();
|
||||||
|
</script>
|
||||||
|
</body></html>
|
||||||
970
assets/page/page.js
Normal file
970
assets/page/page.js
Normal file
@@ -0,0 +1,970 @@
|
|||||||
|
(function(){
|
||||||
|
var ICON_EDIT = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>';
|
||||||
|
var ICON_VIEW = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>';
|
||||||
|
var ICON_ZOOM = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/><path d="M8 11h6"/><path d="M11 8v6"/></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_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 = '__MDP_BTN_EDIT__', L_VIEW = '__MDP_BTN_PREVIEW__', L_HOME = '__MDP_HOME_TAB__';
|
||||||
|
window.__mdPreviewFoldLabel = '__MDP_FOLD_TOGGLE__';
|
||||||
|
window.__mdPreviewCannotSave = '__MDP_CANNOT_SAVE_JS__';
|
||||||
|
|
||||||
|
var btnToggle = document.getElementById('btn-toggle');
|
||||||
|
var btnZoom = document.getElementById('btn-zoom');
|
||||||
|
var btnZoomOut = document.getElementById('btn-zoom-out');
|
||||||
|
var btnZoomReset = document.getElementById('btn-zoom-reset');
|
||||||
|
var btnZoomIn = document.getElementById('btn-zoom-in');
|
||||||
|
var zoomControl = document.getElementById('zoom-control');
|
||||||
|
var findInput = document.getElementById('find-input');
|
||||||
|
var findState = document.getElementById('find-state');
|
||||||
|
var findPrev = document.getElementById('find-prev');
|
||||||
|
var findNext = document.getElementById('find-next');
|
||||||
|
var findClose = document.getElementById('find-close');
|
||||||
|
var tabsEl = document.getElementById('tabs');
|
||||||
|
var docStats = document.getElementById('doc-stats');
|
||||||
|
var tabOpen = document.getElementById('tab-open');
|
||||||
|
var tabMenu = document.getElementById('tab-menu');
|
||||||
|
var tabMenuPath = document.getElementById('tab-menu-path');
|
||||||
|
var tabMenuReveal = document.getElementById('tab-menu-reveal');
|
||||||
|
var tabMenuNewWindow = document.getElementById('tab-menu-new-window');
|
||||||
|
var tabMenuTargetId = 0;
|
||||||
|
var tabDrag = null;
|
||||||
|
var suppressTabClickUntil = 0;
|
||||||
|
var ta = document.getElementById('editor');
|
||||||
|
var dirty = false;
|
||||||
|
var activeTabId = 0;
|
||||||
|
var tabCount = 0;
|
||||||
|
var pendingAutosaveTimer = 0;
|
||||||
|
var autosavePaused = false;
|
||||||
|
var saveBlocked = false;
|
||||||
|
var AUTOSAVE_DEBOUNCE_MS = 700;
|
||||||
|
var composingFind = false;
|
||||||
|
var pendingFindTimer = 0;
|
||||||
|
var FIND_DEBOUNCE_MS = 300;
|
||||||
|
// Tab inserts spaces, never a literal tab. Two spaces matches the
|
||||||
|
// common Markdown/AI-generated document style and keeps list nesting
|
||||||
|
// compact; change this single constant to switch the width.
|
||||||
|
var INDENT = ' ';
|
||||||
|
// The strip stays hidden while the only tab is Home, matching the
|
||||||
|
// original start-up page. Set to false to keep the tab bar always on.
|
||||||
|
var HIDE_SINGLE_HOME_TAB = true;
|
||||||
|
var findHits = [];
|
||||||
|
var currentFindHit = -1;
|
||||||
|
var lastFindQuery = '';
|
||||||
|
var STAT_WORDS = '__MDP_STAT_WORDS_JS__';
|
||||||
|
var STAT_CHARS = '__MDP_STAT_CHARS_JS__';
|
||||||
|
var ZOOM_SAVE_DEBOUNCE_MS = 400;
|
||||||
|
var pendingZoomSaveTimer = 0;
|
||||||
|
var ZOOM_MIN = 50;
|
||||||
|
var ZOOM_MAX = 300;
|
||||||
|
var ZOOM_STEP = 5;
|
||||||
|
var ZOOM_WHEEL_THROTTLE_MS = 90;
|
||||||
|
var zoomWheelAt = 0;
|
||||||
|
var zoomPercent = 100;
|
||||||
|
|
||||||
|
btnToggle.innerHTML = ICON_EDIT;
|
||||||
|
btnZoom.innerHTML = ICON_ZOOM;
|
||||||
|
findPrev.innerHTML = ICON_UP;
|
||||||
|
findNext.innerHTML = ICON_DOWN;
|
||||||
|
findClose.innerHTML = ICON_CLOSE;
|
||||||
|
|
||||||
|
function inEdit() { return document.body.classList.contains('editing'); }
|
||||||
|
function textSegments(text) {
|
||||||
|
if (typeof Intl !== 'undefined' && Intl.Segmenter) {
|
||||||
|
var segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
|
||||||
|
return Array.from(segmenter.segment(text), function(item) { return item.segment; });
|
||||||
|
}
|
||||||
|
return Array.from(text);
|
||||||
|
}
|
||||||
|
function updateDocumentStats(raw) {
|
||||||
|
var segments = textSegments(String(raw || ''));
|
||||||
|
var words = segments.reduce(function(total, segment) {
|
||||||
|
return total + (/^\s+$/u.test(segment) ? 0 : 1);
|
||||||
|
}, 0);
|
||||||
|
var number = new Intl.NumberFormat().format;
|
||||||
|
docStats.textContent =
|
||||||
|
number(words) + ' ' + STAT_WORDS + ' · ' + number(segments.length) + ' ' + STAT_CHARS;
|
||||||
|
}
|
||||||
|
function queueZoomSave() {
|
||||||
|
if (pendingZoomSaveTimer) clearTimeout(pendingZoomSaveTimer);
|
||||||
|
pendingZoomSaveTimer = setTimeout(function() {
|
||||||
|
pendingZoomSaveTimer = 0;
|
||||||
|
if (window.ipc) window.ipc.postMessage('zoom:' + zoomPercent);
|
||||||
|
}, ZOOM_SAVE_DEBOUNCE_MS);
|
||||||
|
}
|
||||||
|
function applyZoom(percent, persist) {
|
||||||
|
zoomPercent = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, percent));
|
||||||
|
document.documentElement.style.setProperty('--content-scale', String(zoomPercent / 100));
|
||||||
|
btnZoomReset.textContent = zoomPercent + '%';
|
||||||
|
if (persist) queueZoomSave();
|
||||||
|
if (inEdit()) autoResize();
|
||||||
|
}
|
||||||
|
function changeZoom(delta) {
|
||||||
|
applyZoom(zoomPercent + delta, true);
|
||||||
|
}
|
||||||
|
function currentScrollProgress() {
|
||||||
|
var root = document.documentElement;
|
||||||
|
var max = Math.max(root.scrollHeight - window.innerHeight, 0);
|
||||||
|
var y = window.scrollY || root.scrollTop || 0;
|
||||||
|
return max > 0 ? Math.min(1, Math.max(0, y / max)) : 0;
|
||||||
|
}
|
||||||
|
// A newer restore supersedes any callback the previous one left behind.
|
||||||
|
var scrollRestoreToken = 0;
|
||||||
|
function restoreScrollProgress(progress) {
|
||||||
|
var token = ++scrollRestoreToken;
|
||||||
|
function restore() {
|
||||||
|
if (token !== scrollRestoreToken) return;
|
||||||
|
var max = Math.max(document.documentElement.scrollHeight - window.innerHeight, 0);
|
||||||
|
window.scrollTo(window.scrollX || 0, max * progress);
|
||||||
|
}
|
||||||
|
restore();
|
||||||
|
requestAnimationFrame(function() {
|
||||||
|
restore();
|
||||||
|
requestAnimationFrame(restore);
|
||||||
|
});
|
||||||
|
// Late layout (tables, math, mermaid) can change the content height.
|
||||||
|
setTimeout(restore, 150);
|
||||||
|
}
|
||||||
|
// Report the viewport so Rust can restore it when the tab comes back. The
|
||||||
|
// tab id travels with the report: a late scroll must not land on the tab
|
||||||
|
// that became active in the meantime.
|
||||||
|
var pendingScrollReport = 0;
|
||||||
|
function reportScroll() {
|
||||||
|
if (pendingScrollReport || !activeTabId) return;
|
||||||
|
pendingScrollReport = setTimeout(function() {
|
||||||
|
pendingScrollReport = 0;
|
||||||
|
if (window.ipc && activeTabId) {
|
||||||
|
window.ipc.postMessage('scroll:' + activeTabId + ':' + currentScrollProgress().toFixed(4));
|
||||||
|
}
|
||||||
|
}, 200);
|
||||||
|
}
|
||||||
|
window.addEventListener('scroll', reportScroll, { passive: true });
|
||||||
|
applyZoom(100, false);
|
||||||
|
window.__mdPreviewSetZoom = function(percent) { applyZoom(percent, false); };
|
||||||
|
updateDocumentStats(ta.value);
|
||||||
|
function shortenPath(path, max) {
|
||||||
|
if (!path || path.length <= max) return path || '';
|
||||||
|
var head = Math.ceil((max - 3) / 2);
|
||||||
|
var tail = Math.floor((max - 3) / 2);
|
||||||
|
return path.slice(0, head) + '...' + path.slice(-tail);
|
||||||
|
}
|
||||||
|
function suppressTabTooltips() {
|
||||||
|
Array.prototype.forEach.call(tabsEl.querySelectorAll('.tab[title]'), function(tab) {
|
||||||
|
tab.setAttribute('data-saved-title', tab.getAttribute('title'));
|
||||||
|
tab.removeAttribute('title');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function restoreTabTooltips() {
|
||||||
|
Array.prototype.forEach.call(tabsEl.querySelectorAll('.tab[data-saved-title]'), function(tab) {
|
||||||
|
var title = tab.getAttribute('data-saved-title');
|
||||||
|
tab.removeAttribute('data-saved-title');
|
||||||
|
if (title) tab.setAttribute('title', title);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function hideTabMenu() {
|
||||||
|
if (!tabMenu || tabMenu.hidden) return;
|
||||||
|
tabMenu.hidden = true;
|
||||||
|
tabMenuTargetId = 0;
|
||||||
|
restoreTabTooltips();
|
||||||
|
}
|
||||||
|
function showTabMenu(id, x, y) {
|
||||||
|
if (!tabMenu) return;
|
||||||
|
if (!tabMenu.hidden) hideTabMenu();
|
||||||
|
suppressTabTooltips();
|
||||||
|
tabMenuTargetId = id;
|
||||||
|
var tabEl = tabsEl.querySelector('.tab[data-tab-id="' + id + '"]');
|
||||||
|
var isHome = tabEl ? tabEl.classList.contains('home') : false;
|
||||||
|
var path = tabEl ? (tabEl.getAttribute('data-tab-path') || '') : '';
|
||||||
|
if (tabMenuPath) {
|
||||||
|
tabMenuPath.textContent = isHome ? L_HOME : shortenPath(path, 42);
|
||||||
|
if (!isHome && path) tabMenuPath.setAttribute('title', path);
|
||||||
|
else tabMenuPath.removeAttribute('title');
|
||||||
|
}
|
||||||
|
tabMenu.hidden = false;
|
||||||
|
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1 || isHome;
|
||||||
|
if (tabMenuReveal) tabMenuReveal.disabled = isHome || !path;
|
||||||
|
tabMenu.style.left = '0px';
|
||||||
|
tabMenu.style.top = '0px';
|
||||||
|
var rect = tabMenu.getBoundingClientRect();
|
||||||
|
var left = Math.max(8, Math.min(x, window.innerWidth - rect.width - 8));
|
||||||
|
var top = Math.max(8, Math.min(y, window.innerHeight - rect.height - 8));
|
||||||
|
tabMenu.style.left = left + 'px';
|
||||||
|
tabMenu.style.top = top + 'px';
|
||||||
|
}
|
||||||
|
function detachTab(id) {
|
||||||
|
if (tabCount <= 1) return;
|
||||||
|
if (saveBlocked) {
|
||||||
|
window.alert(window.__mdPreviewCannotSave || 'Discard unsaved changes?');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
requestTabAction('detach', id);
|
||||||
|
}
|
||||||
|
document.addEventListener('contextmenu', function(e) {
|
||||||
|
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
|
||||||
|
if (tab) {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
showTabMenu(tab.getAttribute('data-tab-id'), e.clientX, e.clientY);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hideTabMenu();
|
||||||
|
if (!inEdit() || e.target !== ta) e.preventDefault();
|
||||||
|
});
|
||||||
|
function setDirty(d) {
|
||||||
|
if (dirty === d) return;
|
||||||
|
dirty = d;
|
||||||
|
window.ipc.postMessage(d ? 'dirty:1' : 'dirty:0');
|
||||||
|
}
|
||||||
|
function cancelPendingAutosave() {
|
||||||
|
if (!pendingAutosaveTimer) return;
|
||||||
|
clearTimeout(pendingAutosaveTimer);
|
||||||
|
pendingAutosaveTimer = 0;
|
||||||
|
}
|
||||||
|
function save() {
|
||||||
|
cancelPendingAutosave();
|
||||||
|
if (!dirty) return;
|
||||||
|
window.ipc.postMessage('save:' + ta.value);
|
||||||
|
}
|
||||||
|
function scheduleAutosave() {
|
||||||
|
cancelPendingAutosave();
|
||||||
|
if (autosavePaused) return;
|
||||||
|
pendingAutosaveTimer = setTimeout(function() {
|
||||||
|
pendingAutosaveTimer = 0;
|
||||||
|
if (dirty) save();
|
||||||
|
}, AUTOSAVE_DEBOUNCE_MS);
|
||||||
|
}
|
||||||
|
window.__mdPreviewSave = save;
|
||||||
|
function requestTabAction(action, id) {
|
||||||
|
cancelPendingAutosave();
|
||||||
|
var message = 'tab-action:' + action + ':' + id + ':' + currentScrollProgress().toFixed(4);
|
||||||
|
if (dirty) {
|
||||||
|
if (saveBlocked) {
|
||||||
|
if (!window.confirm(window.__mdPreviewCannotSave || 'Discard unsaved changes?')) return;
|
||||||
|
} else {
|
||||||
|
message += '\n' + ta.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.ipc.postMessage(message);
|
||||||
|
}
|
||||||
|
function openFile() {
|
||||||
|
if (inEdit()) leaveEdit();
|
||||||
|
window.ipc.postMessage('open');
|
||||||
|
}
|
||||||
|
window.__mdPreviewOpenFile = openFile;
|
||||||
|
function newFile() {
|
||||||
|
if (inEdit()) leaveEdit();
|
||||||
|
window.ipc.postMessage('new-file');
|
||||||
|
}
|
||||||
|
window.__mdPreviewNewFile = newFile;
|
||||||
|
function newTab() {
|
||||||
|
// Reuse the close/activate path so a dirty editor is saved before the
|
||||||
|
// Home tab replaces it.
|
||||||
|
requestTabAction('new-tab', 0);
|
||||||
|
}
|
||||||
|
function selectionSeed() {
|
||||||
|
var sel = window.getSelection && window.getSelection();
|
||||||
|
if (!sel || sel.rangeCount === 0) return null;
|
||||||
|
var anchor = sel.anchorNode;
|
||||||
|
var element = anchor && (anchor.nodeType === 3 ? anchor.parentElement : anchor);
|
||||||
|
if (!element || !element.closest || !element.closest('#preview')) return null;
|
||||||
|
var text = sel.toString();
|
||||||
|
if (!text) return null;
|
||||||
|
var top = null;
|
||||||
|
try {
|
||||||
|
var rect = sel.getRangeAt(0).getBoundingClientRect();
|
||||||
|
if (rect && (rect.width || rect.height)) top = rect.top;
|
||||||
|
} catch (_) {}
|
||||||
|
var lines = text.split(/\r?\n/);
|
||||||
|
for (var i = 0; i < lines.length; i += 1) {
|
||||||
|
var line = lines[i].trim();
|
||||||
|
if (line) return { text: line, top: top };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
function showFind(seed, anchorTop) {
|
||||||
|
if (document.body.classList.contains('home')) return;
|
||||||
|
if (inEdit()) return;
|
||||||
|
document.body.classList.add('finding');
|
||||||
|
if (typeof seed === 'string' && seed) {
|
||||||
|
findInput.value = seed;
|
||||||
|
runFindQuery(seed, anchorTop, false);
|
||||||
|
}
|
||||||
|
setTimeout(function(){
|
||||||
|
try { findInput.focus({ preventScroll: true }); } catch (_) { findInput.focus(); }
|
||||||
|
findInput.select();
|
||||||
|
}, 0);
|
||||||
|
}
|
||||||
|
window.__mdPreviewShowFind = showFind;
|
||||||
|
function hideFind() {
|
||||||
|
document.body.classList.remove('finding');
|
||||||
|
findInput.value = '';
|
||||||
|
clearFindHits();
|
||||||
|
if (pendingFindTimer) { clearTimeout(pendingFindTimer); pendingFindTimer = 0; }
|
||||||
|
var sel = window.getSelection && window.getSelection();
|
||||||
|
if (sel && sel.removeAllRanges) sel.removeAllRanges();
|
||||||
|
}
|
||||||
|
function updateFindState() {
|
||||||
|
findState.textContent = findHits.length ? (currentFindHit + 1) + '/' + findHits.length : '';
|
||||||
|
}
|
||||||
|
function clearFindHits() {
|
||||||
|
findHits.forEach(function(mark) {
|
||||||
|
var parent = mark.parentNode;
|
||||||
|
if (!parent) return;
|
||||||
|
parent.replaceChild(document.createTextNode(mark.textContent), mark);
|
||||||
|
parent.normalize();
|
||||||
|
});
|
||||||
|
findHits = [];
|
||||||
|
currentFindHit = -1;
|
||||||
|
lastFindQuery = '';
|
||||||
|
updateFindState();
|
||||||
|
}
|
||||||
|
function focusFindInput(selectionStart, selectionEnd) {
|
||||||
|
if (!document.body.classList.contains('finding')) return;
|
||||||
|
try {
|
||||||
|
findInput.focus({ preventScroll: true });
|
||||||
|
} catch (_) {
|
||||||
|
findInput.focus();
|
||||||
|
}
|
||||||
|
if (typeof selectionStart === 'number' && typeof selectionEnd === 'number') {
|
||||||
|
try { findInput.setSelectionRange(selectionStart, selectionEnd); } catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function restoreFindInput(selectionStart, selectionEnd) {
|
||||||
|
setTimeout(function() { focusFindInput(selectionStart, selectionEnd); }, 0);
|
||||||
|
requestAnimationFrame(function() {
|
||||||
|
focusFindInput(selectionStart, selectionEnd);
|
||||||
|
setTimeout(function() { focusFindInput(selectionStart, selectionEnd); }, 80);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function selectFindHit(index, reveal) {
|
||||||
|
if (!findHits.length) {
|
||||||
|
currentFindHit = -1;
|
||||||
|
updateFindState();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (currentFindHit >= 0 && findHits[currentFindHit]) {
|
||||||
|
findHits[currentFindHit].classList.remove('current');
|
||||||
|
}
|
||||||
|
currentFindHit = (index + findHits.length) % findHits.length;
|
||||||
|
var hit = findHits[currentFindHit];
|
||||||
|
hit.classList.add('current');
|
||||||
|
if (reveal !== false) {
|
||||||
|
if (window.__mdPreviewExpandFold) window.__mdPreviewExpandFold(hit);
|
||||||
|
hit.scrollIntoView({ block: 'center', inline: 'nearest' });
|
||||||
|
}
|
||||||
|
updateFindState();
|
||||||
|
}
|
||||||
|
function findStartIndex(anchorTop) {
|
||||||
|
if (!findHits.length) return 0;
|
||||||
|
var startTop = typeof anchorTop === 'number' ? anchorTop : 0;
|
||||||
|
var lastAbove = -1;
|
||||||
|
for (var i = 0; i < findHits.length; i += 1) {
|
||||||
|
var rect = findHits[i].getBoundingClientRect();
|
||||||
|
if (!rect.width && !rect.height) continue;
|
||||||
|
if (rect.bottom < startTop) {
|
||||||
|
lastAbove = i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
return lastAbove >= 0 ? lastAbove : 0;
|
||||||
|
}
|
||||||
|
function runFindQuery(query, anchorTop, reveal) {
|
||||||
|
clearFindHits();
|
||||||
|
query = String(query || '').trim();
|
||||||
|
if (!query) return;
|
||||||
|
lastFindQuery = query;
|
||||||
|
var needle = query.toLowerCase();
|
||||||
|
var previewEl = document.getElementById('preview');
|
||||||
|
var walker = document.createTreeWalker(previewEl, NodeFilter.SHOW_TEXT, {
|
||||||
|
acceptNode: function(node) {
|
||||||
|
if (!node.nodeValue || node.nodeValue.toLowerCase().indexOf(needle) < 0) {
|
||||||
|
return NodeFilter.FILTER_REJECT;
|
||||||
|
}
|
||||||
|
var parent = node.parentElement;
|
||||||
|
if (!parent || parent.closest('script,style,svg,mark.search-hit,.katex,.mdp-mermaid')) {
|
||||||
|
return NodeFilter.FILTER_REJECT;
|
||||||
|
}
|
||||||
|
return NodeFilter.FILTER_ACCEPT;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
var nodes = [];
|
||||||
|
while (walker.nextNode()) nodes.push(walker.currentNode);
|
||||||
|
nodes.forEach(function(node) {
|
||||||
|
var text = node.nodeValue;
|
||||||
|
var lower = text.toLowerCase();
|
||||||
|
var fragment = document.createDocumentFragment();
|
||||||
|
var start = 0;
|
||||||
|
var index;
|
||||||
|
while ((index = lower.indexOf(needle, start)) >= 0) {
|
||||||
|
if (index > start) fragment.appendChild(document.createTextNode(text.slice(start, index)));
|
||||||
|
var mark = document.createElement('mark');
|
||||||
|
mark.className = 'search-hit';
|
||||||
|
mark.textContent = text.slice(index, index + query.length);
|
||||||
|
findHits.push(mark);
|
||||||
|
fragment.appendChild(mark);
|
||||||
|
start = index + query.length;
|
||||||
|
}
|
||||||
|
if (start < text.length) fragment.appendChild(document.createTextNode(text.slice(start)));
|
||||||
|
node.parentNode.replaceChild(fragment, node);
|
||||||
|
});
|
||||||
|
selectFindHit(findStartIndex(anchorTop), reveal);
|
||||||
|
}
|
||||||
|
function runFind(backward) {
|
||||||
|
var q = findInput.value;
|
||||||
|
if (!q) { clearFindHits(); return; }
|
||||||
|
var hadFocus = document.activeElement === findInput;
|
||||||
|
var selectionStart = findInput.selectionStart;
|
||||||
|
var selectionEnd = findInput.selectionEnd;
|
||||||
|
var normalized = String(q || '').trim();
|
||||||
|
if (!normalized) {
|
||||||
|
clearFindHits();
|
||||||
|
} else if (normalized !== lastFindQuery) {
|
||||||
|
runFindQuery(normalized);
|
||||||
|
} else {
|
||||||
|
selectFindHit(currentFindHit + (backward ? -1 : 1));
|
||||||
|
}
|
||||||
|
if (hadFocus) restoreFindInput(selectionStart, selectionEnd);
|
||||||
|
}
|
||||||
|
function scheduleFind() {
|
||||||
|
if (pendingFindTimer) clearTimeout(pendingFindTimer);
|
||||||
|
pendingFindTimer = setTimeout(function() {
|
||||||
|
pendingFindTimer = 0;
|
||||||
|
if (!composingFind) runFindQuery(findInput.value);
|
||||||
|
}, FIND_DEBOUNCE_MS);
|
||||||
|
}
|
||||||
|
// Grow textarea height to its content so the page (html) owns the sole
|
||||||
|
// scrollbar; avoids the double-scrollbar you see if textarea keeps its
|
||||||
|
// own internal scroll.
|
||||||
|
function autoResize() {
|
||||||
|
var x = window.scrollX || document.documentElement.scrollLeft || 0;
|
||||||
|
var y = window.scrollY || document.documentElement.scrollTop || 0;
|
||||||
|
ta.style.height = 'auto';
|
||||||
|
var h = Math.max(ta.scrollHeight, window.innerHeight);
|
||||||
|
ta.style.height = h + 'px';
|
||||||
|
window.scrollTo(x, y);
|
||||||
|
}
|
||||||
|
// ---- Source editor commands -------------------------------------------------
|
||||||
|
function editorLineStart(value, pos) {
|
||||||
|
return value.lastIndexOf('\n', Math.max(0, pos - 1)) + 1;
|
||||||
|
}
|
||||||
|
function editorLineEnd(value, pos) {
|
||||||
|
var end = value.indexOf('\n', pos);
|
||||||
|
return end < 0 ? value.length : end;
|
||||||
|
}
|
||||||
|
function replaceEditorRange(text, start, end, selectionStart, selectionEnd) {
|
||||||
|
try {
|
||||||
|
ta.focus({ preventScroll: true });
|
||||||
|
} catch (_) {
|
||||||
|
ta.focus();
|
||||||
|
}
|
||||||
|
ta.setSelectionRange(start, end);
|
||||||
|
var inserted = false;
|
||||||
|
try {
|
||||||
|
if (text === '') {
|
||||||
|
inserted = document.execCommand('delete', false);
|
||||||
|
} else {
|
||||||
|
inserted = document.execCommand('insertText', false, text);
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
inserted = false;
|
||||||
|
}
|
||||||
|
if (!inserted) {
|
||||||
|
ta.setRangeText(text, start, end, 'end');
|
||||||
|
ta.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
}
|
||||||
|
if (typeof selectionStart === 'number' && typeof selectionEnd === 'number') {
|
||||||
|
try { ta.setSelectionRange(selectionStart, selectionEnd); } catch (_) {}
|
||||||
|
}
|
||||||
|
setDirty(true);
|
||||||
|
scheduleAutosave();
|
||||||
|
autoResize();
|
||||||
|
updateDocumentStats(ta.value);
|
||||||
|
}
|
||||||
|
function transformSelectedEditorLines(transform) {
|
||||||
|
var value = ta.value;
|
||||||
|
var start = ta.selectionStart;
|
||||||
|
var end = ta.selectionEnd;
|
||||||
|
if (start === end) return false;
|
||||||
|
var from = editorLineStart(value, start);
|
||||||
|
var last = end - 1;
|
||||||
|
if (last > start && value.charAt(last) === '\n') last -= 1;
|
||||||
|
var to = editorLineEnd(value, last);
|
||||||
|
var block = value.slice(from, to);
|
||||||
|
var lines = block.split('\n');
|
||||||
|
var transformed = lines.map(transform).join('\n');
|
||||||
|
if (transformed !== block) {
|
||||||
|
replaceEditorRange(transformed, from, to, from, from + transformed.length);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
function indentSelectedEditorLines() {
|
||||||
|
transformSelectedEditorLines(function(line) {
|
||||||
|
return INDENT + line;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function outdentSelectedEditorLines() {
|
||||||
|
transformSelectedEditorLines(function(line) {
|
||||||
|
if (line.charAt(0) === '\t') return line.slice(1);
|
||||||
|
var removed = 0;
|
||||||
|
while (removed < INDENT.length && line.charAt(removed) === ' ') removed += 1;
|
||||||
|
return line.slice(removed);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function indentEditor() {
|
||||||
|
var start = ta.selectionStart;
|
||||||
|
var end = ta.selectionEnd;
|
||||||
|
if (start === end) {
|
||||||
|
replaceEditorRange(INDENT, start, end, start + INDENT.length, start + INDENT.length);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
indentSelectedEditorLines();
|
||||||
|
}
|
||||||
|
function outdentEditor() {
|
||||||
|
var value = ta.value;
|
||||||
|
var start = ta.selectionStart;
|
||||||
|
var end = ta.selectionEnd;
|
||||||
|
if (start !== end) {
|
||||||
|
outdentSelectedEditorLines();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var from = editorLineStart(value, start);
|
||||||
|
var line = value.slice(from, editorLineEnd(value, start));
|
||||||
|
var removed = 0;
|
||||||
|
if (line.charAt(0) === '\t') {
|
||||||
|
removed = 1;
|
||||||
|
} else {
|
||||||
|
while (removed < INDENT.length && line.charAt(removed) === ' ') removed += 1;
|
||||||
|
}
|
||||||
|
if (!removed) return;
|
||||||
|
var next = Math.max(from, start - removed);
|
||||||
|
replaceEditorRange('', from, from + removed, next, next);
|
||||||
|
}
|
||||||
|
function insertNewlineWithIndent() {
|
||||||
|
var value = ta.value;
|
||||||
|
var start = ta.selectionStart;
|
||||||
|
var end = ta.selectionEnd;
|
||||||
|
var from = editorLineStart(value, start);
|
||||||
|
var prefix = value.slice(from, start);
|
||||||
|
var leading = /^[ \t]*/.exec(prefix)[0];
|
||||||
|
if (!/\S/.test(prefix)) leading = '';
|
||||||
|
var text = '\n' + leading;
|
||||||
|
var next = start + text.length;
|
||||||
|
replaceEditorRange(text, start, end, next, next);
|
||||||
|
}
|
||||||
|
ta.addEventListener('keydown', function(e) {
|
||||||
|
if (e.isComposing || e.keyCode === 229) return;
|
||||||
|
if (e.key === 'Tab' && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (e.shiftKey) outdentEditor(); else indentEditor();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
insertNewlineWithIndent();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// Edit mode is per tab and owned by Rust; this only paints it.
|
||||||
|
function setEditMode(on) {
|
||||||
|
if (on) {
|
||||||
|
document.body.classList.add('editing');
|
||||||
|
btnToggle.innerHTML = ICON_VIEW;
|
||||||
|
btnToggle.title = L_VIEW;
|
||||||
|
btnToggle.setAttribute('aria-label', L_VIEW);
|
||||||
|
} else {
|
||||||
|
document.body.classList.remove('editing');
|
||||||
|
btnToggle.innerHTML = ICON_EDIT;
|
||||||
|
btnToggle.title = L_EDIT;
|
||||||
|
btnToggle.setAttribute('aria-label', L_EDIT);
|
||||||
|
}
|
||||||
|
autoResize();
|
||||||
|
}
|
||||||
|
function enterEdit() {
|
||||||
|
if (document.body.classList.contains('home')) return;
|
||||||
|
var progress = currentScrollProgress();
|
||||||
|
setEditMode(true);
|
||||||
|
try {
|
||||||
|
ta.focus({ preventScroll: true });
|
||||||
|
} catch (_) {
|
||||||
|
ta.focus();
|
||||||
|
}
|
||||||
|
restoreScrollProgress(progress);
|
||||||
|
if (window.ipc) window.ipc.postMessage('edit-mode:' + activeTabId + ':1');
|
||||||
|
}
|
||||||
|
function leaveEdit() {
|
||||||
|
var progress = currentScrollProgress();
|
||||||
|
if (dirty) save();
|
||||||
|
setEditMode(false);
|
||||||
|
restoreScrollProgress(progress);
|
||||||
|
if (window.ipc) window.ipc.postMessage('edit-mode:' + activeTabId + ':0');
|
||||||
|
}
|
||||||
|
window.__mdPreviewToggleEdit = function() {
|
||||||
|
if (inEdit()) leaveEdit(); else enterEdit();
|
||||||
|
};
|
||||||
|
window.__mdPreviewCloseActiveTab = function() {
|
||||||
|
if (activeTabId) requestTabAction('close', activeTabId);
|
||||||
|
};
|
||||||
|
|
||||||
|
tabOpen.addEventListener('click', newTab);
|
||||||
|
if (tabMenuNewWindow) {
|
||||||
|
tabMenuNewWindow.addEventListener('click', function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
var id = tabMenuTargetId;
|
||||||
|
hideTabMenu();
|
||||||
|
if (id) detachTab(id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (tabMenuReveal) {
|
||||||
|
tabMenuReveal.addEventListener('click', function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
var id = tabMenuTargetId;
|
||||||
|
hideTabMenu();
|
||||||
|
if (id) window.ipc.postMessage('reveal-tab:' + id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
tabsEl.addEventListener('pointerdown', function(e) {
|
||||||
|
if (e.button !== 0 || tabCount <= 1) return;
|
||||||
|
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
|
||||||
|
if (!tab || (e.target.closest && e.target.closest('.tab-close'))) return;
|
||||||
|
if (tab.classList.contains('home')) return;
|
||||||
|
hideTabMenu();
|
||||||
|
tabDrag = { id: tab.getAttribute('data-tab-id'), startY: e.clientY, element: tab, pointerId: e.pointerId, dragged: false };
|
||||||
|
try { tab.setPointerCapture(e.pointerId); } catch (err) {}
|
||||||
|
});
|
||||||
|
tabsEl.addEventListener('pointermove', function(e) {
|
||||||
|
if (!tabDrag || e.pointerId !== tabDrag.pointerId) return;
|
||||||
|
if (!tabDrag.dragged && Math.abs(e.clientY - tabDrag.startY) >= 24) {
|
||||||
|
tabDrag.dragged = true;
|
||||||
|
tabDrag.element.classList.add('dragging');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
tabsEl.addEventListener('pointerup', function(e) {
|
||||||
|
if (!tabDrag || e.pointerId !== tabDrag.pointerId) return;
|
||||||
|
var drag = tabDrag;
|
||||||
|
tabDrag = null;
|
||||||
|
drag.element.classList.remove('dragging');
|
||||||
|
try {
|
||||||
|
if (drag.element.hasPointerCapture(e.pointerId)) drag.element.releasePointerCapture(e.pointerId);
|
||||||
|
} catch (err) {}
|
||||||
|
if (!drag.dragged) return;
|
||||||
|
suppressTabClickUntil = Date.now() + 350;
|
||||||
|
if (tabCount > 1) detachTab(drag.id);
|
||||||
|
});
|
||||||
|
tabsEl.addEventListener('pointercancel', function(e) {
|
||||||
|
if (!tabDrag || e.pointerId !== tabDrag.pointerId) return;
|
||||||
|
var drag = tabDrag;
|
||||||
|
tabDrag = null;
|
||||||
|
drag.element.classList.remove('dragging');
|
||||||
|
});
|
||||||
|
window.addEventListener('resize', hideTabMenu);
|
||||||
|
window.addEventListener('scroll', hideTabMenu, true);
|
||||||
|
window.addEventListener('blur', hideTabMenu);
|
||||||
|
document.addEventListener('click', function(e) {
|
||||||
|
if (Date.now() < suppressTabClickUntil) {
|
||||||
|
var suppressedTab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
|
||||||
|
if (suppressedTab) {
|
||||||
|
suppressTabClickUntil = 0;
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (tabMenu && !tabMenu.hidden) hideTabMenu();
|
||||||
|
var closeTab = e.target && e.target.closest ? e.target.closest('[data-close-tab]') : null;
|
||||||
|
if (closeTab) {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
requestTabAction('close', closeTab.getAttribute('data-close-tab'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var locateTab = e.target && e.target.closest ? e.target.closest('[data-locate-tab]') : null;
|
||||||
|
if (locateTab) {
|
||||||
|
e.preventDefault();
|
||||||
|
window.ipc.postMessage('locate-tab:' + locateTab.getAttribute('data-locate-tab'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
|
||||||
|
if (tab) {
|
||||||
|
e.preventDefault();
|
||||||
|
requestTabAction('activate', tab.getAttribute('data-tab-id'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var newFileBtn = e.target && e.target.closest ? e.target.closest('[data-new-file]') : null;
|
||||||
|
if (newFileBtn) {
|
||||||
|
e.preventDefault();
|
||||||
|
newFile();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var openBtn = e.target && e.target.closest ? e.target.closest('[data-open-file]') : null;
|
||||||
|
if (openBtn) {
|
||||||
|
e.preventDefault();
|
||||||
|
openFile();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var recentBtn = e.target && e.target.closest ? e.target.closest('[data-recent-index]') : null;
|
||||||
|
if (recentBtn) {
|
||||||
|
e.preventDefault();
|
||||||
|
window.ipc.postMessage('open-recent:' + recentBtn.getAttribute('data-recent-index'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
findInput.addEventListener('compositionstart', function() { composingFind = true; });
|
||||||
|
findInput.addEventListener('compositionend', function() { composingFind = false; scheduleFind(); });
|
||||||
|
findInput.addEventListener('input', function(e) {
|
||||||
|
if (composingFind || e.isComposing) return;
|
||||||
|
scheduleFind();
|
||||||
|
});
|
||||||
|
findInput.addEventListener('keydown', function(e) {
|
||||||
|
if (composingFind || e.isComposing) return;
|
||||||
|
if (e.key === 'Enter') { e.preventDefault(); runFind(e.shiftKey); }
|
||||||
|
if (e.key === 'Escape') { e.preventDefault(); hideFind(); }
|
||||||
|
});
|
||||||
|
findPrev.addEventListener('click', function() { runFind(true); });
|
||||||
|
findNext.addEventListener('click', function() { runFind(false); });
|
||||||
|
findClose.addEventListener('click', hideFind);
|
||||||
|
|
||||||
|
btnToggle.addEventListener('click', function() {
|
||||||
|
window.__mdPreviewToggleEdit();
|
||||||
|
});
|
||||||
|
btnZoom.addEventListener('click', function(e) {
|
||||||
|
e.stopPropagation();
|
||||||
|
zoomControl.classList.toggle('open');
|
||||||
|
});
|
||||||
|
btnZoomOut.addEventListener('click', function() { changeZoom(-ZOOM_STEP); });
|
||||||
|
btnZoomReset.addEventListener('click', function() { applyZoom(100, true); });
|
||||||
|
btnZoomIn.addEventListener('click', function() { changeZoom(ZOOM_STEP); });
|
||||||
|
function onContentWheel(e) {
|
||||||
|
if (!e.ctrlKey) return;
|
||||||
|
e.preventDefault();
|
||||||
|
if (Math.abs(e.deltaY) < 0.01) return;
|
||||||
|
var now = Date.now();
|
||||||
|
if (now - zoomWheelAt < ZOOM_WHEEL_THROTTLE_MS) return;
|
||||||
|
zoomWheelAt = now;
|
||||||
|
changeZoom(e.deltaY < 0 ? ZOOM_STEP : -ZOOM_STEP);
|
||||||
|
}
|
||||||
|
window.addEventListener('wheel', onContentWheel, { passive: false });
|
||||||
|
ta.addEventListener('input', function() { setDirty(true); scheduleAutosave(); autoResize(); updateDocumentStats(ta.value); });
|
||||||
|
window.addEventListener('resize', function() { if (inEdit()) autoResize(); });
|
||||||
|
document.addEventListener('click', function(e) {
|
||||||
|
if (!zoomControl.contains(e.target)) zoomControl.classList.remove('open');
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('keydown', function(e) {
|
||||||
|
if (e.key === 'Escape' && tabMenu && !tabMenu.hidden) {
|
||||||
|
hideTabMenu();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.metaKey || e.ctrlKey) && (e.key === 'w' || e.key === 'W')) {
|
||||||
|
if (activeTabId) {
|
||||||
|
e.preventDefault();
|
||||||
|
requestTabAction('close', activeTabId);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.metaKey || e.ctrlKey) && (e.key === 'n' || e.key === 'N')) {
|
||||||
|
e.preventDefault();
|
||||||
|
newFile();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.metaKey || e.ctrlKey) && (e.key === '+' || e.key === '=' || e.code === 'NumpadAdd')) {
|
||||||
|
e.preventDefault();
|
||||||
|
changeZoom(ZOOM_STEP);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.metaKey || e.ctrlKey) && (e.key === '-' || e.code === 'NumpadSubtract')) {
|
||||||
|
e.preventDefault();
|
||||||
|
changeZoom(-ZOOM_STEP);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.metaKey || e.ctrlKey) && (e.key === '0' || e.code === 'Numpad0')) {
|
||||||
|
e.preventDefault();
|
||||||
|
applyZoom(100, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.metaKey || e.ctrlKey) && (e.key === 'r' || e.key === 'R')) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!inEdit()) window.ipc.postMessage('refresh');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.metaKey || e.ctrlKey) && (e.key === 'o' || e.key === 'O')) {
|
||||||
|
e.preventDefault();
|
||||||
|
openFile();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.metaKey || e.ctrlKey) && (e.key === 'f' || e.key === 'F')) {
|
||||||
|
if (inEdit()) return;
|
||||||
|
var seed = (document.body.classList.contains('finding') && document.activeElement === findInput) ? null : selectionSeed();
|
||||||
|
e.preventDefault();
|
||||||
|
showFind(seed ? seed.text : '', seed ? seed.top : null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.metaKey || e.ctrlKey) && (e.key === 'e' || e.key === 'E')) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (inEdit()) leaveEdit(); else enterEdit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.metaKey || e.ctrlKey) && (e.key === 's' || e.key === 'S')) {
|
||||||
|
if (inEdit()) { e.preventDefault(); save(); }
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((e.metaKey || e.ctrlKey) && (e.key === 'p' || e.key === 'P')) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (inEdit()) leaveEdit();
|
||||||
|
setTimeout(function(){ window.ipc.postMessage('print'); }, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (e.key === 'Escape' && document.body.classList.contains('finding')) { hideFind(); return; }
|
||||||
|
if (e.key === 'Escape' && inEdit()) { leaveEdit(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// Called by Rust after a save (only preview is refreshed) or after an
|
||||||
|
// external file change (both preview + textarea are refreshed).
|
||||||
|
window.__setPreview = function(previewHtml, needsMath, needsMermaid) {
|
||||||
|
if (arguments.length > 1 && window.__setFeatureFlags) {
|
||||||
|
window.__setFeatureFlags(needsMath, needsMermaid);
|
||||||
|
}
|
||||||
|
document.getElementById('preview').innerHTML = previewHtml;
|
||||||
|
(window.requestIdleCallback || function(fn){ return setTimeout(fn, 0); })(function() {
|
||||||
|
if (typeof hljs !== 'undefined') hljs.highlightAll();
|
||||||
|
if (window.__enhancePreview) window.__enhancePreview();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
window.__setBaseHref = function(baseHref) {
|
||||||
|
var base = document.getElementById('base-href');
|
||||||
|
if (!base) {
|
||||||
|
base = document.createElement('base');
|
||||||
|
base.id = 'base-href';
|
||||||
|
document.head.insertBefore(base, document.head.firstChild);
|
||||||
|
}
|
||||||
|
if (baseHref) base.setAttribute('href', baseHref);
|
||||||
|
else base.removeAttribute('href');
|
||||||
|
};
|
||||||
|
window.__markSaved = function(savedRaw) {
|
||||||
|
if (typeof savedRaw === 'string' && ta.value !== savedRaw) {
|
||||||
|
window.ipc.postMessage('dirty:1');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
autosavePaused = false;
|
||||||
|
saveBlocked = false;
|
||||||
|
setDirty(false);
|
||||||
|
};
|
||||||
|
window.__markSaveBlocked = function() {
|
||||||
|
saveBlocked = true;
|
||||||
|
autosavePaused = true;
|
||||||
|
};
|
||||||
|
window.__mdPreviewPauseAutosave = function() {
|
||||||
|
cancelPendingAutosave();
|
||||||
|
autosavePaused = true;
|
||||||
|
};
|
||||||
|
window.__mdPreviewResolveExternalChange = function() {
|
||||||
|
cancelPendingAutosave();
|
||||||
|
window.ipc.postMessage('external-change:' + (dirty ? 'dirty' : 'clean'));
|
||||||
|
};
|
||||||
|
window.__setTabs = function(tabs) {
|
||||||
|
hideTabMenu();
|
||||||
|
tabs = Array.isArray(tabs) ? tabs : [];
|
||||||
|
tabCount = tabs.length;
|
||||||
|
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1;
|
||||||
|
tabsEl.textContent = '';
|
||||||
|
activeTabId = 0;
|
||||||
|
var showTabBar = HIDE_SINGLE_HOME_TAB
|
||||||
|
? (tabs.length > 1 || (tabs.length === 1 && !tabs[0].home))
|
||||||
|
: tabs.length > 0;
|
||||||
|
document.body.classList.toggle('has-tabs', showTabBar);
|
||||||
|
tabs.forEach(function(tab) {
|
||||||
|
var isHome = !!tab.home;
|
||||||
|
var item = document.createElement('div');
|
||||||
|
item.className = 'tab' + (isHome ? ' home' : '') + (tab.active ? ' active' : '') + (tab.missing ? ' missing' : '') + (tab.dirty ? ' dirty' : '');
|
||||||
|
item.setAttribute('data-tab-id', tab.id);
|
||||||
|
item.setAttribute('data-tab-path', isHome ? '' : tab.path);
|
||||||
|
item.setAttribute('role', 'button');
|
||||||
|
item.setAttribute('tabindex', '0');
|
||||||
|
item.title = isHome ? L_HOME : tab.path;
|
||||||
|
if (tab.active) activeTabId = tab.id;
|
||||||
|
var status = document.createElement('span');
|
||||||
|
status.className = 'tab-status';
|
||||||
|
status.textContent = tab.missing ? '!' : '';
|
||||||
|
var name = document.createElement('span');
|
||||||
|
name.className = 'tab-name';
|
||||||
|
name.textContent = isHome ? L_HOME : tab.name;
|
||||||
|
var close = document.createElement('button');
|
||||||
|
close.className = 'tab-close';
|
||||||
|
close.type = 'button';
|
||||||
|
close.setAttribute('data-close-tab', tab.id);
|
||||||
|
close.setAttribute('aria-label', 'Close ' + (isHome ? L_HOME : tab.name));
|
||||||
|
close.textContent = '×';
|
||||||
|
// A lone Home tab is the start-up page; there is nothing to close.
|
||||||
|
if (tabCount === 1 && isHome) close.hidden = true;
|
||||||
|
item.appendChild(status);
|
||||||
|
item.appendChild(name);
|
||||||
|
item.appendChild(close);
|
||||||
|
tabsEl.appendChild(item);
|
||||||
|
if (tab.active) requestAnimationFrame(function() { item.scrollIntoView({ block: 'nearest', inline: 'nearest' }); });
|
||||||
|
});
|
||||||
|
};
|
||||||
|
tabsEl.addEventListener('keydown', function(e) {
|
||||||
|
if (e.key !== 'Enter' && e.key !== ' ') return;
|
||||||
|
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
|
||||||
|
if (!tab) return;
|
||||||
|
e.preventDefault();
|
||||||
|
requestTabAction('activate', tab.getAttribute('data-tab-id'));
|
||||||
|
});
|
||||||
|
window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid, editing, scrollRatio) {
|
||||||
|
document.body.classList.remove('home');
|
||||||
|
document.body.classList.remove('missing');
|
||||||
|
hideFind();
|
||||||
|
window.__setBaseHref(baseHref);
|
||||||
|
window.__setPreview(previewHtml, needsMath, needsMermaid);
|
||||||
|
if (!inEdit() || !dirty) {
|
||||||
|
autosavePaused = false;
|
||||||
|
ta.value = rawMd;
|
||||||
|
updateDocumentStats(rawMd);
|
||||||
|
setDirty(false);
|
||||||
|
}
|
||||||
|
setEditMode(!!editing);
|
||||||
|
restoreScrollProgress(typeof scrollRatio === 'number' ? scrollRatio : 0);
|
||||||
|
};
|
||||||
|
window.__setEmptyPreview = function(previewHtml) {
|
||||||
|
document.body.classList.add('home');
|
||||||
|
document.body.classList.remove('missing');
|
||||||
|
setEditMode(false);
|
||||||
|
cancelPendingAutosave();
|
||||||
|
autosavePaused = false;
|
||||||
|
hideFind();
|
||||||
|
window.__setBaseHref('');
|
||||||
|
document.getElementById('preview').innerHTML = previewHtml;
|
||||||
|
ta.value = '';
|
||||||
|
updateDocumentStats('');
|
||||||
|
setDirty(false);
|
||||||
|
window.scrollTo(0, 0);
|
||||||
|
};
|
||||||
|
window.__setMissing = function(previewHtml) {
|
||||||
|
document.body.classList.remove('home');
|
||||||
|
document.body.classList.add('missing');
|
||||||
|
setEditMode(false);
|
||||||
|
cancelPendingAutosave();
|
||||||
|
autosavePaused = false;
|
||||||
|
hideFind();
|
||||||
|
window.__setBaseHref('');
|
||||||
|
document.getElementById('preview').innerHTML = previewHtml;
|
||||||
|
ta.value = '';
|
||||||
|
updateDocumentStats('');
|
||||||
|
setDirty(false);
|
||||||
|
window.scrollTo(0, 0);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Defer hljs parse + initial highlight to idle time.
|
||||||
|
// hljs itself is NOT inlined in this page — Rust injects it via
|
||||||
|
// evaluate_script once we tell it we're painted. Until that injection
|
||||||
|
// runs, typeof hljs === 'undefined' and highlightAll is skipped; once
|
||||||
|
// it lands, hljs.highlightAll() gets called by the injected bootstrap
|
||||||
|
// and __setPreview.
|
||||||
|
|
||||||
|
// Signal Rust after first paint (triggers hljs inject; bench mode exits).
|
||||||
|
requestAnimationFrame(function() {
|
||||||
|
requestAnimationFrame(function() {
|
||||||
|
if (window.ipc) window.ipc.postMessage('ready');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})();
|
||||||
1934
src/app.rs
Normal file
1934
src/app.rs
Normal file
File diff suppressed because it is too large
Load Diff
235
src/config.rs
Normal file
235
src/config.rs
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
//! User data paths, persisted window/zoom/theme state, and the blocking dialogs.
|
||||||
|
|
||||||
|
use std::fs;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use tao::event_loop::EventLoop;
|
||||||
|
use tao::window::{Theme, Window};
|
||||||
|
|
||||||
|
// Window defaults, in logical pixels.
|
||||||
|
pub const DEFAULT_W: f64 = 900.0;
|
||||||
|
pub const DEFAULT_H: f64 = 700.0;
|
||||||
|
|
||||||
|
use crate::app::UserEvent;
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub enum ThemeChoice {
|
||||||
|
#[default]
|
||||||
|
System,
|
||||||
|
Light,
|
||||||
|
Dark,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ThemeChoice {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
ThemeChoice::System => "system",
|
||||||
|
ThemeChoice::Light => "light",
|
||||||
|
ThemeChoice::Dark => "dark",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_str(value: &str) -> Self {
|
||||||
|
match value.trim().to_ascii_lowercase().as_str() {
|
||||||
|
"light" => ThemeChoice::Light,
|
||||||
|
"dark" => ThemeChoice::Dark,
|
||||||
|
_ => ThemeChoice::System,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tao_theme(self) -> Option<Theme> {
|
||||||
|
match self {
|
||||||
|
ThemeChoice::System => None,
|
||||||
|
ThemeChoice::Light => Some(Theme::Light),
|
||||||
|
ThemeChoice::Dark => Some(Theme::Dark),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn config_dir() -> PathBuf {
|
||||||
|
if let Some(path) = std::env::var_os("MD_PREVIEW_CONFIG_DIR") {
|
||||||
|
return PathBuf::from(path);
|
||||||
|
}
|
||||||
|
std::env::var_os("LOCALAPPDATA")
|
||||||
|
.or_else(|| std::env::var_os("APPDATA"))
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.unwrap_or_else(|| PathBuf::from("."))
|
||||||
|
.join("md-preview")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone)]
|
||||||
|
pub struct WindowGeom {
|
||||||
|
pub x: f64,
|
||||||
|
pub y: f64,
|
||||||
|
pub w: f64,
|
||||||
|
pub h: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn geom_path() -> PathBuf {
|
||||||
|
config_dir().join("window.geom")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn theme_path() -> PathBuf {
|
||||||
|
config_dir().join("theme.txt")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_theme_choice() -> ThemeChoice {
|
||||||
|
fs::read_to_string(theme_path())
|
||||||
|
.map(|raw| ThemeChoice::from_str(&raw))
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_theme_choice(choice: ThemeChoice) {
|
||||||
|
let dir = config_dir();
|
||||||
|
let _ = fs::create_dir_all(&dir);
|
||||||
|
let _ = fs::write(dir.join("theme.txt"), choice.as_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
const ZOOM_MIN: u32 = 50;
|
||||||
|
const ZOOM_MAX: u32 = 300;
|
||||||
|
|
||||||
|
pub fn zoom_path() -> PathBuf {
|
||||||
|
config_dir().join("zoom.txt")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clamp_zoom(percent: u32) -> u32 {
|
||||||
|
percent.clamp(ZOOM_MIN, ZOOM_MAX)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_zoom() -> u32 {
|
||||||
|
fs::read_to_string(zoom_path())
|
||||||
|
.ok()
|
||||||
|
.and_then(|raw| raw.trim().parse::<u32>().ok())
|
||||||
|
.map(clamp_zoom)
|
||||||
|
.unwrap_or(100)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_zoom(percent: u32) {
|
||||||
|
let dir = config_dir();
|
||||||
|
let _ = fs::create_dir_all(&dir);
|
||||||
|
let _ = fs::write(zoom_path(), clamp_zoom(percent).to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn show_warning_dialog(title: &str, description: &str) {
|
||||||
|
let _ = rfd::MessageDialog::new()
|
||||||
|
.set_level(rfd::MessageLevel::Warning)
|
||||||
|
.set_title(title)
|
||||||
|
.set_description(description)
|
||||||
|
.show();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn confirm_discard_unsaved(error: &str) -> bool {
|
||||||
|
matches!(
|
||||||
|
rfd::MessageDialog::new()
|
||||||
|
.set_level(rfd::MessageLevel::Warning)
|
||||||
|
.set_title("Could Not Save")
|
||||||
|
.set_description(format!(
|
||||||
|
"{error}\n\nThe file may be read-only or locked by another program. Close the window and discard the unsaved changes?"
|
||||||
|
))
|
||||||
|
.set_buttons(rfd::MessageButtons::OkCancel)
|
||||||
|
.show(),
|
||||||
|
rfd::MessageDialogResult::Ok
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_window_geom() -> Option<WindowGeom> {
|
||||||
|
let txt = fs::read_to_string(geom_path()).ok()?;
|
||||||
|
let parts: Vec<&str> = txt.trim().split(',').collect();
|
||||||
|
if parts.len() != 4 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(WindowGeom {
|
||||||
|
x: parts[0].parse().ok()?,
|
||||||
|
y: parts[1].parse().ok()?,
|
||||||
|
w: parts[2].parse().ok()?,
|
||||||
|
h: parts[3].parse().ok()?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_window_geom(window: &Window) {
|
||||||
|
let Ok(pos) = window.outer_position() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let scale = window.scale_factor();
|
||||||
|
let size = window.inner_size();
|
||||||
|
let geom = WindowGeom {
|
||||||
|
x: pos.x as f64 / scale,
|
||||||
|
y: pos.y as f64 / scale,
|
||||||
|
w: size.width as f64 / scale,
|
||||||
|
h: size.height as f64 / scale,
|
||||||
|
};
|
||||||
|
if geom.w < 200.0 || geom.h < 150.0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let dir = config_dir();
|
||||||
|
let _ = fs::create_dir_all(&dir);
|
||||||
|
let _ = fs::write(
|
||||||
|
dir.join("window.geom"),
|
||||||
|
format!("{},{},{},{}", geom.x, geom.y, geom.w, geom.h),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return the saved geometry only when its center still falls inside
|
||||||
|
/// some connected monitor — prevents the window from landing off-screen
|
||||||
|
/// after a display swap.
|
||||||
|
pub fn geom_visible(geom: &WindowGeom, event_loop: &EventLoop<UserEvent>) -> bool {
|
||||||
|
let cx = geom.x + geom.w / 2.0;
|
||||||
|
let cy = geom.y + geom.h / 2.0;
|
||||||
|
event_loop.available_monitors().any(|mon| {
|
||||||
|
let scale = mon.scale_factor();
|
||||||
|
let mp = mon.position();
|
||||||
|
let ms = mon.size();
|
||||||
|
let mx = mp.x as f64 / scale;
|
||||||
|
let my = mp.y as f64 / scale;
|
||||||
|
let mw = ms.width as f64 / scale;
|
||||||
|
let mh = ms.height as f64 / scale;
|
||||||
|
cx >= mx && cx <= mx + mw && cy >= my && cy <= my + mh
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn centered_geom(event_loop: &EventLoop<UserEvent>) -> WindowGeom {
|
||||||
|
if let Some(mon) = event_loop.primary_monitor() {
|
||||||
|
let scale = mon.scale_factor();
|
||||||
|
let mp = mon.position();
|
||||||
|
let ms = mon.size();
|
||||||
|
let mx = mp.x as f64 / scale;
|
||||||
|
let my = mp.y as f64 / scale;
|
||||||
|
let mw = ms.width as f64 / scale;
|
||||||
|
let mh = ms.height as f64 / scale;
|
||||||
|
WindowGeom {
|
||||||
|
x: mx + (mw - DEFAULT_W) / 2.0,
|
||||||
|
y: my + (mh - DEFAULT_H) / 2.0,
|
||||||
|
w: DEFAULT_W,
|
||||||
|
h: DEFAULT_H,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
WindowGeom {
|
||||||
|
x: 100.0,
|
||||||
|
y: 100.0,
|
||||||
|
w: DEFAULT_W,
|
||||||
|
h: DEFAULT_H,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn zoom_percent_is_clamped_to_supported_range() {
|
||||||
|
assert_eq!(clamp_zoom(10), 50);
|
||||||
|
assert_eq!(clamp_zoom(50), 50);
|
||||||
|
assert_eq!(clamp_zoom(105), 105);
|
||||||
|
assert_eq!(clamp_zoom(300), 300);
|
||||||
|
assert_eq!(clamp_zoom(999), 300);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn theme_choice_parses_menu_values() {
|
||||||
|
assert_eq!(ThemeChoice::from_str("system"), ThemeChoice::System);
|
||||||
|
assert_eq!(ThemeChoice::from_str("light"), ThemeChoice::Light);
|
||||||
|
assert_eq!(ThemeChoice::from_str("dark"), ThemeChoice::Dark);
|
||||||
|
assert_eq!(ThemeChoice::from_str("unexpected"), ThemeChoice::System);
|
||||||
|
assert_eq!(ThemeChoice::Dark.as_str(), "dark");
|
||||||
|
}
|
||||||
|
}
|
||||||
25
src/escape.rs
Normal file
25
src/escape.rs
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
//! Small text/JS escaping helpers shared by the page builder, the Markdown
|
||||||
|
//! pipeline and the renderer.
|
||||||
|
|
||||||
|
pub fn escape_js(s: &str) -> String {
|
||||||
|
s.replace('\\', "\\\\")
|
||||||
|
.replace('\'', "\\'")
|
||||||
|
.replace('\n', "\\n")
|
||||||
|
.replace('\r', "\\r")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn html_escape_ta(s: &str) -> String {
|
||||||
|
s.replace('&', "&").replace('<', "<")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn html_escape_attr(s: &str) -> String {
|
||||||
|
s.replace('&', "&")
|
||||||
|
.replace('"', """)
|
||||||
|
.replace('<', "<")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn html_escape_text(s: &str) -> String {
|
||||||
|
s.replace('&', "&")
|
||||||
|
.replace('<', "<")
|
||||||
|
.replace('>', ">")
|
||||||
|
}
|
||||||
458
src/files.rs
Normal file
458
src/files.rs
Normal file
@@ -0,0 +1,458 @@
|
|||||||
|
//! File-system side effects: the recent-files list, saving the active tab,
|
||||||
|
//! the single-file watcher, supported document types, local-link resolution
|
||||||
|
//! and Explorer integration.
|
||||||
|
|
||||||
|
use notify::{Event, RecursiveMode, Watcher};
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use tao::event_loop::EventLoopProxy;
|
||||||
|
use tao::window::WindowId;
|
||||||
|
|
||||||
|
use crate::app::UserEvent;
|
||||||
|
use crate::session::{self, DocumentSession};
|
||||||
|
|
||||||
|
pub const MAX_RECENT_FILES: usize = 8;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct SelfWriteRecord {
|
||||||
|
pub path: PathBuf,
|
||||||
|
pub content: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn recent_files_path() -> PathBuf {
|
||||||
|
crate::config::config_dir().join("recent-files.txt")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_recent_files() -> Vec<PathBuf> {
|
||||||
|
let Ok(txt) = fs::read_to_string(recent_files_path()) else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut files = Vec::new();
|
||||||
|
for line in txt.lines() {
|
||||||
|
if line.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let path = session::strip_verbatim(PathBuf::from(line));
|
||||||
|
if !path.exists() || files.iter().any(|p| p == &path) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
files.push(path);
|
||||||
|
if files.len() == MAX_RECENT_FILES {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
files
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save_recent_files(files: &[PathBuf]) {
|
||||||
|
let dir = crate::config::config_dir();
|
||||||
|
let _ = fs::create_dir_all(&dir);
|
||||||
|
let body = files
|
||||||
|
.iter()
|
||||||
|
.take(MAX_RECENT_FILES)
|
||||||
|
.map(|p| p.to_string_lossy())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n");
|
||||||
|
let _ = fs::write(dir.join("recent-files.txt"), body);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remember_recent_file(files: &Arc<Mutex<Vec<PathBuf>>>, path: &Path) {
|
||||||
|
let mut recent = files.lock().unwrap();
|
||||||
|
recent.retain(|p| p != path);
|
||||||
|
recent.insert(0, path.to_path_buf());
|
||||||
|
recent.truncate(MAX_RECENT_FILES);
|
||||||
|
save_recent_files(&recent);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn forget_recent_file(files: &Arc<Mutex<Vec<PathBuf>>>, path: &Path) -> bool {
|
||||||
|
let mut recent = files.lock().unwrap();
|
||||||
|
let original_len = recent.len();
|
||||||
|
recent.retain(|p| p != path);
|
||||||
|
if recent.len() == original_len {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
save_recent_files(&recent);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_supported_document(path: &Path) -> bool {
|
||||||
|
path.extension()
|
||||||
|
.map(|extension| {
|
||||||
|
matches!(
|
||||||
|
extension.to_string_lossy().to_ascii_lowercase().as_str(),
|
||||||
|
"md" | "markdown" | "mdown" | "mkd"
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reveal_in_explorer(path: &Path) -> bool {
|
||||||
|
let mut command = std::process::Command::new("explorer.exe");
|
||||||
|
if path.is_file() {
|
||||||
|
command.arg("/select,").arg(path);
|
||||||
|
} else if let Some(parent) = path.parent().filter(|parent| parent.is_dir()) {
|
||||||
|
command.arg(parent);
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
command.spawn().is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolve_document_link(value: &str, active: Option<&Path>) -> Option<PathBuf> {
|
||||||
|
let url = match url::Url::parse(value) {
|
||||||
|
Ok(url) => url,
|
||||||
|
Err(url::ParseError::RelativeUrlWithoutBase) => {
|
||||||
|
url::Url::from_file_path(active?).ok()?.join(value).ok()?
|
||||||
|
}
|
||||||
|
Err(_) => return None,
|
||||||
|
};
|
||||||
|
local_document_path_from_url(url.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn local_document_path_from_url(value: &str) -> Option<PathBuf> {
|
||||||
|
let url = url::Url::parse(value).ok()?;
|
||||||
|
if url.scheme() != "file" {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let path = url.to_file_path().ok()?;
|
||||||
|
if !path.is_file() || !is_supported_document(&path) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
fs::canonicalize(path).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn watch_scope_for_file(path: &Path) -> &Path {
|
||||||
|
path.parent()
|
||||||
|
.filter(|parent| !parent.as_os_str().is_empty())
|
||||||
|
.unwrap_or(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn event_path_matches_file(event_path: &Path, target: &Path) -> bool {
|
||||||
|
event_path == target
|
||||||
|
|| (target.file_name().is_some()
|
||||||
|
&& event_path.file_name() == target.file_name()
|
||||||
|
&& event_path.parent() == target.parent())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn event_should_reload_file(ev: &Event, target: &Path) -> bool {
|
||||||
|
if ev.need_rescan() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !(ev.kind.is_modify() || ev.kind.is_create() || ev.kind.is_remove()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ev.paths
|
||||||
|
.iter()
|
||||||
|
.any(|event_path| event_path_matches_file(event_path, target))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Watch the active file's directory and turn real external changes into
|
||||||
|
/// `FileChanged` events. Watches only the parent directory, so sibling edits
|
||||||
|
/// still arrive and get filtered by [`event_should_reload_file`].
|
||||||
|
pub fn install_file_watcher(
|
||||||
|
holder: &Arc<Mutex<Option<notify::RecommendedWatcher>>>,
|
||||||
|
proxy: &EventLoopProxy<UserEvent>,
|
||||||
|
last_self_write: &Arc<Mutex<Option<SelfWriteRecord>>>,
|
||||||
|
window_id: WindowId,
|
||||||
|
path: Option<PathBuf>,
|
||||||
|
) {
|
||||||
|
let mut current = holder.lock().unwrap();
|
||||||
|
*current = None;
|
||||||
|
*last_self_write.lock().unwrap() = None;
|
||||||
|
let Some(path) = path else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let mut observed_content = fs::read(&path).ok();
|
||||||
|
let target_path = path.clone();
|
||||||
|
let callback_path = path.clone();
|
||||||
|
let proxy = proxy.clone();
|
||||||
|
let last_self_write = Arc::clone(last_self_write);
|
||||||
|
if let Ok(mut watcher) = notify::recommended_watcher(move |result: Result<Event, _>| {
|
||||||
|
if let Ok(event) = result {
|
||||||
|
if event_should_reload_file(&event, &callback_path) {
|
||||||
|
let content = fs::read(&callback_path).ok();
|
||||||
|
let mut last_self_write = last_self_write.lock().unwrap();
|
||||||
|
if file_content_should_reload(
|
||||||
|
&callback_path,
|
||||||
|
content,
|
||||||
|
&mut observed_content,
|
||||||
|
&mut last_self_write,
|
||||||
|
) {
|
||||||
|
let _ =
|
||||||
|
proxy.send_event(UserEvent::FileChanged(window_id, callback_path.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}) {
|
||||||
|
let scope = watch_scope_for_file(&target_path);
|
||||||
|
if scope.exists() && watcher.watch(scope, RecursiveMode::NonRecursive).is_ok() {
|
||||||
|
*current = Some(watcher);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn file_content_should_reload(
|
||||||
|
path: &Path,
|
||||||
|
content: Option<Vec<u8>>,
|
||||||
|
observed: &mut Option<Vec<u8>>,
|
||||||
|
last_self_write: &mut Option<SelfWriteRecord>,
|
||||||
|
) -> bool {
|
||||||
|
if content == *observed {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let is_self_write = last_self_write.as_ref().is_some_and(|record| {
|
||||||
|
record.path == path && content.as_deref() == Some(record.content.as_bytes())
|
||||||
|
});
|
||||||
|
*observed = content;
|
||||||
|
if is_self_write {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// A subsequent revert to our old snapshot is a real change too.
|
||||||
|
if observed.is_some() {
|
||||||
|
*last_self_write = None;
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn self_write_still_matches_disk(record: Option<&SelfWriteRecord>, path: &Path) -> bool {
|
||||||
|
let Some(record) = record else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
record.path == path
|
||||||
|
&& fs::read(path)
|
||||||
|
.map(|content| content == record.content.as_bytes())
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn should_protect_external_change(webview_dirty: bool, session_dirty: bool) -> bool {
|
||||||
|
webview_dirty || session_dirty
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn normalize_new_markdown_path(mut path: PathBuf) -> PathBuf {
|
||||||
|
if !is_supported_document(&path) {
|
||||||
|
path.set_extension("md");
|
||||||
|
}
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write the active tab's file and remember the write as our own so the file
|
||||||
|
/// watcher does not treat it as an external change. Returns false when nothing
|
||||||
|
/// was written (no active file, or the write failed and SaveFailed was sent).
|
||||||
|
pub fn save_active_file(
|
||||||
|
session: &Arc<Mutex<DocumentSession>>,
|
||||||
|
last_self_write: &Arc<Mutex<Option<SelfWriteRecord>>>,
|
||||||
|
proxy: &EventLoopProxy<UserEvent>,
|
||||||
|
window_id: WindowId,
|
||||||
|
content: &str,
|
||||||
|
) -> bool {
|
||||||
|
let Some(path) = session.lock().unwrap().active_path().map(Path::to_path_buf) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
*last_self_write.lock().unwrap() = Some(SelfWriteRecord {
|
||||||
|
path: path.clone(),
|
||||||
|
content: content.to_string(),
|
||||||
|
});
|
||||||
|
match fs::write(&path, content) {
|
||||||
|
Ok(()) => {
|
||||||
|
let _ = proxy.send_event(UserEvent::FileSaved(window_id, path));
|
||||||
|
true
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
let _ = proxy.send_event(UserEvent::SaveFailed(window_id, path, error.to_string()));
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::testutil::temp_dir;
|
||||||
|
use notify::EventKind;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_markdown_extensions_are_supported_documents() {
|
||||||
|
for name in ["note.md", "note.MARKDOWN", "note.mdown", "note.mkd"] {
|
||||||
|
assert!(is_supported_document(Path::new(name)), "{name}");
|
||||||
|
}
|
||||||
|
for name in ["note.txt", "note.html", "note", "note.md.bak"] {
|
||||||
|
assert!(!is_supported_document(Path::new(name)), "{name}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn file_urls_only_open_existing_supported_documents() {
|
||||||
|
let dir = temp_dir("document-links");
|
||||||
|
let linked = dir.join("含 空格.md");
|
||||||
|
let unsupported = dir.join("page.html");
|
||||||
|
fs::write(&linked, "# Linked").unwrap();
|
||||||
|
fs::write(&unsupported, "<h1>Page</h1>").unwrap();
|
||||||
|
|
||||||
|
let linked_url = url::Url::from_file_path(&linked).unwrap().to_string();
|
||||||
|
let unsupported_url = url::Url::from_file_path(&unsupported).unwrap().to_string();
|
||||||
|
let missing_url = url::Url::from_file_path(dir.join("missing.md"))
|
||||||
|
.unwrap()
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
local_document_path_from_url(&format!("{linked_url}#section")),
|
||||||
|
Some(fs::canonicalize(&linked).unwrap())
|
||||||
|
);
|
||||||
|
assert_eq!(local_document_path_from_url(&unsupported_url), None);
|
||||||
|
assert_eq!(local_document_path_from_url(&missing_url), None);
|
||||||
|
assert_eq!(
|
||||||
|
local_document_path_from_url("https://example.com/readme.md"),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
let _ = fs::remove_dir_all(dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn document_links_resolve_against_active_file_without_webview_base() {
|
||||||
|
let dir = temp_dir("relative-doc-links");
|
||||||
|
fs::create_dir_all(dir.join("folder")).unwrap();
|
||||||
|
let active = dir.join("folder/current.md");
|
||||||
|
let linked = dir.join("含 空格.md");
|
||||||
|
fs::write(&linked, "# Linked").unwrap();
|
||||||
|
let expected = Some(fs::canonicalize(&linked).unwrap());
|
||||||
|
assert_eq!(
|
||||||
|
resolve_document_link("../含%20空格.md#section", Some(&active)),
|
||||||
|
expected
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
resolve_document_link("../含 空格.md", Some(&active)),
|
||||||
|
expected
|
||||||
|
);
|
||||||
|
assert_eq!(resolve_document_link("missing.md", Some(&active)), None);
|
||||||
|
assert_eq!(
|
||||||
|
resolve_document_link("https://example.com/file.md", Some(&active)),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
assert_eq!(resolve_document_link("../", Some(&active)), None);
|
||||||
|
assert_eq!(resolve_document_link("relative.md", None), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn new_markdown_path_keeps_markdown_extensions_and_replaces_other_extensions() {
|
||||||
|
assert_eq!(
|
||||||
|
normalize_new_markdown_path(PathBuf::from("/tmp/plan")),
|
||||||
|
PathBuf::from("/tmp/plan.md")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
normalize_new_markdown_path(PathBuf::from("/tmp/plan.markdown")),
|
||||||
|
PathBuf::from("/tmp/plan.markdown")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
normalize_new_markdown_path(PathBuf::from("/tmp/plan.txt")),
|
||||||
|
PathBuf::from("/tmp/plan.md")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vim_style_target_rewrite_events_reload_current_file() {
|
||||||
|
let target = PathBuf::from("/tmp/note.md");
|
||||||
|
let ev = Event::new(EventKind::Create(notify::event::CreateKind::File))
|
||||||
|
.add_path(PathBuf::from("/tmp/note.md"));
|
||||||
|
|
||||||
|
assert!(event_should_reload_file(&ev, &target));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sibling_file_events_do_not_reload_current_file() {
|
||||||
|
let target = PathBuf::from("/tmp/note.md");
|
||||||
|
let ev = Event::new(EventKind::Modify(notify::event::ModifyKind::Data(
|
||||||
|
notify::event::DataChange::Any,
|
||||||
|
)))
|
||||||
|
.add_path(PathBuf::from("/tmp/other.md"));
|
||||||
|
|
||||||
|
assert!(!event_should_reload_file(&ev, &target));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn self_write_suppression_checks_disk_content_not_only_time() {
|
||||||
|
let dir = temp_dir("self-write-suppression");
|
||||||
|
let path = dir.join("note.md");
|
||||||
|
fs::write(&path, "saved by app").unwrap();
|
||||||
|
let record = SelfWriteRecord {
|
||||||
|
path: path.clone(),
|
||||||
|
content: "saved by app".to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(self_write_still_matches_disk(Some(&record), &path));
|
||||||
|
|
||||||
|
fs::write(&path, "external edit").unwrap();
|
||||||
|
assert!(!self_write_still_matches_disk(Some(&record), &path));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sync_events_ignore_identical_bytes_but_detect_external_edits_and_reverts() {
|
||||||
|
let path = PathBuf::from("note.md");
|
||||||
|
let mut observed = Some(b"initial".to_vec());
|
||||||
|
let mut own = Some(SelfWriteRecord {
|
||||||
|
path: path.clone(),
|
||||||
|
content: "saved".to_string(),
|
||||||
|
});
|
||||||
|
assert!(!file_content_should_reload(
|
||||||
|
&path,
|
||||||
|
Some(b"initial".to_vec()),
|
||||||
|
&mut observed,
|
||||||
|
&mut own
|
||||||
|
));
|
||||||
|
assert!(!file_content_should_reload(
|
||||||
|
&path,
|
||||||
|
Some(b"saved".to_vec()),
|
||||||
|
&mut observed,
|
||||||
|
&mut own
|
||||||
|
));
|
||||||
|
for _ in 0..100 {
|
||||||
|
assert!(!file_content_should_reload(
|
||||||
|
&path,
|
||||||
|
Some(b"saved".to_vec()),
|
||||||
|
&mut observed,
|
||||||
|
&mut own
|
||||||
|
));
|
||||||
|
}
|
||||||
|
assert!(file_content_should_reload(
|
||||||
|
&path,
|
||||||
|
Some(b"external".to_vec()),
|
||||||
|
&mut observed,
|
||||||
|
&mut own
|
||||||
|
));
|
||||||
|
assert!(file_content_should_reload(
|
||||||
|
&path,
|
||||||
|
Some(b"saved".to_vec()),
|
||||||
|
&mut observed,
|
||||||
|
&mut own
|
||||||
|
));
|
||||||
|
assert!(file_content_should_reload(
|
||||||
|
&path,
|
||||||
|
None,
|
||||||
|
&mut observed,
|
||||||
|
&mut own
|
||||||
|
));
|
||||||
|
assert!(file_content_should_reload(
|
||||||
|
&path,
|
||||||
|
Some(b"saved".to_vec()),
|
||||||
|
&mut observed,
|
||||||
|
&mut own
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn external_change_protection_uses_dirty_state_from_either_side() {
|
||||||
|
assert!(!should_protect_external_change(false, false));
|
||||||
|
assert!(should_protect_external_change(true, false));
|
||||||
|
assert!(should_protect_external_change(false, true));
|
||||||
|
assert!(should_protect_external_change(true, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn file_watch_scope_is_parent_directory() {
|
||||||
|
let target = PathBuf::from("/tmp/note.md");
|
||||||
|
|
||||||
|
assert_eq!(watch_scope_for_file(&target), Path::new("/tmp"));
|
||||||
|
}
|
||||||
|
}
|
||||||
5464
src/main.rs
5464
src/main.rs
File diff suppressed because it is too large
Load Diff
628
src/markdown.rs
Normal file
628
src/markdown.rs
Normal file
@@ -0,0 +1,628 @@
|
|||||||
|
//! Markdown -> HTML pipeline.
|
||||||
|
//!
|
||||||
|
//! GFM plus the app's deliberate dialect: single newlines are visible line
|
||||||
|
//! breaks (AI output), front matter is split off, local images are embedded as
|
||||||
|
//! data URLs, ==highlight== becomes <mark>, and headings get stable ids for
|
||||||
|
//! folding and anchor navigation.
|
||||||
|
|
||||||
|
use crate::escape::html_escape_text;
|
||||||
|
use pulldown_cmark::{html, CowStr, Event as MdEvent, Options, Parser, Tag, TagEnd};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Component, Path, PathBuf};
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub fn md_to_html(md: &str) -> String {
|
||||||
|
md_to_html_with_base(md, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn md_to_html_with_base(md: &str, base_dir: Option<&Path>) -> String {
|
||||||
|
// A UTF-8 BOM is legal in files but not part of Markdown syntax. Strip it
|
||||||
|
// before front-matter detection so both `---` metadata and a leading
|
||||||
|
// heading still parse.
|
||||||
|
let md = md.strip_prefix('\u{feff}').unwrap_or(md);
|
||||||
|
let (front_matter, markdown) = split_yaml_front_matter(md)
|
||||||
|
.map(|(metadata, body)| (Some(metadata), body))
|
||||||
|
.unwrap_or((None, md));
|
||||||
|
let opts = Options::ENABLE_TABLES
|
||||||
|
| Options::ENABLE_STRIKETHROUGH
|
||||||
|
| Options::ENABLE_TASKLISTS
|
||||||
|
| Options::ENABLE_HEADING_ATTRIBUTES
|
||||||
|
| Options::ENABLE_MATH
|
||||||
|
| Options::ENABLE_GFM
|
||||||
|
| Options::ENABLE_FOOTNOTES
|
||||||
|
| Options::ENABLE_DEFINITION_LIST;
|
||||||
|
let parser = Parser::new_ext(markdown, opts);
|
||||||
|
let events = render_softbreaks_as_hard(embed_local_images(
|
||||||
|
add_mark_highlights(add_heading_ids(parser.collect())),
|
||||||
|
base_dir,
|
||||||
|
));
|
||||||
|
let mut html_out = String::new();
|
||||||
|
if let Some(metadata) = front_matter {
|
||||||
|
html_out.push_str(r#"<aside class="front-matter"><pre>"#);
|
||||||
|
html_out.push_str(&html_escape_text(metadata.trim_end_matches(['\r', '\n'])));
|
||||||
|
html_out.push_str("</pre></aside>\n");
|
||||||
|
}
|
||||||
|
html::push_html(&mut html_out, events.into_iter());
|
||||||
|
html_out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AI-generated Markdown often uses a single newline as a visual line break.
|
||||||
|
/// Treat those soft breaks as hard breaks in normal prose, but keep headings
|
||||||
|
/// untouched: a multi-line setext heading should stay one visual line.
|
||||||
|
fn render_softbreaks_as_hard<'a>(events: Vec<MdEvent<'a>>) -> Vec<MdEvent<'a>> {
|
||||||
|
let mut heading_depth = 0usize;
|
||||||
|
let mut out = Vec::with_capacity(events.len());
|
||||||
|
for event in events {
|
||||||
|
match &event {
|
||||||
|
MdEvent::Start(Tag::Heading { .. }) => heading_depth += 1,
|
||||||
|
MdEvent::End(TagEnd::Heading(_)) => {
|
||||||
|
heading_depth = heading_depth.saturating_sub(1);
|
||||||
|
}
|
||||||
|
MdEvent::SoftBreak if heading_depth == 0 => {
|
||||||
|
out.push(MdEvent::HardBreak);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
out.push(event);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn split_yaml_front_matter(md: &str) -> Option<(&str, &str)> {
|
||||||
|
let mut lines = md.split_inclusive('\n');
|
||||||
|
let first = lines.next()?;
|
||||||
|
if first.trim_end_matches(['\r', '\n']) != "---" {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let metadata_start = first.len();
|
||||||
|
let mut offset = metadata_start;
|
||||||
|
for line in lines {
|
||||||
|
let value = line.trim_end_matches(['\r', '\n']);
|
||||||
|
if value == "---" || value == "..." {
|
||||||
|
let metadata = &md[metadata_start..offset];
|
||||||
|
let body = &md[offset + line.len()..];
|
||||||
|
return Some((metadata, body));
|
||||||
|
}
|
||||||
|
offset += line.len();
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn embed_local_images<'a>(events: Vec<MdEvent<'a>>, base_dir: Option<&Path>) -> Vec<MdEvent<'a>> {
|
||||||
|
let Some(base_dir) = base_dir else {
|
||||||
|
return events;
|
||||||
|
};
|
||||||
|
|
||||||
|
events
|
||||||
|
.into_iter()
|
||||||
|
.map(|event| match event {
|
||||||
|
MdEvent::Start(Tag::Image {
|
||||||
|
link_type,
|
||||||
|
dest_url,
|
||||||
|
title,
|
||||||
|
id,
|
||||||
|
}) => {
|
||||||
|
let embedded = local_image_data_url(base_dir, dest_url.as_ref());
|
||||||
|
MdEvent::Start(Tag::Image {
|
||||||
|
link_type,
|
||||||
|
dest_url: embedded.map(CowStr::from).unwrap_or(dest_url),
|
||||||
|
title,
|
||||||
|
id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
_ => event,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn local_image_data_url(base_dir: &Path, url: &str) -> Option<String> {
|
||||||
|
let image_path = resolve_local_relative_image_path(base_dir, url)?;
|
||||||
|
let mime = image_mime_type(&image_path)?;
|
||||||
|
let bytes = fs::read(image_path).ok()?;
|
||||||
|
Some(format!("data:{mime};base64,{}", base64_encode(&bytes)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_local_relative_image_path(base_dir: &Path, url: &str) -> Option<PathBuf> {
|
||||||
|
let path_part = url.split(['#', '?']).next()?.trim();
|
||||||
|
if !is_local_relative_url(path_part) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut candidate = base_dir.to_path_buf();
|
||||||
|
for segment in path_part.split('/') {
|
||||||
|
if segment.is_empty() || segment == "." {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let decoded = percent_decode_path_segment(segment)?;
|
||||||
|
let segment_path = Path::new(&decoded);
|
||||||
|
if segment_path
|
||||||
|
.components()
|
||||||
|
.any(|component| !matches!(component, Component::Normal(_)))
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
candidate.push(segment_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
if candidate == base_dir {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(candidate)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_local_relative_url(url: &str) -> bool {
|
||||||
|
!url.is_empty()
|
||||||
|
&& !url.starts_with('#')
|
||||||
|
&& !url.starts_with('/')
|
||||||
|
&& !url.starts_with('\\')
|
||||||
|
&& !url.starts_with("//")
|
||||||
|
&& !url.contains(':')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn percent_decode_path_segment(segment: &str) -> Option<String> {
|
||||||
|
let bytes = segment.as_bytes();
|
||||||
|
let mut out = Vec::with_capacity(bytes.len());
|
||||||
|
let mut i = 0;
|
||||||
|
while i < bytes.len() {
|
||||||
|
if bytes[i] == b'%' {
|
||||||
|
let hi = bytes.get(i + 1).and_then(|b| hex_value(*b))?;
|
||||||
|
let lo = bytes.get(i + 2).and_then(|b| hex_value(*b))?;
|
||||||
|
out.push((hi << 4) | lo);
|
||||||
|
i += 3;
|
||||||
|
} else {
|
||||||
|
out.push(bytes[i]);
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String::from_utf8(out).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hex_value(byte: u8) -> Option<u8> {
|
||||||
|
match byte {
|
||||||
|
b'0'..=b'9' => Some(byte - b'0'),
|
||||||
|
b'a'..=b'f' => Some(byte - b'a' + 10),
|
||||||
|
b'A'..=b'F' => Some(byte - b'A' + 10),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn image_mime_type(path: &Path) -> Option<&'static str> {
|
||||||
|
match path
|
||||||
|
.extension()?
|
||||||
|
.to_string_lossy()
|
||||||
|
.to_ascii_lowercase()
|
||||||
|
.as_str()
|
||||||
|
{
|
||||||
|
"png" => Some("image/png"),
|
||||||
|
"jpg" | "jpeg" => Some("image/jpeg"),
|
||||||
|
"gif" => Some("image/gif"),
|
||||||
|
"webp" => Some("image/webp"),
|
||||||
|
"svg" => Some("image/svg+xml"),
|
||||||
|
"bmp" => Some("image/bmp"),
|
||||||
|
"ico" => Some("image/x-icon"),
|
||||||
|
"avif" => Some("image/avif"),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn base64_encode(bytes: &[u8]) -> String {
|
||||||
|
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
|
||||||
|
let mut index = 0;
|
||||||
|
while index + 3 <= bytes.len() {
|
||||||
|
let n = ((bytes[index] as u32) << 16)
|
||||||
|
| ((bytes[index + 1] as u32) << 8)
|
||||||
|
| bytes[index + 2] as u32;
|
||||||
|
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
|
||||||
|
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
|
||||||
|
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
|
||||||
|
out.push(TABLE[(n & 0x3f) as usize] as char);
|
||||||
|
index += 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
match &bytes[index..] {
|
||||||
|
[a] => {
|
||||||
|
let n = (*a as u32) << 16;
|
||||||
|
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
|
||||||
|
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
|
||||||
|
out.push('=');
|
||||||
|
out.push('=');
|
||||||
|
}
|
||||||
|
[a, b] => {
|
||||||
|
let n = ((*a as u32) << 16) | ((*b as u32) << 8);
|
||||||
|
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
|
||||||
|
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
|
||||||
|
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
|
||||||
|
out.push('=');
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_mark_highlights<'a>(events: Vec<MdEvent<'a>>) -> Vec<MdEvent<'a>> {
|
||||||
|
let mut out = Vec::with_capacity(events.len());
|
||||||
|
let mut code_block_depth = 0usize;
|
||||||
|
|
||||||
|
for event in events {
|
||||||
|
match &event {
|
||||||
|
MdEvent::Start(Tag::CodeBlock(_)) => code_block_depth += 1,
|
||||||
|
MdEvent::End(TagEnd::CodeBlock) => {
|
||||||
|
code_block_depth = code_block_depth.saturating_sub(1);
|
||||||
|
}
|
||||||
|
MdEvent::Text(text) if code_block_depth == 0 && text.contains("==") => {
|
||||||
|
push_mark_highlight_events(text.as_ref(), &mut out);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
out.push(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_mark_highlight_events<'a>(text: &str, out: &mut Vec<MdEvent<'a>>) {
|
||||||
|
let mut rest = text;
|
||||||
|
|
||||||
|
while let Some(open) = rest.find("==") {
|
||||||
|
let after_open = open + 2;
|
||||||
|
let Some(close_rel) = rest[after_open..].find("==") else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
let close = after_open + close_rel;
|
||||||
|
let body = &rest[after_open..close];
|
||||||
|
if body.trim().is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if open > 0 {
|
||||||
|
out.push(MdEvent::Text(CowStr::Boxed(
|
||||||
|
rest[..open].to_string().into_boxed_str(),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
out.push(MdEvent::Html(CowStr::Borrowed(
|
||||||
|
r#"<mark class="mdp-mark">"#,
|
||||||
|
)));
|
||||||
|
out.push(MdEvent::Text(CowStr::Boxed(
|
||||||
|
body.to_string().into_boxed_str(),
|
||||||
|
)));
|
||||||
|
out.push(MdEvent::Html(CowStr::Borrowed("</mark>")));
|
||||||
|
rest = &rest[close + 2..];
|
||||||
|
}
|
||||||
|
|
||||||
|
if !rest.is_empty() {
|
||||||
|
out.push(MdEvent::Text(CowStr::Boxed(
|
||||||
|
rest.to_string().into_boxed_str(),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_heading_ids<'a>(mut events: Vec<MdEvent<'a>>) -> Vec<MdEvent<'a>> {
|
||||||
|
let mut seen: HashMap<String, usize> = HashMap::new();
|
||||||
|
|
||||||
|
for i in 0..events.len() {
|
||||||
|
let generate_id = match &events[i] {
|
||||||
|
MdEvent::Start(Tag::Heading { id: Some(id), .. }) => {
|
||||||
|
register_heading_id(id.as_ref(), &mut seen);
|
||||||
|
false
|
||||||
|
}
|
||||||
|
MdEvent::Start(Tag::Heading { id: None, .. }) => true,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
|
||||||
|
if !generate_id {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let text = collect_heading_text(&events, i);
|
||||||
|
let base = heading_slug(&text);
|
||||||
|
let id_value = unique_heading_id(base, &mut seen);
|
||||||
|
if let MdEvent::Start(Tag::Heading { id, .. }) = &mut events[i] {
|
||||||
|
*id = Some(CowStr::Boxed(id_value.into_boxed_str()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
events
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_heading_text(events: &[MdEvent<'_>], start: usize) -> String {
|
||||||
|
let mut text = String::new();
|
||||||
|
|
||||||
|
for event in events.iter().skip(start + 1) {
|
||||||
|
match event {
|
||||||
|
MdEvent::End(TagEnd::Heading(_)) => break,
|
||||||
|
MdEvent::Text(value)
|
||||||
|
| MdEvent::Code(value)
|
||||||
|
| MdEvent::InlineMath(value)
|
||||||
|
| MdEvent::DisplayMath(value) => text.push_str(value.as_ref()),
|
||||||
|
MdEvent::SoftBreak | MdEvent::HardBreak => text.push(' '),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
text
|
||||||
|
}
|
||||||
|
|
||||||
|
fn heading_slug(text: &str) -> String {
|
||||||
|
let mut slug = String::new();
|
||||||
|
let mut last_dash = false;
|
||||||
|
|
||||||
|
for c in text.trim().chars().flat_map(char::to_lowercase) {
|
||||||
|
if c.is_alphanumeric() || c == '_' || c == '-' {
|
||||||
|
slug.push(c);
|
||||||
|
last_dash = false;
|
||||||
|
} else if c.is_whitespace() && !slug.is_empty() && !last_dash {
|
||||||
|
slug.push('-');
|
||||||
|
last_dash = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
while slug.ends_with('-') {
|
||||||
|
slug.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
if slug.is_empty() {
|
||||||
|
"section".to_string()
|
||||||
|
} else {
|
||||||
|
slug
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn register_heading_id(id: &str, seen: &mut HashMap<String, usize>) {
|
||||||
|
if !id.is_empty() {
|
||||||
|
*seen.entry(id.to_string()).or_insert(0) += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unique_heading_id(base: String, seen: &mut HashMap<String, usize>) -> String {
|
||||||
|
let count = seen.entry(base.clone()).or_insert(0);
|
||||||
|
let id = if *count == 0 {
|
||||||
|
base
|
||||||
|
} else {
|
||||||
|
format!("{base}-{count}")
|
||||||
|
};
|
||||||
|
*count += 1;
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::testutil::temp_dir;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn base64_matches_known_vectors() {
|
||||||
|
assert_eq!(base64_encode(b""), "");
|
||||||
|
assert_eq!(base64_encode(b"f"), "Zg==");
|
||||||
|
assert_eq!(base64_encode(b"fo"), "Zm8=");
|
||||||
|
assert_eq!(base64_encode(b"foo"), "Zm9v");
|
||||||
|
assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn dollar_math_is_protected_from_markdown_escapes() {
|
||||||
|
let html = md_to_html(r"$\{x\}$");
|
||||||
|
|
||||||
|
assert!(html.contains(r#"<span class="math math-inline">\{x\}</span>"#));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dollar_math_is_protected_from_markdown_emphasis() {
|
||||||
|
let html = md_to_html(r"$\bar{\mu}_{n}$ and $x_{n}$");
|
||||||
|
|
||||||
|
assert!(html.contains(r#"<span class="math math-inline">\bar{\mu}_{n}</span>"#));
|
||||||
|
assert!(html.contains(r#"<span class="math math-inline">x_{n}</span>"#));
|
||||||
|
assert!(!html.contains("<em>"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn multiline_display_math_is_not_split_by_hard_breaks() {
|
||||||
|
let html = md_to_html("$$\na + b\n$$");
|
||||||
|
|
||||||
|
assert!(html.contains(r#"class="math math-display""#), "{html}");
|
||||||
|
assert!(html.contains("a + b"), "{html}");
|
||||||
|
assert!(!html.contains("<br />"), "{html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn github_alerts_render_as_markdown_alert_blockquotes() {
|
||||||
|
let html = md_to_html("> [!IMPORTANT]\n> This is an alert");
|
||||||
|
|
||||||
|
assert!(html.contains(r#"<blockquote class="markdown-alert-important">"#));
|
||||||
|
assert!(html.contains("<p>This is an alert</p>"));
|
||||||
|
assert!(!html.contains("[!IMPORTANT]"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn soft_breaks_render_as_hard_breaks_in_paragraphs() {
|
||||||
|
let html = md_to_html("2.1 默认只读讨论。\n2.2 默认工作流:先读代码。");
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
html.contains("2.1 默认只读讨论。<br />\n2.2 默认工作流"),
|
||||||
|
"{html}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn blank_lines_still_create_paragraphs() {
|
||||||
|
let html = md_to_html("first line\n\nsecond line");
|
||||||
|
|
||||||
|
assert_eq!(html.matches("<p>").count(), 2, "{html}");
|
||||||
|
assert!(!html.contains("<br />"), "{html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn soft_breaks_inside_headings_stay_soft() {
|
||||||
|
let html = md_to_html("First heading line\nsecond heading line\n===");
|
||||||
|
|
||||||
|
assert!(html.contains("<h1"), "{html}");
|
||||||
|
assert!(!html.contains("<br />"), "{html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn soft_breaks_in_list_items_become_hard_breaks() {
|
||||||
|
let html = md_to_html("- first line\n second line");
|
||||||
|
|
||||||
|
assert!(html.contains("<li>first line<br />"), "{html}");
|
||||||
|
assert!(html.contains("second line</li>"), "{html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn code_blocks_keep_newlines_without_br() {
|
||||||
|
let html = md_to_html("~~~text\nline one\nline two\n~~~");
|
||||||
|
|
||||||
|
assert!(!html.contains("<br />"), "{html}");
|
||||||
|
assert!(html.contains("line one\nline two"), "{html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gfm_footnotes_render_reference_and_definition() {
|
||||||
|
let html = md_to_html("Text with a note[^1].\n\n[^1]: The footnote body.");
|
||||||
|
|
||||||
|
assert!(html.contains(r#"class="footnote-reference""#), "{html}");
|
||||||
|
assert!(html.contains(r#"class="footnote-definition""#), "{html}");
|
||||||
|
assert!(html.contains("The footnote body."), "{html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn definition_lists_render_as_dl_dt_dd() {
|
||||||
|
let html = md_to_html("Term\n: Definition");
|
||||||
|
|
||||||
|
assert!(html.contains("<dl>"), "{html}");
|
||||||
|
assert!(html.contains("<dt>Term</dt>"), "{html}");
|
||||||
|
assert!(html.contains("<dd>Definition</dd>"), "{html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn utf8_bom_is_ignored_before_heading_and_front_matter() {
|
||||||
|
let heading = md_to_html("\u{feff}# BOM heading");
|
||||||
|
assert!(
|
||||||
|
heading.contains(r#"<h1 id="bom-heading">BOM heading</h1>"#),
|
||||||
|
"{heading}"
|
||||||
|
);
|
||||||
|
|
||||||
|
let front_matter = md_to_html("\u{feff}---\ntitle: BOM\n---\n# Body");
|
||||||
|
assert!(
|
||||||
|
front_matter.contains(r#"class="front-matter""#),
|
||||||
|
"{front_matter}"
|
||||||
|
);
|
||||||
|
assert!(front_matter.contains("title: BOM"), "{front_matter}");
|
||||||
|
assert!(
|
||||||
|
front_matter.contains(r#"<h1 id="body">Body</h1>"#),
|
||||||
|
"{front_matter}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn double_equals_highlight_renders_mark_without_touching_code() {
|
||||||
|
let html = md_to_html("Use ==highlight & tag== here and `==literal==` there.");
|
||||||
|
|
||||||
|
assert!(html.contains(r#"Use <mark class="mdp-mark">highlight & tag</mark> here"#));
|
||||||
|
assert!(html.contains("<code>==literal==</code>"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fenced_code_blocks_keep_double_equals_literal() {
|
||||||
|
let html = md_to_html("```csharp\nif (m_Profile == null) {\n return a == b;\n}\n```");
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
html.contains("m_Profile == null"),
|
||||||
|
"comparison must stay literal"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
html.contains("a == b"),
|
||||||
|
"every comparison must be preserved"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!html.contains("mdp-mark"),
|
||||||
|
"code blocks must not get highlight markup"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_relative_images_are_embedded_from_markdown_directory() {
|
||||||
|
let dir = temp_dir("local-image");
|
||||||
|
let assets = dir.join("assets");
|
||||||
|
fs::create_dir_all(&assets).unwrap();
|
||||||
|
fs::write(assets.join("pixel.png"), b"abc").unwrap();
|
||||||
|
|
||||||
|
let html = md_to_html_with_base("", Some(&dir));
|
||||||
|
|
||||||
|
assert!(html.contains(r#"<img src="data:image/png;base64,YWJj" alt="pixel" />"#));
|
||||||
|
let _ = fs::remove_dir_all(dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_relative_images_keep_original_src_when_unreadable() {
|
||||||
|
let dir = temp_dir("missing-image");
|
||||||
|
|
||||||
|
let html = md_to_html_with_base("", Some(&dir));
|
||||||
|
|
||||||
|
assert!(html.contains(r#"<img src="assets/missing.png" alt="missing" />"#));
|
||||||
|
let _ = fs::remove_dir_all(dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_relative_images_do_not_embed_parent_traversal() {
|
||||||
|
let dir = temp_dir("traversal-image");
|
||||||
|
|
||||||
|
let html = md_to_html_with_base("", Some(&dir));
|
||||||
|
|
||||||
|
assert!(html.contains(r#"<img src="../secret.png" alt="secret" />"#));
|
||||||
|
assert!(!html.contains("data:image/png"));
|
||||||
|
let _ = fs::remove_dir_all(dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn yaml_front_matter_keeps_metadata_readable_without_blank_lines() {
|
||||||
|
let html = md_to_html(
|
||||||
|
"---\nname: skill-creator-lite\ndescription: Skill 创建封装工具。\n---\n# Body",
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(html.contains(r#"<aside class="front-matter">"#));
|
||||||
|
assert!(html.contains("name: skill-creator-lite"));
|
||||||
|
assert!(html.contains("description: Skill 创建封装工具。"));
|
||||||
|
assert!(html.contains("<h1 id=\"body\">Body</h1>"));
|
||||||
|
assert!(!html.contains("<h2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn yaml_front_matter_accepts_dots_and_escapes_html() {
|
||||||
|
let html = md_to_html("---\ntitle: <script>alert(1)</script>\n...\nParagraph");
|
||||||
|
|
||||||
|
assert!(html.contains("title: <script>alert(1)</script>"));
|
||||||
|
assert!(!html.contains("<script>alert(1)</script>"));
|
||||||
|
assert!(html.contains("<p>Paragraph</p>"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn horizontal_rules_and_setext_headings_are_not_front_matter() {
|
||||||
|
let html = md_to_html("Title\n---\n\nParagraph\n\n---");
|
||||||
|
|
||||||
|
assert!(!html.contains(r#"<aside class="front-matter">"#));
|
||||||
|
assert!(html.contains(r#"<h2 id="title">Title</h2>"#));
|
||||||
|
assert!(html.contains("<hr />"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn generated_heading_ids_support_cjk_anchor_links() {
|
||||||
|
let html = md_to_html("1. [需求概述](#需求概述)\n\n## 需求概述");
|
||||||
|
|
||||||
|
assert!(html.contains(r##"<a href="#%E9%9C%80%E6%B1%82%E6%A6%82%E8%BF%B0">需求概述</a>"##));
|
||||||
|
assert!(html.contains(r#"<h2 id="需求概述">需求概述</h2>"#));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn generated_heading_ids_are_unique_and_keep_explicit_ids() {
|
||||||
|
let html = md_to_html("## Intro\n## Intro\n## Custom {#fixed}\n## Fixed");
|
||||||
|
|
||||||
|
assert!(html.contains(r#"<h2 id="intro">Intro</h2>"#));
|
||||||
|
assert!(html.contains(r#"<h2 id="intro-1">Intro</h2>"#));
|
||||||
|
assert!(html.contains(r#"<h2 id="fixed">Custom</h2>"#));
|
||||||
|
assert!(html.contains(r#"<h2 id="fixed-1">Fixed</h2>"#));
|
||||||
|
}
|
||||||
|
}
|
||||||
259
src/page.rs
Normal file
259
src/page.rs
Normal file
@@ -0,0 +1,259 @@
|
|||||||
|
//! The single in-memory HTML document the webview loads.
|
||||||
|
//!
|
||||||
|
//! Markup, CSS and JS live in `assets/page/`; this module fills the
|
||||||
|
//! `__MDP_*__` placeholders. Keeping the UI out of the Rust source means
|
||||||
|
//! editing the page no longer requires escaping braces inside a `format!`
|
||||||
|
//! string, and the JS can be syntax-checked as a real file.
|
||||||
|
//!
|
||||||
|
//! User content is substituted last so a document that happens to contain a
|
||||||
|
//! placeholder-looking string is not rewritten by an earlier replacement.
|
||||||
|
|
||||||
|
use crate::app::{EnhanceFlags, Strings};
|
||||||
|
use crate::escape::{escape_js, html_escape_attr, html_escape_ta};
|
||||||
|
|
||||||
|
const PAGE_HTML: &str = include_str!("../assets/page/page.html");
|
||||||
|
const PAGE_CSS: &str = include_str!("../assets/page/page.css");
|
||||||
|
const PAGE_JS: &str = include_str!("../assets/page/page.js");
|
||||||
|
const PREVIEW_ENHANCE_JS: &str = include_str!("../assets/enhance/preview-enhance.js");
|
||||||
|
const HLJS_CODE: &str = include_str!("../assets/hljs/vs-dark.css");
|
||||||
|
|
||||||
|
pub fn build_page(
|
||||||
|
preview_html: &str,
|
||||||
|
raw_md: &str,
|
||||||
|
base_href: Option<&str>,
|
||||||
|
flags: EnhanceFlags,
|
||||||
|
s: &Strings,
|
||||||
|
home: bool,
|
||||||
|
) -> String {
|
||||||
|
let base_tag = base_href
|
||||||
|
.map(|href| format!(r#"<base id="base-href" href="{}">"#, html_escape_attr(href)))
|
||||||
|
.unwrap_or_else(|| r#"<base id="base-href">"#.to_string());
|
||||||
|
|
||||||
|
PAGE_HTML
|
||||||
|
.replace("__MDP_CSS_CODE__", HLJS_CODE)
|
||||||
|
.replace("__MDP_PAGE_CSS__", PAGE_CSS)
|
||||||
|
.replace("__MDP_PAGE_JS__", PAGE_JS)
|
||||||
|
.replace("__MDP_PREVIEW_ENHANCE_JS__", PREVIEW_ENHANCE_JS)
|
||||||
|
.replace("__MDP_BASE_TAG__", &base_tag)
|
||||||
|
.replace("__MDP_BODY_CLASS__", if home { "home" } else { "" })
|
||||||
|
.replace("__MDP_NEW_TAB__", s.new_tab)
|
||||||
|
.replace("__MDP_BTN_OPEN_LOCATION__", s.btn_open_location)
|
||||||
|
.replace("__MDP_BTN_NEW_WINDOW__", s.btn_new_window)
|
||||||
|
.replace("__MDP_BTN_EDIT__", s.btn_edit)
|
||||||
|
.replace("__MDP_BTN_PREVIEW__", s.btn_preview)
|
||||||
|
.replace("__MDP_HOME_TAB__", &escape_js(s.home_tab))
|
||||||
|
.replace("__MDP_FOLD_TOGGLE__", s.fold_toggle)
|
||||||
|
.replace("__MDP_CANNOT_SAVE_JS__", &escape_js(s.cannot_save))
|
||||||
|
.replace("__MDP_BTN_ZOOM__", s.btn_zoom)
|
||||||
|
.replace("__MDP_BTN_ZOOM_OUT__", s.btn_zoom_out)
|
||||||
|
.replace("__MDP_BTN_ZOOM_RESET__", s.btn_zoom_reset)
|
||||||
|
.replace("__MDP_BTN_ZOOM_IN__", s.btn_zoom_in)
|
||||||
|
.replace("__MDP_SEARCH_PLACEHOLDER__", s.search_placeholder)
|
||||||
|
.replace("__MDP_STAT_WORDS_JS__", &escape_js(s.stat_words))
|
||||||
|
.replace("__MDP_STAT_CHARS_JS__", &escape_js(s.stat_chars))
|
||||||
|
.replace(
|
||||||
|
"__MDP_NEEDS_MATH__",
|
||||||
|
if flags.math { "true" } else { "false" },
|
||||||
|
)
|
||||||
|
.replace(
|
||||||
|
"__MDP_NEEDS_MERMAID__",
|
||||||
|
if flags.mermaid { "true" } else { "false" },
|
||||||
|
)
|
||||||
|
.replace("__MDP_PREVIEW_HTML__", preview_html)
|
||||||
|
.replace("__MDP_RAW_MD_ESCAPED__", &html_escape_ta(raw_md))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::app::{EnhanceFlags, Strings};
|
||||||
|
use crate::markdown::md_to_html;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn page_blocks_native_preview_reload_paths() {
|
||||||
|
let strings = Strings::english();
|
||||||
|
let page = build_page(
|
||||||
|
&md_to_html("# Hello"),
|
||||||
|
"# Hello",
|
||||||
|
None,
|
||||||
|
EnhanceFlags::default(),
|
||||||
|
&strings,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(page.contains("document.addEventListener('contextmenu'"));
|
||||||
|
assert!(page.contains("window.ipc.postMessage('refresh')"));
|
||||||
|
assert!(!page.contains("id=\"btn-open\""));
|
||||||
|
assert!(!page.contains("id=\"btn-print\""));
|
||||||
|
assert!(!page.contains("id=\"btn-search\""));
|
||||||
|
assert!(page.contains("window.ipc.postMessage('open')"));
|
||||||
|
assert!(page.contains("window.__mdPreviewOpenFile = openFile"));
|
||||||
|
assert!(page.contains("window.__mdPreviewShowFind = showFind"));
|
||||||
|
assert!(page.contains("window.__mdPreviewToggleEdit"));
|
||||||
|
assert!(page.contains("function selectionSeed()"));
|
||||||
|
assert!(page.contains("showFind(seed ? seed.text : ''"));
|
||||||
|
assert!(page.contains("function findStartIndex(anchorTop)"));
|
||||||
|
assert!(page.contains("return lastAbove >= 0 ? lastAbove : 0"));
|
||||||
|
assert!(page.contains("findInput.focus({ preventScroll: true })"));
|
||||||
|
assert!(page.contains("selectFindHit(findStartIndex(anchorTop), reveal)"));
|
||||||
|
assert!(page.contains("runFindQuery(seed, anchorTop, false)"));
|
||||||
|
assert!(page.contains("var INDENT = ' ';"));
|
||||||
|
assert!(page.contains("insertNewlineWithIndent"));
|
||||||
|
assert!(page.contains("document.execCommand('insertText'"));
|
||||||
|
assert!(page.contains("id=\"hljs-code\""));
|
||||||
|
assert!(page.contains("#preview pre { background: #1e1e1e;"));
|
||||||
|
assert!(!page.contains("hljs-light"));
|
||||||
|
assert!(page.contains("ta.focus({ preventScroll: true })"));
|
||||||
|
assert!(page.contains("window.__setEmptyPreview"));
|
||||||
|
assert!(page.contains("id=\"tabbar\""));
|
||||||
|
assert!(page.contains("window.__setTabs"));
|
||||||
|
assert!(page.contains("tab-action:'));") || page.contains("'tab-action:' + action"));
|
||||||
|
assert!(page.contains("window.__markSaved"));
|
||||||
|
assert!(
|
||||||
|
!page.contains("window.ipc.postMessage('save:' + ta.value);\n\t setDirty(false);")
|
||||||
|
);
|
||||||
|
assert!(page.contains("compositionstart"));
|
||||||
|
assert!(page.contains("e.isComposing"));
|
||||||
|
assert!(page.contains("focusFindInput"));
|
||||||
|
assert!(page.contains("FIND_DEBOUNCE_MS = 300"));
|
||||||
|
assert!(page.contains("document.createTreeWalker(previewEl, NodeFilter.SHOW_TEXT"));
|
||||||
|
assert!(page.contains("mark.className = 'search-hit'"));
|
||||||
|
assert!(page.contains("selectFindHit(currentFindHit + (backward ? -1 : 1))"));
|
||||||
|
assert!(page.contains("#preview mark.search-hit.current"));
|
||||||
|
assert!(page.contains("restoreFindInput(selectionStart, selectionEnd)"));
|
||||||
|
assert!(page.contains("findInput.setSelectionRange(selectionStart, selectionEnd)"));
|
||||||
|
assert!(page.contains("bindAnchorNavigation"));
|
||||||
|
assert!(page.contains("event.target.closest('#preview a[href]')"));
|
||||||
|
assert!(page.contains("window.ipc.postMessage('open-local-link:' + href)"));
|
||||||
|
assert!(page.contains(".markdown-alert-important"));
|
||||||
|
assert!(page.contains(".markdown-alert-title"));
|
||||||
|
let light_alert = page.find("background: #dafbe1").unwrap();
|
||||||
|
let dark_alert = page.rfind("background: #161b22; color: #d4d4d4").unwrap();
|
||||||
|
assert!(dark_alert > light_alert);
|
||||||
|
assert!(page.contains(".mdp-mark"));
|
||||||
|
assert!(!page.contains("Local-first Markdown preview for AI-generated docs"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn page_separates_new_file_from_open_and_debounces_autosave() {
|
||||||
|
let strings = Strings::english();
|
||||||
|
let page = build_page(
|
||||||
|
&md_to_html("# Hello"),
|
||||||
|
"# Hello",
|
||||||
|
None,
|
||||||
|
EnhanceFlags::default(),
|
||||||
|
&strings,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(page.contains("window.ipc.postMessage('new-file')"));
|
||||||
|
assert!(page.contains("tabOpen.addEventListener('click', newTab)"));
|
||||||
|
assert!(!page.contains("tabOpen.addEventListener('click', newFile)"));
|
||||||
|
assert!(!page.contains("tabOpen.addEventListener('click', openFile)"));
|
||||||
|
assert!(page.contains("requestTabAction('new-tab', 0)"));
|
||||||
|
assert!(page.contains("data-new-file"));
|
||||||
|
assert!(page.contains("HIDE_SINGLE_HOME_TAB = true"));
|
||||||
|
assert!(page.contains("tabs.length === 1 && !tabs[0].home"));
|
||||||
|
assert!(page.contains("L_HOME = 'New Tab'"));
|
||||||
|
assert!(
|
||||||
|
page.matches("if (document.body.classList.contains('home')) return;")
|
||||||
|
.count()
|
||||||
|
>= 2
|
||||||
|
);
|
||||||
|
assert!(page.contains("if (tabCount === 1 && isHome) close.hidden = true"));
|
||||||
|
assert!(page.contains("tabMenuNewWindow.disabled = tabCount <= 1 || isHome"));
|
||||||
|
assert!(page.contains("AUTOSAVE_DEBOUNCE_MS = 700"));
|
||||||
|
assert!(page.contains("pendingAutosaveTimer = setTimeout"));
|
||||||
|
assert!(page.contains("window.__markSaved = function(savedRaw)"));
|
||||||
|
assert!(page.contains("window.__markSaveBlocked"));
|
||||||
|
assert!(page.contains("var saveBlocked = false"));
|
||||||
|
assert!(page.contains("window.__mdPreviewCannotSave"));
|
||||||
|
assert!(page.contains("window.__mdPreviewResolveExternalChange"));
|
||||||
|
assert!(page.contains("'external-change:' + (dirty ? 'dirty' : 'clean')"));
|
||||||
|
assert!(page.contains("(e.key === 'n' || e.key === 'N')"));
|
||||||
|
assert!(page.contains("id=\"doc-stats\""));
|
||||||
|
assert!(page.contains("id=\"tab-menu\""));
|
||||||
|
assert!(page.contains("id=\"tab-menu-path\""));
|
||||||
|
assert!(page.contains("id=\"tab-menu-reveal\""));
|
||||||
|
assert!(page.contains("data-tab-path"));
|
||||||
|
assert!(page.contains("function shortenPath"));
|
||||||
|
assert!(page.contains("tabsEl.addEventListener('pointerdown'"));
|
||||||
|
assert!(page.contains("suppressTabClickUntil"));
|
||||||
|
assert!(page.contains("tabCount = tabs.length"));
|
||||||
|
assert!(page.contains("tabMenuNewWindow.disabled = tabCount <= 1"));
|
||||||
|
assert!(page.contains("updateDocumentStats"));
|
||||||
|
assert!(page.contains("restoreScrollProgress"));
|
||||||
|
assert!(page.contains("postMessage('scroll:' + activeTabId"));
|
||||||
|
assert!(page.contains("setEditMode(!!editing)"));
|
||||||
|
assert!(page.contains("postMessage('edit-mode:' + activeTabId"));
|
||||||
|
assert!(page.contains("postMessage('zoom:' + zoomPercent)"));
|
||||||
|
assert!(page.contains("window.__mdPreviewSetZoom"));
|
||||||
|
assert!(page.contains("id=\"btn-zoom-in\""));
|
||||||
|
assert!(page.contains("id=\"btn-zoom-out\""));
|
||||||
|
assert!(page.contains("id=\"btn-zoom-reset\""));
|
||||||
|
assert!(page.contains("var ZOOM_MIN = 50"));
|
||||||
|
assert!(page.contains("var ZOOM_MAX = 300"));
|
||||||
|
assert!(page.contains("var ZOOM_STEP = 5"));
|
||||||
|
assert!(page.contains("ZOOM_WHEEL_THROTTLE_MS = 90"));
|
||||||
|
assert!(page.contains("if (!e.ctrlKey) return;"));
|
||||||
|
assert!(
|
||||||
|
page.contains("window.addEventListener('wheel', onContentWheel, { passive: false })")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn headings_get_hover_fold_toggles() {
|
||||||
|
let strings = Strings::english();
|
||||||
|
let page = build_page(
|
||||||
|
&md_to_html("# A\n\n## B\n\ntext"),
|
||||||
|
"# A\n\n## B\n\ntext",
|
||||||
|
None,
|
||||||
|
EnhanceFlags::default(),
|
||||||
|
&strings,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(page.contains("mdp-fold-toggle"));
|
||||||
|
assert!(page.contains("mdp-fold-body"));
|
||||||
|
assert!(page.contains(".mdp-fold.collapsed > .mdp-fold-body { display: none; }"));
|
||||||
|
assert!(page.contains("window.__mdPreviewFoldLabel"));
|
||||||
|
assert!(page.contains("window.__mdPreviewExpandFold"));
|
||||||
|
assert!(page.contains("sectionizeFolds"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn page_expands_multi_column_tables() {
|
||||||
|
let strings = Strings::english();
|
||||||
|
let page = build_page(
|
||||||
|
&md_to_html("| A | B | C | D |\n|---|---|---|---|\n| 1 | 2 | 3 | 4 |"),
|
||||||
|
"",
|
||||||
|
None,
|
||||||
|
EnhanceFlags::default(),
|
||||||
|
&strings,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(page.contains("mdp-table-wrap"));
|
||||||
|
assert!(page.contains("width: min(calc(100vw - 64px), 1280px)"));
|
||||||
|
assert!(page.contains("if(window.__enhancePreview)window.__enhancePreview();"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closing_the_last_editing_tab_restores_the_empty_preview() {
|
||||||
|
let strings = Strings::english();
|
||||||
|
let page = build_page(
|
||||||
|
&md_to_html("# Hello"),
|
||||||
|
"# Hello",
|
||||||
|
None,
|
||||||
|
EnhanceFlags::default(),
|
||||||
|
&strings,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
let empty_start = page.find("window.__setEmptyPreview = function").unwrap();
|
||||||
|
let missing_start = page.find("window.__setMissing = function").unwrap();
|
||||||
|
let empty_handler = &page[empty_start..missing_start];
|
||||||
|
|
||||||
|
assert!(empty_handler.contains("document.body.classList.add('home')"));
|
||||||
|
assert!(empty_handler.contains("setEditMode(false)"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +1,19 @@
|
|||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
pub struct DocumentTab {
|
pub struct DocumentTab {
|
||||||
pub id: u64,
|
pub id: u64,
|
||||||
/// `None` marks the built-in Home tab; Home has no file on disk.
|
/// `None` marks the built-in Home tab; Home has no file on disk.
|
||||||
pub path: Option<PathBuf>,
|
pub path: Option<PathBuf>,
|
||||||
pub dirty: bool,
|
pub dirty: bool,
|
||||||
pub missing: bool,
|
pub missing: bool,
|
||||||
pub edit_on_open: bool,
|
/// Edit mode belongs to the tab, so switching tabs restores the mode the
|
||||||
|
/// tab was left in instead of carrying one global mode across documents.
|
||||||
|
pub editing: bool,
|
||||||
|
/// Viewport position as a 0.0 (top) ..= 1.0 (bottom) fraction. Stores a
|
||||||
|
/// ratio rather than pixels so zoom and reflow do not move the reader.
|
||||||
|
pub scroll_ratio: f32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DocumentTab {
|
impl DocumentTab {
|
||||||
@@ -37,7 +42,7 @@ impl DocumentSession {
|
|||||||
.find(|tab| tab.path.as_deref() == Some(path.as_path()))
|
.find(|tab| tab.path.as_deref() == Some(path.as_path()))
|
||||||
{
|
{
|
||||||
tab.missing = !path.exists();
|
tab.missing = !path.exists();
|
||||||
tab.edit_on_open |= edit_on_open;
|
tab.editing |= edit_on_open;
|
||||||
self.active_id = Some(tab.id);
|
self.active_id = Some(tab.id);
|
||||||
return tab.id;
|
return tab.id;
|
||||||
}
|
}
|
||||||
@@ -50,7 +55,8 @@ impl DocumentSession {
|
|||||||
path: Some(path),
|
path: Some(path),
|
||||||
dirty: false,
|
dirty: false,
|
||||||
missing,
|
missing,
|
||||||
edit_on_open,
|
editing: edit_on_open,
|
||||||
|
scroll_ratio: 0.0,
|
||||||
});
|
});
|
||||||
self.active_id = Some(id);
|
self.active_id = Some(id);
|
||||||
id
|
id
|
||||||
@@ -65,7 +71,8 @@ impl DocumentSession {
|
|||||||
path: None,
|
path: None,
|
||||||
dirty: false,
|
dirty: false,
|
||||||
missing: false,
|
missing: false,
|
||||||
edit_on_open: false,
|
editing: false,
|
||||||
|
scroll_ratio: 0.0,
|
||||||
});
|
});
|
||||||
self.active_id = Some(id);
|
self.active_id = Some(id);
|
||||||
id
|
id
|
||||||
@@ -92,7 +99,7 @@ impl DocumentSession {
|
|||||||
.find(|tab| tab.id != active_id && tab.path.as_deref() == Some(path.as_path()))
|
.find(|tab| tab.id != active_id && tab.path.as_deref() == Some(path.as_path()))
|
||||||
{
|
{
|
||||||
existing.missing = !path.exists();
|
existing.missing = !path.exists();
|
||||||
existing.edit_on_open |= edit_on_open;
|
existing.editing |= edit_on_open;
|
||||||
let existing_id = existing.id;
|
let existing_id = existing.id;
|
||||||
// The blank tab did its job; drop it the way a browser would.
|
// The blank tab did its job; drop it the way a browser would.
|
||||||
self.tabs.retain(|tab| tab.id != active_id);
|
self.tabs.retain(|tab| tab.id != active_id);
|
||||||
@@ -109,7 +116,8 @@ impl DocumentSession {
|
|||||||
tab.path = Some(path);
|
tab.path = Some(path);
|
||||||
tab.missing = missing;
|
tab.missing = missing;
|
||||||
tab.dirty = false;
|
tab.dirty = false;
|
||||||
tab.edit_on_open = edit_on_open;
|
tab.editing = edit_on_open;
|
||||||
|
tab.scroll_ratio = 0.0;
|
||||||
active_id
|
active_id
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,6 +203,33 @@ impl DocumentSession {
|
|||||||
self.active().is_some_and(DocumentTab::is_home)
|
self.active().is_some_and(DocumentTab::is_home)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Remember the viewport of the active tab (0.0 top .. 1.0 bottom).
|
||||||
|
pub fn set_active_scroll_ratio(&mut self, ratio: f32) {
|
||||||
|
if !ratio.is_finite() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Some(tab) = self.active_mut() {
|
||||||
|
tab.scroll_ratio = ratio.clamp(0.0, 1.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Store the viewport by tab id; late scroll reports must not land on a tab
|
||||||
|
/// that was activated in the meantime.
|
||||||
|
pub fn set_tab_scroll_ratio(&mut self, id: u64, ratio: f32) {
|
||||||
|
if !ratio.is_finite() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Some(tab) = self.get_mut(id) {
|
||||||
|
tab.scroll_ratio = ratio.clamp(0.0, 1.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_tab_editing(&mut self, id: u64, editing: bool) {
|
||||||
|
if let Some(tab) = self.get_mut(id) {
|
||||||
|
tab.editing = editing;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get_mut(&mut self, id: u64) -> Option<&mut DocumentTab> {
|
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)
|
||||||
}
|
}
|
||||||
@@ -285,7 +320,7 @@ mod tests {
|
|||||||
assert_eq!(first, second);
|
assert_eq!(first, second);
|
||||||
assert_eq!(session.tabs.len(), 1);
|
assert_eq!(session.tabs.len(), 1);
|
||||||
assert_eq!(session.active_id, Some(first));
|
assert_eq!(session.active_id, Some(first));
|
||||||
assert!(session.tabs[0].edit_on_open);
|
assert!(session.tabs[0].editing);
|
||||||
let _ = fs::remove_dir_all(dir);
|
let _ = fs::remove_dir_all(dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -354,7 +389,7 @@ mod tests {
|
|||||||
assert_eq!(session.tabs.len(), 1);
|
assert_eq!(session.tabs.len(), 1);
|
||||||
assert!(!session.tabs[0].is_home());
|
assert!(!session.tabs[0].is_home());
|
||||||
assert_eq!(session.tabs[0].file_path(), Some(file.as_path()));
|
assert_eq!(session.tabs[0].file_path(), Some(file.as_path()));
|
||||||
assert!(session.tabs[0].edit_on_open);
|
assert!(session.tabs[0].editing);
|
||||||
let _ = fs::remove_dir_all(dir);
|
let _ = fs::remove_dir_all(dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -404,6 +439,30 @@ mod tests {
|
|||||||
let _ = fs::remove_dir_all(dir);
|
let _ = fs::remove_dir_all(dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn edit_mode_and_scroll_position_are_remembered_per_tab() {
|
||||||
|
let dir = temp_dir("per-tab-view");
|
||||||
|
let mut session = DocumentSession::default();
|
||||||
|
let first = session.open(dir.join("one.md"), true);
|
||||||
|
session.set_active_scroll_ratio(0.75);
|
||||||
|
let second = session.open(dir.join("two.md"), false);
|
||||||
|
|
||||||
|
assert_ne!(first, second);
|
||||||
|
assert!(!session.active().unwrap().editing);
|
||||||
|
assert_eq!(session.active().unwrap().scroll_ratio, 0.0);
|
||||||
|
|
||||||
|
assert!(session.activate(first));
|
||||||
|
assert!(session.active().unwrap().editing);
|
||||||
|
assert_eq!(session.active().unwrap().scroll_ratio, 0.75);
|
||||||
|
|
||||||
|
// Late reports address the tab by id, not by whichever tab is active.
|
||||||
|
session.set_tab_scroll_ratio(second, 0.4);
|
||||||
|
assert!(session.activate(second));
|
||||||
|
assert_eq!(session.active().unwrap().scroll_ratio, 0.4);
|
||||||
|
assert!(!session.active().unwrap().editing);
|
||||||
|
let _ = fs::remove_dir_all(dir);
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
#[test]
|
#[test]
|
||||||
fn opened_paths_drop_windows_verbatim_prefix() {
|
fn opened_paths_drop_windows_verbatim_prefix() {
|
||||||
@@ -419,7 +478,10 @@ mod tests {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
.to_string_lossy()
|
.to_string_lossy()
|
||||||
.to_string();
|
.to_string();
|
||||||
assert!(!stored.starts_with(r"\\?\"), "verbatim prefix leaked: {stored}");
|
assert!(
|
||||||
|
!stored.starts_with(r"\\?\"),
|
||||||
|
"verbatim prefix leaked: {stored}"
|
||||||
|
);
|
||||||
assert!(session.tabs[0].file_path().unwrap().ends_with("note.md"));
|
assert!(session.tabs[0].file_path().unwrap().ends_with("note.md"));
|
||||||
let _ = fs::remove_dir_all(dir);
|
let _ = fs::remove_dir_all(dir);
|
||||||
}
|
}
|
||||||
|
|||||||
18
src/testutil.rs
Normal file
18
src/testutil.rs
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
//! Test-only helpers shared by the module test suites.
|
||||||
|
|
||||||
|
use std::fs;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
/// Create a unique scratch directory under the platform temp dir (the test
|
||||||
|
/// runner points TEMP/TMP at `target\tmp`).
|
||||||
|
pub 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-{name}-{}-{unique}", std::process::id()));
|
||||||
|
fs::create_dir_all(&dir).unwrap();
|
||||||
|
dir
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user