13 Commits

22 changed files with 916 additions and 70 deletions

View File

@@ -10,13 +10,13 @@
> 成品只发布到 `C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe`(Medium),仓库内不再放 exe。
> 本文第 4 节等处的 “Medium / danger-full-access” 是旧模型;以 `agent/docs/migration-2026-11-02.md` 和 `AGENTS.md` 为准。
>
> **2026-11-06**:功能不变的重构继续拆出 `src/files.rs` 与 `src/app.rs`;`main.rs` 只剩入口(`app::run()`);测试各随模块,60 tests 全绿。剩余项见 `agent/docs/next-2026-11-03.md` §3。
> **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`)
- 改造目标:**本地预览器,不联网、不自动更新**;预览/编辑/标签/会话等功能与上游一致
- 源码规模(2026-11-06):`src/main.rs` 18 行(入口)、`src/app.rs` 1934 行(CLI/启动/状态/渲染/事件循环)、`src/markdown.rs` 628 行、`src/session.rs` 488 行、`src/files.rs` 458 行、`src/page.rs` 260 行、`src/config.rs` 235 行、`src/instance.rs` 207 行、`src/escape.rs` 25 行;页面资源在 `assets/page/`
- 源码规模(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` 删除

View File

@@ -218,17 +218,22 @@ cargo test
- 架构拆分阶段 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 这条边界没有编译器检查。
- 白屏 bug(2026-11-04 修复):当时 `render_active_document` 给 `window.__setContent` 传了 8 个参数,页面签名只有 7 个(多传了 `active.id`),标签 id 被当成 `previewHtml` 渲染——窗口白屏、打开标签依次显示 1/2/3/4。修复:抽出 `set_content_script()`(单一参数源),新增精确输出 + 页面签名对照测试 `set_content_script_matches_the_page_signature`(60 tests)。教训:Rust→JS 这条边界没有编译器检查。
- 发布前 UI 冒烟:`agent/tests/ui-smoke.cmd`(普通桌面 PowerShell;启动 CDP、断言页面渲染、截图、写 `target/ui-test/ui-smoke.json`)。DSH 沙箱禁止命名管道,WebView2/Chromium 在沙箱内无法启动(窗口白屏、`msedgewebview2.exe` 立即退出),所以这一项只能由用户手动跑。**2026-11-04 已在本机跑通:8/8 checks,截图确认页面正常渲染**(`target/ui-test/ui-smoke.png`,不入库)。
- 规则调整(`agent/AGENTS.md`):仓库内新增文件/拆模块不需要事先询问;bug 修复、重构、测试、文档可直接做(每项独立提交);只有仓库外修改、发布、新第三方库(>200 KB vendored 资源)和不变量变化需要先问。
- 编辑区样式化(2026-11-06 决定,未开工):**改用内嵌 CodeMirror 5**(MIT、离线 vendored,core + markdown/xml mode + search/fold/lineNumbers 约 +270–320 KB,vendor 时附 LICENSE)。
- 理由:行号、**编辑区折叠**、替换已确认近期要做;透明叠加层(方案 A)只能做同字号着色,覆盖不了这三项。自研 contenteditable(方案 B)不做。
- 集成前先在 page.js 立**编辑器适配层**(`getValue/setValue/focus/getScrollRatio/setScrollRatio/onChange/setEditable`),textarea 与 CM5 共用同一套 autosave/标签状态/注入逻辑。
- 集成要点:编辑模式改为 CM 内部滚动(编辑时隐藏页面滚动条),按标签分别记录编辑/阅读滚动比例;标记保持显示(markdown mode 的 `cm-formatting` 标记 + `cm-strong` 内容加粗);autosave 仍 700ms;替换用 search 插件,阅读模式的既有 find 不动。
- 编辑区 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`(当前 60)、`cargo clippy --all-targets`、`cargo fmt -- --check`、`agent\scripts\build.ps1`。
- 代码级:`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):ui-smoke 8/8 checks,截图确认页面正常渲染。
- 已验证(2026-11-04、2026-11-06 多次):ui-smoke 8/8 checks,截图确认页面正常渲染。CM5 改版后由用户手动验证编辑/保存/折叠/替换/滚动,ui-smoke 仍 8/8。

