Compare commits

..
1 Commits
Author SHA1 Message Date
cflmy 492790e985 release: v2.5.1 — flowing source annotations and labeled toolbar 2026-11-07 13:08:09 +08:00
16 changed files with 498 additions and 91 deletions

No files matched your search

+3
View File
@@ -126,6 +126,9 @@ jobs:
## Marqdo ${{ github.ref_name }}
### 亮点 / Highlights
- **v2.5.1**:View 连线优化——真实源码锚点、连续 S 形曲线、错落与避让;工具栏文字标签;保留深浅色配色
- **v2.5.1**: View annotation refinement — exact source anchors, flowing S-curves, staggered notes and collision avoidance; labeled toolbar; preserved themes
- **v2.5.1 ext**:扩展包同步 2.5.1 / Ext pack 2.5.1
- **v2.5.0**:View 阅读界面重构——暖白金色主题、新 Logo、左右执行标注、导航搜索与悬浮工具栏;离线公式;重跑同次捕获刷新
- **v2.5.0**: View reader redesign — warm paper theme, new logo, margin execution notes, navigation/search and floating controls; offline math; same-capture live refresh
- **v2.5.0 ext**:扩展包同步 2.5.0 / Ext pack 2.5.0
+20
View File
@@ -8,6 +8,26 @@
### Changed
## v2.5.1 — 2026-11-07
### Highlights
**View 标注连线与工具栏优化 / View annotation and toolbar refinement**:执行标注精确绑定源码行与字节区间;连续 S 形曲线取代水平长线,标注贴近正文错落排布,并避让正文和相邻连线;浮动工具栏增加文字说明。CLI · wasm · ext **2.5.1**。
**核心表面 Δ(Core surface Δ)**:**无增删**(仍 19 个构造);无 Markdown 语法或插件 ABI 变更。
### Fixed
- 执行标注从实际源码片段引出并连接标注标题,不再从正文边缘引出;多调用帧与循环轮次共用准确的源码区间,避免按类型猜测锚点。
- 处理源码换行、重跑、窗口变化与字体加载后的连线定位;保留密集区域和窄屏的文内降级。
- 连线连续弯曲、柔和金绿过渡,并为相邻曲线保留间距;宽屏标注更靠近正文,横纵方向错落排布。
### Changed
- 底部工具栏显示“刷新、设置、运行、清理、更多”,保留深浅色配色与原有操作行为。
- 新增七种屏宽、曲率、连线交叉、两端定位及共享源码帧绑定的浏览器回归。
- CLI、WASM、扩展包和 VS Code / Cursor 扩展同步 **2.5.1**;扩展包功能沿用 v2.5.0。
## v2.5.0 — 2026-11-07
### Highlights
Generated
+2 -2
View File
@@ -572,7 +572,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "marqdo"
version = "2.5.0"
version = "2.5.1"
dependencies = [
"anyhow",
"assert_cmd",
@@ -611,7 +611,7 @@ dependencies = [
[[package]]
name = "marqdo-wasm"
version = "2.5.0"
version = "2.5.1"
dependencies = [
"marqdo",
"serde_json",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo"
version = "2.5.0"
version = "2.5.1"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo — Markdown markers as an interpreted programming language"
+6 -4
View File
@@ -284,7 +284,9 @@ marqdo catalog public -o .marqdo
---
## 现状(v2.5.0)
## 现状(v2.5.1)
- **View 连线与工具栏(v2.5.1)**:真实源码锚点、连续 S 形曲线、错落标注与连线避让;底部工具栏增加文字标签。深浅色配色保持一致。CLI · wasm · ext 同步 **2.5.1**。
- **View 阅读界面(v2.5.0)**:暖白金色主题、新 Logo 与花枝装饰;真实执行信息左右引出、窄屏内联;导航/搜索/阅读设置/工具栏;重跑同步刷新与离线公式。CLI · wasm · ext 同步 **2.5.0**。
@@ -335,7 +337,7 @@ marqdo catalog public -o .marqdo
- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 JS;桥内可含列表/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM;`web.client_embed`;示例 [browser-hello](examples/browser-hello/) · [browser-app](examples/browser-app/) · [browser-media](examples/browser-media/) · [web-client-site](examples/web-client-site/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [D](doc/roadmap/browser-wasm-d.md) · [E](doc/roadmap/browser-wasm-e.md) · [F](doc/roadmap/browser-wasm-f.md))
- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM](doc/adr/0002-browser-marqdo-wasm.md)(C0–C5 完结,见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))· [ADR 0003 — 异步效应](doc/adr/0003-browser-async-effects.md)
### 如何使用最新 Marqdo(v2.5.0)
### 如何使用最新 Marqdo(v2.5.1)
**安装解释器(任选其一)**
@@ -350,7 +352,7 @@ marqdo catalog public -o .marqdo
```bash
# 1) 源码安装(跟 tag 或 main)
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout v2.5.0 # 或留在 main
git checkout v2.5.1 # 或留在 main
cargo build --release
export PATH="$PWD/target/release:$PATH"
marqdo version
@@ -391,7 +393,7 @@ marqdo wasm build
# → dist/wasm/ … 见 examples/browser-hello/
# 6) Releases:Windows exe/zip/vsix;Linux CLI zip + native `.so` zip
# https://github.com/cflmy/marqdo/releases/tag/v2.5.0
# https://github.com/cflmy/marqdo/releases/tag/v2.5.1
```
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo-wasm"
version = "2.5.0"
version = "2.5.1"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
+7
View File
@@ -1,3 +1,10 @@
marqdo (2.5.1-1ppa1) noble; urgency=medium
* Marqdo 2.5.1: exact source anchors, flowing annotation curves,
staggered margin notes, connector avoidance and a labeled toolbar.
-- Marqdo Maintainers <cflmy@users.noreply.github.com> Sat, 07 Nov 2026 13:05:55 +0800
marqdo (2.5.0-1ppa1) noble; urgency=medium
* Marqdo 2.5.0: redesigned document reader, margin execution annotations,
+19 -7
View File
@@ -14,13 +14,23 @@ Welcome files get a larger introduction; ordinary files retain compact titles.
## Runtime notes
Annotations keep their existing owner band, stable IDs, source anchor, call frame
and loop iteration data. On viewports wider than 1000px with 180px available on
each side, notes alternate between margin rails with collision avoidance. Dense
bands that would drift more than 140px from their statement retain inline notes.
and loop iteration data. Chips serialize source line and byte spans so another
call/iteration frame can find the same source mark without guessing by kind.
On viewports wider than 1000px with 180px available on each side, notes use both
page margins, varying horizontal reach and vertical offset with collision
avoidance. Dense bands that would drift more than 170px retain inline notes.
Compact screens, printing, and expanded overflow bands use ordinary document
flow. Connectors are CSS lines in the gutter, avoiding the paragraph text;
hover/focus highlights the precise source anchor. Clicking a note shows its full
captured detail. No explanatory prose or runtime values are invented.
flow. A shared SVG overlay draws continuously curved connections from the actual
mark's source-facing lower edge to the annotation title. The default is a full
S-curve with restrained gold/olive gradient; candidate sweeps are checked against
visible source text and already drawn connections. Tight prose uses two joined
curves below the text baseline and through the free margin, with no straight rail.
Notes sit closer to the document with varying horizontal/vertical offsets, rather
than stretching every connector across the entire page. Wrapped source marks use
their actual line fragments. Hover/focus highlights the exact source and connector.
Unresolved source anchors retain inline results instead of inventing a connection.
Clicking a note shows its full captured detail. No explanatory prose or runtime
values are invented.
Layout updates after window/font/structure resize, frame selection and live DOM
replacement. Static HTML includes the same code and embedded assets. All KaTeX
@@ -37,6 +47,7 @@ Document returns to prose. Functions/Variables move the real existing panels int
a modal and restore them on close, preserving their existing event handlers.
Memory shows the captured execution report, labeled as a snapshot on exports.
Run navigates to the output section. Search finds document, function and file text.
The floating toolbar labels its icons 刷新 / 设置 / 运行 / 清理 / 更多.
The bottom play button invokes actual live execution; static pages explain how to
start a live view. Static clear hides captured output locally; reload restores it.
Settings control light/dark theme, text size and annotation visibility. More keeps
@@ -48,5 +59,6 @@ Run `cargo test --offline --lib view::` and `cargo test --offline --test gold vi
The browser regression is `tests/view/reader.browser.cjs <URL>`; it accepts
`MARQDO_PLAYWRIGHT_MODULE`, `MARQDO_CHROMIUM`, and optional
`MARQDO_SCREENSHOT_DIR`. It blocks HTTPS resources to exercise offline reading,
checks six viewport widths, note bounds/collisions, real panel restoration,
checks seven viewport widths, note bounds/collisions, source/label curve endpoints, visible curvature and non-crossing paths,
shared-source frame binding, stable redraw, real panel restoration,
search, frame selection, note inspection and live/static run behavior.
+1 -1
View File
@@ -1 +1 @@
2.5.0
2.5.1
+5 -1
View File
@@ -6,7 +6,7 @@ description: Local browse and static export from the interpreter
# main
Version 2.5.0: `marqdo view` and `view output` share a warm paper reader with a new
Version 2.5.1: `marqdo view` and `view output` share a warm paper reader with a new
Marqdo logo, serif document text, botanical ornaments, navigation, search and a
floating action toolbar. Wide screens place real execution notes in the margins;
compact screens keep them below the corresponding paragraph. Click a note to
@@ -17,6 +17,10 @@ play button runs the document in live view; static pages retain their captured
results and explain how to start a live view. Ordinary document reruns update
prose, bindings and notes from the same execution capture.
Annotations follow the exact source span across calls and loop iterations. Flowing
curves and staggered margin notes avoid source text and neighboring connections.
The floating toolbar labels its actions: refresh, settings, run, clear and more.
Local: `marqdo view public`
Static export: `marqdo view output public -o public`
+4 -1
View File
@@ -6,7 +6,7 @@ description: 本地浏览与静态导出由解释器生成
# main
版本 2.5.0:`marqdo view` 与 `view output` 共用暖白金色阅读界面,新 Marqdo 标志、
版本 2.5.1:`marqdo view` 与 `view output` 共用暖白金色阅读界面,新 Marqdo 标志、
衬线正文、花枝装饰、导航搜索与底部悬浮工具栏。宽屏将真实执行结果沿左右页边引出,
窄屏将标注放回对应段落下方;点击标注可查看完整捕获值,调用帧和循环轮次仍可切换。
@@ -14,6 +14,9 @@ description: 本地浏览与静态导出由解释器生成
运行文档;静态页面保留导出结果,并提示如何启动实时 view。普通文档重跑后,正文、
变量和执行标注使用同一次执行捕获同步刷新。
执行标注跨调用帧与循环轮次精确对应源码区间。连续曲线与错落标注会避让正文和相邻连线;
底部工具栏显示“刷新、设置、运行、清理、更多”,深浅色配色保持一致。
本地浏览:`marqdo view public`
静态导出:`marqdo view output public -o public`
+10 -1
View File
@@ -865,9 +865,17 @@ pub fn render_annot_band(annots: &[ViewAnnot], max_visible: usize) -> String {
.arm_index
.map(|c| format!(r#" data-arm-index="{c}""#))
.unwrap_or_default();
// All call/iteration chips share the same source span, even when the
// rendered mark carries another frame's annotation ID.
let source_attr = format!(
" data-anchor-line=\"{}\"{}{}",
a.anchor_line,
a.anchor_byte_start.map(|n| format!(" data-anchor-byte-start=\"{n}\"")).unwrap_or_default(),
a.anchor_byte_end.map(|n| format!(" data-anchor-byte-end=\"{n}\"")).unwrap_or_default(),
);
let hidden_attr = if frame_miss { " hidden" } else { "" };
s.push_str(&format!(
r#"<button type="button" class="{classes}" data-annot-id="{id}" data-annot-kind="{kind}"{call}{loop_id}{iter}{arm}{hidden} title="{detail}">
r#"<button type="button" class="{classes}" data-annot-id="{id}" data-annot-kind="{kind}"{call}{loop_id}{iter}{arm}{source}{hidden} title="{detail}">
<span class="annot-label">{label}</span>
<span class="annot-value">{value}</span>
</button>"#,
@@ -878,6 +886,7 @@ pub fn render_annot_band(annots: &[ViewAnnot], max_visible: usize) -> String {
loop_id = loop_attr,
iter = iter_attr,
arm = arm_attr,
source = source_attr,
hidden = hidden_attr,
detail = escape(&a.detail),
label = escape(&a.label),
+5 -5
View File
@@ -1715,11 +1715,11 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
<div class="reader-ornament reader-blossom-bottom" aria-hidden="true"></div>
<footer class="reader-footer"><span>MARQDO</span><span>代码即文档 · 文档即知识库 · 知识即可执行</span></footer>
<div class="reader-dock" role="toolbar" aria-label="文档操作">
<button type="button" class="icon-button" data-reader-action="reload" aria-label="重新加载">{reload_icon}</button>
<button type="button" class="icon-button" data-reader-action="settings" aria-label="阅读设置">{settings_icon}</button>
<button type="button" class="reader-play icon-button" data-reader-action="run" aria-label="运行文档">{play_icon}</button>
<button type="button" class="icon-button" data-reader-action="clear" aria-label="清理输出">{clear_icon}</button>
<button type="button" class="icon-button" data-reader-action="more" aria-label="更多操作">{more_icon}</button>
<button type="button" class="icon-button" data-reader-action="reload" aria-label="重新加载"><span class="reader-dock-icon">{reload_icon}</span><span class="reader-dock-label" aria-hidden="true">刷新</span></button>
<button type="button" class="icon-button" data-reader-action="settings" aria-label="阅读设置"><span class="reader-dock-icon">{settings_icon}</span><span class="reader-dock-label" aria-hidden="true">设置</span></button>
<button type="button" class="reader-play icon-button" data-reader-action="run" aria-label="运行文档"><span class="reader-dock-icon">{play_icon}</span><span class="reader-dock-label" aria-hidden="true">运行</span></button>
<button type="button" class="icon-button" data-reader-action="clear" aria-label="清理输出"><span class="reader-dock-icon">{clear_icon}</span><span class="reader-dock-label" aria-hidden="true">清理</span></button>
<button type="button" class="icon-button" data-reader-action="more" aria-label="更多操作"><span class="reader-dock-icon">{more_icon}</span><span class="reader-dock-label" aria-hidden="true">更多</span></button>
</div>
<div class="reader-toast" role="status" aria-live="polite" hidden></div>
<dialog id="reader-dialog" class="reader-dialog" aria-labelledby="reader-dialog-title"><div class="reader-dialog-head"><h2 id="reader-dialog-title"></h2><button type="button" class="icon-button" data-reader-action="close-dialog" aria-label="关闭">×</button></div><div id="reader-dialog-content"></div></dialog>
+25 -12
View File
@@ -83,23 +83,34 @@ body.reader-page .annot-chip.annot-return { border-left-color:var(--olive); }
body.reader-page .annot-chip:hover,body.reader-page .annot-chip.is-focus { background:var(--hover); }
body.reader-page .annot-label { color:var(--olive); }.reader-page .annot-value { color:var(--ink); }
/* Side notes retain their owning band and frame attributes. JS only positions them. */
body.reader-page .doc-block.has-margin-notes > .annot-band { height:0; margin:0; padding:0; position:static; }
body.reader-page .document-surface { position:relative; padding-bottom:var(--reader-note-tail, 0px); }
body.reader-page .doc-list-item { position:relative; }
body.reader-page .has-margin-notes > .annot-band { height:0; margin:0; padding:0; position:static; }
body.reader-page .has-margin-notes > .annot-band > .annot-chips { position:static; display:block; }
body.reader-page .annot-chip.is-margin-note { position:absolute; width:150px; max-width:none; display:flex; flex-direction:column; align-items:flex-start; gap:4px; padding:4px 0; border:0; border-radius:0; background:var(--bg); font:13px/1.55 var(--sans); overflow-wrap:anywhere; z-index:3; }
body.reader-page .annot-chip.is-margin-note { position:absolute; width:170px; max-width:none; display:flex; flex-direction:column; align-items:flex-start; gap:6px; padding:5px 0; border:0; border-radius:0; background:var(--bg); font:13px/1.65 var(--sans); overflow-wrap:anywhere; z-index:3; }
body.reader-page .is-margin-note .annot-label { font:600 18px/1.4 var(--serif); }
body.reader-page .is-margin-note .annot-value { max-height:100px; overflow:auto; max-width:100%; }
body.reader-page .is-margin-note:hover { background:var(--fill); }
body.reader-page .reader-leader { position:absolute; pointer-events:none; height:1px; border-top:1px solid var(--olive); opacity:.65; transform-origin:left center; }
.reader-leader::before,.reader-leader::after { content:""; position:absolute; width:4px; height:4px; top:-2px; background:var(--gold); border-radius:50%; }
.reader-leader::before { left:0; }.reader-leader::after { right:0; }
.reader-connectors { position:absolute; top:0; overflow:visible; pointer-events:none; z-index:4; }
.reader-connectors path { fill:none; stroke-linecap:round; stroke-linejoin:round; }
.reader-connectors .reader-leader-halo { stroke:var(--bg); stroke-width:4; }
.reader-connectors .reader-leader { stroke:var(--olive); stroke-width:1.05; opacity:.78; }
.reader-connectors circle { fill:var(--gold); }
.reader-curve-gold { stop-color:var(--gold); }
.reader-curve-olive { stop-color:var(--olive); }
.reader-connectors .is-focus .reader-leader { opacity:1; stroke-width:1.5; }
body.reader-page #notebook-bar,body.reader-page #nb-stdin-bar,body.reader-page #nb-state-actions { display:none; }
body.reader-page.reader-tools #notebook-bar,body.reader-page.reader-tools #nb-stdin-bar,body.reader-page.reader-tools #nb-state-actions:not([hidden]) { display:flex; position:static; flex-wrap:wrap; border-radius:10px; margin-bottom:14px; }
body.reader-page #nb-status { white-space:normal; }
body.reader-page .exec-block { border-top:1px solid var(--line); padding-top:24px; margin-top:46px; }
body.reader-page .out,body.reader-page .source { background:var(--fill); border:1px solid var(--line); border-radius:10px; }
body.reader-page .source-block { color:var(--muted); font-size:13px; }
.reader-dock { position:fixed; z-index:20; bottom:24px; left:50%; transform:translateX(-50%); display:flex; align-items:center; gap:17px; padding:6px 17px; border:1px solid var(--line); border-radius:50px; background:color-mix(in srgb,var(--bg) 90%,transparent); backdrop-filter:blur(18px); box-shadow:0 8px 28px #78562614,inset 0 1px #ffffff55; }
.reader-dock .reader-play { width:56px; height:56px; margin:-9px 2px; color:white; background:linear-gradient(125deg,#a97632,#edc57e 55%,#c5964e); border:1px solid #f9e3bb; box-shadow:0 3px 12px #b18c4530; }
.reader-dock { position:fixed; z-index:20; bottom:24px; left:50%; transform:translateX(-50%); display:flex; align-items:flex-end; gap:17px; padding:10px 18px 8px; max-width:calc(100vw - 24px); border:1px solid var(--line); border-radius:44px; background:color-mix(in srgb,var(--bg) 90%,transparent); backdrop-filter:blur(18px); box-shadow:0 8px 28px #78562614,inset 0 1px #ffffff55; }
.reader-dock > .icon-button { display:flex; flex-direction:column; gap:5px; padding:0 3px; min-width:44px; border-radius:20px; }
.reader-dock-icon { display:flex; align-items:center; justify-content:center; width:34px; height:34px; }
.reader-dock-label { font:11px/1.6 var(--sans); letter-spacing:.08em; color:var(--muted); white-space:nowrap; }
.reader-dock .reader-play .reader-dock-icon { width:54px; height:54px; margin-top:-13px; color:white; border-radius:50%; background:linear-gradient(125deg,#a97632,#edc57e 55%,#c5964e); border:1px solid #f9e3bb; box-shadow:0 3px 12px #b18c4530; }
.reader-dock .reader-play .reader-dock-label { color:var(--focus); }
.reader-play svg { fill:currentColor; width:22px; }
.reader-footer { position:relative; padding:32px 20px 125px; display:flex; flex-direction:column; gap:10px; align-items:center; color:var(--muted); font:11px/1.8 var(--sans); letter-spacing:2px; border-top:1px solid var(--line); background:linear-gradient(170deg,transparent,var(--fill)); }
.reader-footer > :first-child { letter-spacing:5px; color:var(--gold); }
@@ -111,7 +122,7 @@ body.reader-page .source-block { color:var(--muted); font-size:13px; }
.reader-dialog input[type="search"] { width:100%; background:var(--surface); color:var(--ink); border:1px solid var(--line); border-radius:8px; padding:12px; font:15px var(--sans); }
.reader-dialog button.reader-option { display:block; width:100%; padding:12px; margin:8px 0; text-align:left; background:var(--fill); color:var(--ink); border:1px solid var(--line); border-radius:8px; cursor:pointer; }
.reader-dialog .vars-panel { max-height:none; }.reader-dialog .outline-section { border:0; background:transparent; }
.reader-toast { position:fixed; z-index:60; bottom:110px; left:50%; transform:translateX(-50%); max-width:calc(100vw - 32px); padding:10px 18px; border:1px solid var(--line); border-radius:12px; background:var(--surface); color:var(--ink); box-shadow:0 4px 25px #33241318; font:13px/1.5 var(--sans); }
.reader-toast { position:fixed; z-index:60; bottom:130px; left:50%; transform:translateX(-50%); max-width:calc(100vw - 32px); padding:10px 18px; border:1px solid var(--line); border-radius:12px; background:var(--surface); color:var(--ink); box-shadow:0 4px 25px #33241318; font:13px/1.5 var(--sans); }
body.reader-page.reader-large .doc-prose { font-size:22px; }
body.reader-page.reader-hide-notes .annot-band,body.reader-page.reader-hide-notes .annot-leaders { display:none; }
.reader-search-result { display:block; padding:12px 0; border-bottom:1px solid var(--line); font:14px/1.6 var(--sans); }
@@ -129,18 +140,18 @@ body.reader-page.reader-hide-notes .annot-band,body.reader-page.reader-hide-note
.reader-hero .eyebrow { font-size:10px; letter-spacing:5px; }.reader-hero .reader-motto { font-size:11px; letter-spacing:1px; }
body.reader-page .structure .doc-prose { font-size:17px; line-height:1.8; }body.reader-page .doc-fun-title { font-size:28px; }
.reader-blossom-top { width:115px; opacity:.28; }.reader-blossom-bottom { width:120px; height:150px; opacity:.3; }
.reader-dock { gap:12px; bottom:16px; padding:6px 13px; }.reader-dock .reader-play { width:50px; height:50px; }
.reader-dock { gap:10px; bottom:16px; padding:10px 12px 7px; }.reader-dock .reader-play .reader-dock-icon { width:50px; height:50px; }.reader-dock-label { font-size:10px; }
}
@media(prefers-reduced-motion:reduce) { .reader-page *, .reader-page *::before { scroll-behavior:auto!important; transition:none!important; } }
@media print {
.reader-header,.reader-dock,.reader-ornament,.reader-footer,.reader-toast { display:none!important; }
.reader-header,.reader-dock,.reader-ornament,.reader-footer,.reader-toast,.reader-connectors { display:none!important; }
body.reader-page main.panel { max-width:none; padding:0; }.reader-page .annot-chip.is-margin-note { position:static; width:auto; }
body.reader-page .doc-block.has-margin-notes > .annot-band { height:auto; }
body.reader-page .has-margin-notes > .annot-band { height:auto; }
}
/* Refine document rhythm without the old notebook cell dividers. */
body.reader-page #document-section > h2 { display:none; }
body.reader-page .doc-fun { border:0; margin:24px 0 12px; padding:0; }
body.reader-page .document-surface { padding:0; }
body.reader-page .document-surface { padding:0 0 var(--reader-note-tail, 0px); }
body.reader-page .reader-hero h1::after { content:""; width:85px; height:90px; vertical-align:middle; margin-left:12px; background-size:contain; background-position:center; background-repeat:no-repeat; }
body.reader-page .mq-anchor.mq-decl,body.reader-page .mq-anchor.mq-code { border-bottom-color:var(--gold); }
body.reader-page .mq-anchor.mq-return { border-bottom-color:var(--olive); }
@@ -156,3 +167,5 @@ body.reader-page.reader-welcome h1.page { display:none; }
body.reader-page .nav { visibility:hidden; }
body.reader-page #nav-toggle:checked ~ .shell .nav { visibility:visible; }
@media print { body.reader-page .document-surface { padding-bottom:0; } }
+306 -50
View File
@@ -110,57 +110,304 @@
option('打印 / 保存为 PDF', function () { dialog.close(); window.print(); });
}
}
function findAnchor(block, chip) {
var id = chip.dataset.annotId;
var anchors = block.querySelectorAll('.mq-anchor');
for (var i = 0; i < anchors.length; i++) if (anchors[i].dataset.annotId === id) return anchors[i];
var kind = chip.dataset.annotKind;
return block.querySelector(kind === 'bind' ? '.mq-decl' : kind === 'return' ? '.mq-return' : '.mq-code') || block.querySelector('.doc-line, .doc-prose') || block;
var anchorSequence = 0;
function noteOwner(band) {
return band ? band.closest('.doc-block, .doc-list-item') : null;
}
function findAnchor(owner, chip) {
if (!owner) return null;
var line = chip.dataset.anchorLine, start = Number(chip.dataset.anchorByteStart);
var end = Number(chip.dataset.anchorByteEnd), id = chip.dataset.annotId;
var anchors = Array.from(owner.querySelectorAll('.mq-anchor')).filter(function (el) {
return el.closest('.doc-block, .doc-list-item') === owner;
});
var exact = anchors.find(function (el) { return id && el.dataset.annotId === id; });
if (exact) return exact;
var onLine = anchors.filter(function (el) { return line && el.dataset.line === line; });
if (chip.hasAttribute('data-anchor-byte-start')) {
var span = onLine.filter(function (el) {
return el.hasAttribute('data-byte-start') && Number(el.dataset.byteStart) <= start
&& Number(el.dataset.byteEnd) > start;
}).sort(function (x, y) {
return (Number(x.dataset.byteEnd) - Number(x.dataset.byteStart))
- (Number(y.dataset.byteEnd) - Number(y.dataset.byteStart));
});
if (span.length) return span[0];
if (chip.hasAttribute('data-anchor-byte-end')) {
var overlap = onLine.find(function (el) {
return Number(el.dataset.byteStart) < end && Number(el.dataset.byteEnd) > start;
});
if (overlap) return overlap;
}
}
// A branch chip belongs to this arm, not to the first arm's source line.
if (owner.matches('.doc-list-item') && chip.dataset.annotKind === 'branch') {
return owner.querySelector(':scope > .doc-list-head');
}
if (onLine.length === 1) return onLine[0];
if (line && owner.dataset.line === line) {
return owner.querySelector(':scope > .doc-list-head, :scope > .doc-line.doc-stmt, :scope > .doc-line.doc-occl');
}
// No guessed first declaration / whole paragraph: retain an inline result.
return null;
}
function anchorFragments(anchor) {
var rects;
if (anchor.matches('.mq-anchor')) rects = Array.from(anchor.getClientRects());
else {
var range = document.createRange(); range.selectNodeContents(anchor);
rects = Array.from(range.getClientRects());
}
return rects.filter(function (r) { return r.width > 1 && r.height > 1; });
}
function resetNotes(bands, surface) {
bands.forEach(function (band) {
var owner = noteOwner(band);
if (owner) {
owner.classList.remove('has-margin-notes', 'is-keyed');
owner.querySelectorAll(':scope > .annot-leaders').forEach(function (el) { el.replaceChildren(); });
}
band.classList.remove('is-keyed');
band.querySelectorAll('.annot-chip').forEach(function (chip) {
chip.classList.remove('is-margin-note');
['left', 'top', 'width'].forEach(function (key) { chip.style.removeProperty(key); });
delete chip.dataset.readerAnchor; delete chip.dataset.readerSide;
});
});
if (surface) surface.querySelectorAll(':scope > .reader-connectors').forEach(function (el) { el.remove(); });
}
function setNoteTail(surface, height) {
var value = Math.ceil(Math.max(0, height)) + 'px';
if (surface.style.getPropertyValue('--reader-note-tail') !== value) surface.style.setProperty('--reader-note-tail', value);
}
function curvePoint(points, t) {
var u = 1 - t;
return {x:u*u*u*points[0].x + 3*u*u*t*points[1].x + 3*u*t*t*points[2].x + t*t*t*points[3].x,
y:u*u*u*points[0].y + 3*u*u*t*points[1].y + 3*u*t*t*points[2].y + t*t*t*points[3].y};
}
function splitCurve(points) {
function mid(a,b) { return {x:(a.x+b.x)/2,y:(a.y+b.y)/2}; }
var a=mid(points[0],points[1]), b=mid(points[1],points[2]), c=mid(points[2],points[3]);
var d=mid(a,b), e=mid(b,c), center=mid(d,e);
return [[points[0],a,d,center],[center,e,c,points[3]]];
}
function curveData(curves) {
var first=curves[0][0], path='M '+first.x+' '+first.y;
curves.forEach(function (curve) {
path+=' C '+curve[1].x+' '+curve[1].y+' '+curve[2].x+' '+curve[2].y+' '+curve[3].x+' '+curve[3].y;
});
return path;
}
function sourceObstacles(surface, inset, top) {
var rects=[], walker=document.createTreeWalker(surface,NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
var text=walker.currentNode, parent=text.parentElement;
if (!text.textContent.trim() || !parent || parent.closest('.annot-band,.annot-leaders,.reader-connectors,script,style')) continue;
var range=document.createRange(); range.selectNodeContents(text);
Array.from(range.getClientRects()).forEach(function (r) {
if (r.width>1 && r.height>1) rects.push({left:r.left-inset-2,right:r.right-inset+2,top:r.top-top-1,bottom:r.bottom-top+1});
});
}
surface.querySelectorAll('.doc-table,.code-card,.formula-card').forEach(function (el) {
var r=el.getBoundingClientRect();
rects.push({left:r.left-inset-3,right:r.right-inset+3,top:r.top-top-2,bottom:r.bottom-top+2});
});
return rects;
}
function clearCurve(points, obstacles) {
var left=Math.min.apply(Math,points.map(function(p){return p.x;}));
var right=Math.max.apply(Math,points.map(function(p){return p.x;}));
var top=Math.min.apply(Math,points.map(function(p){return p.y;}));
var bottom=Math.max.apply(Math,points.map(function(p){return p.y;}));
var nearby=obstacles.filter(function(r){return r.left<right&&r.right>left&&r.top<bottom&&r.bottom>top;});
for (var step=1;step<48;step++) {
var p=curvePoint(points,step/48);
if (nearby.some(function(r){return p.x>r.left&&p.x<r.right&&p.y>r.top&&p.y<r.bottom;})) return false;
}
return true;
}
function routeSamples(curves) {
var samples=[];
curves.forEach(function(curve,index){
for(var step=index?1:0;step<=20;step++) samples.push(curvePoint(curve,step/20));
});
samples.bounds=samples.reduce(function(box,p){
return {left:Math.min(box.left,p.x),right:Math.max(box.right,p.x),top:Math.min(box.top,p.y),bottom:Math.max(box.bottom,p.y)};
},{left:Infinity,right:-Infinity,top:Infinity,bottom:-Infinity});
return samples;
}
function clearRoutes(curves, routes) {
var samples=routeSamples(curves);
function cross(a,b,c){return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);}
function distance(p,a,b){
var dx=b.x-a.x,dy=b.y-a.y, t=Math.max(0,Math.min(1,((p.x-a.x)*dx+(p.y-a.y)*dy)/(dx*dx+dy*dy||1)));
return Math.pow(p.x-a.x-t*dx,2)+Math.pow(p.y-a.y-t*dy,2);
}
return routes.every(function(other){
var box=samples.bounds, prior=other.bounds;
if(box.right+8<prior.left||box.left-8>prior.right||box.bottom+8<prior.top||box.top-8>prior.bottom) return true;
for(var i=1;i<samples.length;i++) for(var j=1;j<other.length;j++) {
var a=samples[i-1],b=samples[i],c=other[j-1],d=other[j];
if(Math.max(a.x,b.x)+8<Math.min(c.x,d.x)||Math.min(a.x,b.x)-8>Math.max(c.x,d.x)
||Math.max(a.y,b.y)+8<Math.min(c.y,d.y)||Math.min(a.y,b.y)-8>Math.max(c.y,d.y)) continue;
if(cross(a,b,c)*cross(a,b,d)<0 && cross(c,d,a)*cross(c,d,b)<0) return false;
var shared=Math.hypot(samples[0].x-other[0].x,samples[0].y-other[0].y)<3;
if(shared && Math.hypot(a.x-samples[0].x,a.y-samples[0].y)<16
&& Math.hypot(c.x-other[0].x,c.y-other[0].y)<16) continue;
if(Math.min(distance(a,c,d),distance(b,c,d),distance(c,a,b),distance(d,a,b))<64) return false;
}
return true;
});
}
function flowingCurve(start, end, direction, bounds, inset, obstacles, routes) {
var distance=Math.abs(end.x-start.x);
var amplitude=Math.max(32,Math.min(128,distance*.24));
var preferred=end.y>=start.y?-1:1;
// Prefer one continuous, visible S-curve. Try the opposite sweep when a
// paragraph occupies that space; never trade readable prose for ornament.
for (var scale=1;scale>=.3;scale-=.35) {
for (var signIndex=0;signIndex<2;signIndex++) {
var wave=preferred*(signIndex===0?1:-1)*amplitude*scale;
var points=[start,{x:start.x+direction*distance*.34,y:start.y+wave},
{x:end.x-direction*distance*.34,y:end.y-wave},end];
var curves=splitCurve(points);
if (clearCurve(points,obstacles) && clearRoutes(curves,routes)) return curves;
}
}
// In flowing paragraphs, keep a gently bowed passage beneath the source
// line, then devote the free margin to a fuller curve. No straight rails.
var edge={x:(direction<0?bounds.left-14:bounds.right+14)-inset,y:start.y+5};
var innerDistance=Math.abs(edge.x-start.x), outerDistance=Math.abs(end.x-edge.x);
var outerWave=Math.max(22,Math.min(84,outerDistance*.32));
var fallback;
for(var sweep=0;sweep<2;sweep++) {
var wave=(sweep===0?1:-1)*outerWave;
fallback=[[start,{x:start.x+direction*innerDistance*.28,y:start.y+8},
{x:edge.x-direction*innerDistance*.28,y:edge.y},edge],
[edge,{x:edge.x+direction*outerDistance*.34,y:edge.y},
{x:end.x-direction*outerDistance*.34,y:end.y-wave},end]];
if(fallback.every(function(curve){return clearCurve(curve,obstacles);}) && clearRoutes(fallback,routes)) return fallback;
}
return fallback;
}
function drawConnections(surface, bounds, inset, notes) {
var ns = 'http://www.w3.org/2000/svg';
var svg = document.createElementNS(ns, 'svg');
svg.classList.add('reader-connectors'); svg.setAttribute('aria-hidden', 'true');
svg.style.left = (inset - bounds.left) + 'px';
svg.setAttribute('width', String(innerWidth - inset * 2));
svg.setAttribute('height', String(surface.offsetHeight));
var obstacles=sourceObstacles(surface,inset,bounds.top), routes=[];
var defs=document.createElementNS(ns,'defs');svg.appendChild(defs);
notes.forEach(function (note, noteIndex) {
var fragments = anchorFragments(note.anchor);
var a = note.side === 0 ? fragments[0] : fragments[fragments.length - 1];
if (!a) return;
var c = note.chip.getBoundingClientRect(), heading = note.chip.querySelector('.annot-label').getBoundingClientRect();
var direction = note.side === 0 ? -1 : 1;
var sx = (note.side === 0 ? a.left - 2 : a.right + 2) - inset, sy = a.bottom - bounds.top + 2;
var ex = (note.side === 0 ? heading.right + 9 : heading.left - 9) - inset;
var ey = heading.top + heading.height / 2 - bounds.top;
var curves=flowingCurve({x:sx,y:sy},{x:ex,y:ey},direction,bounds,inset,obstacles,routes);
routes.push(routeSamples(curves));
var pathData=curveData(curves);
var gradient=document.createElementNS(ns,'linearGradient');
gradient.id='reader-curve-ink-'+noteIndex;gradient.setAttribute('gradientUnits','userSpaceOnUse');
gradient.setAttribute('x1',sx);gradient.setAttribute('y1',sy);gradient.setAttribute('x2',ex);gradient.setAttribute('y2',ey);
[['0%','reader-curve-gold'],['55%','reader-curve-olive'],['100%','reader-curve-gold']].forEach(function(stop){
var node=document.createElementNS(ns,'stop');node.setAttribute('offset',stop[0]);node.setAttribute('class',stop[1]);gradient.appendChild(node);
});
defs.appendChild(gradient);
var group = document.createElementNS(ns, 'g'); group.classList.add('reader-connector');
group.dataset.annotId = note.chip.dataset.annotId;
if (!note.anchor.dataset.readerSourceAnchor) note.anchor.dataset.readerSourceAnchor = 'reader-anchor-' + (++anchorSequence);
group.dataset.readerAnchor = note.anchor.dataset.readerSourceAnchor;
note.chip.dataset.readerAnchor = group.dataset.readerAnchor;
group.dataset.startX = String(sx + inset); group.dataset.startY = String(sy + bounds.top);
['reader-leader-halo', 'reader-leader'].forEach(function (cls) {
var path = document.createElementNS(ns, 'path'); path.setAttribute('class', cls); path.setAttribute('d', pathData);
if(cls==='reader-leader') path.style.stroke='url(#'+gradient.id+')';
group.appendChild(path);
});
[[sx, sy, 'reader-source-dot'], [ex, ey, 'reader-note-dot']].forEach(function (point) {
var dot = document.createElementNS(ns, 'circle'); dot.setAttribute('cx', point[0]); dot.setAttribute('cy', point[1]);
dot.setAttribute('r', point[2] === 'reader-source-dot' ? '2.2' : '1.7'); dot.setAttribute('class', point[2]); group.appendChild(dot);
});
svg.appendChild(group);
});
surface.appendChild(svg);
}
function layoutAnnotations() {
var bands = document.querySelectorAll('[data-annot-band]');
// Reset geometry first; fallback is ordinary flow with all controls preserved.
bands.forEach(function (band) {
var block = band.closest('.doc-block'); if (!block) return;
block.classList.remove('has-margin-notes', 'is-keyed'); band.classList.remove('is-keyed');
block.querySelectorAll(':scope > .annot-leaders').forEach(function (el) { el.replaceChildren(); });
band.querySelectorAll('.annot-chip').forEach(function (chip) { chip.classList.remove('is-margin-note'); chip.style.removeProperty('left'); chip.style.removeProperty('top'); });
});
var bands = Array.from(document.querySelectorAll('[data-annot-band]'));
var surface = document.querySelector('.document-surface');
if (!surface || innerWidth <= 1000 || document.body.classList.contains('reader-hide-notes') || matchMedia('print').matches) return;
var bounds = surface.getBoundingClientRect(), nextY = [bounds.top + scrollY, bounds.top + scrollY];
if (bounds.left < 180 || innerWidth - bounds.right < 180) return;
bands.forEach(function (band) {
var block = band.closest('.doc-block'); if (!block || !block.getClientRects().length) return;
var chips = Array.from(band.querySelectorAll('.annot-chip')).filter(function (c) { return !c.hidden && !c.classList.contains('is-frame-hidden') && (!c.classList.contains('annot-chip-overflow') || band.classList.contains('is-expanded')); });
if (!chips.length || chips.length > 4 || !band.querySelector('[data-annot-more][hidden]') && band.querySelector('[data-annot-more]')) return;
var rect = block.getBoundingClientRect(), savedY = nextY.slice(), placed = [];
block.classList.add('has-margin-notes');
chips.forEach(function (chip) {
var anchor = findAnchor(block, chip), a = anchor.getBoundingClientRect();
var side = nextY[0] <= nextY[1] ? 0 : 1;
var y = Math.max(a.top + scrollY - 4, nextY[side]);
var left = side === 0 ? bounds.left - rect.left - 180 : bounds.right - rect.left + 30;
chip.classList.add('is-margin-note'); chip.style.left = left + 'px'; chip.style.top = (y - scrollY - rect.top) + 'px';
nextY[side] = y + chip.offsetHeight + 20;
placed.push({ chip:chip, anchor:a, side:side, y:y });
resetNotes(bands, surface);
if (!surface) return;
if (innerWidth <= 1000 || document.body.classList.contains('reader-hide-notes') || matchMedia('print').matches) {
setNoteTail(surface, 0); return;
}
var inset = Math.max(24, Math.min(56, innerWidth * .025));
var bounds = surface.getBoundingClientRect();
var space = [bounds.left - inset, innerWidth - inset - bounds.right];
if (Math.min.apply(Math, space) < 180) { setNoteTail(surface, 0); return; }
var eligible = bands.map(function (band) {
var owner = noteOwner(band);
if (!owner || !owner.getClientRects().length || owner.matches('.doc-table-wrap')) return null;
var chips = Array.from(band.querySelectorAll('.annot-chip')).filter(function (chip) {
return !chip.hidden && !chip.classList.contains('is-frame-hidden')
&& (!chip.classList.contains('annot-chip-overflow') || band.classList.contains('is-expanded'));
});
// If dense notes drift too far away from their statement, retain inline notes.
if (placed.some(function (p) { return p.y - (p.anchor.top + scrollY) > 140; })) {
nextY = savedY; block.classList.remove('has-margin-notes');
chips.forEach(function (c) { c.classList.remove('is-margin-note'); c.style.removeProperty('left'); c.style.removeProperty('top'); }); return;
}
var leaders = block.querySelector(':scope > .annot-leaders');
if (!leaders) { leaders = document.createElement('div'); leaders.className = 'annot-leaders'; leaders.setAttribute('aria-hidden','true'); block.prepend(leaders); }
placed.forEach(function (p) {
var c = p.chip.getBoundingClientRect(), a = p.anchor;
var x0 = p.side === 0 ? c.right + 7 : bounds.right + 4, y0 = p.side === 0 ? c.top + 15 : a.top + a.height/2;
var x1 = p.side === 0 ? bounds.left - 4 : c.left - 7, y1 = p.side === 0 ? a.top + a.height/2 : c.top + 15;
var line = document.createElement('span'); line.className = 'reader-leader';
line.style.left = (x0-rect.left)+'px'; line.style.top = (y0-rect.top)+'px';
line.style.width = Math.hypot(x1-x0,y1-y0)+'px'; line.style.transform = 'rotate('+Math.atan2(y1-y0,x1-x0)+'rad)'; leaders.appendChild(line);
var more = band.querySelector('[data-annot-more]');
if (!chips.length || chips.length > 4 || more && !more.hidden) return null;
var items = chips.map(function (chip) { return {chip:chip, anchor:findAnchor(owner,chip), owner:owner, band:band}; });
return items.every(function (it) { return it.anchor && anchorFragments(it.anchor).length; }) ? {band:band, owner:owner, items:items} : null;
}).filter(Boolean);
var excluded = new Set(), finalNotes = [];
// Falling back to flow changes later source positions. Re-measure the whole
// document after each fallback batch, instead of leaving stale endpoints.
for (var pass = 0; pass <= eligible.length; pass++) {
resetNotes(bands, surface);
var active = eligible.filter(function (b) { return !excluded.has(b.band); });
active.forEach(function (b) { b.owner.classList.add('has-margin-notes'); });
bounds = surface.getBoundingClientRect();
var nextY = [bounds.top + scrollY + 6, bounds.top + scrollY + 6], counts = [0,0];
var items = [].concat.apply([], active.map(function (b) { return b.items; }));
items.sort(function (a,b) { return a.anchor.getBoundingClientRect().top - b.anchor.getBoundingClientRect().top; });
var rejected = new Set(), notes = [];
items.forEach(function (item, index) {
if (rejected.has(item.band)) return;
var fragments = anchorFragments(item.anchor);
var width = Math.max(140, Math.min(190, Math.min.apply(Math, space) * .58));
item.chip.classList.add('is-margin-note'); item.chip.style.width = width + 'px';
var height = item.chip.offsetHeight, stagger = [-58, 44, -34, 68][index % 4];
var choices = nextY.map(function (y, side) {
var fragment = side === 0 ? fragments[0] : fragments[fragments.length - 1];
var desired = Math.max(bounds.top + scrollY + 6, fragment.bottom + scrollY - 16 + stagger);
var top = Math.max(desired, y);
return {side:side, anchor:fragment, top:top,
cost:Math.max(0, y - desired) * 3 + counts[side] * 35 + (side === index % 2 ? 0 : 24)};
});
var choice = choices[0].cost <= choices[1].cost ? choices[0] : choices[1];
var side = choice.side, top = choice.top;
if (top - (choice.anchor.bottom + scrollY) > 170) { rejected.add(item.band); return; }
var maxGap=space[side]-width;
var baseGap=Math.min(130,space[side]*.24,maxGap-12);
var gap=Math.max(24,Math.min(maxGap,baseGap+[0,28,-16,44][counts[side]%4]));
var x=side===0?bounds.left-gap-width:bounds.right+gap;
var ownerRect = item.owner.getBoundingClientRect();
item.chip.style.left = (x - ownerRect.left) + 'px'; item.chip.style.top = (top - scrollY - ownerRect.top) + 'px';
item.chip.dataset.readerSide = side === 0 ? 'left' : 'right';
nextY[side] = top + height + 28; counts[side]++;
notes.push({chip:item.chip,anchor:item.anchor,side:side});
});
});
if (rejected.size) { rejected.forEach(function (band) { excluded.add(band); }); continue; }
finalNotes = notes; break;
}
var tail = parseFloat(surface.style.getPropertyValue('--reader-note-tail')) || 0;
var bottom = bounds.bottom - tail;
var noteBottom = finalNotes.reduce(function (max,note) { return Math.max(max,note.chip.getBoundingClientRect().bottom); }, bottom);
setNoteTail(surface, noteBottom > bottom ? noteBottom - bottom + 20 : 0);
if (finalNotes.length) drawConnections(surface, bounds, inset, finalNotes);
}
function refreshAnnotations() {
if (pending) return; pending = true;
@@ -199,9 +446,13 @@
if (dialog.open && ev.target.closest('.outline-panel a')) { dialog.close(); }
});
function focusNote(ev, focus) {
var chip = ev.target.closest('.annot-chip'); if (!chip) return;
var block = chip.closest('.doc-block'); if (!block) return;
findAnchor(block,chip).classList.toggle('is-focus', focus); chip.classList.toggle('is-focus',focus);
var chip = ev.target.closest('.annot-chip'); if (!chip || ev.relatedTarget && chip.contains(ev.relatedTarget)) return;
var owner = noteOwner(chip.closest('[data-annot-band]'));
var anchor = findAnchor(owner,chip); if (anchor) anchor.classList.toggle('is-focus', focus);
chip.classList.toggle('is-focus',focus);
document.querySelectorAll('.reader-connector').forEach(function (group) {
if (group.dataset.annotId === chip.dataset.annotId) group.classList.toggle('is-focus',focus);
});
}
document.addEventListener('pointerover',function(e){focusNote(e,true);});
document.addEventListener('pointerout',function(e){focusNote(e,false);});
@@ -223,7 +474,12 @@
var surface = document.getElementById('structure');
if (surface) {
new MutationObserver(function (changes) {
if (changes.some(function(m){ return Array.from(m.addedNodes).concat(Array.from(m.removedNodes)).some(function(n){return n.nodeType===1 && !n.matches('.reader-leader,.annot-leaders');}); })) refreshAnnotations();
if (changes.some(function(m){
if (m.target.closest && m.target.closest('.reader-connectors')) return false;
return Array.from(m.addedNodes).concat(Array.from(m.removedNodes)).some(function(n){
return n.nodeType===1 && !n.matches('.reader-connectors,.reader-leader,.annot-leaders');
});
})) refreshAnnotations();
}).observe(surface,{childList:true,subtree:true});
if (typeof ResizeObserver !== 'undefined') new ResizeObserver(refreshAnnotations).observe(surface);
}
+83 -5
View File
@@ -10,7 +10,7 @@ const { chromium } = require(process.env.MARQDO_PLAYWRIGHT_MODULE || 'playwright
await page.route('https://**/*',route=>route.abort());
await page.goto(process.argv[2]); await page.waitForTimeout(400);
assert.equal(await page.locator('#structure').count(),1,'unique content target');
for (const width of [1440,1100,1024,1000,800,390]) {
for (const width of [1920,1440,1100,1024,1000,800,390]) {
await page.setViewportSize({width,height:1000}); await page.waitForTimeout(100);
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),'horizontal overflow at '+width);
const notes=await page.locator('.is-margin-note').count();
@@ -18,11 +18,89 @@ const { chromium } = require(process.env.MARQDO_PLAYWRIGHT_MODULE || 'playwright
else assert.equal(notes,0,'compact view should use inline notes');
const rects=await page.locator('.is-margin-note').evaluateAll(nodes=>nodes.map(n=>{const r=n.getBoundingClientRect();return {left:r.left,right:r.right,top:r.top,bottom:r.bottom};}));
rects.forEach(r=>assert(r.left>=0&&r.right<=width,'offscreen note'));
if(width>=1440) await checkConnections();
for(let i=0;i<rects.length;i++) for(let j=i+1;j<rects.length;j++) {
const a=rects[i],b=rects[j]; assert(!(a.left<b.right&&b.left<a.right&&a.top<b.bottom&&b.top<a.bottom),'overlapping notes');
}
}
await page.setViewportSize({width:1440,height:1000});
async function checkConnections() {
const issues = await page.evaluate(() => {
const issues=[];
document.querySelectorAll('.reader-connector').forEach(group => {
const path=group.querySelector('.reader-leader');
const anchor=Array.from(document.querySelectorAll('[data-reader-source-anchor]')).find(a=>a.dataset.readerSourceAnchor===group.dataset.readerAnchor);
if(!anchor){issues.push('missing actual source anchor');return;}
const chip=Array.from(document.querySelectorAll('.is-margin-note')).find(c=>c.dataset.annotId===group.dataset.annotId);
const p=path.getPointAtLength(0), start=new DOMPoint(p.x,p.y).matrixTransform(path.getScreenCTM());
let rects;
if(anchor.matches('.mq-anchor')) rects=Array.from(anchor.getClientRects());
else{const range=document.createRange();range.selectNodeContents(anchor);rects=Array.from(range.getClientRects());}
if(!rects.some(r=>Math.abs(start.x-(chip.dataset.readerSide==='left'?r.left-2:r.right+2))<2&&Math.abs(start.y-(r.bottom+2))<2)) issues.push('connector starts away from its source');
const label=chip.querySelector('.annot-label').getBoundingClientRect();
const q=path.getPointAtLength(path.getTotalLength()), finish=new DOMPoint(q.x,q.y).matrixTransform(path.getScreenCTM());
const expectedX=chip.dataset.readerSide==='left'?label.right+9:label.left-9;
if(Math.abs(finish.x-expectedX)>2||Math.abs(finish.y-(label.top+label.height/2))>2) issues.push('connector misses the annotation label');
if((path.getAttribute('d').match(/C /g)||[]).length<2) issues.push('missing Bézier curve');
if(path.getTotalLength()<80) issues.push('connector is too short at desktop width');
if(/(?:^|\s)L(?:\s|$)/.test(path.getAttribute('d'))) issues.push('straight rail segment');
let bow=0;const length=path.getTotalLength();
for(let i=1;i<20;i++){
const t=path.getPointAtLength(length*i/20);
const screen=new DOMPoint(t.x,t.y).matrixTransform(path.getScreenCTM());
bow=Math.max(bow,Math.abs((finish.x-start.x)*(start.y-screen.y)-(start.x-screen.x)*(finish.y-start.y))/Math.hypot(finish.x-start.x,finish.y-start.y));
}
if(bow<6) issues.push('curve is visually flat');
});
const routes=Array.from(document.querySelectorAll('.reader-connector')).map(group=>{
const path=group.querySelector('.reader-leader'),length=path.getTotalLength(),matrix=path.getScreenCTM();
return {anchor:group.dataset.readerAnchor,points:Array.from({length:41},(_,i)=>{
const p=path.getPointAtLength(length*i/40);return new DOMPoint(p.x,p.y).matrixTransform(matrix);
})};
});
for(let i=0;i<routes.length;i++)for(let j=i+1;j<routes.length;j++){
if(routes[i].anchor===routes[j].anchor)continue;
const a=routes[i].points,b=routes[j].points;
for(let p=1;p<a.length;p++)for(let q=1;q<b.length;q++){
const u=a[p-1],v=a[p],w=b[q-1],z=b[q];
const denominator=(v.x-u.x)*(z.y-w.y)-(v.y-u.y)*(z.x-w.x);
if(Math.abs(denominator)<.001)continue;
const t=((w.x-u.x)*(z.y-w.y)-(w.y-u.y)*(z.x-w.x))/denominator;
const k=((w.x-u.x)*(v.y-u.y)-(w.y-u.y)*(v.x-u.x))/denominator;
if(t>0&&t<1&&k>0&&k<1)issues.push('crossed execution connectors');
}
}
return issues;
});
assert.deepEqual(issues,[],'actual-source curve geometry');
assert.equal(await page.locator('.reader-connector').count(),await page.locator('.is-margin-note').count(),'one real connector per margin note');
}
await page.setViewportSize({width:1440,height:1000}); await page.waitForTimeout(100);
await checkConnections();
assert.deepEqual(await page.locator('.reader-dock-label').allTextContents(),['刷新','设置','运行','清理','更多']);
// Another frame's annotation ID must resolve by source span, never by the
// first declaration of the same kind on the line. Also exercise wrapped marks.
await page.evaluate(()=>{
const fixture=document.createElement('div');fixture.id='reader-source-regression';fixture.className='doc-block doc-exec';fixture.dataset.line='999';
fixture.innerHTML='<div class="doc-line"><mark class="mq-anchor mq-decl" data-line="999" data-byte-start="0" data-byte-end="5" data-annot-id="frame-one-left">left</mark> then <mark class="mq-anchor mq-decl" data-line="999" data-byte-start="20" data-byte-end="26" data-annot-id="frame-one-right">right</mark></div><div class="annot-band" data-annot-band><div class="annot-chips"><button class="annot-chip annot-bind" data-annot-id="frame-two-right" data-annot-kind="bind" data-anchor-line="999" data-anchor-byte-start="20" data-anchor-byte-end="26" title="right=2"><span class="annot-label">right</span><span class="annot-value">2</span></button></div></div>';
const line=document.createElement('div');line.className='doc-line';
line.innerHTML='<mark class="mq-anchor mq-code" data-line="1000" data-byte-start="0" data-byte-end="300" data-annot-id="frame-one-wrap">'+('wrapped source token '.repeat(14))+'</mark>';
fixture.insertBefore(line,fixture.querySelector('[data-annot-band]'));
fixture.querySelector('.annot-chips').insertAdjacentHTML('beforeend','<button class="annot-chip annot-expr" data-annot-id="frame-two-wrap" data-annot-kind="expr" data-anchor-line="1000" data-anchor-byte-start="0" data-anchor-byte-end="300" title="wrapped=3"><span class="annot-label">wrapped</span><span class="annot-value">3</span></button>');
document.querySelector('.document-surface').appendChild(fixture);window.MarqdoReader.refreshAnnotations();
});
await page.waitForTimeout(100);
assert(await page.evaluate(()=>{
const chip=document.querySelector('#reader-source-regression .annot-chip');
const anchor=document.querySelector('#reader-source-regression [data-annot-id="frame-one-right"]');
return chip.dataset.readerAnchor===anchor.dataset.readerSourceAnchor&&!!chip.dataset.readerAnchor;
}),'second frame binds the second declaration');
assert(await page.evaluate(()=>document.querySelector('[data-annot-id="frame-one-wrap"]').getClientRects().length>1),'wrapped source fixture');
await checkConnections();
await page.evaluate(()=>{document.getElementById('reader-source-regression').remove();window.MarqdoReader.refreshAnnotations();});
await page.waitForTimeout(150);
await page.evaluate(()=>{window.__readerOverlay=document.querySelector('.reader-connectors');});
await page.waitForTimeout(250);
assert(await page.evaluate(()=>window.__readerOverlay===document.querySelector('.reader-connectors')),'connector drawing must not trigger a mutation/resize loop');
await page.locator('[data-reader-action="functions"]').click();
assert(await page.locator('#reader-dialog #fn-outline').count());
await page.keyboard.press('Escape'); await page.locator('#outline-rail #fn-outline').waitFor({state:'attached'}); assert(await page.locator('#outline-rail #fn-outline').count(),'restore real function panel');
@@ -34,7 +112,7 @@ const { chromium } = require(process.env.MARQDO_PLAYWRIGHT_MODULE || 'playwright
await page.keyboard.press('Escape');
const visibleChip=page.locator('.annot-chip:visible').first(); await visibleChip.click(); assert(await page.locator('#reader-dialog pre').isVisible()); await page.keyboard.press('Escape');
for (const picker of await page.locator('.call-picker,.loop-picker').all()) {
const opts=await picker.locator('option').count(); if(opts>1) {await picker.selectOption({index:0});await picker.selectOption({index:opts-1});}
const opts=await picker.locator('option').count(); if(opts>1) {await picker.selectOption({index:0});await picker.selectOption({index:opts-1});await page.waitForTimeout(100);await checkConnections();}
}
await page.locator('[data-reader-action="settings"]').click();
await page.getByRole('button',{name:'切换标准 / 大号正文'}).click(); await page.keyboard.press('Escape');
@@ -44,13 +122,13 @@ const { chromium } = require(process.env.MARQDO_PLAYWRIGHT_MODULE || 'playwright
const response=page.waitForResponse(r=>r.url().endsWith('/api/session/run_document'));
await page.locator('[data-reader-action="run"]').click(); const result=await (await response).json();
assert(result.ok&&result.structure_html&&result.trace_json,'live run must return matching annotations');
await page.waitForTimeout(200); assert(await page.locator('.is-margin-note').count()>0,'annotations survive rerun');
await page.waitForTimeout(200); assert(await page.locator('.is-margin-note').count()>0,'annotations survive rerun');await checkConnections();
} else {
await page.locator('[data-reader-action="run"]').click(); assert((await page.locator('.reader-toast').textContent()).includes('静态页面'));
}
assert.deepEqual(errors,[],'browser JavaScript errors');
const out=process.env.MARQDO_SCREENSHOT_DIR;
if(out){await page.screenshot({path:out+'/desktop.png'});await page.setViewportSize({width:390,height:844});await page.waitForTimeout(100);await page.screenshot({path:out+'/mobile.png'});}
console.log(JSON.stringify({ok:true,live,sizes:6,errors,formulaCount:await page.locator('.katex').count()}));
console.log(JSON.stringify({ok:true,live,sizes:7,errors,formulaCount:await page.locator('.katex').count()}));
await browser.close();
})().catch(e=>{console.error(e);process.exit(1);});