2 Commits

Author SHA1 Message Date
d5ba2495ba docs: record the page/markdown module split 2026-11-03 23:03:44 +08:00
1115052762 refactor: split the page, markdown pipeline and escaping out of main.rs
- assets/page/{page.html,page.css,page.js} now hold the UI. build_page only
  fills __MDP_*__ placeholders, so editing the page no longer means escaping
  braces inside a format! string. Output was verified byte-identical for the
  home page, a math/mermaid document and the startup page.
- src/markdown.rs: md -> html pipeline (GFM, AI-output dialect, front matter,
  embedded images, ==highlight==, heading ids).
- src/page.rs: page assembly.
- src/escape.rs: shared JS/HTML escaping.
- src/main.rs drops from 5535 to 3709 lines. No behavior change; 62 tests.
2026-11-03 23:02:58 +08:00
9 changed files with 1889 additions and 1836 deletions

View File

@@ -14,7 +14,7 @@
- 上游版本:`md-preview 1.4.2`(源码来自 `backup/md-preview-master.zip`) - 上游版本:`md-preview 1.4.2`(源码来自 `backup/md-preview-master.zip`)
- 改造目标:**本地预览器,不联网、不自动更新**;预览/编辑/标签/会话等功能与上游一致 - 改造目标:**本地预览器,不联网、不自动更新**;预览/编辑/标签/会话等功能与上游一致
- 源码规模:`src/main.rs` 5535 行、`src/session.rs` 488 行、`src/instance.rs` 207 行 - 源码规模:`src/main.rs` 3709 行、`src/session.rs` 488 行、`src/instance.rs` 207 行;`src/markdown.rs` 405 行、`src/page.rs` 65 行、`src/escape.rs` 25 行;页面资源在 `assets/page/`
- 当前产物(2026-11-02 起):`C:\Users\wucl1\Nutstore\1\Scripts\MD-Preview-windows-x64.exe` - 当前产物(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 字节) - 当前发布版见 `STATUS.md` 第 2 节(v1.4.2-local.5,5,505,024 字节)
- 仓库内不再放成品 exe;旧 `D:\Scripts\md-preview\MD-Preview-windows-x64.exe` 由 `publish.ps1` 删除 - 仓库内不再放成品 exe;旧 `D:\Scripts\md-preview\MD-Preview-windows-x64.exe` 由 `publish.ps1` 删除

View File

