29 Commits

Author SHA1 Message Date
56a167d98c docs: prepare v1.4.2-local.7 release 2026-11-11 14:37:49 +08:00
6565352ab5 fix(editor): track dirty changes after the first autosave
CodeMirror 5 change handlers receive (instance, changeObj). The handler named the first argument change, so once the fold gutter populated __mdpFenceCache it threw on change.from.line before setDirty(true). Edits after the first autosave stayed clean: Ctrl+S and Ctrl+E skipped saving and the preview stayed stale. Use the correct signature, return early for remote setValue, and guard the cache update. Add a page regression test.
2026-11-11 14:19:16 +08:00
f1bda62d84 docs: prepare v1.4.2-local.6 release 2026-11-06 11:29:38 +08:00
0bbb840778 docs: record the CodeMirror 5 editor work 2026-11-06 11:23:31 +08:00
e911876bbb fix(editor): preserve BOM, load tabs reliably and cache fence state 2026-11-06 11:18:26 +08:00
f300abf359 fix(editor): keep the edit find bar out of preview find mode 2026-11-06 11:12:42 +08:00
10f1d4fca2 style(editor): match replace-button hover with find controls 2026-11-06 11:10:16 +08:00
0544c78633 style(editor): make replace buttons text-only and bold 2026-11-06 11:06:07 +08:00
171fbaf59d fix(editor): hide UTF-8 BOM and lighten replace buttons 2026-11-06 10:58:23 +08:00
a206ce8450 fix(editor): stable per-tab line restore and fold closing fences 2026-11-06 10:12:18 +08:00
9f12b91a14 fix(editor): fold fence parity, search bar layout and per-tab scroll memory 2026-11-06 10:03:23 +08:00
2117551af7 fix(editor): fold ranges, stacked replace bar and container scrolling 2026-11-06 09:14:20 +08:00
a58a94b05f fix(editor): add find/replace bar and tidy CodeMirror scrolling 2026-11-06 09:00:35 +08:00
715c8068f8 feat(editor): run markdown source editing on CodeMirror 5 2026-11-06 08:23:13 +08:00
8b4d1fa03e build: vendor CodeMirror 5.65.16 for the source editor 2026-11-06 08:23:13 +08:00
b2a4fd41ca refactor(page): route editor access through an adapter 2026-11-06 08:17:59 +08:00
0bb804e4df docs: decide on CodeMirror 5 for the editor 2026-11-06 08:12:50 +08:00
6c0bb8253b docs: record the test relocation and slim main entry 2026-11-06 07:36:09 +08:00
a5c0b0801d refactor: move module tests into their files and startup into app::run 2026-11-06 07:35:49 +08:00
3ecf96fb04 docs: record the files.rs and app.rs refactor stages 2026-11-06 07:27:25 +08:00
fb10fc5de0 refactor(app): move app state, rendering and event loop into app.rs 2026-11-06 07:27:10 +08:00
1208386452 refactor(files): move file IO, watcher and link helpers into files.rs 2026-11-06 07:23:51 +08:00
d78d1aa722 docs: record the UI verification workflow and its limits
- AGENTS §3: UI/GUI verification must be run by the user via
  ui-smoke.cmd; the DSH sandbox blocks named pipes so WebView2 cannot
  start, and Rust->JS calls have no compiler check.
- HANDOFF §4.1: canonical description (why the sandbox fails, the script
  flow, the report/screenshot outputs, when to run it, maintenance notes).
- STATUS §12: current verification matrix; README: command.
2026-11-04 17:33:34 +08:00
1ad4a265c3 docs: record the passing UI smoke and add it to the checklists
ui-smoke.cmd ran on the user's desktop: 8/8 checks, screenshot shows the
page restored (tab bar, headings, VS Dark code block). Add it to the README
build steps and the HANDOFF acceptance checklist, and note the verified run
in STATUS.
2026-11-04 17:30:19 +08:00
a4616d0228 fix: resolve node correctly and wait for a real CDP endpoint
The smoke script passed a CommandInfo from Get-Command straight to
Test-Path, so Node was reported missing even when installed. Resolve the
executable path (Get-Command .Path, then the usual install directories) and
add a -Node override.

Wait for /json/list to answer instead of a TCP connect: WebView2 opens the
port briefly and dies under the sandbox, which made the script run the
driver against a dead endpoint. The summary now reports report.errors
instead of printing "OK: 0 checks".
2026-11-04 17:28:37 +08:00
9a568774d8 chore: keep .cmd wrappers CRLF in the working tree 2026-11-04 17:12:43 +08:00
2fc3f740ca test: add a bypass wrapper for the UI smoke script
Windows PowerShell with an AllSigned policy refuses unsigned .ps1 files.
ui-smoke.cmd runs ui-smoke.ps1 with a process-scoped -ExecutionPolicy Bypass
(no system policy change) and keeps the window open when double-clicked.
2026-11-04 17:12:32 +08:00
590a9a016c fix: restore the page content call and stop writing the registry
- render_active_document passed the tab id as the first __setContent argument,
  but the page signature starts with previewHtml, so #preview rendered the tab
  id ("1", "2", "3" as tabs were opened) and the window looked blank. The call
  now goes through set_content_script(), and a test pins the exact script plus
  the page signature so the two cannot drift silently.
- remove register_as_default() and the winreg dependency: the app no longer
  writes HKCU on launch. publish.ps1 still refreshes the .md association.
2026-11-04 15:25:13 +08:00
0b97bcb6dc test: add a CDP-based pre-release UI smoke harness
The DSH sandbox blocks named pipes, so Chromium/WebView2 cannot start inside
it (window renders white, msedgewebview2 exits immediately; Edge headless
fails with a Mojo platform-channel access-denied fatal). UI verification
therefore moves to a script the user runs from a normal desktop shell.

- agent/tests/ui-smoke.ps1: launches the built exe with an isolated config
  and --remote-debugging-port, waits for the port, runs the driver, closes.
- agent/tests/ui-smoke.mjs: connects over CDP, snapshots the page (preview
  content, headings, fold toggles, highlighted code, window.ipc bridge),
  saves a screenshot and a JSON report for the agent to read.
- The driver was validated against a mock CDP server; the real end-to-end run
  needs a desktop shell (sandbox cannot host WebView2).
2026-11-04 15:15:24 +08:00
38 changed files with 4358 additions and 2978 deletions

3
.gitattributes vendored
View File

@@ -1 +1,4 @@
* text=auto eol=lf
# cmd.exe wants CRLF; keep it stable in the working tree.
*.cmd text eol=crlf
*.bat text eol=crlf

77
Cargo.lock generated
View File