View File

@@ -35,7 +35,7 @@
- 影响:新机器上应用不再自动出现在“打开方式”;首次在 Windows“打开方式 → 选择其他应用”里选一次;exe 移动后由发布脚本刷新关联。
- README 第 3 步、STATUS §11 已同步。
### 4.2 编辑区样式化(2026-11-06 决定:内嵌 CodeMirror 5)
### 4.2 编辑区样式化(已完成:内嵌 CodeMirror 5,2026-11-06)
需求:编辑模式里 `**加粗**` 显示为粗体、`# 标题` 整行加粗加大、行内代码换字体。**标记保持显示**。用户已确认行号、编辑区折叠、替换近期一定会做。
@@ -54,7 +54,13 @@
5. autosave 仍 700ms,接 `onChange`;`__setContent`/标签切换/缩放/暗色主题都要重新验证;超大文档保护(>2 MB 或 >2 万行)可保留。
6. 阅读模式既有 find 与折叠不动;编辑模式 find/replace 由 CM search 提供,UI 统一是后续小工作。
**验证**:用户跑 `agent/tests/ui-smoke.cmd` + 手动冒烟(编辑/保存/切标签/折叠/替换/IME/滚动切换)。
**状态(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. 验证配方

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;
@@ -373,4 +378,92 @@ body.editing #app { max-width: none; padding: 0; }
#preview pre { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
#preview .mdp-fold-body { display: block !important; }
#preview .mdp-fold-toggle { display: none !important; }
}
}
/* ---- 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,359 @@
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);
cm.on('change', function(change) {
if (cm.__mdpFenceCache) {
cm.__mdpFenceCache.validTo = Math.min(cm.__mdpFenceCache.validTo, change.from.line);
}
if (applyingRemote) return;
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 +1018,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 +1106,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 +1170,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 +1207,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 +1257,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 +1284,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 +1309,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 +1332,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 +1372,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 +1384,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.

View File

@@ -58,6 +58,7 @@ pub(crate) enum UserEvent {
Quit,
RecentChanged,
Ready(WindowId), // first paint landed: inject hljs now; if bench mode, also exit
NeedEditor(WindowId), // first edit mode: inject CodeMirror, then call the page hook
}
pub(crate) struct WindowState {
@@ -201,6 +202,36 @@ pub(crate) const HLJS_EXTRA_LANGS: &str = concat!(
// Delphi / Pascal (aliases: dpr, dfm, pas, pascal) — user requested
include_str!("../assets/hljs/delphi.min.js"),
);
// CodeMirror 5.65.16 (MIT, vendored under assets/codemirror). The bundle is
// only evaluated when the page asks for it on the first edit-mode switch, so
// the ~230 KB never touches the first-paint HTML.
const CM_SOURCE: &str = concat!(
include_str!("../assets/codemirror/codemirror.min.js"),
";\n",
include_str!("../assets/codemirror/mode/xml/xml.min.js"),
";\n",
include_str!("../assets/codemirror/mode/meta.min.js"),
";\n",
include_str!("../assets/codemirror/mode/markdown/markdown.min.js"),
";\n",
include_str!("../assets/codemirror/addon/search/searchcursor.min.js"),
";\n",
include_str!("../assets/codemirror/addon/search/search.min.js"),
";\n",
include_str!("../assets/codemirror/addon/dialog/dialog.min.js"),
";\n",
include_str!("../assets/codemirror/addon/fold/foldcode.min.js"),
";\n",
include_str!("../assets/codemirror/addon/fold/foldgutter.min.js"),
);
pub(crate) fn cm_bootstrap() -> String {
format!(
"(function(){{{source}\nwindow.__mdpEditorSourceReady=true;if(window.__mdpOnEditorSource)window.__mdpOnEditorSource();}})();",
source = CM_SOURCE
)
}
const KATEX_JS: &str = include_str!("../assets/katex/katex.min.js");
const KATEX_CSS: &str = include_str!("../assets/katex/katex.inline.css");
const MERMAID_JS: &str = include_str!("../assets/mermaid/mermaid.min.js");
@@ -538,16 +569,18 @@ pub(crate) fn set_content_script(
flags: EnhanceFlags,
editing: bool,
scroll_ratio: f32,
tab_id: u64,
) -> String {
format!(
"if(window.__setContent)window.__setContent('{}', '{}', '{}', {}, {}, {}, {});",
"if(window.__setContent)window.__setContent('{}', '{}', '{}', {}, {}, {}, {}, {});",
escape_js(html),
escape_js(raw),
escape_js(base_href),
flags.math,
flags.mermaid,
editing,
scroll_ratio
scroll_ratio,
tab_id
)
}
@@ -587,6 +620,7 @@ fn render_active_document(
flags,
active.editing,
active.scroll_ratio,
active.id,
));
for script in build_enhancer_bootstrap(flags, *loaded_enhancers) {
let _ = webview.evaluate_script(&script);
@@ -784,6 +818,8 @@ pub(crate) fn build_webview(
let _ = proxy_for_ipc.send_event(UserEvent::Print(window_id));
} else if body == "ready" {
let _ = proxy_for_ipc.send_event(UserEvent::Ready(window_id));
} else if body == "need-editor" {
let _ = proxy_for_ipc.send_event(UserEvent::NeedEditor(window_id));
} else if let Some(percent) = body.strip_prefix("zoom:") {
if let Ok(percent) = percent.parse::<u32>() {
save_zoom(percent);
@@ -999,6 +1035,7 @@ pub(crate) fn run_event_loop(
mut app: AppState,
proxy: EventLoopProxy<UserEvent>,
hljs_bootstrap: String,
editor_bootstrap: String,
bench: bool,
t0: Instant,
) {
@@ -1529,6 +1566,11 @@ pub(crate) fn run_event_loop(
ws.window.set_theme(choice.tao_theme());
}
}
TaoEvent::UserEvent(UserEvent::NeedEditor(window_id)) => {
if let Some(ws) = app.windows.get_mut(&window_id) {
let _ = ws.webview.evaluate_script(&editor_bootstrap);
}
}
TaoEvent::UserEvent(UserEvent::Ready(window_id)) => {
let Some(ws) = app.windows.get_mut(&window_id) else {
return;
@@ -1765,6 +1807,8 @@ pub(crate) fn run() {
hljs_extra = HLJS_EXTRA_LANGS,
);
let editor_bootstrap = cm_bootstrap();
// File watcher state
let watcher_holder: Arc<Mutex<Option<notify::RecommendedWatcher>>> = Arc::new(Mutex::new(None));
@@ -1800,7 +1844,15 @@ pub(crate) fn run() {
web_context,
};
run_event_loop(event_loop, app, proxy, hljs_bootstrap, bench, t0);
run_event_loop(
event_loop,
app,
proxy,
hljs_bootstrap,
editor_bootstrap,
bench,
t0,
);
}
#[cfg(test)]
@@ -1869,10 +1921,11 @@ mod tests {
},
true,
0.25,
5,
);
assert_eq!(
script,
"if(window.__setContent)window.__setContent('<p>x</p>', '# x', 'file:///D:/tmp/', true, false, true, 0.25);"
"if(window.__setContent)window.__setContent('<p>x</p>', '# x', 'file:///D:/tmp/', true, false, true, 0.25, 5);"
);
// The page must declare the same argument order; a mismatch renders a
@@ -1886,10 +1939,19 @@ mod tests {
true,
);
assert!(page.contains(
"window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid, editing, scrollRatio)"
"window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid, editing, scrollRatio, tabId)"
));
}
#[test]
fn editor_bootstrap_injects_codemirror_and_hands_off_to_the_page() {
let script = cm_bootstrap();
assert!(script.contains("defineMode(\"markdown\""));
assert!(script.contains("window.__mdpEditorSourceReady"));
assert!(script.contains("window.__mdpOnEditorSource"));
assert!(script.len() > 200_000);
}
#[test]
fn empty_state_exposes_open_and_recent_files() {
let strings = Strings::english();

View File

@@ -16,6 +16,13 @@ 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,
@@ -31,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)
@@ -221,6 +229,76 @@ mod tests {
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 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();