@@ -212,6 +212,7 @@ cargo test
- `.txt` 不再作为文档类型:打开、重新定位、本地链接、命令行都只认 `md/markdown/mdown/mkd`。 - `.txt` 不再作为文档类型:打开、重新定位、本地链接、命令行都只认 `md/markdown/mdown/mkd`。
- 非 md 本地链接(pdf/png/html)仍无反应,仅记录,不处理。 - 非 md 本地链接(pdf/png/html)仍无反应,仅记录,不处理。
- 代码整理:`cargo fmt` 通过;clippy 7 条清零;保存写盘合并为 `save_active_file()`;`build.ps1` 的禁止字符串不再包含泛化的 `powershell`。 - 代码整理:`cargo fmt` 通过;clippy 7 条清零;保存写盘合并为 `save_active_file()`;`build.ps1` 的禁止字符串不再包含泛化的 `powershell`。
- 架构拆分(功能不变,`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 对比,逐字节一致。
- 规则调整(`agent/AGENTS.md`):仓库内新增文件/拆模块不需要事先询问;bug 修复、重构、测试、文档可直接做(每项独立提交);只有仓库外修改、发布、新第三方库(>200 KB vendored 资源)和不变量变化需要先问。 - 规则调整(`agent/AGENTS.md`):仓库内新增文件/拆模块不需要事先询问;bug 修复、重构、测试、文档可直接做(每项独立提交);只有仓库外修改、发布、新第三方库(>200 KB vendored 资源)和不变量变化需要先问。
- 下一步(讨论中,未动手):编辑区样式化——加粗、标题加粗加大、行内代码换字体。 - 下一步(讨论中,未动手):编辑区样式化——加粗、标题加粗加大、行内代码换字体。
- 技术前提:`<textarea>` 不支持字符级样式;改字号会改变软换行与光标位置,透明叠加层只适合“同字号”样式。 - 技术前提:`<textarea>` 不支持字符级样式;改字号会改变软换行与光标位置,透明叠加层只适合“同字号”样式。

376
assets/page/page.css Normal file
View File

@@ -0,0 +1,376 @@
:root { color-scheme: light dark; --chrome-top: 10px; --content-scale: 1; }
/* Reserve scrollbar space permanently so the fixed toolbar doesn't shift
between modes (one with scrollbar, one without). */
html { overflow-y: scroll; scrollbar-gutter: stable; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
margin: 0; padding: 0;
line-height: 1.6; font-size: 15px;
color: #1a1a1a; background: #fff;
}
body.has-tabs { --chrome-top: 50px; }
#app { width: 100%; box-sizing: border-box; margin: 0 auto; padding: 24px 48px; }
#preview { font-size: calc(15px * var(--content-scale)); }
#preview .front-matter {
margin: 0 0 1.5em;
padding: .85em 0;
border-top: 1px solid #e1e4e8;
border-bottom: 1px solid #e1e4e8;
color: #59636e;
}
#preview .front-matter pre {
margin: 0;
padding: 0;
border-radius: 0;
overflow: visible;
background: transparent;
color: inherit;
font: inherit;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
#preview h1,#preview h2,#preview h3,#preview h4 { margin-top: 1.4em; }
#preview h1 { border-bottom: 1px solid #e1e4e8; padding-bottom: .3em; }
#preview h2 { border-bottom: 1px solid #e1e4e8; padding-bottom: .2em; }
/* Heading folding: triangle shows on heading hover; the body collapses down to
the next heading of the same or higher level. State is per-render only. */
#preview .mdp-fold > h1,
#preview .mdp-fold > h2,
#preview .mdp-fold > h3,
#preview .mdp-fold > h4,
#preview .mdp-fold > h5,
#preview .mdp-fold > h6 { position: relative; }
/* Fixed 90%-of-H2 size for every heading level. */
#preview .mdp-fold-toggle {
position: absolute; left: -34px; top: 50%;
width: 30px; height: 30px; padding: 0; border: 0; border-radius: 50%;
transform: translateY(-50%);
display: grid; place-items: center;
background: transparent; color: #999; cursor: pointer;
opacity: 0; transition: opacity .12s ease, background .12s ease;
}
#preview .mdp-fold-toggle svg { grid-area: 1 / 1; overflow: visible; }
#preview .mdp-fold-toggle .mdp-fold-i-right { display: none; width: 13.5px; height: 20px; }
#preview .mdp-fold-toggle .mdp-fold-i-down { display: block; width: 20px; height: 13.5px; }
#preview h1:hover > .mdp-fold-toggle,
#preview h2:hover > .mdp-fold-toggle,
#preview h3:hover > .mdp-fold-toggle,
#preview h4:hover > .mdp-fold-toggle,
#preview h5:hover > .mdp-fold-toggle,
#preview h6:hover > .mdp-fold-toggle,
#preview .mdp-fold-toggle:focus-visible { opacity: .6; }
#preview .mdp-fold-toggle:hover { opacity: 1; background: rgba(0,0,0,.07); }
#preview .mdp-fold.collapsed > :is(h1, h2, h3, h4, h5, h6) > .mdp-fold-toggle .mdp-fold-i-right { display: block; }
#preview .mdp-fold.collapsed > :is(h1, h2, h3, h4, h5, h6) > .mdp-fold-toggle .mdp-fold-i-down { display: none; }
#preview .mdp-fold.collapsed > .mdp-fold-body { display: none; }
#preview code { background: #f0f0f0; padding: 2px 6px; border-radius: 4px; font-size: 90%; }
/* Code blocks stay dark (VS Dark) even in the light app theme. */
#preview pre { background: #1e1e1e; color: #d4d4d4; padding: 16px; border-radius: 8px; overflow-x: auto; }
#preview pre code { background: none; padding: 0; font-size: 14px; }
#preview blockquote { border-left: 4px solid #ddd; margin: 0; padding: 0 1em; color: #666; }
#preview .markdown-alert-note,
#preview .markdown-alert-tip,
#preview .markdown-alert-important,
#preview .markdown-alert-warning,
#preview .markdown-alert-caution {
margin: 1em 0;
padding: 0.75em 1em;
border-radius: 6px;
color: inherit;
}
#preview .markdown-alert-title {
display: flex;
align-items: center;
gap: .35em;
margin: 0 0 .45em;
font-weight: 600;
line-height: 1.25;
}
#preview .markdown-alert-title + p { margin-top: 0; }
#preview .markdown-alert-note { border-color: #0969da; background: #ddf4ff; }
#preview .markdown-alert-tip { border-color: #1a7f37; background: #dafbe1; }
#preview .markdown-alert-important { border-color: #8250df; background: #fbefff; }
#preview .markdown-alert-warning { border-color: #9a6700; background: #fff8c5; }
#preview .markdown-alert-caution { border-color: #cf222e; background: #ffebe9; }
#preview .markdown-alert-note .markdown-alert-title { color: #0969da; }
#preview .markdown-alert-tip .markdown-alert-title { color: #1a7f37; }
#preview .markdown-alert-important .markdown-alert-title { color: #8250df; }
#preview .markdown-alert-warning .markdown-alert-title { color: #9a6700; }
#preview .markdown-alert-caution .markdown-alert-title { color: #cf222e; }
#preview .mdp-mark { border-radius: 3px; padding: 0 0.12em; background: #fff2a8; color: inherit; }
#preview mark.search-hit { border-radius: 3px; padding: 0 0.12em; background: #fff2a8; color: inherit; }
#preview mark.search-hit.current { background: #ffcc4d; color: #1a1a1a; }
#preview table { border-collapse: collapse; width: 100%; }
#preview .mdp-table-wrap {
width: min(calc(100vw - 64px), 1280px);
margin: 1em 0 1em 50%;
transform: translateX(-50%);
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
#preview .mdp-table-wrap table { width: max-content; min-width: 100%; }
#preview table th, #preview table td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
#preview table th { background: #f6f8fa; font-weight: 600; color: #1a1a1a; white-space: nowrap; }
#preview table td { min-width: 64px; max-width: 360px; vertical-align: top; overflow-wrap: break-word; }
#preview img { max-width: 100%; }
#preview .katex-display { overflow-x: auto; overflow-y: hidden; padding: 0.15em 0; }
#preview .mdp-mermaid { margin: 1.2em 0; overflow-x: auto; text-align: center; }
/* Compensate zoom's percentage width so window-fitted diagrams can grow and scroll. */
#preview .mdp-mermaid svg { max-width: 100%; height: auto; display: block; margin: 0 auto; width: calc(100% * var(--content-scale)); zoom: var(--content-scale); }
#preview .mdp-mermaid-error, #preview .mdp-math-error { color: #b42318; }
#preview hr { border: none; border-top: 1px solid #e1e4e8; margin: 2em 0; }
#preview a { color: #0969da; text-decoration: none; }
#preview a:hover { text-decoration: underline; }
#preview ul, #preview ol { padding-left: 2em; }
#preview input[type="checkbox"] { margin-right: 6px; }
#preview dl { margin: 1em 0; }
#preview dt { font-weight: 600; }
#preview dd { margin: 0 0 .6em 1.5em; }
#preview .footnote-reference { font-size: .75em; }
#preview .footnote-definition {
margin-top: 1.5em;
padding-top: .75em;
border-top: 1px solid #e1e4e8;
color: #59636e;
font-size: .9em;
}
#preview .footnote-definition-label { margin-right: .35em; font-weight: 600; }
.empty { display: flex; flex-direction: column; align-items: center; justify-content: center;
min-height: 60vh; color: #999; font-size: 18px; gap: 12px; text-align: center; }
.empty.has-recent {
justify-content: flex-start;
min-height: calc(100vh - var(--chrome-top) - 38px);
padding: clamp(56px, 10vh, 96px) 0 40px;
box-sizing: border-box;
}
.empty .icon { font-size: 48px; opacity: 0.4; }
.empty-actions { display: flex; gap: 8px; margin-top: 6px; }
.empty-open {
min-height: 40px; padding: 0 16px;
border: 1px solid #ddd; border-radius: 8px; background: #fff;
color: #1a1a1a; font: inherit; font-size: 15px; cursor: pointer;
}
.empty-open:hover { background: #f5f5f5; color: #000; }
.recent { width: min(480px, 100%); margin-top: 16px; text-align: left; }
.recent-title { margin: 0 0 8px; padding: 0; border: 0; font-size: 11px; font-weight: 600; letter-spacing: 0; color: #b6b6b6; text-transform: uppercase; }
.recent-list { display: grid; gap: 6px; }
.recent-item {
width: 100%; min-height: 44px; padding: 7px 10px; border: 1px solid #eee;
border-radius: 8px; background: #fff; color: inherit; text-align: left; cursor: pointer;
display: grid; gap: 1px;
}
.recent-item:hover { background: #f7f7f7; }
.recent-name { color: #555; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.recent-path { color: #aaa; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tabbar {
display: none; position: sticky; top: 0; z-index: 110; height: 40px;
box-sizing: border-box; align-items: stretch; gap: 4px; padding: 4px 8px;
border-bottom: 1px solid #e6e6e6; background: rgba(248,248,248,0.96);
backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
}
body.has-tabs .tabbar { display: flex; }
.tabs { display: flex; flex: 1; min-width: 0; gap: 4px; overflow-x: auto; scrollbar-width: none; }
.tabs::-webkit-scrollbar { display: none; }
.tab {
flex: 0 1 180px; min-width: 96px; max-width: 200px; height: 31px;
display: flex; align-items: center; gap: 7px; padding: 0 8px 0 10px;
box-sizing: border-box; border: 1px solid transparent; border-radius: 7px;
color: #6b6b6b; background: transparent; cursor: default; user-select: none;
font-size: 13px;
}
.tab:hover { background: rgba(0,0,0,0.045); }
.tab.dragging { opacity: .55; cursor: grabbing; }
.tab.active { color: #202020; background: #fff; border-color: #ddd; box-shadow: 0 1px 2px rgba(0,0,0,.04); }
.tab.missing { color: #a15c00; }
.tab-status { width: 7px; height: 7px; flex: 0 0 auto; border-radius: 50%; background: transparent; }
.tab.dirty .tab-status { background: #2979c9; }
.tab.missing .tab-status { width: auto; height: auto; background: none; border-radius: 0; font-weight: 700; }
.tab-name { min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tab-close {
width: 20px; height: 20px; flex: 0 0 auto; padding: 0; border: 0; border-radius: 5px;
display: grid; place-items: center; color: inherit; background: transparent; cursor: pointer;
font: 16px/1 -apple-system, BlinkMacSystemFont, sans-serif; opacity: .58;
}
.tab-close:hover { opacity: 1; background: rgba(0,0,0,.08); }
.tab-close[hidden] { display: none; }
.tab-menu {
position: fixed; z-index: 200; min-width: 188px; padding: 4px;
background: #fff; border: 1px solid #ddd; border-radius: 8px;
box-shadow: 0 8px 24px rgba(0,0,0,.16);
}
.tab-menu[hidden] { display: none; }
.tab-menu-path {
max-width: 280px; padding: 3px 8px 5px; overflow: hidden;
color: #8a8a8a; font-size: 11px; line-height: 1.3;
white-space: nowrap; text-overflow: ellipsis;
}
.tab-menu button {
display: block; width: 100%; padding: 5px 8px; border: 0; border-radius: 5px;
background: transparent; color: #222; text-align: left; font: inherit;
font-size: 13px; cursor: pointer;
}
.tab-menu button:hover { background: #f2f2f2; }
.tab-menu button:disabled { opacity: .42; cursor: default; }
.tab-menu button:disabled:hover { background: transparent; }
.tab-open {
width: 31px; height: 31px; flex: 0 0 auto; padding: 0; border: 0; border-radius: 7px;
color: #666; background: transparent; cursor: pointer; font: 20px/1 -apple-system, sans-serif;
}
.tab-open:hover { color: #111; background: rgba(0,0,0,.06); }
.doc-stats {
flex: 0 0 auto; align-self: center; padding: 0 6px;
color: #8b8b8b; font-size: 11px; white-space: nowrap; user-select: none;
font-variant-numeric: tabular-nums;
}
.missing-file { min-height: 55vh; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; text-align: center; }
.missing-file h2, .missing-file p { margin: 0; }
.missing-file p { color: #777; }
.missing-file code { max-width: min(620px, 90vw); overflow-wrap: anywhere; color: #8a5a12; }
.missing-mark { width: 38px; height: 38px; border: 2px solid #c98322; border-radius: 50%; display: grid; place-items: center; color: #a15c00; font-weight: 700; font-size: 22px; }
.missing-actions { display: flex; gap: 8px; margin-top: 8px; }
.missing-actions button { min-height: 36px; padding: 0 13px; border: 1px solid #d8d8d8; border-radius: 7px; background: #fff; color: #333; cursor: pointer; font: inherit; }
.missing-actions button:hover { background: #f4f4f4; }
/* Floating toolbar (top-right) — hover-reveal, hidden in empty state */
.toolbar {
position: fixed; top: var(--chrome-top); right: 12px;
display: flex; gap: 6px; z-index: 100;
opacity: 0; pointer-events: none;
transition: opacity 0.18s ease;
}
html:hover .toolbar { opacity: 1; pointer-events: auto; }
body.home .toolbar { display: none !important; }
.toolbar button {
width: 34px; height: 34px; padding: 0;
background: rgba(255,255,255,0.8);
backdrop-filter: blur(6px);
-webkit-backdrop-filter: blur(6px);
border: 1px solid rgba(0,0,0,0.08);
border-radius: 8px;
display: grid; place-items: center;
cursor: pointer; color: #555;
transition: color 0.15s, background 0.15s;
}
.toolbar button:hover { color: #000; background: rgba(255,255,255,1); }
.toolbar button[hidden] { display: none !important; }
.zoom-control { position: relative; }
.zoom-popover {
position: absolute; top: 40px; right: 0;
display: none; align-items: center; gap: 2px; padding: 4px;
border: 1px solid rgba(0,0,0,.1); border-radius: 8px;
background: rgba(255,255,255,.96); box-shadow: 0 6px 20px rgba(0,0,0,.12);
backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
}
.zoom-control.open .zoom-popover { display: flex; }
.toolbar .zoom-popover button { width: 30px; height: 30px; border: 0; background: transparent; }
.toolbar .zoom-popover button:hover { background: rgba(0,0,0,.06); }
.toolbar .zoom-popover .zoom-reset {
width: 52px; font-size: 11px; font-variant-numeric: tabular-nums;
}
.findbar {
position: fixed; top: var(--chrome-top); left: 50%; transform: translateX(-50%);
display: none; align-items: center; gap: 6px; z-index: 101;
padding: 6px; border: 1px solid rgba(0,0,0,0.08); border-radius: 10px;
background: rgba(255,255,255,0.96); box-shadow: 0 8px 24px rgba(0,0,0,0.12);
backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
}
body.finding .findbar { display: flex; }
.findbar input {
width: min(42vw, 320px); height: 30px; box-sizing: border-box; border: 0;
outline: none; background: transparent; color: inherit; font: inherit;
}
.findbar span { min-width: 14px; color: #8c959f; text-align: center; }
.findbar button {
width: 30px; height: 30px; padding: 0; border: 0; border-radius: 7px;
display: grid; place-items: center; color: #555; background: transparent; cursor: pointer;
}
.findbar button:hover { background: #f0f0f0; color: #111; }
@media (prefers-color-scheme: dark) {
body { color: #d4d4d4; background: #1e1e1e; }
#preview a { color: #6cb6ff; }
#preview h1, #preview h2 { border-color: #333; }
#preview .mdp-fold-toggle { color: #aaa; }
#preview .mdp-fold-toggle:hover { background: rgba(255,255,255,.1); }
#preview .front-matter { border-color: #333; color: #a9b1ba; }
#preview .front-matter pre { background: transparent !important; }
#preview code:not(pre code) { background: #2d2d2d; }
#preview blockquote { border-color: #444; color: #aaa; }
#preview .footnote-definition { border-color: #444; color: #aaa; }
#preview .markdown-alert-note,
#preview .markdown-alert-tip,
#preview .markdown-alert-important,
#preview .markdown-alert-warning,
#preview .markdown-alert-caution { background: #161b22; color: #d4d4d4; }
#preview .markdown-alert-note { border-color: #2f81f7; }
#preview .markdown-alert-tip { border-color: #3fb950; }
#preview .markdown-alert-important { border-color: #a371f7; }
#preview .markdown-alert-warning { border-color: #d29922; }
#preview .markdown-alert-caution { border-color: #f85149; }
#preview .markdown-alert-note .markdown-alert-title { color: #2f81f7; }
#preview .markdown-alert-tip .markdown-alert-title { color: #3fb950; }
#preview .markdown-alert-important .markdown-alert-title { color: #a371f7; }
#preview .markdown-alert-warning .markdown-alert-title { color: #d29922; }
#preview .markdown-alert-caution .markdown-alert-title { color: #f85149; }
#preview table th { background: #2d2d2d; color: #f0f0f0; }
#preview table td, #preview table th { border-color: #444; }
#preview hr { border-color: #333; }
.toolbar button {
background: rgba(40,40,40,0.8);
border-color: rgba(255,255,255,0.1);
color: #bbb;
}
.toolbar button:hover { color: #fff; background: rgba(55,55,55,1); }
.zoom-popover { background: rgba(34,34,34,.96); border-color: rgba(255,255,255,.12); }
.toolbar .zoom-popover button:hover { background: rgba(255,255,255,.1); }
.empty-open { background: #242424; border-color: #444; color: #ddd; }
.empty-open:hover { background: #2d2d2d; color: #fff; }
.recent-name { color: #ddd; }
.recent-item { background: #242424; border-color: #333; }
.recent-item:hover { background: #2d2d2d; }
.findbar { background: rgba(34,34,34,0.96); border-color: rgba(255,255,255,0.1); }
.findbar button:hover { background: #333; color: #fff; }
.tabbar { background: rgba(28,28,28,.96); border-color: #363636; }
.tab { color: #aaa; }
.tab:hover { background: rgba(255,255,255,.07); }
.tab.active { color: #eee; background: #2c2c2c; border-color: #444; }
.tab.missing { color: #e3a04b; }
.tab-close:hover, .tab-open:hover { background: rgba(255,255,255,.1); color: #fff; }
.tab-menu { background: #2a2a2a; border-color: #444; box-shadow: 0 8px 24px rgba(0,0,0,.45); }
.tab-menu-path { color: #999; }
.tab-menu button { color: #ddd; }
.tab-menu button:hover { background: rgba(255,255,255,.08); }
.tab-menu button:disabled:hover { background: transparent; }
.missing-file p { color: #aaa; }
.missing-actions button { background: #292929; border-color: #444; color: #ddd; }
.missing-actions button:hover { background: #333; }
}
/* Source editor textarea — height is auto-grown by JS to match content,
so the page (html) owns the only vertical scrollbar. */
#editor {
display: none;
width: 100%;
box-sizing: border-box;
border: none; outline: none; resize: none;
overflow: hidden;
font: calc(14px * var(--content-scale))/1.6 "SF Mono","Menlo","Consolas",monospace;
background: transparent; color: inherit;
padding: 0;
}
body.editing #preview { display: none; }
body.editing #editor { display: block; padding: 16px 48px; }
body.editing #app { max-width: none; padding: 0; }
@page {
margin: 12mm;
}
@media print {
.toolbar, .tabbar, #editor { display: none !important; }
#preview { display: block !important; }
#app { max-width: none; padding: 0; }
#preview .mdp-table-wrap { width: auto; margin: 1em 0; transform: none; overflow: visible; }
#preview pre { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
#preview .mdp-fold-body { display: block !important; }
#preview .mdp-fold-toggle { display: none !important; }
}

37
assets/page/page.html Normal file
View File

@@ -0,0 +1,37 @@
<!DOCTYPE html><html><head><meta charset="utf-8">
__MDP_BASE_TAG__
<style id="hljs-code">__MDP_CSS_CODE__</style>
<style>
__MDP_PAGE_CSS__
</style></head><body class="__MDP_BODY_CLASS__">
<div class="tabbar" id="tabbar"><div class="tabs" id="tabs"></div><div class="doc-stats" id="doc-stats" aria-live="polite"></div><button class="tab-open" id="tab-open" type="button" title="__MDP_NEW_TAB__" aria-label="__MDP_NEW_TAB__">+</button></div>
<div class="tab-menu" id="tab-menu" hidden><div class="tab-menu-path" id="tab-menu-path"></div><button type="button" id="tab-menu-reveal">__MDP_BTN_OPEN_LOCATION__</button><button type="button" id="tab-menu-new-window">__MDP_BTN_NEW_WINDOW__</button></div>
<div class="toolbar">
<button id="btn-toggle" title="__MDP_BTN_EDIT__" aria-label="__MDP_BTN_EDIT__"></button>
<div class="zoom-control" id="zoom-control">
<button id="btn-zoom" title="__MDP_BTN_ZOOM__" aria-label="__MDP_BTN_ZOOM__"></button>
<div class="zoom-popover">
<button id="btn-zoom-out" title="__MDP_BTN_ZOOM_OUT__" aria-label="__MDP_BTN_ZOOM_OUT__">−</button>
<button id="btn-zoom-reset" class="zoom-reset" title="__MDP_BTN_ZOOM_RESET__" aria-label="__MDP_BTN_ZOOM_RESET__">100%</button>
<button id="btn-zoom-in" title="__MDP_BTN_ZOOM_IN__" aria-label="__MDP_BTN_ZOOM_IN__">+</button>
</div>
</div>
</div>
<div class="findbar" role="search">
<input id="find-input" type="search" placeholder="__MDP_SEARCH_PLACEHOLDER__" aria-label="__MDP_SEARCH_PLACEHOLDER__">
<span id="find-state"></span>
<button id="find-prev" title="Previous" aria-label="Previous"></button>
<button id="find-next" title="Next" aria-label="Next"></button>
<button id="find-close" title="Close" aria-label="Close"></button>
</div>
<div id="app">
<div id="preview">__MDP_PREVIEW_HTML__</div>
<textarea id="editor" spellcheck="false">__MDP_RAW_MD_ESCAPED__</textarea>
</div>
<script>
__MDP_PAGE_JS__
window.__mdPreviewFeatureFlags = { math: __MDP_NEEDS_MATH__, mermaid: __MDP_NEEDS_MERMAID__ };
__MDP_PREVIEW_ENHANCE_JS__
if(window.__enhancePreview)window.__enhancePreview();
</script>
</body></html>

970
assets/page/page.js Normal file
View File

@@ -0,0 +1,970 @@
(function(){
var ICON_EDIT = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>';
var ICON_VIEW = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>';
var ICON_ZOOM = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/><path d="M8 11h6"/><path d="M11 8v6"/></svg>';
var ICON_UP = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m18 15-6-6-6 6"/></svg>';
var ICON_DOWN = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>';
var ICON_CLOSE = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>';
var L_EDIT = '__MDP_BTN_EDIT__', L_VIEW = '__MDP_BTN_PREVIEW__', L_HOME = '__MDP_HOME_TAB__';
window.__mdPreviewFoldLabel = '__MDP_FOLD_TOGGLE__';
window.__mdPreviewCannotSave = '__MDP_CANNOT_SAVE_JS__';
var btnToggle = document.getElementById('btn-toggle');
var btnZoom = document.getElementById('btn-zoom');
var btnZoomOut = document.getElementById('btn-zoom-out');
var btnZoomReset = document.getElementById('btn-zoom-reset');
var btnZoomIn = document.getElementById('btn-zoom-in');
var zoomControl = document.getElementById('zoom-control');
var findInput = document.getElementById('find-input');
var findState = document.getElementById('find-state');
var findPrev = document.getElementById('find-prev');
var findNext = document.getElementById('find-next');
var findClose = document.getElementById('find-close');
var tabsEl = document.getElementById('tabs');
var docStats = document.getElementById('doc-stats');
var tabOpen = document.getElementById('tab-open');
var tabMenu = document.getElementById('tab-menu');
var tabMenuPath = document.getElementById('tab-menu-path');
var tabMenuReveal = document.getElementById('tab-menu-reveal');
var tabMenuNewWindow = document.getElementById('tab-menu-new-window');
var tabMenuTargetId = 0;
var tabDrag = null;
var suppressTabClickUntil = 0;
var ta = document.getElementById('editor');
var dirty = false;
var activeTabId = 0;
var tabCount = 0;
var pendingAutosaveTimer = 0;
var autosavePaused = false;
var saveBlocked = false;
var AUTOSAVE_DEBOUNCE_MS = 700;
var composingFind = false;
var pendingFindTimer = 0;
var FIND_DEBOUNCE_MS = 300;
// Tab inserts spaces, never a literal tab. Two spaces matches the
// common Markdown/AI-generated document style and keeps list nesting
// compact; change this single constant to switch the width.
var INDENT = ' ';
// The strip stays hidden while the only tab is Home, matching the
// original start-up page. Set to false to keep the tab bar always on.
var HIDE_SINGLE_HOME_TAB = true;
var findHits = [];
var currentFindHit = -1;
var lastFindQuery = '';
var STAT_WORDS = '__MDP_STAT_WORDS_JS__';
var STAT_CHARS = '__MDP_STAT_CHARS_JS__';
var ZOOM_SAVE_DEBOUNCE_MS = 400;
var pendingZoomSaveTimer = 0;
var ZOOM_MIN = 50;
var ZOOM_MAX = 300;
var ZOOM_STEP = 5;
var ZOOM_WHEEL_THROTTLE_MS = 90;
var zoomWheelAt = 0;
var zoomPercent = 100;
btnToggle.innerHTML = ICON_EDIT;
btnZoom.innerHTML = ICON_ZOOM;
findPrev.innerHTML = ICON_UP;
findNext.innerHTML = ICON_DOWN;
findClose.innerHTML = ICON_CLOSE;
function inEdit() { return document.body.classList.contains('editing'); }
function textSegments(text) {
if (typeof Intl !== 'undefined' && Intl.Segmenter) {
var segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
return Array.from(segmenter.segment(text), function(item) { return item.segment; });
}
return Array.from(text);
}
function updateDocumentStats(raw) {
var segments = textSegments(String(raw || ''));
var words = segments.reduce(function(total, segment) {
return total + (/^\s+$/u.test(segment) ? 0 : 1);
}, 0);
var number = new Intl.NumberFormat().format;
docStats.textContent =
number(words) + ' ' + STAT_WORDS + ' · ' + number(segments.length) + ' ' + STAT_CHARS;
}
function queueZoomSave() {
if (pendingZoomSaveTimer) clearTimeout(pendingZoomSaveTimer);
pendingZoomSaveTimer = setTimeout(function() {
pendingZoomSaveTimer = 0;
if (window.ipc) window.ipc.postMessage('zoom:' + zoomPercent);
}, ZOOM_SAVE_DEBOUNCE_MS);
}
function applyZoom(percent, persist) {
zoomPercent = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, percent));
document.documentElement.style.setProperty('--content-scale', String(zoomPercent / 100));
btnZoomReset.textContent = zoomPercent + '%';
if (persist) queueZoomSave();
if (inEdit()) autoResize();
}
function changeZoom(delta) {
applyZoom(zoomPercent + delta, true);
}
function currentScrollProgress() {
var root = document.documentElement;
var max = Math.max(root.scrollHeight - window.innerHeight, 0);
var y = window.scrollY || root.scrollTop || 0;
return max > 0 ? Math.min(1, Math.max(0, y / max)) : 0;
}
// A newer restore supersedes any callback the previous one left behind.
var scrollRestoreToken = 0;
function restoreScrollProgress(progress) {
var token = ++scrollRestoreToken;
function restore() {
if (token !== scrollRestoreToken) return;
var max = Math.max(document.documentElement.scrollHeight - window.innerHeight, 0);
window.scrollTo(window.scrollX || 0, max * progress);
}
restore();
requestAnimationFrame(function() {
restore();
requestAnimationFrame(restore);
});
// Late layout (tables, math, mermaid) can change the content height.
setTimeout(restore, 150);
}
// Report the viewport so Rust can restore it when the tab comes back. The
// tab id travels with the report: a late scroll must not land on the tab
// that became active in the meantime.
var pendingScrollReport = 0;
function reportScroll() {
if (pendingScrollReport || !activeTabId) return;
pendingScrollReport = setTimeout(function() {
pendingScrollReport = 0;
if (window.ipc && activeTabId) {
window.ipc.postMessage('scroll:' + activeTabId + ':' + currentScrollProgress().toFixed(4));
}
}, 200);
}
window.addEventListener('scroll', reportScroll, { passive: true });
applyZoom(100, false);
window.__mdPreviewSetZoom = function(percent) { applyZoom(percent, false); };
updateDocumentStats(ta.value);
function shortenPath(path, max) {
if (!path || path.length <= max) return path || '';
var head = Math.ceil((max - 3) / 2);
var tail = Math.floor((max - 3) / 2);
return path.slice(0, head) + '...' + path.slice(-tail);
}
function suppressTabTooltips() {
Array.prototype.forEach.call(tabsEl.querySelectorAll('.tab[title]'), function(tab) {
tab.setAttribute('data-saved-title', tab.getAttribute('title'));
tab.removeAttribute('title');
});
}
function restoreTabTooltips() {
Array.prototype.forEach.call(tabsEl.querySelectorAll('.tab[data-saved-title]'), function(tab) {
var title = tab.getAttribute('data-saved-title');
tab.removeAttribute('data-saved-title');
if (title) tab.setAttribute('title', title);
});
}
function hideTabMenu() {
if (!tabMenu || tabMenu.hidden) return;
tabMenu.hidden = true;
tabMenuTargetId = 0;
restoreTabTooltips();
}
function showTabMenu(id, x, y) {
if (!tabMenu) return;
if (!tabMenu.hidden) hideTabMenu();
suppressTabTooltips();
tabMenuTargetId = id;
var tabEl = tabsEl.querySelector('.tab[data-tab-id="' + id + '"]');
var isHome = tabEl ? tabEl.classList.contains('home') : false;
var path = tabEl ? (tabEl.getAttribute('data-tab-path') || '') : '';
if (tabMenuPath) {
tabMenuPath.textContent = isHome ? L_HOME : shortenPath(path, 42);
if (!isHome && path) tabMenuPath.setAttribute('title', path);
else tabMenuPath.removeAttribute('title');
}
tabMenu.hidden = false;
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1 || isHome;
if (tabMenuReveal) tabMenuReveal.disabled = isHome || !path;
tabMenu.style.left = '0px';
tabMenu.style.top = '0px';
var rect = tabMenu.getBoundingClientRect();
var left = Math.max(8, Math.min(x, window.innerWidth - rect.width - 8));
var top = Math.max(8, Math.min(y, window.innerHeight - rect.height - 8));
tabMenu.style.left = left + 'px';
tabMenu.style.top = top + 'px';
}
function detachTab(id) {
if (tabCount <= 1) return;
if (saveBlocked) {
window.alert(window.__mdPreviewCannotSave || 'Discard unsaved changes?');
return;
}
requestTabAction('detach', id);
}
document.addEventListener('contextmenu', function(e) {
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
if (tab) {
e.preventDefault();
e.stopPropagation();
showTabMenu(tab.getAttribute('data-tab-id'), e.clientX, e.clientY);
return;
}
hideTabMenu();
if (!inEdit() || e.target !== ta) e.preventDefault();
});
function setDirty(d) {
if (dirty === d) return;
dirty = d;
window.ipc.postMessage(d ? 'dirty:1' : 'dirty:0');
}
function cancelPendingAutosave() {
if (!pendingAutosaveTimer) return;
clearTimeout(pendingAutosaveTimer);
pendingAutosaveTimer = 0;
}
function save() {
cancelPendingAutosave();
if (!dirty) return;
window.ipc.postMessage('save:' + ta.value);
}
function scheduleAutosave() {
cancelPendingAutosave();
if (autosavePaused) return;
pendingAutosaveTimer = setTimeout(function() {
pendingAutosaveTimer = 0;
if (dirty) save();
}, AUTOSAVE_DEBOUNCE_MS);
}
window.__mdPreviewSave = save;
function requestTabAction(action, id) {
cancelPendingAutosave();
var message = 'tab-action:' + action + ':' + id + ':' + currentScrollProgress().toFixed(4);
if (dirty) {
if (saveBlocked) {
if (!window.confirm(window.__mdPreviewCannotSave || 'Discard unsaved changes?')) return;
} else {
message += '\n' + ta.value;
}
}
window.ipc.postMessage(message);
}
function openFile() {
if (inEdit()) leaveEdit();
window.ipc.postMessage('open');
}
window.__mdPreviewOpenFile = openFile;
function newFile() {
if (inEdit()) leaveEdit();
window.ipc.postMessage('new-file');
}
window.__mdPreviewNewFile = newFile;
function newTab() {
// Reuse the close/activate path so a dirty editor is saved before the
// Home tab replaces it.
requestTabAction('new-tab', 0);
}
function selectionSeed() {
var sel = window.getSelection && window.getSelection();
if (!sel || sel.rangeCount === 0) return null;
var anchor = sel.anchorNode;
var element = anchor && (anchor.nodeType === 3 ? anchor.parentElement : anchor);
if (!element || !element.closest || !element.closest('#preview')) return null;
var text = sel.toString();
if (!text) return null;
var top = null;
try {
var rect = sel.getRangeAt(0).getBoundingClientRect();
if (rect && (rect.width || rect.height)) top = rect.top;
} catch (_) {}
var lines = text.split(/\r?\n/);
for (var i = 0; i < lines.length; i += 1) {
var line = lines[i].trim();
if (line) return { text: line, top: top };
}
return null;
}
function showFind(seed, anchorTop) {
if (document.body.classList.contains('home')) return;
if (inEdit()) return;
document.body.classList.add('finding');
if (typeof seed === 'string' && seed) {
findInput.value = seed;
runFindQuery(seed, anchorTop, false);
}
setTimeout(function(){
try { findInput.focus({ preventScroll: true }); } catch (_) { findInput.focus(); }
findInput.select();
}, 0);
}
window.__mdPreviewShowFind = showFind;
function hideFind() {
document.body.classList.remove('finding');
findInput.value = '';
clearFindHits();
if (pendingFindTimer) { clearTimeout(pendingFindTimer); pendingFindTimer = 0; }
var sel = window.getSelection && window.getSelection();
if (sel && sel.removeAllRanges) sel.removeAllRanges();
}
function updateFindState() {
findState.textContent = findHits.length ? (currentFindHit + 1) + '/' + findHits.length : '';
}
function clearFindHits() {
findHits.forEach(function(mark) {
var parent = mark.parentNode;
if (!parent) return;
parent.replaceChild(document.createTextNode(mark.textContent), mark);
parent.normalize();
});
findHits = [];
currentFindHit = -1;
lastFindQuery = '';
updateFindState();
}
function focusFindInput(selectionStart, selectionEnd) {
if (!document.body.classList.contains('finding')) return;
try {
findInput.focus({ preventScroll: true });
} catch (_) {
findInput.focus();
}
if (typeof selectionStart === 'number' && typeof selectionEnd === 'number') {
try { findInput.setSelectionRange(selectionStart, selectionEnd); } catch (_) {}
}
}
function restoreFindInput(selectionStart, selectionEnd) {
setTimeout(function() { focusFindInput(selectionStart, selectionEnd); }, 0);
requestAnimationFrame(function() {
focusFindInput(selectionStart, selectionEnd);
setTimeout(function() { focusFindInput(selectionStart, selectionEnd); }, 80);
});
}
function selectFindHit(index, reveal) {
if (!findHits.length) {
currentFindHit = -1;
updateFindState();
return;
}
if (currentFindHit >= 0 && findHits[currentFindHit]) {
findHits[currentFindHit].classList.remove('current');
}
currentFindHit = (index + findHits.length) % findHits.length;
var hit = findHits[currentFindHit];
hit.classList.add('current');
if (reveal !== false) {
if (window.__mdPreviewExpandFold) window.__mdPreviewExpandFold(hit);
hit.scrollIntoView({ block: 'center', inline: 'nearest' });
}
updateFindState();
}
function findStartIndex(anchorTop) {
if (!findHits.length) return 0;
var startTop = typeof anchorTop === 'number' ? anchorTop : 0;
var lastAbove = -1;
for (var i = 0; i < findHits.length; i += 1) {
var rect = findHits[i].getBoundingClientRect();
if (!rect.width && !rect.height) continue;
if (rect.bottom < startTop) {
lastAbove = i;
continue;
}
return i;
}
return lastAbove >= 0 ? lastAbove : 0;
}
function runFindQuery(query, anchorTop, reveal) {
clearFindHits();
query = String(query || '').trim();
if (!query) return;
lastFindQuery = query;
var needle = query.toLowerCase();
var previewEl = document.getElementById('preview');
var walker = document.createTreeWalker(previewEl, NodeFilter.SHOW_TEXT, {
acceptNode: function(node) {
if (!node.nodeValue || node.nodeValue.toLowerCase().indexOf(needle) < 0) {
return NodeFilter.FILTER_REJECT;
}
var parent = node.parentElement;
if (!parent || parent.closest('script,style,svg,mark.search-hit,.katex,.mdp-mermaid')) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
});
var nodes = [];
while (walker.nextNode()) nodes.push(walker.currentNode);
nodes.forEach(function(node) {
var text = node.nodeValue;
var lower = text.toLowerCase();
var fragment = document.createDocumentFragment();
var start = 0;
var index;
while ((index = lower.indexOf(needle, start)) >= 0) {
if (index > start) fragment.appendChild(document.createTextNode(text.slice(start, index)));
var mark = document.createElement('mark');
mark.className = 'search-hit';
mark.textContent = text.slice(index, index + query.length);
findHits.push(mark);
fragment.appendChild(mark);
start = index + query.length;
}
if (start < text.length) fragment.appendChild(document.createTextNode(text.slice(start)));
node.parentNode.replaceChild(fragment, node);
});
selectFindHit(findStartIndex(anchorTop), reveal);
}
function runFind(backward) {
var q = findInput.value;
if (!q) { clearFindHits(); return; }
var hadFocus = document.activeElement === findInput;
var selectionStart = findInput.selectionStart;
var selectionEnd = findInput.selectionEnd;
var normalized = String(q || '').trim();
if (!normalized) {
clearFindHits();
} else if (normalized !== lastFindQuery) {
runFindQuery(normalized);
} else {
selectFindHit(currentFindHit + (backward ? -1 : 1));
}
if (hadFocus) restoreFindInput(selectionStart, selectionEnd);
}
function scheduleFind() {
if (pendingFindTimer) clearTimeout(pendingFindTimer);
pendingFindTimer = setTimeout(function() {
pendingFindTimer = 0;
if (!composingFind) runFindQuery(findInput.value);
}, FIND_DEBOUNCE_MS);
}
// Grow textarea height to its content so the page (html) owns the sole
// scrollbar; avoids the double-scrollbar you see if textarea keeps its
// own internal scroll.
function autoResize() {
var x = window.scrollX || document.documentElement.scrollLeft || 0;
var y = window.scrollY || document.documentElement.scrollTop || 0;
ta.style.height = 'auto';
var h = Math.max(ta.scrollHeight, window.innerHeight);
ta.style.height = h + 'px';
window.scrollTo(x, y);
}
// ---- Source editor commands -------------------------------------------------
function editorLineStart(value, pos) {
return value.lastIndexOf('\n', Math.max(0, pos - 1)) + 1;
}
function editorLineEnd(value, pos) {
var end = value.indexOf('\n', pos);
return end < 0 ? value.length : end;
}
function replaceEditorRange(text, start, end, selectionStart, selectionEnd) {
try {
ta.focus({ preventScroll: true });
} catch (_) {
ta.focus();
}
ta.setSelectionRange(start, end);
var inserted = false;
try {
if (text === '') {
inserted = document.execCommand('delete', false);
} else {
inserted = document.execCommand('insertText', false, text);
}
} catch (_) {
inserted = false;
}
if (!inserted) {
ta.setRangeText(text, start, end, 'end');
ta.dispatchEvent(new Event('input', { bubbles: true }));
}
if (typeof selectionStart === 'number' && typeof selectionEnd === 'number') {
try { ta.setSelectionRange(selectionStart, selectionEnd); } catch (_) {}
}
setDirty(true);
scheduleAutosave();
autoResize();
updateDocumentStats(ta.value);
}
function transformSelectedEditorLines(transform) {
var value = ta.value;
var start = ta.selectionStart;
var end = ta.selectionEnd;
if (start === end) return false;
var from = editorLineStart(value, start);
var last = end - 1;
if (last > start && value.charAt(last) === '\n') last -= 1;
var to = editorLineEnd(value, last);
var block = value.slice(from, to);
var lines = block.split('\n');
var transformed = lines.map(transform).join('\n');
if (transformed !== block) {
replaceEditorRange(transformed, from, to, from, from + transformed.length);
}
return true;
}
function indentSelectedEditorLines() {
transformSelectedEditorLines(function(line) {
return INDENT + line;
});
}
function outdentSelectedEditorLines() {
transformSelectedEditorLines(function(line) {
if (line.charAt(0) === '\t') return line.slice(1);
var removed = 0;
while (removed < INDENT.length && line.charAt(removed) === ' ') removed += 1;
return line.slice(removed);
});
}
function indentEditor() {
var start = ta.selectionStart;
var end = ta.selectionEnd;
if (start === end) {
replaceEditorRange(INDENT, start, end, start + INDENT.length, start + INDENT.length);
return;
}
indentSelectedEditorLines();
}
function outdentEditor() {
var value = ta.value;
var start = ta.selectionStart;
var end = ta.selectionEnd;
if (start !== end) {
outdentSelectedEditorLines();
return;
}
var from = editorLineStart(value, start);
var line = value.slice(from, editorLineEnd(value, start));
var removed = 0;
if (line.charAt(0) === '\t') {
removed = 1;
} else {
while (removed < INDENT.length && line.charAt(removed) === ' ') removed += 1;
}
if (!removed) return;
var next = Math.max(from, start - removed);
replaceEditorRange('', from, from + removed, next, next);
}
function insertNewlineWithIndent() {
var value = ta.value;
var start = ta.selectionStart;
var end = ta.selectionEnd;
var from = editorLineStart(value, start);
var prefix = value.slice(from, start);
var leading = /^[ \t]*/.exec(prefix)[0];
if (!/\S/.test(prefix)) leading = '';
var text = '\n' + leading;
var next = start + text.length;
replaceEditorRange(text, start, end, next, next);
}
ta.addEventListener('keydown', function(e) {
if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Tab' && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
if (e.shiftKey) outdentEditor(); else indentEditor();
return;
}
if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
insertNewlineWithIndent();
}
});
// Edit mode is per tab and owned by Rust; this only paints it.
function setEditMode(on) {
if (on) {
document.body.classList.add('editing');
btnToggle.innerHTML = ICON_VIEW;
btnToggle.title = L_VIEW;
btnToggle.setAttribute('aria-label', L_VIEW);
} else {
document.body.classList.remove('editing');
btnToggle.innerHTML = ICON_EDIT;
btnToggle.title = L_EDIT;
btnToggle.setAttribute('aria-label', L_EDIT);
}
autoResize();
}
function enterEdit() {
if (document.body.classList.contains('home')) return;
var progress = currentScrollProgress();
setEditMode(true);
try {
ta.focus({ preventScroll: true });
} catch (_) {
ta.focus();
}
restoreScrollProgress(progress);
if (window.ipc) window.ipc.postMessage('edit-mode:' + activeTabId + ':1');
}
function leaveEdit() {
var progress = currentScrollProgress();
if (dirty) save();
setEditMode(false);
restoreScrollProgress(progress);
if (window.ipc) window.ipc.postMessage('edit-mode:' + activeTabId + ':0');
}
window.__mdPreviewToggleEdit = function() {
if (inEdit()) leaveEdit(); else enterEdit();
};
window.__mdPreviewCloseActiveTab = function() {
if (activeTabId) requestTabAction('close', activeTabId);
};
tabOpen.addEventListener('click', newTab);
if (tabMenuNewWindow) {
tabMenuNewWindow.addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
var id = tabMenuTargetId;
hideTabMenu();
if (id) detachTab(id);
});
}
if (tabMenuReveal) {
tabMenuReveal.addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
var id = tabMenuTargetId;
hideTabMenu();
if (id) window.ipc.postMessage('reveal-tab:' + id);
});
}
tabsEl.addEventListener('pointerdown', function(e) {
if (e.button !== 0 || tabCount <= 1) return;
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
if (!tab || (e.target.closest && e.target.closest('.tab-close'))) return;
if (tab.classList.contains('home')) return;
hideTabMenu();
tabDrag = { id: tab.getAttribute('data-tab-id'), startY: e.clientY, element: tab, pointerId: e.pointerId, dragged: false };
try { tab.setPointerCapture(e.pointerId); } catch (err) {}
});
tabsEl.addEventListener('pointermove', function(e) {
if (!tabDrag || e.pointerId !== tabDrag.pointerId) return;
if (!tabDrag.dragged && Math.abs(e.clientY - tabDrag.startY) >= 24) {
tabDrag.dragged = true;
tabDrag.element.classList.add('dragging');
}
});
tabsEl.addEventListener('pointerup', function(e) {
if (!tabDrag || e.pointerId !== tabDrag.pointerId) return;
var drag = tabDrag;
tabDrag = null;
drag.element.classList.remove('dragging');
try {
if (drag.element.hasPointerCapture(e.pointerId)) drag.element.releasePointerCapture(e.pointerId);
} catch (err) {}
if (!drag.dragged) return;
suppressTabClickUntil = Date.now() + 350;
if (tabCount > 1) detachTab(drag.id);
});
tabsEl.addEventListener('pointercancel', function(e) {
if (!tabDrag || e.pointerId !== tabDrag.pointerId) return;
var drag = tabDrag;
tabDrag = null;
drag.element.classList.remove('dragging');
});
window.addEventListener('resize', hideTabMenu);
window.addEventListener('scroll', hideTabMenu, true);
window.addEventListener('blur', hideTabMenu);
document.addEventListener('click', function(e) {
if (Date.now() < suppressTabClickUntil) {
var suppressedTab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
if (suppressedTab) {
suppressTabClickUntil = 0;
e.preventDefault();
e.stopPropagation();
return;
}
}
if (tabMenu && !tabMenu.hidden) hideTabMenu();
var closeTab = e.target && e.target.closest ? e.target.closest('[data-close-tab]') : null;
if (closeTab) {
e.preventDefault();
e.stopPropagation();
requestTabAction('close', closeTab.getAttribute('data-close-tab'));
return;
}
var locateTab = e.target && e.target.closest ? e.target.closest('[data-locate-tab]') : null;
if (locateTab) {
e.preventDefault();
window.ipc.postMessage('locate-tab:' + locateTab.getAttribute('data-locate-tab'));
return;
}
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
if (tab) {
e.preventDefault();
requestTabAction('activate', tab.getAttribute('data-tab-id'));
return;
}
var newFileBtn = e.target && e.target.closest ? e.target.closest('[data-new-file]') : null;
if (newFileBtn) {
e.preventDefault();
newFile();
return;
}
var openBtn = e.target && e.target.closest ? e.target.closest('[data-open-file]') : null;
if (openBtn) {
e.preventDefault();
openFile();
return;
}
var recentBtn = e.target && e.target.closest ? e.target.closest('[data-recent-index]') : null;
if (recentBtn) {
e.preventDefault();
window.ipc.postMessage('open-recent:' + recentBtn.getAttribute('data-recent-index'));
}
});
findInput.addEventListener('compositionstart', function() { composingFind = true; });
findInput.addEventListener('compositionend', function() { composingFind = false; scheduleFind(); });
findInput.addEventListener('input', function(e) {
if (composingFind || e.isComposing) return;
scheduleFind();
});
findInput.addEventListener('keydown', function(e) {
if (composingFind || e.isComposing) return;
if (e.key === 'Enter') { e.preventDefault(); runFind(e.shiftKey); }
if (e.key === 'Escape') { e.preventDefault(); hideFind(); }
});
findPrev.addEventListener('click', function() { runFind(true); });
findNext.addEventListener('click', function() { runFind(false); });
findClose.addEventListener('click', hideFind);
btnToggle.addEventListener('click', function() {
window.__mdPreviewToggleEdit();
});
btnZoom.addEventListener('click', function(e) {
e.stopPropagation();
zoomControl.classList.toggle('open');
});
btnZoomOut.addEventListener('click', function() { changeZoom(-ZOOM_STEP); });
btnZoomReset.addEventListener('click', function() { applyZoom(100, true); });
btnZoomIn.addEventListener('click', function() { changeZoom(ZOOM_STEP); });
function onContentWheel(e) {
if (!e.ctrlKey) return;
e.preventDefault();
if (Math.abs(e.deltaY) < 0.01) return;
var now = Date.now();
if (now - zoomWheelAt < ZOOM_WHEEL_THROTTLE_MS) return;
zoomWheelAt = now;
changeZoom(e.deltaY < 0 ? ZOOM_STEP : -ZOOM_STEP);
}
window.addEventListener('wheel', onContentWheel, { passive: false });
ta.addEventListener('input', function() { setDirty(true); scheduleAutosave(); autoResize(); updateDocumentStats(ta.value); });
window.addEventListener('resize', function() { if (inEdit()) autoResize(); });
document.addEventListener('click', function(e) {
if (!zoomControl.contains(e.target)) zoomControl.classList.remove('open');
});
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape' && tabMenu && !tabMenu.hidden) {
hideTabMenu();
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'w' || e.key === 'W')) {
if (activeTabId) {
e.preventDefault();
requestTabAction('close', activeTabId);
}
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'n' || e.key === 'N')) {
e.preventDefault();
newFile();
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === '+' || e.key === '=' || e.code === 'NumpadAdd')) {
e.preventDefault();
changeZoom(ZOOM_STEP);
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === '-' || e.code === 'NumpadSubtract')) {
e.preventDefault();
changeZoom(-ZOOM_STEP);
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === '0' || e.code === 'Numpad0')) {
e.preventDefault();
applyZoom(100, true);
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'r' || e.key === 'R')) {
e.preventDefault();
if (!inEdit()) window.ipc.postMessage('refresh');
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'o' || e.key === 'O')) {
e.preventDefault();
openFile();
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'f' || e.key === 'F')) {
if (inEdit()) return;
var seed = (document.body.classList.contains('finding') && document.activeElement === findInput) ? null : selectionSeed();
e.preventDefault();
showFind(seed ? seed.text : '', seed ? seed.top : null);
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'e' || e.key === 'E')) {
e.preventDefault();
if (inEdit()) leaveEdit(); else enterEdit();
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 's' || e.key === 'S')) {
if (inEdit()) { e.preventDefault(); save(); }
return;
}
if ((e.metaKey || e.ctrlKey) && (e.key === 'p' || e.key === 'P')) {
e.preventDefault();
if (inEdit()) leaveEdit();
setTimeout(function(){ window.ipc.postMessage('print'); }, 0);
return;
}
if (e.key === 'Escape' && document.body.classList.contains('finding')) { hideFind(); return; }
if (e.key === 'Escape' && inEdit()) { leaveEdit(); }
});
// Called by Rust after a save (only preview is refreshed) or after an
// external file change (both preview + textarea are refreshed).
window.__setPreview = function(previewHtml, needsMath, needsMermaid) {
if (arguments.length > 1 && window.__setFeatureFlags) {
window.__setFeatureFlags(needsMath, needsMermaid);
}
document.getElementById('preview').innerHTML = previewHtml;
(window.requestIdleCallback || function(fn){ return setTimeout(fn, 0); })(function() {
if (typeof hljs !== 'undefined') hljs.highlightAll();
if (window.__enhancePreview) window.__enhancePreview();
});
};
window.__setBaseHref = function(baseHref) {
var base = document.getElementById('base-href');
if (!base) {
base = document.createElement('base');
base.id = 'base-href';
document.head.insertBefore(base, document.head.firstChild);
}
if (baseHref) base.setAttribute('href', baseHref);
else base.removeAttribute('href');
};
window.__markSaved = function(savedRaw) {
if (typeof savedRaw === 'string' && ta.value !== savedRaw) {
window.ipc.postMessage('dirty:1');
return;
}
autosavePaused = false;
saveBlocked = false;
setDirty(false);
};
window.__markSaveBlocked = function() {
saveBlocked = true;
autosavePaused = true;
};
window.__mdPreviewPauseAutosave = function() {
cancelPendingAutosave();
autosavePaused = true;
};
window.__mdPreviewResolveExternalChange = function() {
cancelPendingAutosave();
window.ipc.postMessage('external-change:' + (dirty ? 'dirty' : 'clean'));
};
window.__setTabs = function(tabs) {
hideTabMenu();
tabs = Array.isArray(tabs) ? tabs : [];
tabCount = tabs.length;
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1;
tabsEl.textContent = '';
activeTabId = 0;
var showTabBar = HIDE_SINGLE_HOME_TAB
? (tabs.length > 1 || (tabs.length === 1 && !tabs[0].home))
: tabs.length > 0;
document.body.classList.toggle('has-tabs', showTabBar);
tabs.forEach(function(tab) {
var isHome = !!tab.home;
var item = document.createElement('div');
item.className = 'tab' + (isHome ? ' home' : '') + (tab.active ? ' active' : '') + (tab.missing ? ' missing' : '') + (tab.dirty ? ' dirty' : '');
item.setAttribute('data-tab-id', tab.id);
item.setAttribute('data-tab-path', isHome ? '' : tab.path);
item.setAttribute('role', 'button');
item.setAttribute('tabindex', '0');
item.title = isHome ? L_HOME : tab.path;
if (tab.active) activeTabId = tab.id;
var status = document.createElement('span');
status.className = 'tab-status';
status.textContent = tab.missing ? '!' : '';
var name = document.createElement('span');
name.className = 'tab-name';
name.textContent = isHome ? L_HOME : tab.name;
var close = document.createElement('button');
close.className = 'tab-close';
close.type = 'button';
close.setAttribute('data-close-tab', tab.id);
close.setAttribute('aria-label', 'Close ' + (isHome ? L_HOME : tab.name));
close.textContent = '×';
// A lone Home tab is the start-up page; there is nothing to close.
if (tabCount === 1 && isHome) close.hidden = true;
item.appendChild(status);
item.appendChild(name);
item.appendChild(close);
tabsEl.appendChild(item);
if (tab.active) requestAnimationFrame(function() { item.scrollIntoView({ block: 'nearest', inline: 'nearest' }); });
});
};
tabsEl.addEventListener('keydown', function(e) {
if (e.key !== 'Enter' && e.key !== ' ') return;
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
if (!tab) return;
e.preventDefault();
requestTabAction('activate', tab.getAttribute('data-tab-id'));
});
window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid, editing, scrollRatio) {
document.body.classList.remove('home');
document.body.classList.remove('missing');
hideFind();
window.__setBaseHref(baseHref);
window.__setPreview(previewHtml, needsMath, needsMermaid);
if (!inEdit() || !dirty) {
autosavePaused = false;
ta.value = rawMd;
updateDocumentStats(rawMd);
setDirty(false);
}
setEditMode(!!editing);
restoreScrollProgress(typeof scrollRatio === 'number' ? scrollRatio : 0);
};
window.__setEmptyPreview = function(previewHtml) {
document.body.classList.add('home');
document.body.classList.remove('missing');
setEditMode(false);
cancelPendingAutosave();
autosavePaused = false;
hideFind();
window.__setBaseHref('');
document.getElementById('preview').innerHTML = previewHtml;
ta.value = '';
updateDocumentStats('');
setDirty(false);
window.scrollTo(0, 0);
};
window.__setMissing = function(previewHtml) {
document.body.classList.remove('home');
document.body.classList.add('missing');
setEditMode(false);
cancelPendingAutosave();
autosavePaused = false;
hideFind();
window.__setBaseHref('');
document.getElementById('preview').innerHTML = previewHtml;
ta.value = '';
updateDocumentStats('');
setDirty(false);
window.scrollTo(0, 0);
};
// Defer hljs parse + initial highlight to idle time.
// hljs itself is NOT inlined in this page — Rust injects it via
// evaluate_script once we tell it we're painted. Until that injection
// runs, typeof hljs === 'undefined' and highlightAll is skipped; once
// it lands, hljs.highlightAll() gets called by the injected bootstrap
// and __setPreview.
// Signal Rust after first paint (triggers hljs inject; bench mode exits).
requestAnimationFrame(function() {
requestAnimationFrame(function() {
if (window.ipc) window.ipc.postMessage('ready');
});
});
})();

25
src/escape.rs Normal file
View File

@@ -0,0 +1,25 @@
//! Small text/JS escaping helpers shared by the page builder, the Markdown
//! pipeline and the renderer.
pub fn escape_js(s: &str) -> String {
s.replace('\\', "\\\\")
.replace('\'', "\\'")
.replace('\n', "\\n")
.replace('\r', "\\r")
}
pub fn html_escape_ta(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;")
}
pub fn html_escape_attr(s: &str) -> String {
s.replace('&', "&amp;")
.replace('"', "&quot;")
.replace('<', "&lt;")
}
pub fn html_escape_text(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
}

File diff suppressed because it is too large Load Diff

405
src/markdown.rs Normal file
View File

@@ -0,0 +1,405 @@
//! Markdown -> HTML pipeline.
//!
//! GFM plus the app's deliberate dialect: single newlines are visible line
//! breaks (AI output), front matter is split off, local images are embedded as
//! data URLs, ==highlight== becomes <mark>, and headings get stable ids for
//! folding and anchor navigation.
use crate::escape::html_escape_text;
use pulldown_cmark::{html, CowStr, Event as MdEvent, Options, Parser, Tag, TagEnd};
use std::collections::HashMap;
use std::fs;
use std::path::{Component, Path, PathBuf};
#[cfg(test)]
pub fn md_to_html(md: &str) -> String {
md_to_html_with_base(md, None)
}
pub fn md_to_html_with_base(md: &str, base_dir: Option<&Path>) -> String {
// A UTF-8 BOM is legal in files but not part of Markdown syntax. Strip it
// before front-matter detection so both `---` metadata and a leading
// heading still parse.
let md = md.strip_prefix('\u{feff}').unwrap_or(md);
let (front_matter, markdown) = split_yaml_front_matter(md)
.map(|(metadata, body)| (Some(metadata), body))
.unwrap_or((None, md));
let opts = Options::ENABLE_TABLES
| Options::ENABLE_STRIKETHROUGH
| Options::ENABLE_TASKLISTS
| Options::ENABLE_HEADING_ATTRIBUTES
| Options::ENABLE_MATH
| Options::ENABLE_GFM
| Options::ENABLE_FOOTNOTES
| Options::ENABLE_DEFINITION_LIST;
let parser = Parser::new_ext(markdown, opts);
let events = render_softbreaks_as_hard(embed_local_images(
add_mark_highlights(add_heading_ids(parser.collect())),
base_dir,
));
let mut html_out = String::new();
if let Some(metadata) = front_matter {
html_out.push_str(r#"<aside class="front-matter"><pre>"#);
html_out.push_str(&html_escape_text(metadata.trim_end_matches(['\r', '\n'])));
html_out.push_str("</pre></aside>\n");
}
html::push_html(&mut html_out, events.into_iter());
html_out
}
/// AI-generated Markdown often uses a single newline as a visual line break.
/// Treat those soft breaks as hard breaks in normal prose, but keep headings
/// untouched: a multi-line setext heading should stay one visual line.
fn render_softbreaks_as_hard<'a>(events: Vec<MdEvent<'a>>) -> Vec<MdEvent<'a>> {
let mut heading_depth = 0usize;
let mut out = Vec::with_capacity(events.len());
for event in events {
match &event {
MdEvent::Start(Tag::Heading { .. }) => heading_depth += 1,
MdEvent::End(TagEnd::Heading(_)) => {
heading_depth = heading_depth.saturating_sub(1);
}
MdEvent::SoftBreak if heading_depth == 0 => {
out.push(MdEvent::HardBreak);
continue;
}
_ => {}
}
out.push(event);
}
out
}
fn split_yaml_front_matter(md: &str) -> Option<(&str, &str)> {
let mut lines = md.split_inclusive('\n');
let first = lines.next()?;
if first.trim_end_matches(['\r', '\n']) != "---" {
return None;
}
let metadata_start = first.len();
let mut offset = metadata_start;
for line in lines {
let value = line.trim_end_matches(['\r', '\n']);
if value == "---" || value == "..." {
let metadata = &md[metadata_start..offset];
let body = &md[offset + line.len()..];
return Some((metadata, body));
}
offset += line.len();
}
None
}
fn embed_local_images<'a>(events: Vec<MdEvent<'a>>, base_dir: Option<&Path>) -> Vec<MdEvent<'a>> {
let Some(base_dir) = base_dir else {
return events;
};
events
.into_iter()
.map(|event| match event {
MdEvent::Start(Tag::Image {
link_type,
dest_url,
title,
id,
}) => {
let embedded = local_image_data_url(base_dir, dest_url.as_ref());
MdEvent::Start(Tag::Image {
link_type,
dest_url: embedded.map(CowStr::from).unwrap_or(dest_url),
title,
id,
})
}
_ => event,
})
.collect()
}
fn local_image_data_url(base_dir: &Path, url: &str) -> Option<String> {
let image_path = resolve_local_relative_image_path(base_dir, url)?;
let mime = image_mime_type(&image_path)?;
let bytes = fs::read(image_path).ok()?;
Some(format!("data:{mime};base64,{}", base64_encode(&bytes)))
}
fn resolve_local_relative_image_path(base_dir: &Path, url: &str) -> Option<PathBuf> {
let path_part = url.split(['#', '?']).next()?.trim();
if !is_local_relative_url(path_part) {
return None;
}
let mut candidate = base_dir.to_path_buf();
for segment in path_part.split('/') {
if segment.is_empty() || segment == "." {
continue;
}
let decoded = percent_decode_path_segment(segment)?;
let segment_path = Path::new(&decoded);
if segment_path
.components()
.any(|component| !matches!(component, Component::Normal(_)))
{
return None;
}
candidate.push(segment_path);
}
if candidate == base_dir {
return None;
}
Some(candidate)
}
fn is_local_relative_url(url: &str) -> bool {
!url.is_empty()
&& !url.starts_with('#')
&& !url.starts_with('/')
&& !url.starts_with('\\')
&& !url.starts_with("//")
&& !url.contains(':')
}
fn percent_decode_path_segment(segment: &str) -> Option<String> {
let bytes = segment.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' {
let hi = bytes.get(i + 1).and_then(|b| hex_value(*b))?;
let lo = bytes.get(i + 2).and_then(|b| hex_value(*b))?;
out.push((hi << 4) | lo);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).ok()
}
fn hex_value(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
fn image_mime_type(path: &Path) -> Option<&'static str> {
match path
.extension()?
.to_string_lossy()
.to_ascii_lowercase()
.as_str()
{
"png" => Some("image/png"),
"jpg" | "jpeg" => Some("image/jpeg"),
"gif" => Some("image/gif"),
"webp" => Some("image/webp"),
"svg" => Some("image/svg+xml"),
"bmp" => Some("image/bmp"),
"ico" => Some("image/x-icon"),
"avif" => Some("image/avif"),
_ => None,
}
}
fn base64_encode(bytes: &[u8]) -> String {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
let mut index = 0;
while index + 3 <= bytes.len() {
let n = ((bytes[index] as u32) << 16)
| ((bytes[index + 1] as u32) << 8)
| bytes[index + 2] as u32;
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
out.push(TABLE[(n & 0x3f) as usize] as char);
index += 3;
}
match &bytes[index..] {
[a] => {
let n = (*a as u32) << 16;
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
out.push('=');
out.push('=');
}
[a, b] => {
let n = ((*a as u32) << 16) | ((*b as u32) << 8);
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
out.push('=');
}
_ => {}
}
out
}
fn add_mark_highlights<'a>(events: Vec<MdEvent<'a>>) -> Vec<MdEvent<'a>> {
let mut out = Vec::with_capacity(events.len());
let mut code_block_depth = 0usize;
for event in events {
match &event {
MdEvent::Start(Tag::CodeBlock(_)) => code_block_depth += 1,
MdEvent::End(TagEnd::CodeBlock) => {
code_block_depth = code_block_depth.saturating_sub(1);
}
MdEvent::Text(text) if code_block_depth == 0 && text.contains("==") => {
push_mark_highlight_events(text.as_ref(), &mut out);
continue;
}
_ => {}
}
out.push(event);
}
out
}
fn push_mark_highlight_events<'a>(text: &str, out: &mut Vec<MdEvent<'a>>) {
let mut rest = text;
while let Some(open) = rest.find("==") {
let after_open = open + 2;
let Some(close_rel) = rest[after_open..].find("==") else {
break;
};
let close = after_open + close_rel;
let body = &rest[after_open..close];
if body.trim().is_empty() {
break;
}
if open > 0 {
out.push(MdEvent::Text(CowStr::Boxed(
rest[..open].to_string().into_boxed_str(),
)));
}
out.push(MdEvent::Html(CowStr::Borrowed(
r#"<mark class="mdp-mark">"#,
)));
out.push(MdEvent::Text(CowStr::Boxed(
body.to_string().into_boxed_str(),
)));
out.push(MdEvent::Html(CowStr::Borrowed("</mark>")));
rest = &rest[close + 2..];
}
if !rest.is_empty() {
out.push(MdEvent::Text(CowStr::Boxed(
rest.to_string().into_boxed_str(),
)));
}
}
fn add_heading_ids<'a>(mut events: Vec<MdEvent<'a>>) -> Vec<MdEvent<'a>> {
let mut seen: HashMap<String, usize> = HashMap::new();
for i in 0..events.len() {
let generate_id = match &events[i] {
MdEvent::Start(Tag::Heading { id: Some(id), .. }) => {
register_heading_id(id.as_ref(), &mut seen);
false
}
MdEvent::Start(Tag::Heading { id: None, .. }) => true,
_ => false,
};
if !generate_id {
continue;
}
let text = collect_heading_text(&events, i);
let base = heading_slug(&text);
let id_value = unique_heading_id(base, &mut seen);
if let MdEvent::Start(Tag::Heading { id, .. }) = &mut events[i] {
*id = Some(CowStr::Boxed(id_value.into_boxed_str()));
}
}
events
}
fn collect_heading_text(events: &[MdEvent<'_>], start: usize) -> String {
let mut text = String::new();
for event in events.iter().skip(start + 1) {
match event {
MdEvent::End(TagEnd::Heading(_)) => break,
MdEvent::Text(value)
| MdEvent::Code(value)
| MdEvent::InlineMath(value)
| MdEvent::DisplayMath(value) => text.push_str(value.as_ref()),
MdEvent::SoftBreak | MdEvent::HardBreak => text.push(' '),
_ => {}
}
}
text
}
fn heading_slug(text: &str) -> String {
let mut slug = String::new();
let mut last_dash = false;
for c in text.trim().chars().flat_map(char::to_lowercase) {
if c.is_alphanumeric() || c == '_' || c == '-' {
slug.push(c);
last_dash = false;
} else if c.is_whitespace() && !slug.is_empty() && !last_dash {
slug.push('-');
last_dash = true;
}
}
while slug.ends_with('-') {
slug.pop();
}
if slug.is_empty() {
"section".to_string()
} else {
slug
}
}
fn register_heading_id(id: &str, seen: &mut HashMap<String, usize>) {
if !id.is_empty() {
*seen.entry(id.to_string()).or_insert(0) += 1;
}
}
fn unique_heading_id(base: String, seen: &mut HashMap<String, usize>) -> String {
let count = seen.entry(base.clone()).or_insert(0);
let id = if *count == 0 {
base
} else {
format!("{base}-{count}")
};
*count += 1;
id
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn base64_matches_known_vectors() {
assert_eq!(base64_encode(b""), "");
assert_eq!(base64_encode(b"f"), "Zg==");
assert_eq!(base64_encode(b"fo"), "Zm8=");
assert_eq!(base64_encode(b"foo"), "Zm9v");
assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
}
}

65
src/page.rs Normal file
View File

@@ -0,0 +1,65 @@
//! The single in-memory HTML document the webview loads.
//!
//! Markup, CSS and JS live in `assets/page/`; this module fills the
//! `__MDP_*__` placeholders. Keeping the UI out of the Rust source means
//! editing the page no longer requires escaping braces inside a `format!`
//! string, and the JS can be syntax-checked as a real file.
//!
//! User content is substituted last so a document that happens to contain a
//! placeholder-looking string is not rewritten by an earlier replacement.
use crate::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");
pub fn build_page(
preview_html: &str,
raw_md: &str,
base_href: Option<&str>,
flags: EnhanceFlags,
s: &Strings,
home: bool,
) -> String {
let base_tag = base_href
.map(|href| format!(r#"<base id="base-href" href="{}">"#, html_escape_attr(href)))
.unwrap_or_else(|| r#"<base id="base-href">"#.to_string());
PAGE_HTML
.replace("__MDP_CSS_CODE__", HLJS_CODE)
.replace("__MDP_PAGE_CSS__", PAGE_CSS)
.replace("__MDP_PAGE_JS__", PAGE_JS)
.replace("__MDP_PREVIEW_ENHANCE_JS__", PREVIEW_ENHANCE_JS)
.replace("__MDP_BASE_TAG__", &base_tag)
.replace("__MDP_BODY_CLASS__", if home { "home" } else { "" })
.replace("__MDP_NEW_TAB__", s.new_tab)
.replace("__MDP_BTN_OPEN_LOCATION__", s.btn_open_location)
.replace("__MDP_BTN_NEW_WINDOW__", s.btn_new_window)
.replace("__MDP_BTN_EDIT__", s.btn_edit)
.replace("__MDP_BTN_PREVIEW__", s.btn_preview)
.replace("__MDP_HOME_TAB__", &escape_js(s.home_tab))
.replace("__MDP_FOLD_TOGGLE__", s.fold_toggle)
.replace("__MDP_CANNOT_SAVE_JS__", &escape_js(s.cannot_save))
.replace("__MDP_BTN_ZOOM__", s.btn_zoom)
.replace("__MDP_BTN_ZOOM_OUT__", s.btn_zoom_out)
.replace("__MDP_BTN_ZOOM_RESET__", s.btn_zoom_reset)
.replace("__MDP_BTN_ZOOM_IN__", s.btn_zoom_in)
.replace("__MDP_SEARCH_PLACEHOLDER__", s.search_placeholder)
.replace("__MDP_STAT_WORDS_JS__", &escape_js(s.stat_words))
.replace("__MDP_STAT_CHARS_JS__", &escape_js(s.stat_chars))
.replace(
"__MDP_NEEDS_MATH__",
if flags.math { "true" } else { "false" },
)
.replace(
"__MDP_NEEDS_MERMAID__",
if flags.mermaid { "true" } else { "false" },
)
.replace("__MDP_PREVIEW_HTML__", preview_html)
.replace("__MDP_RAW_MD_ESCAPED__", &html_escape_ta(raw_md))
}