@@ -1683,7 +1683,6 @@ dependencies = [
"serde_json",
"tao",
"url",
"winreg",
"winresource",
"wry",
]
@@ -3722,15 +3721,6 @@ dependencies = [
"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]]
name = "windows-sys"
version = "0.52.0"
@@ -3773,21 +3763,6 @@ dependencies = [
"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]]
name = "windows-targets"
version = "0.52.6"
@@ -3828,12 +3803,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
@@ -3846,12 +3815,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
@@ -3864,12 +3827,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
@@ -3888,12 +3845,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
@@ -3906,12 +3857,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "windows_x86_64_gnu"
version = "0.52.6"
@@ -3924,12 +3869,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
@@ -3942,12 +3881,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "windows_x86_64_msvc"
version = "0.52.6"
@@ -3981,16 +3914,6 @@ dependencies = [
"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]]
name = "winresource"
version = "0.1.31"

View File

@@ -16,9 +16,6 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
url = "2"
[target.'cfg(windows)'.dependencies]
winreg = "0.52"
[target.'cfg(windows)'.build-dependencies]
winresource = "0.1"

View File

@@ -10,11 +10,12 @@
## 特点
- **双击即开**:单个 exe(约 5.5 MB),不用安装;可设为 `.md` 的默认打开方式。
- **双击即开**:单个 exe(约 5.8 MB),不用安装;可设为 `.md` 的默认打开方式。
- **完全离线**:不联网、不检查更新、无遥测;外部链接交给系统浏览器打开。
- **多标签 + 多窗口**:新标签页(New Tab)本身就是一个默认标签,标签栏的 `+` 新建一个 New Tab;在 New Tab 里打开文件会直接替换该标签(浏览器语义);关闭最后一个文件标签回到 New Tab,只剩 New Tab 时标签栏自动隐藏。标签右键可在新窗口打开,也可以上下拖动标签直接移出;同一文件全局只开一次,重复打开只聚焦;不恢复上次标签,启动显示最近文件、缺失文件可重新定位。
- **英文界面**:界面文案统一为英文,不随系统语言切换,避免中英文混排。
- **预览 / 编辑一体**:`Ctrl+E` 切换;编辑模式与滚动位置按标签记忆,切回时恢复;编辑时 700ms 自动保存,`Ctrl+S` 立即保存。
- **编辑区升级**:行号、Markdown 着色、标题/代码围栏折叠;`Ctrl+F` 查找、`Ctrl+H` 替换;带 BOM 的文件也能正确识别首行标题。
- **编辑更顺手**:Tab 插入 2 个空格、Shift+Tab 反缩进,多行选区整体缩进;Enter 自动跟随上一行缩进;保留原生撤销。
- **长文档友好**:
- 鼠标移到标题左侧出现折角箭头,点击即可折叠到下一个同级标题(H1–H6);
@@ -26,9 +27,9 @@
## 下载与运行
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.6`,2026-11-06);
2. 放到一个固定目录(例如 `C:\Tools\md-preview\`),不要随意改名/移动;
3. 双击运行,或在任意 `.md` 上右键 → 打开方式 → 选择该 exe 并设为默认;
3. 双击运行,或在任意 `.md` 上右键 → 打开方式 → 选择该 exe 并设为默认(程序本身不再写注册表;首次需要在“打开方式 → 选择其他应用”里选一次);
4. Windows 10/11 一般自带 WebView2 Runtime;若提示缺失,安装微软的 Evergreen Runtime 即可。
> exe 未做代码签名,SmartScreen 可能提示“未知发布者”,选择“更多信息 → 仍要运行”即可。
@@ -47,7 +48,7 @@
| 打开文件所在位置 | 右键标签 → “Show in Explorer”(文件丢失时打开所在目录) |
| 预览 / 编辑切换 | `Ctrl+E` |
| 保存 | 自动(停止输入 700ms)或 `Ctrl+S` |
| 查找 | `Ctrl+F`(工具栏没有搜索按钮,快捷键随时可用);阅读模式选中文字后会自动填入,打开时不滚动 |
| 查找 | `Ctrl+F`(阅读模式选中文字后自动填入;编辑模式是字面查找,`Ctrl+H` 替换);工具栏没有搜索按钮 |
| 打印 | `Ctrl+P` |
| 缩放 | `Ctrl+滚轮`、`Ctrl++`、`Ctrl+-`、`Ctrl+0` 复位 |
| 折叠标题 | 鼠标移到标题左侧,点折角箭头 |
@@ -86,6 +87,7 @@
```powershell
cargo test
.\agent\scripts\build.ps1 # release 构建 + 校验(产物留在 target\release\)
.\agent\tests\ui-smoke.cmd # 发布前 UI 冒烟(普通桌面 PowerShell + Node 21+)
.\agent\scripts\publish.ps1 # 发布到 Nutstore(用户手动,普通 PowerShell)
```

View File

@@ -53,6 +53,10 @@
- 开发构建:`.\agent\scripts\build.ps1`(cargo test + build --release + 字符串校验;产物留在 `target\release\`)。
- 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/`,禁止使用。

View File

@@ -18,6 +18,7 @@
| `scripts/build.ps1` | 开发构建(cargo test + build --release + 校验) |
| `scripts/publish.ps1` | 用户手动发布到 Nutstore(Medium) |
| `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 样例 |
| `reports/` | 验证记录(文本;截图放 `agent/tmp/`,不入库) |
| `notes/` | 草稿 |
@@ -41,6 +42,9 @@ cargo test
# 冒烟(发布后;含注册表与可选启动)
.\agent\tests\smoke.ps1 -Launch
# 发布前 UI 冒烟(用户桌面;CDP + 截图)
.\agent\tests\ui-smoke.cmd
# 发布(必须由用户在自己的普通 PowerShell 运行)
.\agent\scripts\publish.ps1
~~~

View File

@@ -1,6 +1,6 @@
# MD Preview 本地维护交接
> 最后更新:2026-11-03
> 最后更新:2026-11-06
> 维护范围:仅 Windows 本地构建,目标产物 `MD-Preview-windows-x64.exe`
>
> **Agent 必须先读 `agent/AGENTS.md`**:最高优先级是工作区边界,任何工作区外的文件修改都要先停下询问用户。
@@ -10,17 +10,17 @@
> 成品只发布到 `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-03**:功能不变的重构(页面资源外置、markdown/page/escape/config 拆模块、删除 macOS/Linux 死代码)。未做功能与下一步见 `agent/docs/next-2026-11-03.md`。
> **2026-11-06**:编辑区已切到内嵌 CodeMirror 5(行号/折叠/查找替换/按标签行号恢复),63 tests 全绿,ui-smoke 8/8。重构阶段 3–5 见 `STATUS.md` §11;CM5 细节见 `next-2026-11-03.md` §4.2。
## 1. 当前状态
- 上游版本:`md-preview 1.4.2`(源码来自 `backup/md-preview-master.zip`)
- 改造目标:**本地预览器,不联网、不自动更新**;预览/编辑/标签/会话等功能与上游一致
- 源码规模:`src/main.rs` 2822 行、`src/session.rs` 488 行、`src/instance.rs` 207 行;`src/markdown.rs` 405 行、`src/config.rs` 212 行、`src/page.rs` 65 行、`src/escape.rs` 25 行;页面资源在 `assets/page/`
- 源码规模(2026-11-06):`src/main.rs` 18 行(入口)、`src/app.rs` 约 1950 行(CLI/启动/状态/渲染/事件循环)、`src/markdown.rs` 628 行、`src/session.rs` 488 行、`src/files.rs` 458 行、`src/page.rs` 约 300 行、`src/config.rs` 235 行、`src/instance.rs` 207 行、`src/escape.rs` 25 行;页面资源在 `assets/page/`,CM5 在 `assets/codemirror/`
- 当前产物(2026-11-02 起):`C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`
- 当前发布版见 `STATUS.md` 第 2 节(v1.4.2-local.5,5,505,024 字节)
- 仓库内不再放成品 exe;旧 `D:\Scripts\md-preview\MD-Preview-windows-x64.exe` 由 `publish.ps1` 删除
- 测试:`cargo test` → 59 passed, 0 failed(2026-11-03;删除 3 个随死代码一起消失的测试)
- 测试:`cargo test` → 60 passed, 0 failed(2026-11-06)
- 编译警告:0;`cargo clippy --all-targets` 0 warning,`cargo fmt -- --check` 通过
- 2026-10-21 的全部功能需求已完成并部署,细节与实现要点见第 14 节。
@@ -69,6 +69,25 @@ cd D:\Scripts\md-preview\AgentLowWorking
- 如果发布后仍报 os error 5:`icacls <Nutstore exe> | Select-String 'Mandatory Label'` 应为 Medium;确认不是从 Low 目录直接启动。
- 不要再把仓库改回 Medium,也不要为了改代码申请 danger-full-access。
### 4.1 UI 验证:只能由用户执行(2026-11-04 起)
**DSH 沙箱禁止命名管道**,Chromium/WebView2 的 Mojo IPC 起不来:应用窗口会出现,但 `msedgewebview2.exe` 立即退出、页面白屏;Edge headless 也会报 `FATAL: mojo platform_channel ... 拒绝访问 (0x5)`。这是环境限制,不是应用 bug,也不要用沙箱里的白屏判断页面好坏。
因此 GUI/UI 验证统一走这条链路:
1. 用户在自己桌面 PowerShell 运行 `.\agent\tests\ui-smoke.cmd`(默认跑 `target\release\md-preview.exe`,独立配置目录 `target\ui-test\config`)。
- 机器执行策略是 AllSigned,未签名 `.ps1` 会被拒;`.cmd` 内部用 `-ExecutionPolicy Bypass`,不改系统策略。
- 需要 Node 21+(本机 `C:\Program Files\nodejs` 的 24.x);脚本会自己找,也可 `-Node <path>`。
- 用 `-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”就是发布前没跑它。
维护细节(改脚本前看):
- 就绪判断必须用 `/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. 已删除的联网/更新功能(不要加回来)
- 工具栏 Update 按钮、`#btn-update`、更新相关 CSS/JS
@@ -158,12 +177,15 @@ Git 由用户自行初始化(私有仓库;`backup/` 与成品 exe 不入 git
cd D:\Scripts\md-preview\AgentLowWorking
cargo test
.\agent\scripts\build.ps1
# 发布前 UI 冒烟(普通桌面 PowerShell / Node 21+):
.\agent\tests\ui-smoke.cmd
# 发布由用户在自己的普通 PowerShell 运行:
.\agent\scripts\publish.ps1
~~~
手工检查:
- [ ] `ui-smoke.cmd` 输出 `OK: N checks`,截图里能看到正文、标题和代码高亮
- [ ] 窗口标题为 `文件名 — MD Preview`
- [ ] 工具栏只有 编辑 / 缩放(无 Update / Open / Print / Find)
- [ ] 多标签切换、关闭;切回标签仍保持编辑模式和滚动位置

View File

@@ -1,11 +1,13 @@
# 项目状态(滚动更新)
> 最后更新:2026-11-03
> 最后更新:2026-11-11
> 用途:上下文压缩/交接后快速恢复。详细背景见 AGENTS.md、HANDOFF.md、scan-2026-10-21.md、roadmap.md。
>
> **当前(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-11):仓库根 `D:\Scripts\md-preview\AgentLowWorking`,整棵树 Low、DSH workspace-write 可编译;成品只发布到 Nutstore;仓库内 exe 已删除。功能基线 v1.4.2-local.7(64 tests);仓库已是 Windows-only。**
>
> 2026-11-03 已做:编辑模式与滚动位置按标签记忆;不再把 `.txt` 当文档;clippy 清零、`cargo fmt` 通过;AGENTS 允许拆模块/新增文件;功能不变地拆出 page/markdown/escape/config 模块并删除 macOS/Linux 死代码。未做功能与下一步见 `docs/next-2026-11-03.md`。
>
> 2026-11-11:修复 CodeMirror 5 编辑区回归(`change` 回调签名用错,第一次自动保存后不再置脏、`Ctrl+S`/`Ctrl+E` 不保存);发布 v1.4.2-local.7。
## 1. 仓库
@@ -176,7 +178,14 @@ cargo test
## 9. 发布(Gitea)
- 实例 Gitea 24.5.4,仓库私有。
- Release `v1.4.2-local.5`(最新,2026-10-30):https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.5
- Release `v1.4.2-local.7`(最新,2026-11-11):https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.7
- 附件 `MD-Preview-windows-x64.exe`,5,760,000 字节
- SHA256 `318A27372FA5BF75746F102315BEDB87F131E769AE5BD40A4AA57C0B4CAD1652`
- 修复:CodeMirror 5 `change` 回调签名用错,第一次自动保存后输入不再置脏;正文来源 `agent/docs/release-notes-v1.4.2-local.7.md`
- Release `v1.4.2-local.6`(2026-11-06):https://git.wucl12.cn/wucl12/md-preview/releases/tag/v1.4.2-local.6
- 附件 5,759,488 字节;SHA256 `7421BFAF223C967AF40D02CBB5DFA3F354E87FA9847A3CAADDFAE553DC5FE860`
- 正文来源:`agent/docs/release-notes-v1.4.2-local.6.md`
- 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 字节
- SHA256 `A632EF0363D04CE6F72B9779BA742681868AC31D36A7FE57E4F6D44E7BEAD988`(已下载复核一致)
- 正文来源:`agent/docs/release-notes-v1.4.2-local.5.md`
@@ -214,8 +223,26 @@ cargo test
- 代码整理:`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 个平台专用测试)。
- 已决定、未实施:移除应用启动时的 HKCU 关联写入;`publish.ps1` 维持现状(继续写关联)。
- 架构拆分阶段 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 资源)和不变量变化需要先问。
- 下一步(讨论中,未动手):编辑区样式化——加粗、标题加粗加大、行内代码换字体。
- 技术前提:`<textarea>` 不支持字符级样式;改字号会改变软换行与光标位置,透明叠加层只适合“同字号”样式。
- 候选:A 透明 textarea + 样式层(只能同字号);B 自研 contenteditable 行编辑器;C 内嵌 CodeMirror 5(单文件、离线、约 +280 KB)。倾向 C,待用户确认体积与交互取舍。
- 编辑区 CodeMirror 5(2026-11-06 完成,未发布;`8b4d1fa` → `e911876`):
- `assets/codemirror/` vendored 5.65.16:core + xml/meta/markdown + searchcursor/search/dialog + foldcode/foldgutter,约 218 KB,附 LICENSE。启动 HTML 不含 CM;首次进编辑通过 `need-editor` IPC 注入,注入失败保留 textarea。
- page.js 先抽 `createTextareaEditor`/`createCodeMirrorEditor` 适配层;编辑模式有行号、markdown 着色(标题/加粗/斜体/链接/引用,标记不隐藏)、标题+围栏折叠、CM 内部滚动;页面滚动改到 `#app` 容器,阅读/编辑滚动条都在标签栏下沿。
- 折叠:围栏状态按文档缓存、change 行处增量失效;只有开围栏有箭头,折叠包含收尾围栏;代码块里的 `#` 不再当标题。
- 查找替换:页面自己的两行 findbar(Find + ↑↓× / Replace + Replace All),Esc 只关查找条;Ctrl+E 退出编辑;阅读模式 find 保持原样。
- 滚动:JS `cmTabLines` 按标签记顶部行号,Rust `scroll_ratio` 兜底;`__setContent` 增加第 8 参数 tab id,切标签先加载目标内容、在绘制前滚到行首。
- BOM:编辑器值去掉开头 U+FEFF,保存时原样加回;首行标题/围栏识别正常。
- 大文档(>2 MB 或 >2 万行)回退 textarea:无行号/折叠/编辑查找。
- 已知限制:编辑查找为字面匹配、大小写不敏感,不支持 CM 对话框的 `/re/` 正则;阅读→编辑滚动仍按比例近似;打印只有 CSS 层验证。
## 12. 测试与验证(2026-11-04 起)
- 代码级:`cargo test`(当前 63)、`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、2026-11-06 多次):ui-smoke 8/8 checks,截图确认页面正常渲染。CM5 改版后由用户手动验证编辑/保存/折叠/替换/滚动,ui-smoke 仍 8/8。

View File

@@ -20,32 +20,47 @@
## 3. 剩余重构(仍不改行为,建议顺序)
1. `src/files.rs`:最近文件、保存写盘、文件监听、支持的扩展名、本地链接解析、Explorer 定位。
2. `src/app.rs`:`UserEvent`/`WindowState`/`AppState`、find/focus、`render_*`、`build_webview`、窗口创建/关闭。
3. `main.rs` 只留 `main()`、CLI、事件循环接线;事件 match 可拆成按事件分组的处理函数。
4. 测试跟着模块走(`markdown.rs`/`files.rs`/`page.rs` 各自 `#[cfg(test)]`),共享 `testutil::temp_dir`。
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 写入(已定方向,未实施)
### 4.1 移除应用自身的 HKCU 写入(2026-11-04 已完成)
- 删除 `main()` 里的 `register_as_default()` 调用和该函数(`src/main.rs`);应用不再写注册表。
- 已删除 `main()` 里的 `register_as_default()` 调用、该函数以及 `winreg` 依赖;应用不再写注册表。
- **`publish.ps1` 维持现状**(继续写 ProgID/关联),这是用户明确决定。
- 影响:新机器上应用不再自动出现在“打开方式”;用户通过 Windows 设置选择一次默认应用;exe 移动后由发布脚本刷新关联。
- 需要同步:README“下载与运行”里的关联说明、STATUS 的注册表相关条目。
- 影响:新机器上应用不再自动出现在“打开方式”;首次在 Windows“打开方式 → 选择其他应用”里选一次;exe 移动后由发布脚本刷新关联。
- README 第 3 步、STATUS §11 已同步。
### 4.2 编辑区样式化(需求已明确,实现未选型)
### 4.2 编辑区样式化(已完成:内嵌 CodeMirror 5,2026-11-06)
需求:编辑模式里 `**加粗**` 显示为粗体、`# 标题` 整行加粗加大、行内代码换字体。**标记保持显示**(源码模式,不做隐藏标记的 WYSIWYG)。
需求:编辑模式里 `**加粗**` 显示为粗体、`# 标题` 整行加粗加大、行内代码换字体。**标记保持显示**。用户已确认行号、编辑区折叠、替换近期一定会做。
技术结论(详见 STATUS §11):
**决策(2026-11-06)**:
- `<textarea>` 不支持字符级样式;透明叠加层只能做“同字号”样式,**标题改字号会让软换行与光标错位**。
- 候选:A 叠加层(做不到加大);B 自研 contenteditable 行编辑器(3–5 天,高风险);C 内嵌 CodeMirror 5(单文件 UMD、离线 vendored,约 +270 KB,exe 5.51→5.78 MB)。**倾向 C,需用户确认后才可引入**(AGENTS:>200 KB vendored 资源要先确认)。
- 已确认的交互:标记显示;编辑/阅读查找统一(编辑模式的 WebView2 原生查找会消失);超大文档(>2 MB 或 >2 万行)退回纯 textarea。
- 待验证:CM5 自动高度 + 软换行能否保持“整页一个滚动条、滚动与阅读模式一致”的现状;不行就得接受编辑区内部滚动,并同步预览/编辑滚动位置。
- 已实现的前置条件:编辑模式、滚动位置都按标签存在 `DocumentTab`(`editing`、`scroll_ratio`),换编辑器时只需替换页面的应用/读取逻辑。
- 采用 **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 统一是后续小工作。
**状态(2026-11-06)**:已完成并推送(`8b4d1fa` → `e911876`)。实现与计划的差异:
- CM 资源改为首次进编辑时经 `need-editor` IPC 注入,启动 HTML 不增加;
- 查找替换没有用 CM 自带 dialog,改为页面两行 findbar(Find + ↑↓× / Replace + Replace All),Esc 只关查找条;
- 滚动没有拆两个比例字段:JS `cmTabLines` 按标签记顶部行号,Rust `scroll_ratio` 仅作重启兜底;`__setContent` 增加第 8 参数 tab id;
- 补充 BOM 保留、围栏缓存、代码块内 `#` 不折叠、`#app` 容器滚动等修复。
**验证**:用户已手动验证编辑/保存/切标签/折叠/替换/滚动;ui-smoke 8/8。已知限制:编辑查找不支持 `/re/` 正则;超大文档回退 textarea;阅读→编辑滚动仍是比例近似。
## 5. 验证配方
@@ -65,9 +80,34 @@ cargo fmt -- --check
手动冒烟(无自动化):多标签切换、编辑/阅读、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%`。

View File

@@ -0,0 +1,40 @@
# v1.4.2-local.6(2026-11-06)
Windows 本地 Markdown 预览器,基于上游 md-preview 1.4.2 的离线定制版。本次更新把编辑模式换成了内嵌 CodeMirror 5,并统一了阅读/编辑的滚动与查找体验。
## 下载
- **MD-Preview-windows-x64.exe**
- 大小:5,759,488 字节
- SHA256:7421BFAF223C967AF40D02CBB5DFA3F354E87FA9847A3CAADDFAE553DC5FE860
- 系统要求:Windows 10/11 x64;WebView2 Runtime(一般随系统自带)。
- 免安装:下载后放到固定目录直接运行;可在 .md 的“打开方式”里设为默认。
> exe 未签名,SmartScreen 可能提示未知发布者,选择“更多信息 → 仍要运行”。
## 本次更新
- **编辑区改用内嵌 CodeMirror 5**(MIT、离线 vendored):行号、Markdown 着色、标题/加粗/斜体/链接/引用、标题与代码围栏折叠;标记字符保持显示,不做隐藏。
- **编辑区查找/替换**:`Ctrl+F` 打开查找条(带上一个/下一个/关闭按钮),`Ctrl+H` 展开 Replace / Replace All;`Esc` 只关闭查找条,不再退出编辑模式。
- **滚动统一**:阅读与编辑的滚动条都位于标签栏下方;编辑区使用 CM 内部滚动,切换标签按顶部行号恢复,不再逐次偏移。
- **折叠细节**:代码围栏只有开围栏行有折叠箭头,折叠范围包含收尾围栏;代码块里的 `#` 不会被当成标题。
- **BOM 处理**:带 UTF-8 BOM 的文件在编辑区不再显示红点,首行标题/围栏识别正常;保存时 BOM 原样保留。
- **阅读模式 Find 修复**:不再被编辑查找条覆盖;进入编辑时自动关闭阅读查找。
- 编辑区 >2 MB 或 >2 万行时回退纯 textarea,避免长文档卡顿。
## 包含上一版功能
- 新标签页、多标签/多窗口、标签拖拽移出、同文件全局聚焦。
- 英文界面、标题折叠、Ctrl+滚轮缩放、代码块始终深色、700ms 自动保存、外部修改热重载、单实例转发。
- GFM 脚注、定义列表、front matter、GitHub Alerts、`==高亮==`、KaTeX、Mermaid。
## 已知限制
- 编辑查找为字面匹配、大小写不敏感,不支持正则 `/re/`。
- 阅读→编辑的滚动位置仍按比例近似,但会对齐到整行。
- 超大文档回退 textarea 时没有行号、折叠或编辑查找。
- 仅 Windows;不自动更新;升级请手动替换 exe。
## 从上一版升级
退出旧程序,用新 exe 覆盖原文件即可。设置、最近文件和缩放记录保存在 `%LOCALAPPDATA%\md-preview\`。

View File

@@ -0,0 +1,40 @@
# v1.4.2-local.7(2026-11-11)
Windows 本地 Markdown 预览器,基于上游 md-preview 1.4.2 的离线定制版。本次修复 CodeMirror 5 编辑区的自动保存回归:第一次自动保存之后继续输入不再触发保存,`Ctrl+S` 和 `Ctrl+E` 也会跳过保存。
## 下载
- **MD-Preview-windows-x64.exe**
- 大小:5,760,000 字节
- SHA256:318A27372FA5BF75746F102315BEDB87F131E769AE5BD40A4AA57C0B4CAD1652
- 系统要求:Windows 10/11 x64;WebView2 Runtime(一般随系统自带)。
- 免安装:下载后放到固定目录直接运行;可在 .md 的“打开方式”里设为默认。
> exe 未签名,SmartScreen 可能提示未知发布者,选择“更多信息 → 仍要运行”。
## 本次修复
- **第一次自动保存后继续输入不保存**:CodeMirror 5 的 `change` 回调签名是 `(instance, changeObj)`,旧代码把第一个参数当成 change 对象。折叠缓存初始化后,每次输入都会在 `change.from.line` 抛异常,`setDirty(true)` 被跳过,标签保持 clean。
- 现象:新建或打开 md 后输入,第一次 700ms 自动保存把当时的内容写入文件;继续输入、手动 `Ctrl+S`、按 `Ctrl+E` 切预览都不会再保存,预览停留在第一次保存的内容。
- 修复:使用正确的 change 回调参数;把远程 `setValue` 的提前返回放到折叠缓存更新之前,并对 `change.from` 做存在性检查。
- 回归测试:`page::tests::editor_change_handler_uses_the_codemirror_instance_and_change_object`;另用 jsdom 对照旧/新页面,确认第二次输入会重新发出 `dirty:1`。
- 这是 `v1.4.2-local.6`(CodeMirror 5 编辑区)的回归修复,建议所有 local.6 用户升级。
## 包含上一版功能
- 编辑区使用内嵌 CodeMirror 5:行号、Markdown 着色、标题/代码围栏折叠;`Ctrl+F` / `Ctrl+H` 查找替换。
- 新标签页、多标签/多窗口、标签拖拽移出、同文件全局聚焦。
- 英文界面、标题折叠、`Ctrl+滚轮` 缩放、代码块始终深色、700ms 自动保存、外部修改热重载、单实例转发。
- GFM 脚注、定义列表、front matter、GitHub Alerts、`==高亮==`、KaTeX、Mermaid。
- UTF-8 BOM 容错与保存保留;新文件创建后直接进入编辑模式;相对图片/文档链接。
## 已知限制
- 编辑查找为字面匹配、大小写不敏感,不支持正则 `/re/`。
- 阅读→编辑的滚动位置按比例近似,但对齐到整行。
- 超过 2 MB 或 2 万行时编辑区回退纯 textarea(无行号/折叠/编辑查找)。
- 仅 Windows;不自动更新;升级请手动替换 exe。
## 从上一版升级
退出旧程序,用新 exe 覆盖原文件即可。设置、最近文件和缩放记录保存在 `%LOCALAPPDATA%\md-preview\`。

11
agent/tests/ui-smoke.cmd Normal file
View 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
View 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
View 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

21
assets/codemirror/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (C) 2017 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,17 @@
# CodeMirror 5.65.16 (vendored)
MIT-licensed source editor used only in edit mode. Nothing here is loaded at
startup: Rust injects the concatenated bundle the first time the page asks for
it (`need-editor` IPC), then calls `window.__mdpOnEditorSource()`.
Files are the minified builds from the cdnjs 5.65.16 package
(`https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/`):
- `codemirror.min.js`, `codemirror.min.css`
- `mode/xml/xml.min.js`, `mode/meta.min.js`, `mode/markdown/markdown.min.js`
- `addon/search/searchcursor.min.js`, `addon/search/search.min.js`
- `addon/dialog/dialog.min.js`, `addon/dialog/dialog.css`
- `addon/fold/foldcode.min.js`, `addon/fold/foldgutter.min.js`, `addon/fold/foldgutter.css`
See `LICENSE` for the upstream license. Keep this directory offline-only; do
not point the page at a CDN.

View File

@@ -0,0 +1,32 @@
.CodeMirror-dialog {
position: absolute;
left: 0; right: 0;
background: inherit;
z-index: 15;
padding: .1em .8em;
overflow: hidden;
color: inherit;
}
.CodeMirror-dialog-top {
border-bottom: 1px solid #eee;
top: 0;
}
.CodeMirror-dialog-bottom {
border-top: 1px solid #eee;
bottom: 0;
}
.CodeMirror-dialog input {
border: none;
outline: none;
background: transparent;
width: 20em;
color: inherit;
font-family: monospace;
}
.CodeMirror-dialog button {
font-size: 70%;
}

View File

@@ -0,0 +1 @@
!function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(s){function f(e,o,n){var e=e.getWrapperElement(),t=e.appendChild(document.createElement("div"));return t.className=n?"CodeMirror-dialog CodeMirror-dialog-bottom":"CodeMirror-dialog CodeMirror-dialog-top","string"==typeof o?t.innerHTML=o:t.appendChild(o),s.addClass(e,"dialog-opened"),t}function p(e,o){e.state.currentNotificationClose&&e.state.currentNotificationClose(),e.state.currentNotificationClose=o}s.defineExtension("openDialog",function(e,o,n){n=n||{},p(this,null);var t=f(this,e,n.bottom),i=!1,r=this;function u(e){"string"==typeof e?l.value=e:i||(i=!0,s.rmClass(t.parentNode,"dialog-opened"),t.parentNode.removeChild(t),r.focus(),n.onClose&&n.onClose(t))}var l=t.getElementsByTagName("input")[0];return l?(l.focus(),n.value&&(l.value=n.value,!1!==n.selectValueOnOpen&&l.select()),n.onInput&&s.on(l,"input",function(e){n.onInput(e,l.value,u)}),n.onKeyUp&&s.on(l,"keyup",function(e){n.onKeyUp(e,l.value,u)}),s.on(l,"keydown",function(e){n&&n.onKeyDown&&n.onKeyDown(e,l.value,u)||((27==e.keyCode||!1!==n.closeOnEnter&&13==e.keyCode)&&(l.blur(),s.e_stop(e),u()),13==e.keyCode&&o(l.value,e))}),!1!==n.closeOnBlur&&s.on(t,"focusout",function(e){null!==e.relatedTarget&&u()})):(e=t.getElementsByTagName("button")[0])&&(s.on(e,"click",function(){u(),r.focus()}),!1!==n.closeOnBlur&&s.on(e,"blur",u),e.focus()),u}),s.defineExtension("openConfirm",function(e,o,n){p(this,null);var t=f(this,e,n&&n.bottom),i=t.getElementsByTagName("button"),r=!1,u=this,l=1;function a(){r||(r=!0,s.rmClass(t.parentNode,"dialog-opened"),t.parentNode.removeChild(t),u.focus())}i[0].focus();for(var c=0;c<i.length;++c){var d=i[c];!function(o){s.on(d,"click",function(e){s.e_preventDefault(e),a(),o&&o(u)})}(o[c]),s.on(d,"blur",function(){--l,setTimeout(function(){l<=0&&a()},200)}),s.on(d,"focus",function(){++l})}}),s.defineExtension("openNotification",function(e,o){p(this,r);var n,t=f(this,e,o&&o.bottom),i=!1,e=o&&void 0!==o.duration?o.duration:5e3;function r(){i||(i=!0,clearTimeout(n),s.rmClass(t.parentNode,"dialog-opened"),t.parentNode.removeChild(t))}return s.on(t,"click",function(e){s.e_preventDefault(e),r()}),e&&(n=setTimeout(r,e)),r})});

View File

@@ -0,0 +1 @@
!function(n){"object"==typeof exports&&"object"==typeof module?n(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],n):n(CodeMirror)}(function(c){"use strict";function t(t,i,n,f){n&&n.call?(l=n,n=null):l=a(t,n,"rangeFinder"),"number"==typeof i&&(i=c.Pos(i,0));var l,d=a(t,n,"minFoldSize");function o(n){var o=l(t,i);if(!o||o.to.line-o.from.line<d)return null;if("fold"===f)return o;for(var e=t.findMarksAt(o.from),r=0;r<e.length;++r)if(e[r].__isFold){if(!n)return null;o.cleared=!0,e[r].clear()}return o}var e,r,u=o(!0);if(a(t,n,"scanUp"))for(;!u&&i.line>t.firstLine();)i=c.Pos(i.line-1,0),u=o(!1);u&&!u.cleared&&"unfold"!==f&&(e=function(n,o,e){n=a(n,o,"widget");"function"==typeof n&&(n=n(e.from,e.to));"string"==typeof n?(o=document.createTextNode(n),(n=document.createElement("span")).appendChild(o),n.className="CodeMirror-foldmarker"):n=n&&n.cloneNode(!0);return n}(t,n,u),c.on(e,"mousedown",function(n){r.clear(),c.e_preventDefault(n)}),(r=t.markText(u.from,u.to,{replacedWith:e,clearOnEnter:a(t,n,"clearOnEnter"),__isFold:!0})).on("clear",function(n,o){c.signal(t,"unfold",t,n,o)}),c.signal(t,"fold",t,u.from,u.to))}c.newFoldFunction=function(e,r){return function(n,o){t(n,o,{rangeFinder:e,widget:r})}},c.defineExtension("foldCode",function(n,o,e){t(this,n,o,e)}),c.defineExtension("isFolded",function(n){for(var o=this.findMarksAt(n),e=0;e<o.length;++e)if(o[e].__isFold)return!0}),c.commands.toggleFold=function(n){n.foldCode(n.getCursor())},c.commands.fold=function(n){n.foldCode(n.getCursor(),null,"fold")},c.commands.unfold=function(n){n.foldCode(n.getCursor(),{scanUp:!1},"unfold")},c.commands.foldAll=function(e){e.operation(function(){for(var n=e.firstLine(),o=e.lastLine();n<=o;n++)e.foldCode(c.Pos(n,0),{scanUp:!1},"fold")})},c.commands.unfoldAll=function(e){e.operation(function(){for(var n=e.firstLine(),o=e.lastLine();n<=o;n++)e.foldCode(c.Pos(n,0),{scanUp:!1},"unfold")})},c.registerHelper("fold","combine",function(){var t=Array.prototype.slice.call(arguments,0);return function(n,o){for(var e=0;e<t.length;++e){var r=t[e](n,o);if(r)return r}}}),c.registerHelper("fold","auto",function(n,o){for(var e=n.getHelpers(o,"fold"),r=0;r<e.length;r++){var t=e[r](n,o);if(t)return t}});var r={rangeFinder:c.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1,clearOnEnter:!0};function a(n,o,e){if(o&&void 0!==o[e])return o[e];o=n.options.foldOptions;return(o&&void 0!==o[e]?o:r)[e]}c.defineOption("foldOptions",null),c.defineExtension("foldOption",function(n,o){return a(this,n,o)})});

View File

@@ -0,0 +1,20 @@
.CodeMirror-foldmarker {
color: blue;
text-shadow: #b9f 1px 1px 2px, #b9f -1px -1px 2px, #b9f 1px -1px 2px, #b9f -1px 1px 2px;
font-family: arial;
line-height: .3;
cursor: pointer;
}
.CodeMirror-foldgutter {
width: .7em;
}
.CodeMirror-foldgutter-open,
.CodeMirror-foldgutter-folded {
cursor: pointer;
}
.CodeMirror-foldgutter-open:after {
content: "\25BE";
}
.CodeMirror-foldgutter-folded:after {
content: "\25B8";
}

View File

@@ -0,0 +1 @@
!function(t){"object"==typeof exports&&"object"==typeof module?t(require("../../lib/codemirror"),require("./foldcode")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./foldcode"],t):t(CodeMirror)}(function(n){"use strict";n.defineOption("foldGutter",!1,function(t,o,e){e&&e!=n.Init&&(t.clearGutter(t.state.foldGutter.options.gutter),t.state.foldGutter=null,t.off("gutterClick",d),t.off("changes",u),t.off("viewportChange",l),t.off("fold",m),t.off("unfold",m),t.off("swapDoc",u),t.off("optionChange",a)),o&&(t.state.foldGutter=new r(function(t){!0===t&&(t={});null==t.gutter&&(t.gutter="CodeMirror-foldgutter");null==t.indicatorOpen&&(t.indicatorOpen="CodeMirror-foldgutter-open");null==t.indicatorFolded&&(t.indicatorFolded="CodeMirror-foldgutter-folded");return t}(o)),f(t),t.on("gutterClick",d),t.on("changes",u),t.on("viewportChange",l),t.on("fold",m),t.on("unfold",m),t.on("swapDoc",u),t.on("optionChange",a))});var c=n.Pos;function r(t){this.options=t,this.from=this.to=0}function s(t,o){for(var e=t.findMarks(c(o,0),c(o+1,0)),n=0;n<e.length;++n)if(e[n].__isFold){var r=e[n].find(-1);if(r&&r.line===o)return e[n]}}function p(t){var o;return"string"==typeof t?((o=document.createElement("div")).className=t+" CodeMirror-guttermarker-subtle",o):t.cloneNode(!0)}function i(r,t,o){var i=r.state.foldGutter.options,f=t-1,d=r.foldOption(i,"minFoldSize"),a=r.foldOption(i,"rangeFinder"),u="string"==typeof i.indicatorFolded&&e(i.indicatorFolded),l="string"==typeof i.indicatorOpen&&e(i.indicatorOpen);r.eachLine(t,o,function(t){++f;var o=null,e=(e=t.gutterMarkers)&&e[i.gutter];if(s(r,f)){if(u&&e&&u.test(e.className))return;o=p(i.indicatorFolded)}else{var n=c(f,0),n=a&&a(r,n);if(n&&n.to.line-n.from.line>=d){if(l&&e&&l.test(e.className))return;o=p(i.indicatorOpen)}}(o||e)&&r.setGutterMarker(t,i.gutter,o)})}function e(t){return new RegExp("(^|\\s)"+t+"(?:$|\\s)\\s*")}function f(t){var o=t.getViewport(),e=t.state.foldGutter;e&&(t.operation(function(){i(t,o.from,o.to)}),e.from=o.from,e.to=o.to)}function d(t,o,e){var n=t.state.foldGutter;!n||e==(e=n.options).gutter&&((n=s(t,o))?n.clear():t.foldCode(c(o,0),e))}function a(t,o){"mode"==o&&u(t)}function u(t){var o,e=t.state.foldGutter;e&&(o=e.options,e.from=e.to=0,clearTimeout(e.changeUpdate),e.changeUpdate=setTimeout(function(){f(t)},o.foldOnChangeTimeSpan||600))}function l(o){var t,e=o.state.foldGutter;e&&(t=e.options,clearTimeout(e.changeUpdate),e.changeUpdate=setTimeout(function(){var t=o.getViewport();e.from==e.to||20<t.from-e.to||20<e.from-t.to?f(o):o.operation(function(){t.from<e.from&&(i(o,t.from,e.from),e.from=t.from),t.to>e.to&&(i(o,e.to,t.to),e.to=t.to)})},t.updateViewportTimeSpan||400))}function m(t,o){var e=t.state.foldGutter;!e||(o=o.line)>=e.from&&o<e.to&&i(t,o,o+1)}});

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1
assets/codemirror/codemirror.min.css vendored Normal file

File diff suppressed because one or more lines are too long

1
assets/codemirror/codemirror.min.js vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1
assets/codemirror/mode/meta.min.js vendored Normal file

File diff suppressed because one or more lines are too long

1
assets/codemirror/mode/xml/xml.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,15 +1,20 @@
: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; }
/* The document scrolls inside #app, below the tab strip. Preview and edit mode
therefore show the same scrollbar position and size. */
html { overflow: hidden; }
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;
height: 100vh; display: flex; flex-direction: column; overflow: hidden;
}
body.has-tabs { --chrome-top: 50px; }
#app { width: 100%; box-sizing: border-box; margin: 0 auto; padding: 24px 48px; }
#app { flex: 1 1 auto; min-height: 0; width: 100%; box-sizing: border-box; margin: 0 auto; padding: 24px 48px; overflow-y: auto; overflow-x: hidden; scrollbar-gutter: stable; }
#app::-webkit-scrollbar { width: 10px; }
#app::-webkit-scrollbar-track { background: transparent; }
#app::-webkit-scrollbar-thumb { background: rgba(128,128,128,.45); border-radius: 6px; }
#app::-webkit-scrollbar-thumb:hover { background: rgba(128,128,128,.65); }
#preview { font-size: calc(15px * var(--content-scale)); }
#preview .front-matter {
margin: 0 0 1.5em;
@@ -163,7 +168,7 @@ body.has-tabs { --chrome-top: 50px; }
.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;
display: none; flex: 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);
@@ -274,7 +279,7 @@ body.home .toolbar { display: none !important; }
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; }
body.finding .findbar:not(#edit-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;
@@ -374,3 +379,91 @@ body.editing #app { max-width: none; padding: 0; }
#preview .mdp-fold-body { display: block !important; }
#preview .mdp-fold-toggle { display: none !important; }
}
/* ---- CodeMirror source editor ------------------------------------------- */
#cm-editor { display: none; }
body.editing.cm-active { display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
body.editing.cm-active .tabbar { flex: none; }
body.editing.cm-active #app { flex: 1; min-height: 0; width: 100%; max-width: none; padding: 0; overflow: hidden; scrollbar-gutter: auto; }
body.editing.cm-active #editor { display: none; }
body.editing.cm-active #cm-editor { display: block; height: 100%; padding: 10px 0 0 14px; box-sizing: border-box; }
#cm-editor .CodeMirror { height: 100%; background: transparent; color: inherit; font: 14px/1.6 "SF Mono","Menlo","Consolas",monospace; }
#cm-editor .CodeMirror-gutters { background: transparent; border-right: 1px solid rgba(128,128,128,.18); }
#cm-editor .CodeMirror-linenumber { color: #9aa0a6; padding: 0 10px 0 4px; }
#cm-editor .CodeMirror-foldgutter { width: .9em; }
#cm-editor .CodeMirror-foldgutter-open, #cm-editor .CodeMirror-foldgutter-folded { color: #9aa0a6; }
#cm-editor .CodeMirror-cursor { border-left: 1.5px solid #333; }
#cm-editor .CodeMirror-selected { background: #d7e4f5; }
#cm-editor .CodeMirror-focused .CodeMirror-selected { background: #b9d3f2; }
#cm-editor .cm-searching { background: rgba(255, 213, 0, .45); }
#cm-editor .CodeMirror-matchingbracket { color: inherit; text-decoration: underline; }
#cm-editor .cm-header { font-weight: 700; color: #0550ae; }
#cm-editor .cm-strong { font-weight: 700; }
#cm-editor .cm-em { font-style: italic; }
#cm-editor .cm-link { color: #0969da; }
#cm-editor .cm-url { color: #6e7781; }
#cm-editor .cm-comment { color: #6e7781; }
#cm-editor .cm-quote { color: #57606a; font-style: italic; }
#cm-editor .cm-formatting { color: #8c959f; }
#cm-editor .cm-variable-2 { color: #953800; }
#cm-editor .CodeMirror-dialog { background: #fff; color: #1a1a1a; border-color: #ddd; }
#cm-editor .CodeMirror-dialog input { font: inherit; }
#cm-editor .CodeMirror-dialog button { color: #1a1a1a; }
#cm-editor .CodeMirror-foldmarker { color: #0550ae; text-shadow: none; background: rgba(9,105,218,.08); border-radius: 3px; padding: 0 .3em; }
#cm-editor .CodeMirror-lines { padding: 4px 24px 24px 0; }
#cm-editor .CodeMirror-scroll { overflow-x: hidden !important; }
#cm-editor .CodeMirror-scrollbar-filler { display: none !important; }
@media (prefers-color-scheme: dark) {
#cm-editor .CodeMirror { color: #d4d4d4; }
#cm-editor .CodeMirror-gutters { border-color: rgba(255,255,255,.12); }
#cm-editor .CodeMirror-linenumber { color: #6b7280; }
#cm-editor .CodeMirror-foldgutter-open, #cm-editor .CodeMirror-foldgutter-folded { color: #6b7280; }
#cm-editor .CodeMirror-cursor { border-left-color: #e6e6e6; }
#cm-editor .CodeMirror-selected { background: #264f78; }
#cm-editor .CodeMirror-focused .CodeMirror-selected { background: #2f5f8f; }
#cm-editor .cm-header { color: #79c0ff; }
#cm-editor .cm-link { color: #58a6ff; }
#cm-editor .cm-url, #cm-editor .cm-comment { color: #8b949e; }
#cm-editor .cm-quote { color: #a8b1bb; }
#cm-editor .cm-formatting { color: #7d8590; }
#cm-editor .cm-variable-2 { color: #ffa657; }
#cm-editor .CodeMirror-dialog { background: #2a2a2a; color: #ddd; border-color: #444; }
#cm-editor .CodeMirror-dialog button { color: #ddd; }
#cm-editor .CodeMirror-foldmarker { color: #79c0ff; background: rgba(88,166,255,.12); }
}
@media print {
#cm-editor { display: none !important; }
.findbar { display: none !important; }
html, body { height: auto !important; overflow: visible !important; display: block !important; }
#app { flex: none !important; height: auto !important; min-height: 0 !important; overflow: visible !important; scrollbar-gutter: auto; }
}
/* Edit-mode find/replace bar: same look as the preview findbar. */
html.cm-editing { overflow: hidden; scrollbar-gutter: auto; }
#edit-findbar { top: calc(var(--chrome-top) + 8px); z-index: 130; width: min(560px, calc(100vw - 32px)); padding: 8px 10px; }
body.edit-finding #edit-findbar { display: flex; flex-direction: column; align-items: stretch; gap: 6px; }
#edit-findbar .edit-find-row { display: flex; align-items: center; gap: 6px; width: 100%; }
#edit-findbar .edit-find-row input { flex: 1 1 auto; width: auto; min-width: 0; }
#edit-findbar .edit-replace-row { display: flex; align-items: center; gap: 6px; width: 100%; border-top: 1px solid rgba(0,0,0,.08); padding-top: 6px; }
#edit-findbar .edit-replace-row[hidden] { display: none; }
#edit-findbar #edit-replace-input { flex: 1 1 auto; width: auto; min-width: 0; }
#edit-findbar button.edit-replace-btn { width: auto; height: 30px; min-width: 0; padding: 0 8px; border: 0; border-radius: 7px; background: transparent; color: #666; font: inherit; font-size: 15px; font-weight: 600; }
#edit-findbar button.edit-replace-btn:hover { background: #f0f0f0; color: #111; }
#cm-editor .cm-edit-find-hit { background: rgba(255, 213, 0, .38); }
/* Use the same thin scrollbar inside CodeMirror as the preview container. */
#cm-editor .CodeMirror-vscrollbar::-webkit-scrollbar { width: 10px; }
#cm-editor .CodeMirror-vscrollbar::-webkit-scrollbar-track { background: transparent; }
#cm-editor .CodeMirror-vscrollbar::-webkit-scrollbar-thumb { background: rgba(128,128,128,.45); border-radius: 6px; }
#cm-editor .CodeMirror-vscrollbar::-webkit-scrollbar-thumb:hover { background: rgba(128,128,128,.65); }
@media (prefers-color-scheme: dark) {
#app::-webkit-scrollbar-thumb { background: rgba(200,200,200,.35); }
#app::-webkit-scrollbar-thumb:hover { background: rgba(200,200,200,.55); }
#cm-editor .CodeMirror-vscrollbar::-webkit-scrollbar-thumb { background: rgba(200,200,200,.35); }
#cm-editor .CodeMirror-vscrollbar::-webkit-scrollbar-thumb:hover { background: rgba(200,200,200,.55); }
#edit-findbar .edit-replace-row { border-top-color: rgba(255,255,255,.12); }
#edit-findbar button.edit-replace-btn { color: #bbb; }
#edit-findbar button.edit-replace-btn:hover { background: #333; color: #fff; }
}

View File

@@ -3,7 +3,8 @@ __MDP_BASE_TAG__
<style id="hljs-code">__MDP_CSS_CODE__</style>
<style>
__MDP_PAGE_CSS__
</style></head><body class="__MDP_BODY_CLASS__">
</style>
<style id="cm-css">__MDP_CM_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">
@@ -24,9 +25,24 @@ __MDP_PAGE_CSS__
<button id="find-next" title="Next" aria-label="Next"></button>
<button id="find-close" title="Close" aria-label="Close"></button>
</div>
<div class="findbar" id="edit-findbar" role="search" hidden>
<div class="edit-find-row">
<input id="edit-find-input" type="search" placeholder="__MDP_SEARCH_PLACEHOLDER__" aria-label="__MDP_SEARCH_PLACEHOLDER__">
<span id="edit-find-state"></span>
<button id="edit-find-prev" title="Previous" aria-label="Previous"></button>
<button id="edit-find-next" title="Next" aria-label="Next"></button>
<button id="edit-find-close" title="Close" aria-label="Close"></button>
</div>
<div class="edit-replace-row" id="edit-replace-group" hidden>
<input id="edit-replace-input" type="text" placeholder="Replace with" aria-label="Replace with">
<button id="edit-replace-one" class="edit-replace-btn" type="button">Replace</button>
<button id="edit-replace-all" class="edit-replace-btn" type="button">Replace All</button>
</div>
</div>
<div id="app">
<div id="preview">__MDP_PREVIEW_HTML__</div>
<textarea id="editor" spellcheck="false">__MDP_RAW_MD_ESCAPED__</textarea>
<div id="cm-editor" aria-label="Source editor"></div>
</div>
<script>
__MDP_PAGE_JS__

View File

@@ -20,6 +20,16 @@
var findPrev = document.getElementById('find-prev');
var findNext = document.getElementById('find-next');
var findClose = document.getElementById('find-close');
var editFindBar = document.getElementById('edit-findbar');
var editFindInput = document.getElementById('edit-find-input');
var editFindState = document.getElementById('edit-find-state');
var editFindPrev = document.getElementById('edit-find-prev');
var editFindNextBtn = document.getElementById('edit-find-next');
var editFindClose = document.getElementById('edit-find-close');
var editReplaceGroup = document.getElementById('edit-replace-group');
var editReplaceInput = document.getElementById('edit-replace-input');
var editReplaceOne = document.getElementById('edit-replace-one');
var editReplaceAll = document.getElementById('edit-replace-all');
var tabsEl = document.getElementById('tabs');
var docStats = document.getElementById('doc-stats');
var tabOpen = document.getElementById('tab-open');
@@ -31,6 +41,7 @@
var tabDrag = null;
var suppressTabClickUntil = 0;
var ta = document.getElementById('editor');
var appEl = document.getElementById('app');
var dirty = false;
var activeTabId = 0;
var tabCount = 0;
@@ -49,6 +60,11 @@
// original start-up page. Set to false to keep the tab bar always on.
var HIDE_SINGLE_HOME_TAB = true;
var findHits = [];
var editFinding = false;
var editFindMatches = [];
var editFindIndex = -1;
var editFindOverlay = null;
var editFindTimer = 0;
var currentFindHit = -1;
var lastFindQuery = '';
var STAT_WORDS = '__MDP_STAT_WORDS_JS__';
@@ -61,12 +77,30 @@
var ZOOM_WHEEL_THROTTLE_MS = 90;
var zoomWheelAt = 0;
var zoomPercent = 100;
// CodeMirror is loaded on demand (first edit mode), never at startup.
var CM_MAX_BYTES = 2 * 1024 * 1024;
var CM_MAX_LINES = 20000;
var cm = null;
var cmLoading = false;
var cmDisabled = false;
var applyingRemote = false;
var pendingScrollRatio = 0;
var cmTabLines = {};
var fileHasBom = false;
var pendingEditFind = null;
// All source-text access goes through this adapter. The CodeMirror
// implementation replaces the returned object; callers never touch ta.
var ed = createTextareaEditor(ta);
ed.bind();
btnToggle.innerHTML = ICON_EDIT;
btnZoom.innerHTML = ICON_ZOOM;
findPrev.innerHTML = ICON_UP;
findNext.innerHTML = ICON_DOWN;
findClose.innerHTML = ICON_CLOSE;
editFindPrev.innerHTML = ICON_UP;
editFindNextBtn.innerHTML = ICON_DOWN;
editFindClose.innerHTML = ICON_CLOSE;
function inEdit() { return document.body.classList.contains('editing'); }
function textSegments(text) {
@@ -97,25 +131,79 @@
document.documentElement.style.setProperty('--content-scale', String(zoomPercent / 100));
btnZoomReset.textContent = zoomPercent + '%';
if (persist) queueZoomSave();
if (inEdit()) autoResize();
if (cm) updateEditorZoom();
else if (inEdit()) ed.resize();
}
function changeZoom(delta) {
applyZoom(zoomPercent + delta, true);
}
function cmTopLine() {
if (!cm) return 0;
var info = cm.getScrollInfo();
// +1px lands inside the first visible line instead of on its exact top
// boundary, where CM can report the previous line and drift one line per
// tab switch.
var line = cm.lineAtHeight(info.top + 1, 'local');
if (line > cm.lastLine()) line = cm.lastLine();
return line;
}
function cmScrollToLine(line) {
if (!cm) return;
if (line < 0) line = 0;
if (line > cm.lastLine()) line = cm.lastLine();
cm.scrollTo(null, Math.ceil(cm.heightAtLine(line, 'local')));
}
function cmRememberLine() {
if (!cm || !inEdit() || !activeTabId) return;
cmTabLines[activeTabId] = cmTopLine();
}
function currentScrollProgress() {
var root = document.documentElement;
var max = Math.max(root.scrollHeight - window.innerHeight, 0);
var y = window.scrollY || root.scrollTop || 0;
if (cm && inEdit()) {
var info = cm.getScrollInfo();
var cmMax = info.height - info.clientHeight;
if (cmMax <= 0) return 0;
var lineTop = cm.heightAtLine(cmTopLine(), 'local');
return Math.min(1, Math.max(0, lineTop / cmMax));
}
var max = Math.max(appEl.scrollHeight - appEl.clientHeight, 0);
var y = appEl.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) {
function restoreScrollProgress(progress, useRemembered) {
if (cm && inEdit()) {
pendingScrollRatio = progress;
var immediateLine = useRemembered ? cmTabLines[activeTabId] : undefined;
if (typeof immediateLine === 'number') cmScrollToLine(immediateLine);
var cmToken = ++scrollRestoreToken;
var applyCm = function() {
if (cmToken !== scrollRestoreToken) return;
var remembered = useRemembered ? cmTabLines[activeTabId] : undefined;
if (typeof remembered === 'number') {
cmScrollToLine(remembered);
return;
}
var info = cm.getScrollInfo();
var cmMax = Math.max(info.height - info.clientHeight, 0);
cm.scrollTo(null, cmMax * progress);
cmScrollToLine(cmTopLine());
};
requestAnimationFrame(function() {
if (cmToken !== scrollRestoreToken) return;
cm.refresh();
applyCm();
requestAnimationFrame(applyCm);
});
// Late layout inside CodeMirror can change the scroll height too.
setTimeout(applyCm, 150);
return;
}
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);
var max = Math.max(appEl.scrollHeight - appEl.clientHeight, 0);
appEl.scrollTop = max * progress;
}
restore();
requestAnimationFrame(function() {
@@ -138,10 +226,10 @@
}
}, 200);
}
window.addEventListener('scroll', reportScroll, { passive: true });
appEl.addEventListener('scroll', reportScroll, { passive: true });
applyZoom(100, false);
window.__mdPreviewSetZoom = function(percent) { applyZoom(percent, false); };
updateDocumentStats(ta.value);
updateDocumentStats(ed.value());
function shortenPath(path, max) {
if (!path || path.length <= max) return path || '';
var head = Math.ceil((max - 3) / 2);
@@ -208,7 +296,7 @@
return;
}
hideTabMenu();
if (!inEdit() || e.target !== ta) e.preventDefault();
if (!inEdit() || !ed.isTarget(e.target)) e.preventDefault();
});
function setDirty(d) {
if (dirty === d) return;
@@ -220,10 +308,13 @@
clearTimeout(pendingAutosaveTimer);
pendingAutosaveTimer = 0;
}
function fileContentForSave() {
return (fileHasBom ? '\uFEFF' : '') + ed.value();
}
function save() {
cancelPendingAutosave();
if (!dirty) return;
window.ipc.postMessage('save:' + ta.value);
window.ipc.postMessage('save:' + fileContentForSave());
}
function scheduleAutosave() {
cancelPendingAutosave();
@@ -235,13 +326,14 @@
}
window.__mdPreviewSave = save;
function requestTabAction(action, id) {
cmRememberLine();
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;
message += '\n' + fileContentForSave();
}
}
window.ipc.postMessage(message);
@@ -437,12 +529,11 @@
// 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;
var y = appEl.scrollTop;
ta.style.height = 'auto';
var h = Math.max(ta.scrollHeight, window.innerHeight);
var h = Math.max(ta.scrollHeight, appEl.clientHeight);
ta.style.height = h + 'px';
window.scrollTo(x, y);
appEl.scrollTop = y;
}
// ---- Source editor commands -------------------------------------------------
function editorLineStart(value, pos) {
@@ -552,7 +643,7 @@
var next = start + text.length;
replaceEditorRange(text, start, end, next, next);
}
ta.addEventListener('keydown', function(e) {
function editorKeydown(e) {
if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Tab' && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
@@ -563,9 +654,363 @@
e.preventDefault();
insertNewlineWithIndent();
}
});
}
function createTextareaEditor(ta) {
return {
value: function() { return ta.value; },
setValue: function(text) { ta.value = text; },
focus: function() {
try { ta.focus({ preventScroll: true }); } catch (_) { ta.focus(); }
},
selection: function() { return { start: ta.selectionStart, end: ta.selectionEnd }; },
setSelection: function(start, end) { try { ta.setSelectionRange(start, end); } catch (_) {} },
replaceRange: replaceEditorRange,
indent: indentEditor,
outdent: outdentEditor,
newlineWithIndent: insertNewlineWithIndent,
resize: autoResize,
isTarget: function(node) { return node === ta; },
bind: function() {
ta.addEventListener('keydown', editorKeydown);
ta.addEventListener('input', editorInput);
}
};
}
// ---- CodeMirror implementation -------------------------------------------
function updateEditorZoom() {
if (!cm) return;
cm.getWrapperElement().style.fontSize = (14 * zoomPercent / 100) + 'px';
cm.refresh();
}
function editorTooLarge() {
var text = ed.value();
if (text.length > CM_MAX_BYTES) return true;
return text.split('\n').length > CM_MAX_LINES;
}
function requestEditorSource() {
if (cm || cmLoading || cmDisabled) return;
if (editorTooLarge()) { cmDisabled = true; return; }
cmLoading = true;
if (window.ipc) window.ipc.postMessage('need-editor');
}
window.__mdpOnEditorSource = function() {
cmLoading = false;
if (cm || cmDisabled || typeof CodeMirror === 'undefined') return;
createCodeMirror();
};
function createCodeMirror() {
var host = document.getElementById('cm-editor');
if (!host) return;
try {
cm = CodeMirror(host, {
value: ed.value(),
mode: { name: 'markdown', highlightFormatting: true },
lineNumbers: true,
lineWrapping: true,
foldGutter: { rangeFinder: markdownFoldRange, minFoldSize: 0 },
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
foldOptions: { rangeFinder: markdownFoldRange, minFoldSize: 0, widget: '⋯' },
indentUnit: 2,
tabSize: 2,
indentWithTabs: false,
// Keep the file's UTF-8 BOM invisible: CM otherwise draws it as a
// red special-character dot. The value still round-trips on save.
specialChars: /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufff9-\ufffc]/g,
viewportMargin: 10,
extraKeys: {
'Tab': function(instance) {
if (instance.somethingSelected()) instance.execCommand('indentMore');
else instance.replaceSelection(INDENT, 'end');
},
'Shift-Tab': function(instance) {
if (instance.somethingSelected()) { instance.execCommand('indentLess'); return; }
var cursor = instance.getCursor();
var line = instance.getLine(cursor.line) || '';
var removed = line.charAt(0) === '\t' ? 1 : 0;
while (removed < INDENT.length && line.charAt(removed) === ' ') removed += 1;
if (removed) instance.replaceRange('', { line: cursor.line, ch: 0 }, { line: cursor.line, ch: removed });
},
'Enter': function(instance) { instance.execCommand('newlineAndIndent'); },
'Ctrl-F': function() { openEditFind(false); },
'Cmd-F': function() { openEditFind(false); },
'Ctrl-H': function() { openEditFind(true); },
'Cmd-H': function() { openEditFind(true); },
'Ctrl-S': function() { save(); },
'Cmd-S': function() { save(); },
'Esc': function() { if (editFinding) closeEditFind(); }
}
});
} catch (err) {
cm = null;
cmDisabled = true;
return;
}
ed = createCodeMirrorEditor(cm);
// CodeMirror 5 calls change handlers as (instance, changeObj). Naming the
// first argument `change` made `change.from` undefined; once the fold
// gutter had populated __mdpFenceCache this threw before setDirty(true),
// so edits after the first autosave never saved. Keep the object second.
cm.on('change', function(instance, change) {
if (applyingRemote) return;
if (cm.__mdpFenceCache && change && change.from) {
cm.__mdpFenceCache.validTo = Math.min(cm.__mdpFenceCache.validTo, change.from.line);
}
setDirty(true);
scheduleAutosave();
updateDocumentStats(ed.value());
});
cm.on('scroll', reportScroll);
updateEditorZoom();
if (pendingEditFind !== null) {
var pendingMode = pendingEditFind;
pendingEditFind = null;
openEditFind(pendingMode);
}
document.body.classList.toggle('cm-active', inEdit());
document.documentElement.classList.toggle('cm-editing', inEdit());
if (inEdit()) {
ed.focus();
restoreScrollProgress(pendingScrollRatio);
}
}
function createCodeMirrorEditor(instance) {
function setValue(text) {
applyingRemote = true;
instance.__mdpFenceCache = null;
try { instance.setValue(text); } finally { applyingRemote = false; }
}
return {
value: function() { return instance.getValue(); },
setValue: setValue,
focus: function() { instance.focus(); },
selection: function() {
var ranges = instance.listSelections();
var head = ranges && ranges.length ? ranges[0].head : instance.getCursor();
var anchor = ranges && ranges.length ? ranges[0].anchor : head;
return { start: instance.indexFromPos(anchor), end: instance.indexFromPos(head) };
},
setSelection: function(start, end) {
instance.setSelection(instance.posFromIndex(start), instance.posFromIndex(end));
},
replaceRange: function(text, start, end) {
instance.replaceRange(text, instance.posFromIndex(start), instance.posFromIndex(end));
},
indent: function() { instance.execCommand('indentMore'); },
outdent: function() { instance.execCommand('indentLess'); },
newlineWithIndent: function() { instance.execCommand('newlineAndIndent'); },
resize: function() { updateEditorZoom(); },
isTarget: function(node) { return instance.getWrapperElement().contains(node); },
bind: function() {}
};
}
// Fence state is cached per document and extended on demand: foldgutter
// asks for every visible line, so rescanning from the top each time would be
// O(n^2) on long files.
function fenceCharAt(instance, lineNo) {
var cache = instance.__mdpFenceCache;
if (!cache) {
cache = { validTo: 0, states: [null] };
instance.__mdpFenceCache = cache;
}
while (cache.validTo < lineNo) {
var state = cache.states[cache.validTo];
var text = instance.getLine(cache.validTo) || '';
var match = /^\s*(```+|~~~+)/.exec(text);
var next = state;
if (match) {
var ch = match[1].charAt(0);
if (!state) next = ch;
else if (state === ch) next = null;
}
cache.validTo += 1;
cache.states[cache.validTo] = next;
}
return cache.states[lineNo] || null;
}
function markdownFoldRange(instance, line) {
// CodeMirror passes a Pos here; accept a plain line number too.
var lineNo = typeof line === 'number' ? line : line.line;
var text = instance.getLine(lineNo);
if (!text) return null;
// Lines inside a fenced block (including its closing fence) only fold as
// part of that block.
if (fenceCharAt(instance, lineNo)) return null;
var fence = /^\s*(```+|~~~+)/.exec(text);
if (fence) {
var marker = fence[1];
var fenceEnd = -1;
for (var f = lineNo + 1; f <= instance.lastLine(); f += 1) {
var fenceLine = instance.getLine(f) || '';
if (/^\s*(```+|~~~+)\s*$/.test(fenceLine) && fenceLine.indexOf(marker.charAt(0)) >= 0) {
fenceEnd = f;
break;
}
}
if (fenceEnd > lineNo) {
return { from: CodeMirror.Pos(lineNo + 1, 0), to: CodeMirror.Pos(fenceEnd, instance.getLine(fenceEnd).length) };
}
return null;
}
var heading = /^(#{1,6})\s/.exec(text);
var level = heading ? heading[1].length : 0;
if (!heading) {
var underline = instance.getLine(lineNo + 1) || '';
if (text.trim() && /^(=+|-+)\s*$/.test(underline)) {
level = underline.charAt(0) === '=' ? 1 : 2;
}
}
if (!level) return null;
var endLine = lineNo;
for (var i = lineNo + 1; i <= instance.lastLine(); i += 1) {
var bodyLine = instance.getLine(i) || '';
if (fenceCharAt(instance, i)) { endLine = i; continue; }
if (/^\s*(```+|~~~+)/.test(bodyLine)) { endLine = i; continue; }
var nextHeading = /^(#{1,6})\s/.exec(bodyLine);
var nextLevel = nextHeading ? nextHeading[1].length : 0;
if (!nextHeading && bodyLine.trim()) {
var nextUnderline = instance.getLine(i + 1) || '';
if (/^(=+|-+)\s*$/.test(nextUnderline)) {
nextLevel = nextUnderline.charAt(0) === '=' ? 1 : 2;
}
}
if (nextLevel && nextLevel <= level) break;
if (bodyLine.trim()) endLine = i;
}
if (endLine <= lineNo) return null;
return { from: CodeMirror.Pos(lineNo + 1, 0), to: CodeMirror.Pos(endLine, instance.getLine(endLine).length) };
}
// ---- Edit-mode find/replace ----------------------------------------------
function editFindOverlayFor(query) {
var escaped = query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
var re = new RegExp(escaped, 'gi');
return { token: function(stream) {
re.lastIndex = stream.pos;
var match = re.exec(stream.string);
if (match && match.index === stream.pos) {
stream.pos += match[0].length || 1;
return 'edit-find-hit';
}
if (match) { stream.pos = match.index; } else { stream.skipToEnd(); }
}};
}
function editFindClearOverlay() {
if (cm && editFindOverlay) cm.removeOverlay(editFindOverlay);
editFindOverlay = null;
}
function editFindVisible(on) {
editFinding = on;
document.body.classList.toggle('edit-finding', on);
editFindBar.hidden = !on;
if (!on) {
if (editFindTimer) { clearTimeout(editFindTimer); editFindTimer = 0; }
editFindClearOverlay();
editFindMatches = [];
editFindIndex = -1;
editFindState.textContent = '';
if (cm && inEdit()) cm.focus();
}
}
function openEditFind(replaceMode) {
if (!inEdit()) return;
if (!cm) {
if (cmLoading) pendingEditFind = replaceMode;
return;
}
editReplaceGroup.hidden = !replaceMode;
editFindVisible(true);
var selected = cm.getSelection();
if (selected && selected.indexOf('\n') < 0) editFindInput.value = selected;
editFindInput.focus();
editFindInput.select();
editFindRun(true);
}
function closeEditFind() {
editFindVisible(false);
}
function editFindSelect(index) {
if (!editFindMatches.length) {
editFindIndex = -1;
editFindState.textContent = '';
return;
}
editFindIndex = (index + editFindMatches.length) % editFindMatches.length;
var match = editFindMatches[editFindIndex];
editFindState.textContent = (editFindIndex + 1) + '/' + editFindMatches.length;
cm.setSelection(match.from, match.to);
try { cm.scrollIntoView({ from: match.from, to: match.to }, 40); } catch (_) {}
}
function editFindRun(reset) {
if (!cm || !editFinding) return;
var query = editFindInput.value;
editFindClearOverlay();
editFindMatches = [];
editFindIndex = -1;
if (!query) {
editFindState.textContent = '';
return;
}
editFindOverlay = editFindOverlayFor(query);
cm.addOverlay(editFindOverlay);
var cursor = cm.getSearchCursor(query, CodeMirror.Pos(cm.firstLine(), 0), { caseFold: true });
while (cursor.findNext()) {
editFindMatches.push({ from: cursor.from(), to: cursor.to() });
if (editFindMatches.length >= 5000) break;
}
if (!editFindMatches.length) {
editFindState.textContent = '0/0';
return;
}
if (reset) {
var current = cm.getCursor('from');
var start = 0;
for (var i = 0; i < editFindMatches.length; i += 1) {
if (CodeMirror.cmpPos(editFindMatches[i].from, current) >= 0) { start = i; break; }
}
editFindSelect(start);
} else {
editFindSelect(0);
}
}
function editFindStep(backward) {
if (!editFinding) return;
if (!editFindMatches.length) { editFindRun(true); return; }
editFindSelect(editFindIndex + (backward ? -1 : 1));
}
function editFindReplaceOne() {
if (!cm || !editFinding) return;
var query = editFindInput.value;
if (!query) return;
if (!editFindMatches.length) editFindRun(true);
var match = editFindMatches[editFindIndex];
if (!match) return;
var replacement = editReplaceInput.value;
if (cm.getRange(match.from, match.to) !== cm.getSelection()) {
editFindSelect(editFindIndex);
return;
}
cm.replaceRange(replacement, match.from, match.to, '+input');
editFindRun(true);
}
function editFindReplaceAll() {
if (!cm || !editFinding) return;
var query = editFindInput.value;
if (!query) return;
if (!editFindMatches.length) editFindRun(true);
if (!editFindMatches.length) return;
var replacement = editReplaceInput.value;
var matches = editFindMatches.slice();
cm.operation(function() {
for (var i = matches.length - 1; i >= 0; i -= 1) {
cm.replaceRange(replacement, matches[i].from, matches[i].to, '+input');
}
});
editFindRun(true);
}
// Edit mode is per tab and owned by Rust; this only paints it.
function setEditMode(on) {
if (!on) pendingEditFind = null;
if (!on && editFinding) closeEditFind();
if (on && !cm && !cmDisabled) requestEditorSource();
if (on) {
document.body.classList.add('editing');
btnToggle.innerHTML = ICON_VIEW;
@@ -577,21 +1022,27 @@
btnToggle.title = L_EDIT;
btnToggle.setAttribute('aria-label', L_EDIT);
}
autoResize();
if (cm) {
document.body.classList.toggle('cm-active', on);
document.documentElement.classList.toggle('cm-editing', on);
if (on) cm.refresh();
} else {
document.documentElement.classList.remove('cm-editing');
ed.resize();
}
}
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');
}
if (document.body.classList.contains('home')) return;
if (document.body.classList.contains('finding')) hideFind();
var progress = currentScrollProgress();
pendingScrollRatio = progress;
setEditMode(true);
ed.focus();
restoreScrollProgress(progress);
if (window.ipc) window.ipc.postMessage('edit-mode:' + activeTabId + ':1');
}
function leaveEdit() {
cmRememberLine();
var progress = currentScrollProgress();
if (dirty) save();
setEditMode(false);
@@ -659,7 +1110,7 @@
drag.element.classList.remove('dragging');
});
window.addEventListener('resize', hideTabMenu);
window.addEventListener('scroll', hideTabMenu, true);
appEl.addEventListener('scroll', hideTabMenu, true);
window.addEventListener('blur', hideTabMenu);
document.addEventListener('click', function(e) {
if (Date.now() < suppressTabClickUntil) {
@@ -723,6 +1174,22 @@
findPrev.addEventListener('click', function() { runFind(true); });
findNext.addEventListener('click', function() { runFind(false); });
findClose.addEventListener('click', hideFind);
editFindInput.addEventListener('input', function() {
if (editFindTimer) clearTimeout(editFindTimer);
editFindTimer = setTimeout(function() { editFindTimer = 0; editFindRun(true); }, 120);
});
editFindInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter') { e.preventDefault(); editFindStep(e.shiftKey); }
else if (e.key === 'Escape') { e.preventDefault(); closeEditFind(); }
});
editFindPrev.addEventListener('click', function() { editFindStep(true); });
editFindNextBtn.addEventListener('click', function() { editFindStep(false); });
editFindClose.addEventListener('click', closeEditFind);
editReplaceOne.addEventListener('click', editFindReplaceOne);
editReplaceAll.addEventListener('click', editFindReplaceAll);
editReplaceInput.addEventListener('keydown', function(e) {
if (e.key === 'Escape') { e.preventDefault(); closeEditFind(); }
});
btnToggle.addEventListener('click', function() {
window.__mdPreviewToggleEdit();
@@ -744,13 +1211,14 @@
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(); });
function editorInput() { setDirty(true); scheduleAutosave(); autoResize(); updateDocumentStats(ta.value); }
window.addEventListener('resize', function() { if (inEdit()) ed.resize(); });
document.addEventListener('click', function(e) {
if (!zoomControl.contains(e.target)) zoomControl.classList.remove('open');
});
document.addEventListener('keydown', function(e) {
if (e.defaultPrevented) return;
if (e.key === 'Escape' && tabMenu && !tabMenu.hidden) {
hideTabMenu();
return;
@@ -793,12 +1261,17 @@
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();
if (inEdit()) { openEditFind(false); return; }
var seed = (document.body.classList.contains('finding') && document.activeElement === findInput) ? null : selectionSeed();
showFind(seed ? seed.text : '', seed ? seed.top : null);
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'h' || e.key === 'H') && inEdit()) {
e.preventDefault();
openEditFind(true);
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'e' || e.key === 'E')) {
e.preventDefault();
if (inEdit()) leaveEdit(); else enterEdit();
@@ -815,7 +1288,6 @@
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
@@ -841,7 +1313,8 @@
else base.removeAttribute('href');
};
window.__markSaved = function(savedRaw) {
if (typeof savedRaw === 'string' && ta.value !== savedRaw) {
var savedText = typeof savedRaw === 'string' ? savedRaw.replace(/^\uFEFF/, '') : savedRaw;
if (typeof savedText === 'string' && ed.value().replace(/^\uFEFF/, '') !== savedText) {
window.ipc.postMessage('dirty:1');
return;
}
@@ -863,6 +1336,7 @@
};
window.__setTabs = function(tabs) {
hideTabMenu();
var previousActiveTabId = activeTabId;
tabs = Array.isArray(tabs) ? tabs : [];
tabCount = tabs.length;
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1;
@@ -902,6 +1376,10 @@
tabsEl.appendChild(item);
if (tab.active) requestAnimationFrame(function() { item.scrollIntoView({ block: 'nearest', inline: 'nearest' }); });
});
if (activeTabId && activeTabId !== previousActiveTabId && cm && inEdit() &&
typeof cmTabLines[activeTabId] === 'number') {
cmScrollToLine(cmTabLines[activeTabId]);
}
};
tabsEl.addEventListener('keydown', function(e) {
if (e.key !== 'Enter' && e.key !== ' ') return;
@@ -910,48 +1388,60 @@
e.preventDefault();
requestTabAction('activate', tab.getAttribute('data-tab-id'));
});
window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid, editing, scrollRatio) {
window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid, editing, scrollRatio, tabId) {
var previousTabId = activeTabId;
var switched = typeof tabId === 'number' && tabId !== previousTabId;
if (cm && inEdit() && previousTabId) cmTabLines[previousTabId] = cmTopLine();
if (typeof tabId === 'number' && tabId) activeTabId = tabId;
if (editFinding) closeEditFind();
document.body.classList.remove('home');
document.body.classList.remove('missing');
hideFind();
window.__setBaseHref(baseHref);
window.__setPreview(previewHtml, needsMath, needsMermaid);
if (!inEdit() || !dirty) {
if (switched || !inEdit() || !dirty) {
autosavePaused = false;
ta.value = rawMd;
updateDocumentStats(rawMd);
var loaded = typeof rawMd === 'string' ? rawMd : '';
fileHasBom = loaded.charAt(0) === '\uFEFF';
var editorText = fileHasBom ? loaded.slice(1) : loaded;
ed.setValue(editorText);
updateDocumentStats(editorText);
setDirty(false);
}
setEditMode(!!editing);
restoreScrollProgress(typeof scrollRatio === 'number' ? scrollRatio : 0);
restoreScrollProgress(typeof scrollRatio === 'number' ? scrollRatio : 0, true);
};
window.__setEmptyPreview = function(previewHtml) {
if (editFinding) closeEditFind();
document.body.classList.add('home');
document.body.classList.remove('missing');
setEditMode(false);
cancelPendingAutosave();
autosavePaused = false;
hideFind();
fileHasBom = false;
window.__setBaseHref('');
document.getElementById('preview').innerHTML = previewHtml;
ta.value = '';
ed.setValue('');
updateDocumentStats('');
setDirty(false);
window.scrollTo(0, 0);
appEl.scrollTop = 0;
};
window.__setMissing = function(previewHtml) {
if (editFinding) closeEditFind();
document.body.classList.remove('home');
document.body.classList.add('missing');
setEditMode(false);
cancelPendingAutosave();
autosavePaused = false;
hideFind();
fileHasBom = false;
window.__setBaseHref('');
document.getElementById('preview').innerHTML = previewHtml;
ta.value = '';
ed.setValue('');
updateDocumentStats('');
setDirty(false);
window.scrollTo(0, 0);
appEl.scrollTop = 0;
};
// Defer hljs parse + initial highlight to idle time.

1996
src/app.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -9,7 +9,7 @@ use tao::window::{Theme, Window};
pub const DEFAULT_W: f64 = 900.0;
pub const DEFAULT_H: f64 = 700.0;
use crate::UserEvent;
use crate::app::UserEvent;
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum ThemeChoice {
@@ -210,3 +210,26 @@ pub fn centered_geom(event_loop: &EventLoop<UserEvent>) -> WindowGeom {
}
}
}
#[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");
}
}

458
src/files.rs Normal file
View 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"));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -393,6 +393,7 @@ fn unique_heading_id(base: String, seen: &mut HashMap<String, usize>) -> String
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::temp_dir;
#[test]
fn base64_matches_known_vectors() {
@@ -402,4 +403,226 @@ mod tests {
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 &amp; 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("![pixel](assets/pixel.png)", 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("![missing](assets/missing.png)", 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("![secret](../secret.png)", 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: &lt;script&gt;alert(1)&lt;/script&gt;"));
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>"#));
}
}

View File

@@ -8,15 +8,21 @@
//! 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};
use crate::EnhanceFlags;
use crate::Strings;
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");
const CM_CSS: &str = concat!(
include_str!("../assets/codemirror/codemirror.min.css"),
"\n",
include_str!("../assets/codemirror/addon/fold/foldgutter.css"),
"\n",
include_str!("../assets/codemirror/addon/dialog/dialog.css"),
);
pub fn build_page(
preview_html: &str,
@@ -32,6 +38,7 @@ pub fn build_page(
PAGE_HTML
.replace("__MDP_CSS_CODE__", HLJS_CODE)
.replace("__MDP_CM_CSS__", CM_CSS)
.replace("__MDP_PAGE_CSS__", PAGE_CSS)
.replace("__MDP_PAGE_JS__", PAGE_JS)
.replace("__MDP_PREVIEW_ENHANCE_JS__", PREVIEW_ENHANCE_JS)
@@ -63,3 +70,294 @@ pub fn build_page(
.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_loads_codemirror_lazily_on_first_edit() {
let strings = Strings::english();
let page = build_page(
&md_to_html("# Hello"),
"# Hello",
None,
EnhanceFlags::default(),
&strings,
false,
);
// The editor bundle arrives through Rust on demand, never in the
// first-paint HTML; the page only declares the host and the hook.
assert!(page.contains(r#"<div id="cm-editor""#));
assert!(page.contains("window.ipc.postMessage('need-editor')"));
assert!(page.contains("window.__mdpOnEditorSource"));
assert!(page.contains("function createCodeMirror()"));
assert!(page.contains("CM_MAX_BYTES = 2 * 1024 * 1024"));
assert!(page.contains("CodeMirror-linenumbers"));
assert!(page.contains("rangeFinder: markdownFoldRange"));
assert!(page.contains("body.finding .findbar:not(#edit-findbar)"));
assert!(page.contains("var fileHasBom = false"));
assert!(page.contains("function fileContentForSave()"));
assert!(page.contains("pendingEditFind"));
assert!(page.contains("var switched ="));
assert!(page.contains("function fenceCharAt"));
assert!(page.contains("__mdpFenceCache"));
assert!(page.contains("specialChars: /["));
assert!(!page.contains("\\ufeff"));
assert!(page.contains("openEditFind(false)"));
assert!(page.contains("openEditFind(true)"));
assert!(!page.contains("CodeMirror.defineMode"));
}
#[test]
fn editor_change_handler_uses_the_codemirror_instance_and_change_object() {
let strings = Strings::english();
let page = build_page(
&md_to_html("# Hello"),
"# Hello",
None,
EnhanceFlags::default(),
&strings,
false,
);
// CodeMirror 5 calls change handlers as (instance, changeObj). Using the
// first argument as the change object made change.from undefined; once
// the fold cache existed, the handler threw before setDirty(true), so
// edits after the first autosave were never marked dirty or saved.
assert!(page.contains("cm.on('change', function(instance, change) {"));
assert!(
page.contains(
"if (applyingRemote) return;\n if (cm.__mdpFenceCache && change && change.from) {"
),
"the remote guard must run before the fold-cache update"
);
assert!(!page.contains("cm.on('change', function(change) {"));
}
#[test]
fn edit_mode_find_bar_has_clickable_controls_and_no_escape_exit() {
let strings = Strings::english();
let page = build_page(
&md_to_html("# A\n\ntext"),
"# A\n\ntext",
None,
EnhanceFlags::default(),
&strings,
false,
);
assert!(page.contains(r#"id="edit-findbar""#));
assert!(page.contains(r#"id="edit-find-input""#));
assert!(page.contains(r#"id="edit-find-prev""#));
assert!(page.contains(r#"id="edit-find-next""#));
assert!(page.contains(r#"id="edit-replace-input""#));
assert!(page.contains(r#"id="edit-replace-all""#));
assert!(page.contains("function openEditFind(replaceMode)"));
assert!(page.contains("function closeEditFind()"));
assert!(page.contains("cm.getSearchCursor(query"));
assert!(page.contains("document.documentElement.classList.toggle('cm-editing'"));
assert!(page.contains("minFoldSize: 0"));
assert!(page.contains("var lineNo = typeof line === 'number'"));
assert!(page.contains("appEl.addEventListener('scroll', reportScroll"));
assert!(page.contains("cm.lineAtHeight(info.top + 1, 'local')"));
assert!(page.contains("function cmScrollToLine(line)"));
assert!(page.contains("width: min(560px, calc(100vw - 32px))"));
assert!(page.contains("edit-find-row"));
assert!(page.contains("widget: '⋯'"));
// Escape closes the find bar; it must not leave edit mode anymore.
assert!(!page.contains("if (e.key === 'Escape' && inEdit()) { leaveEdit(); }"));
assert!(!page.contains("'Esc': function() { leaveEdit(); }"));
}
#[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)"));
}
}

18
src/testutil.rs Normal file
View 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
}