Compare commits

...
1 Commits
Author SHA1 Message Date
cflmy eac6921524 view: preserve disclosure state and release CLI 2.7.1 2026-11-11 00:44:32 +08:00
21 changed files with 976 additions and 228 deletions

No files matched your search

+24 -3
View File
@@ -118,6 +118,7 @@ jobs:
echo "VSIX=$vsix" >> $env:GITHUB_ENV
echo "SOURCE=$source" >> $env:GITHUB_ENV
echo "PUBLIC=$public" >> $env:GITHUB_ENV
echo "PUBLISH_EXT=$((Get-Content ext/VERSION -Raw).Trim() -eq $ver)" >> $env:GITHUB_ENV
echo "EXT=$extZip" >> $env:GITHUB_ENV
echo "NATIVE=$nativeZip" >> $env:GITHUB_ENV
@@ -129,8 +130,6 @@ jobs:
dist/${{ env.EXE }}
dist/${{ env.ZIP }}
dist/${{ env.STDLIB }}
dist/${{ env.EXT }}
dist/${{ env.NATIVE }}
dist/${{ env.VSIX }}
dist/${{ env.SOURCE }}
dist/${{ env.PUBLIC }}
@@ -138,6 +137,17 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Upload independently versioned extension assets
if: env.PUBLISH_EXT == 'True'
uses: softprops/action-gh-release@v2
with:
files: |
dist/${{ env.EXT }}
dist/${{ env.NATIVE }}
fail_on_unmatched_files: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
linux:
runs-on: ubuntu-latest
# Wait until Windows has created the GitHub Release, then attach Linux zips
@@ -169,6 +179,9 @@ jobs:
set -euo pipefail
VER="${GITHUB_REF_NAME#v}"
TARGET="x86_64-unknown-linux-gnu"
if [[ "$(tr -d '[:space:]' < ext/VERSION)" == "$VER" ]]; then
echo "PUBLISH_EXT=true" >> "$GITHUB_ENV"
fi
mkdir -p dist/stage-native/native
for lib in libweb.so libagent.so libquantum.so liblinalg.so libllm.so libengineering.so; do
src="target/release/${lib}"
@@ -197,8 +210,16 @@ jobs:
uses: softprops/action-gh-release@v2
with:
files: |
dist/${{ env.NATIVE }}
dist/${{ env.LINUX_ZIP }}
fail_on_unmatched_files: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Upload independently versioned Linux native pack
if: env.PUBLISH_EXT == 'true'
uses: softprops/action-gh-release@v2
with:
files: dist/${{ env.NATIVE }}
fail_on_unmatched_files: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+8
View File
@@ -2,6 +2,14 @@
## Unreleased
## v2.7.1 — 2026-11-11
CLI 修复发布:View 实际逻辑的手动开合不再被布局重排或运行结果刷新覆盖;函数、链接、列表和记录按内容排版,手机详情整行展示。核心仍为 19 个构造;拓展库保留 2.7.0。
CLI fix release: implementation disclosures retain mouse/keyboard choices across resize, nested source reading and live replacement. Typed call/link/value details preserve real navigation and read-only inspection. Independent extension packs remain 2.7.0.
详见 [双语发布说明](doc/releases/v2.7.1.md)。旧静态站点需要用新 CLI 重新导出。
## v2.7.0 — 2026-11-10
### Highlights / 亮点
Generated
+2 -2
View File
@@ -615,7 +615,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "marqdo"
version = "2.7.0"
version = "2.7.1"
dependencies = [
"anyhow",
"assert_cmd",
@@ -656,7 +656,7 @@ dependencies = [
[[package]]
name = "marqdo-wasm"
version = "2.7.0"
version = "2.7.1"
dependencies = [
"marqdo",
"serde_json",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo"
version = "2.7.0"
version = "2.7.1"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo — Markdown markers as an interpreted programming language"
+4
View File
@@ -16,6 +16,10 @@ v2.2.0 起,`marqdo call` 可以直接调用这份文件里的一个函数。
开发标准库和拓展库请直接阅读[可执行库开发指南](doc/library-development.mq.md):契约表、叙述式实现、遮蔽调用与多文件工程组织均有可运行示范。
当前 CLI **2.7.1** 修复 View 详情展开后自动折叠,并改进函数、链接及结构化内容侧注;已有静态页面需重新导出。独立拓展库继续使用 **2.7.0**。参见[发布说明](doc/releases/v2.7.1.md)与[阅读示例](examples/view-details.mq.md)。
CLI **2.7.1** preserves View disclosure choices across layout and live updates. Regenerate existing static exports to include the fix; independent extension packs stay at **2.7.0**.
## 核心优势:可执行知识(Executable Knowledge)
> **Knowledge That Can Run —— 知识即可执行。**
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo-wasm"
version = "2.7.0"
version = "2.7.1"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
+6
View File
@@ -1,3 +1,9 @@
marqdo (2.7.1-1ppa1) noble; urgency=medium
* Release 2.7.1; see the reviewed upstream CHANGELOG.
-- Marqdo Maintainers <cflmy@users.noreply.github.com> Wed, 11 Nov 2026 00:03:29 +0800
marqdo (2.7.0-1ppa2) noble; urgency=medium
* Repair engineering plugin compatibility for this 2.7.0 release.
+41
View File
@@ -0,0 +1,41 @@
# Marqdo 2.7.1
本次为 CLI 修复发布,重点修复 View 中“实际逻辑”展开后立即折叠的问题,并完成描述链接的细节排版。官方拓展库继续使用 2.7.0,不发布新的独立拓展包,也不移动 CDN VERSION。
This CLI release fixes implementation disclosures that collapsed immediately after opening and improves typed details for descriptive links. Official extension packs remain at 2.7.0; no independent extension assets or CDN VERSION update are included.
## 修复与改进 / Fixes and improvements
- View 布局只记录自己的自动开合,不再覆盖用户选择;鼠标、键盘、窗口变化、嵌套原始写法及同一文档的运行结果刷新均保留手动状态。
- Disclosure choices survive layout, resize and live DOM replacement. Layout-generated toggle events do not become user intent or trigger another reset loop.
- 函数调用按函数名、命名参数和嵌套调用排版;本页函数可以定位到定义。链接在正文及侧注中保留跳转,相对 mq.md 链接适配实时和离线页面。
- Lists, records and prose have typed presentation with optional original source. Empty payloads remain explicit placeholders; reading details never runs payloads.
- 手机详情按整行排列,展开卡片不再撑高相邻卡片。新增可执行阅读示例 examples/view-details.mq.md。
## 核心表面与范围 / Core surface and scope
核心构造仍为 19 个,没有新增语法、标准库接口或插件 ABI。变更属于 CLI 内嵌 View 前端、只读渲染与发布产物选择。浏览器不会因查看详情而执行实现或自动抓取链接预览。
The core surface stays at 19 constructs. Standard-library and extension APIs are unchanged. CLI and WASM manifest versions are 2.7.1; extension source packs stay 2.7.0. The matching VS Code package is built from its separate source branch. This release does not deploy gh-pages.
## 下载与安装 / Downloads and installation
| 产物 / Asset | 内容 / Contents |
|---|---|
| marqdo-2.7.1-x86_64-pc-windows-msvc.exe | Windows CLI,内嵌标准库 / CLI with embedded standard library |
| marqdo-2.7.1-x86_64-pc-windows-msvc.zip | Windows CLI 与配套库及原生插件 / complete Windows bundle |
| marqdo-2.7.1-x86_64-unknown-linux-gnu.zip | Linux CLI 与配套库及原生插件 / complete Linux bundle |
| marqdo-2.7.1-stdlib.zip | 标准库源码,API 未变 / standard-library sources with unchanged APIs |
| marqdo-2.7.1-source.zip | 本标签源码 / tagged source snapshot |
| marqdo-2.7.1.vsix | 独立编辑器分支构建 / editor extension from its separate branch |
| marqdo-2.7.1-public.zip | 使用修复后的 View 导出的用户文档 / public docs exported with the fixed View |
下载并解压对应平台 ZIP,使用其中的 CLI;独立 Windows EXE 内嵌标准库。Ubuntu noble 用户可使用 ppa:cflmy/marqdo 安装或升级,实际包可用性由发版最终验证单独检查。旧的静态导出需用新 CLI 重新执行 marqdo view output,才能包含修复后的前端。
Unpack the matching platform bundle, or use the standalone Windows executable. The maintained Ubuntu noble installation route is ppa:cflmy/marqdo. Regenerate older static exports with marqdo view output to include the fixed reader script. A CLI-only release keeps the existing official extension installation version.
## 验证范围 / Validation
本地全量 Rust 验收为 1039 通过、0 失败、2 个原有忽略项;用户文档成功导出 102 页。本地验收覆盖真实详情点击、键盘开合、原始写法、反复布局、窗口变化、实时 DOM 替换,以及静态/实时页面、桌面/手机和无脚本阅读。另验证只读导出不会触发逻辑、现有运行标注与连线、文档间跳转和示例函数调用。
Windows and Linux builds, exact-commit Release/EK jobs, archive contents and hashes, and Ubuntu source/build/apt availability are independent final release gates. Local browser tests do not establish Windows build success, and upload acceptance does not establish apt availability.
+29
View File
@@ -0,0 +1,29 @@
---
markup: occlusion
title: 描述与细节
---
这份文档把意图留在句子中,把细节放在侧注里。阅读和展开详情都不会运行示例中的函数,只有主动调用才会计算。
可以先看 [函数与参数](计算费用(单价=12, 数量=2)),再看 [嵌套调用](计算费用(单价=abs(-12), 数量=2)),了解每个输入来自哪里。
引用 [列表内容]([1, 2, 3]) 和 [记录内容]({"名称": "茶", "单价": 12}) 时,侧注会按内容的结构排列;[补充说明]("数量以实际购买件数为准。") 则直接呈现文字。
[待实现的步骤]() 会明确提示待补充,避免把缺失逻辑当成已经完成的工作。
通过 [跳到函数定义](#fn-16) 可以在当前文档中定位,通过 [查看阅读示例](view-reading.mq.md) 可以打开同目录文档;[访问项目仓库](https://github.com/cflmy/marqdo) 保留正常的网页跳转。
## 计算费用
| 参数 | 类型 | 默认值 | 含义 |
| --- | --- | --- | --- |
| 单价 | number | 0 | 每件商品的价格 |
| 数量 | number | 1 | 本次购买的件数 |
| 返回值 | 类型 | 含义 |
| --- | --- | --- |
| 费用 | number | 单价与数量的乘积 |
调用方提供 `单价`=0 和 `数量`=1 后,可以直接按件数计算。这一示例只处理简单乘法,未包含税费、折扣或金额舍入规则,实际项目应根据业务补齐这些约定。
在确认输入符合业务要求之后,返回 *[按件数计算](单价 * 数量)*,调用方便得到了本次购买的总费用。
+47 -3
View File
@@ -124,9 +124,53 @@ import:
#[test]
fn fetch_mq_load_returns_fetch_effect() {
let src = std::fs::read_to_string("examples/browser-hello/fetch.mq.md")
.expect("fetch.mq.md");
let (mut sess, wire) = BrowserSession::boot(&src).expect("boot");
// A protocol regression must not depend on a retired public example.
let src = r###"---
markup: occlusion
title: browser fetch (C4)
description: fetch/after effects via lib/browser — no json glue
import:
browser: lib/browser.mq.md
---
# main
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#load" | click | load |
| 2 | "#ping" | click | ping |
*`wire`*
## load
**`msg` = > browser.set_text sel="#status" text="loading…"**
**`req` = > browser.fetch url="https://httpbin.org/uuid" then="on_uuid"**
*> browser.merge a=msg b=req*
## on_uuid
+ `ok`
+ `status`
+ `body`=""
+ `error`=""
1. ok
*> browser.set_text sel="#status" text=body*
2. *
*> browser.set_text sel="#status" text="fetch failed"*
## ping
**`msg` = > browser.set_text sel="#status" text="wait 600ms…"**
**`t` = > browser.after ms=600 then="on_ping"**
*> browser.merge a=msg b=t*
## on_ping
+ `ok`=True
*> browser.set_text sel="#status" text="pong"*
"###;
let (mut sess, wire) = BrowserSession::boot(src).expect("boot");
assert!(matches!(wire, Value::List(_)));
let v = sess.call("load", "{}").expect("load");
let j = value_as_json(&v).unwrap();
+95 -206
View File
@@ -55,22 +55,23 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
let body_start = skip_frontmatter_end(&lines).unwrap_or(1);
let mut para: Vec<(u32, String)> = Vec::new();
let flush_para = |para: &mut Vec<(u32, String)>, out: &mut String| {
if para.is_empty() {
return;
}
if para.is_empty() { return; }
let first_line = para[0].0;
let text = para
.iter()
.map(|(_, t)| t.as_str())
.collect::<Vec<_>>()
.join(" ");
let source_anchors=para.iter().skip(1).map(|(line,_)|format!(r#"<span class="source-line-anchor" id="stmt-{line}" aria-hidden="true"></span>"#)).collect::<String>();
let source_anchors = para.iter().skip(1).map(|(line,_)|
format!(r#"<span class="source-line-anchor" id="stmt-{line}" aria-hidden="true"></span>"#)).collect::<String>();
let mut replacements = Vec::new();
let mut notes = String::new();
let text = para.iter().map(|(line, text)| {
let fragment = super::logic::narrative(*line, text, 0);
replacements.extend(fragment.replacements);
notes.push_str(&fragment.notes);
fragment.markdown
}).collect::<Vec<_>>().join(" ");
para.clear();
let md = comment_markdown_to_html(&text);
let md = super::logic::replace(comment_markdown_to_html(&text), &replacements);
let band = render_document_band(&[], &notes);
out.push_str(&format!(
r#"<div class="doc-block" data-line="{line}" id="stmt-{line}">{source_anchors}<div class="doc-prose">{md}</div></div>"#,
line = first_line,
md = md
r#"<div class="doc-block" data-line="{first_line}" id="stmt-{first_line}">{source_anchors}<div class="doc-prose">{md}</div>{band}</div>"#
));
};
@@ -218,7 +219,7 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
}
flush_para(&mut para, &mut out);
out.push_str("</div>");
out
super::logic::link_definitions(out, module)
}
#[derive(Clone, Copy)]
@@ -305,60 +306,39 @@ fn render_table_block(
line = first_line
);
let mut header_done = false;
for (idx, (_ln, row)) in rows.iter().enumerate() {
if looks_like_table_sep(row) {
continue;
}
let cells: Vec<&str> = row
.trim()
.trim_matches('|')
.split('|')
.map(|c| c.trim())
.collect();
let mut notes = String::new();
for (idx, (line, row)) in rows.iter().enumerate() {
if looks_like_table_sep(row) { continue; }
let cells: Vec<&str> = row.trim().trim_matches('|').split('|').map(str::trim).collect();
let rendered: Vec<String> = cells.iter().map(|cell| {
let base = cell.as_ptr() as usize - row.as_ptr() as usize;
notes.push_str(&super::logic::narrative(*line, cell, base).notes);
render_narrative_inline(*line, cell, base)
}).collect();
if !header_done {
html.push_str("<thead><tr>");
for c in &cells {
html.push_str(&format!("<th>{}</th>", escape(c)));
}
for cell in &rendered { html.push_str(&format!("<th>{cell}</th>")); }
html.push_str("</tr></thead><tbody>");
header_done = true;
// If next is sep, skip handled above; if only one data row treated as header+body empty ok
if idx + 1 < rows.len() && looks_like_table_sep(&rows[idx + 1].1) {
continue;
}
// Single-row table without sep: also emit as body
if idx + 1 < rows.len() && looks_like_table_sep(&rows[idx + 1].1) { continue; }
if rows.len() == 1 {
html.push_str("<tr>");
for c in &cells {
html.push_str(&format!("<td>{}</td>", escape(c)));
}
for cell in &cells { html.push_str(&format!("<td>{}</td>", escape(cell))); }
html.push_str("</tr>");
}
continue;
}
html.push_str("<tr>");
for c in &cells {
html.push_str(&format!("<td>{}</td>", escape(c)));
}
for cell in &rendered { html.push_str(&format!("<td>{cell}</td>")); }
html.push_str("</tr>");
}
if header_done {
html.push_str("</tbody>");
}
if header_done { html.push_str("</tbody>"); }
html.push_str("</table>");
// Annots on first table line (bind of collection).
if let Some(list) = by_line.get(&first_line) {
// A table is already its own readable value; a call chip would collapse
// the whole collection into an ellipsis. Keep only non-call chips.
let owned: Vec<ViewAnnot> = list
.iter()
.filter(|a| a.kind != crate::view::annot::AnnotKind::Call)
.map(|a| (*a).clone())
.collect();
if !owned.is_empty() {
html.push_str(&render_annot_band(&owned, MAX_VISIBLE_ANNOTS));
}
}
// The table is already a readable collection; retain only non-call results.
let owned: Vec<ViewAnnot> = by_line.get(&first_line).into_iter().flatten()
.filter(|a| a.kind != crate::view::annot::AnnotKind::Call)
.map(|a| (**a).clone()).collect();
html.push_str(&render_document_band(&owned, &notes));
if let Some(body) = writebacks.get(&first_line) {
html.push_str(&crate::view::render::render_output_card(first_line, body));
}
@@ -526,11 +506,7 @@ fn render_list_block(
}
}
}
let notes = if occluded_lines.contains(&lines[i].line_no) {
render_logic_notes(lines[i].line_no, head, &[])
} else {
String::new()
};
let notes = render_logic_notes(lines[i].line_no, head, &scan_prose_line(head), occluded_lines.contains(&lines[i].line_no));
html.push_str(&render_document_band(&head_annots, &notes));
// Body: following lines with greater indent until next sibling.
i += 1;
@@ -622,7 +598,7 @@ fn render_surface_line(
if head.trim() == "*" {
return r#"<span class="mq-else">else</span>"#.into();
}
format!(r#"<span class="doc-cond">{}</span>"#, escape(head))
format!(r#"<span class="doc-cond">{}</span>"#, render_narrative_inline(line_no, head, 0))
} else {
let annots = by_line.get(&line_no).map(|v| v.as_slice()).unwrap_or(&[]);
render_prose_with_marks(line_no, head, &bits, annots, false)
@@ -741,156 +717,57 @@ fn parse_args_brief(brief: &str) -> HashMap<String, String> {
/// Display-only source spans. The AST decides whether this line contains an occlusion.
/// Scan only executable fragments, preserving quoted links as literal data.
struct OcclusionSpan<'a> { start: usize, end: usize, label: &'a str, payload: &'a str }
fn occlusion_spans(text: &str) -> Vec<OcclusionSpan<'_>> {
let bytes = text.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < bytes.len() {
if matches!(bytes[i], b'"' | b'\'' | b'`') {
let quote = bytes[i];
i += 1;
while i < bytes.len() {
if bytes[i] == b'\\' {
i += 2;
} else if bytes[i] == quote {
i += 1;
break;
} else {
i += 1;
}
}
continue;
}
if bytes[i] == b'\\' {
i += 2;
continue;
}
if bytes[i] != b'[' || bytes.get(i + 1) == Some(&b'^') {
i += 1;
continue;
}
let start = i;
let mut j = i + 1;
let mut depth = 1;
while j < bytes.len() {
match bytes[j] {
b'\\' => {
j += 2;
continue;
}
b'[' => depth += 1,
b']' => {
depth -= 1;
if depth == 0 {
break;
}
}
_ => {}
}
j += 1;
}
if depth != 0 || bytes.get(j + 1) != Some(&b'(') {
i += 1;
continue;
}
let label_end = j;
j += 2;
let payload_start = j;
depth = 1;
while j < bytes.len() {
match bytes[j] {
b'"' | b'\'' | b'`' => {
let quote = bytes[j];
j += 1;
while j < bytes.len() {
if bytes[j] == b'\\' {
j += 2;
} else if bytes[j] == quote {
j += 1;
break;
} else {
j += 1;
}
}
continue;
}
b'(' => depth += 1,
b')' => {
depth -= 1;
if depth == 0 {
break;
}
}
_ => {}
}
j += 1;
}
if depth == 0 {
out.push(OcclusionSpan {
start,
end: j + 1,
label: &text[start + 1..label_end],
payload: text[payload_start..j].trim(),
});
i = j + 1;
} else {
i += 1;
}
}
out
}
fn logic_id(line: u32, at: usize) -> String {
format!("logic-{line}-{at}")
fn occlusion_spans(text: &str) -> Vec<super::logic::Span<'_>> {
super::logic::spans(text, true)
}
fn render_occlusion_text(line: u32, text: &str, base: usize) -> String {
let mut html = String::new();
let mut cursor = 0;
for span in occlusion_spans(text) {
html.push_str(&escape(&text[cursor..span.start]));
let id = logic_id(line, base + span.start);
let label = if span.label.is_empty() {
"未命名动作"
} else {
span.label
};
html.push_str(&format!(r#"<button type="button" class="occl-label" id="{id}-source" data-logic-id="{id}" aria-controls="{id}-note" title="查看实际逻辑(阅读不会执行)">{}</button>"#,escape(label)));
if span.payload.is_empty() {
html.push_str(r#"<span class="occl-stub">待补充实际逻辑</span>"#);
}
html.push_str(&super::logic::source(line, &span, base));
cursor = span.end;
}
html.push_str(&escape(&text[cursor..]));
html
}
fn render_logic_notes(line: u32, text: &str, bits: &[ProseBit]) -> String {
fn render_logic_notes(line: u32, text: &str, bits: &[ProseBit], occluded: bool) -> String {
let mut notes = String::new();
let fragments: Vec<(usize, usize, &str)> =
if bits.iter().all(|bit| matches!(bit, ProseBit::Decl { .. })) {
vec![(0, text.len(), text)]
} else {
bits.iter()
.filter_map(|bit| match bit {
ProseBit::BoldCode { inner, .. } | ProseBit::ItalicReturn { inner, .. } => {
Some((bit_at(bit), prose_bit_end(text, bit), inner.as_str()))
}
_ => None,
})
.collect()
};
for (start, end, fragment) in fragments {
for span in occlusion_spans(fragment) {
let id = logic_id(line, start + span.start);
let payload = if span.payload.is_empty() {
"待补充实际逻辑;当前空遮蔽返回 None。"
} else {
span.payload
};
notes.push_str(&format!(r#"<details class="annot-chip annot-implementation" id="{id}-note" data-annot-id="{id}" data-annot-kind="implementation" data-anchor-line="{line}" data-anchor-byte-start="{start}" data-anchor-byte-end="{end}"><summary class="annot-label">实际逻辑 · {label}</summary><code class="annot-value occl-code">{payload}</code><small class="logic-hint">源码说明 · 不是运行结果</small></details>"#,label=escape(span.label),payload=escape(payload)));
if occluded && bits.iter().all(|bit| matches!(bit, ProseBit::Decl { .. })) {
for span in occlusion_spans(text) {
notes.push_str(&super::logic::note(line, &span, 0, true));
}
return notes;
}
let mut cursor = 0;
for bit in bits {
let start = bit_at(bit);
let end = prose_bit_end(text, bit);
if start > cursor {
notes.push_str(&super::logic::narrative(line, &text[cursor..start], cursor).notes);
}
if occluded {
if let ProseBit::BoldCode { inner, .. } | ProseBit::ItalicReturn { inner, .. } = bit {
for span in occlusion_spans(inner) {
notes.push_str(&super::logic::note(line, &span, inner_offset(text, bit), true));
}
}
}
cursor = end.max(cursor);
}
if cursor < text.len() {
notes.push_str(&super::logic::narrative(line, &text[cursor..], cursor).notes);
}
notes
}
fn inner_offset(text: &str, bit: &ProseBit) -> usize {
let start = bit_at(bit);
match bit {
ProseBit::BoldCode { inner, .. } | ProseBit::ItalicReturn { inner, .. } =>
start + text[start..prose_bit_end(text, bit)].find(inner).unwrap_or(0),
_ => start,
}
}
fn render_document_band(annots: &[ViewAnnot], notes: &str) -> String {
let band = render_annot_band(annots, MAX_VISIBLE_ANNOTS);
if notes.is_empty() {
@@ -1000,8 +877,8 @@ fn render_line_block(
.map(|a| (*a).clone())
.collect()
};
let notes = if special.is_none() && occluded_lines.contains(&line_no) {
render_logic_notes(line_no, text, bits)
let notes = if special.is_none() {
render_logic_notes(line_no, text, bits, occluded_lines.contains(&line_no))
} else {
String::new()
};
@@ -1066,15 +943,16 @@ fn render_narrative_fence(lines: &[ClassifiedLine], start: usize) -> (String, us
/// Preserve ordinary Markdown links/emphasis outside executable marks. Raw HTML
/// stays literal here, as it did in mixed executable prose before this renderer.
fn render_narrative_inline(text: &str) -> String {
fn render_narrative_inline(line: u32, text: &str, base: usize) -> String {
let inner = text.trim();
if inner.is_empty() {
return escape(text);
}
let start = text.find(inner).unwrap();
let end = start + inner.len();
let parser = pulldown_cmark::Parser::new(inner).map(|event| match event {
pulldown_cmark::Event::Html(html) => pulldown_cmark::Event::Text(html),
let fragment = super::logic::narrative(line, inner, base + start);
let parser = pulldown_cmark::Parser::new(&fragment.markdown).map(|event| match event {
pulldown_cmark::Event::Html(html) | pulldown_cmark::Event::InlineHtml(html) => pulldown_cmark::Event::Text(html),
other => other,
});
let mut html = String::new();
@@ -1085,7 +963,7 @@ fn render_narrative_inline(text: &str) -> String {
else {
return escape(text);
};
format!("{}{}{}", escape(&text[..start]), body, escape(&text[end..]))
format!("{}{}{}", escape(&text[..start]), super::logic::replace(body.to_string(), &fragment.replacements), escape(&text[end..]))
}
/// Render prose with markers stripped; show surface inner text only.
@@ -1102,7 +980,7 @@ fn render_prose_with_marks(
let start = bit_at(bit);
let end = prose_bit_end(text, bit);
if start > cursor {
html.push_str(&render_narrative_inline(&text[cursor..start]));
html.push_str(&render_narrative_inline(line_no, &text[cursor..start], cursor));
}
if start < end && end <= text.len() {
let (cls, display) = bit_display(bit);
@@ -1117,13 +995,13 @@ fn render_prose_with_marks(
start = start,
end = end,
aid = escape(annot_id),
inner = if occluded && !matches!(bit,ProseBit::Decl{..}) {render_occlusion_text(line_no,&display,start)}else{escape(&display)},
inner = if occluded && !matches!(bit,ProseBit::Decl{..}) {render_occlusion_text(line_no,&display,inner_offset(text, bit))}else{escape(&display)},
));
}
cursor = end.max(cursor);
}
if cursor < text.len() {
html.push_str(&render_narrative_inline(&text[cursor..]));
html.push_str(&render_narrative_inline(line_no, &text[cursor..], cursor));
}
html
}
@@ -1480,7 +1358,7 @@ mod tests {
let module = crate::parse::parse_source(src).unwrap();
let html = render_module_document(&module, src, &[]);
assert!(
html.contains("<a href=\"https://github.com/cflmy/marqdo\">仓库</a>"),
html.contains("href=\"https://github.com/cflmy/marqdo\"") && html.contains(">仓库</a>") && html.contains("data-logic-kind=\"link\""),
"{html}"
);
}
@@ -1708,7 +1586,7 @@ fn render_syntax_guide() -> String {
"hr"=>"分隔内容,不能把分隔线当作函数返回。", "writeback"=>"程序写回的结果,区别于作者原始正文。",
"ident"=>"叙述中的参数或变量;默认值跟在名称之后。", "bold-code"=>"执行语句:赋值、调用或计算;不是打印,也不是返回。",
"italic-return"=>"返回表达式;句中以返回、Return 等明确引出。", "empty-return"=>"显式返回空值或结束当前函数。",
"link-index"=>"默认模式是 [动作](实现) 遮蔽,正文只显示动作;空括号表示待补充实际逻辑。classic 模式才解释为旧链接取元。",
"link-index"=>"正文显示描述,侧注按函数与参数、可跳转链接、结构化内容展示括号内的细节;空括号表示待补充实际逻辑。阅读不会执行调用。classic 模式保留旧链接取元。",
"bracket-call"=>"兼容的带修饰调用;不能把任意普通链接当作执行授权。", "footnote-index"=>"兼容的脚注取元;当前库优先用 access 读取集合。",
"soft-emphasis"=>"普通强调仍属于文字;界面按真实解析结果区分强调、语句与返回。", _=>"按源码中的真实结构阅读。"
};
@@ -1764,6 +1642,15 @@ mod readable_occlusion_tests {
assert!(html.contains("当前空遮蔽返回 None"));
}
#[test]
fn table_links_and_prose_content_are_readable_with_exact_source_notes() {
let html = render("# main\n\n| 内容 | 说明 |\n| --- | --- |\n| [指南](guide.mq.md) | [解释](plain explanatory text with **emphasis**) |\n\n*None*\n");
assert!(html.contains(">指南</a>"));
assert!(html.contains("<strong>emphasis</strong>"));
assert_eq!(html.matches("class=\"annot-chip annot-implementation\"").count(), 2);
assert_eq!(html.matches("data-logic-kind=\"link\"").count(), 1);
assert_eq!(html.matches("data-logic-kind=\"content\"").count(), 1);
}
#[test]
fn navigation_and_quoted_links_are_not_executable_occlusions() {
let html=render("# main\n\n参阅 [普通链接](https://example.com/guide)。\n\n得到**literal = \"[数据链接](should_stay_text)\"**,以及**value = [真实动作](5)**,参阅 [混合链接](https://example.com/mixed)。\n");
assert!(html.contains("href=\"https://example.com/guide\""));
@@ -1771,9 +1658,11 @@ mod readable_occlusion_tests {
assert_eq!(
html.matches("class=\"annot-chip annot-implementation\"")
.count(),
1
3
);
assert!(html.contains("[数据链接](should_stay_text)"));
assert_eq!(html.matches("data-logic-kind=\"link\"").count(), 2);
assert_eq!(html.matches("文档引用 · 阅读不会执行").count(), 2);
let classic = render("---\nmarkup: classic\n---\n# main\n\n**value = [key](`record`)**\n");
assert!(!classic.contains("class=\"annot-chip annot-implementation\""));
}
+99 -2
View File
@@ -4012,6 +4012,102 @@ body.notebook-page .wb-source-text { color: var(--nb-text); }
</script>"#
}
/// Resolve links to documents in this View tree; retain the authored target so
/// live responses and static exports can share the same read model.
pub(crate) fn document_links(source: &str, files: &[PathBuf], rel: &str, links: &LinkMode) -> String {
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
let start = tag.find(&format!(" {name}=\""))? + name.len() + 3;
tag[start..].split('"').next()
}
fn decode(value: &str) -> String {
value.replace("&quot;", "\"").replace("&#39;", "'")
.replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&")
}
let mut out = String::new();
let mut rest = source;
while let Some(start) = rest.find("<a ") {
out.push_str(&rest[..start]);
rest = &rest[start..];
let Some(end) = rest.find('>') else { break };
let tag = &rest[..=end];
let mut replacement = None;
if let Some(original) = attribute(tag, "data-document-href") {
let target = decode(original);
let split = target.find(['?', '#']).unwrap_or(target.len());
let path = &target[..split];
if path.ends_with(".mq.md") && !path.contains(':') && !path.starts_with("//") {
let path = percent_decode_document_path(path);
let joined = if path.starts_with('/') { PathBuf::from(path.trim_start_matches('/')) }
else { Path::new(rel).parent().unwrap_or(Path::new("")).join(path) };
let mut parts = Vec::new();
let mut valid = true;
for component in joined.components() {
match component {
Component::Normal(part) => parts.push(part.to_string_lossy().into_owned()),
Component::ParentDir => { if parts.pop().is_none() { valid = false; break; } }
Component::CurDir => {}
_ => { valid = false; break; }
}
}
let resolved = parts.join("/");
if valid && files.iter().any(|file| file.to_string_lossy().replace('\\', "/") == resolved) {
if let Some(current) = attribute(tag, "href") {
let suffix = &target[split..];
let suffix = if matches!(links, LinkMode::Live) && suffix.starts_with('?') {
format!("&{}", &suffix[1..])
} else { suffix.to_string() };
let href = format!("{}{suffix}", href_file(links, &resolved));
replacement = Some(tag.replacen(&format!(" href=\"{current}\""), &format!(" href=\"{}\"", escape(&href)), 1));
}
}
}
}
out.push_str(replacement.as_deref().unwrap_or(tag));
rest = &rest[end+1..];
}
out.push_str(rest);
out
}
#[cfg(test)]
mod document_link_tests {
use super::*;
#[test]
fn document_links_round_trip_between_live_and_offline_views() {
let files = vec![PathBuf::from("docs/entry.mq.md"), PathBuf::from("read me.mq.md")];
let tag = r#"<a href="../read%20me.mq.md?stdin=a&amp;b=c#fn-2" data-document-href="../read%20me.mq.md?stdin=a&amp;b=c#fn-2">打开</a>"#;
let live = document_links(tag, &files, "docs/entry.mq.md", &LinkMode::Live);
assert!(live.contains("href=\"/file?path=read%20me.mq.md&amp;stdin=a&amp;b=c#fn-2\""), "{live}");
let offline = document_links(&live, &files, "docs/entry.mq.md", &LinkMode::Static {from: Some("docs/entry.mq.md".into())});
assert!(offline.contains("href=\"../read me.mq.md.html?stdin=a&amp;b=c#fn-2\""), "{offline}");
}
#[test]
fn unknown_paths_external_urls_and_encoded_unicode_stay_intact() {
let files = vec![PathBuf::from("next.mq.md")];
for target in ["../../next.mq.md", "https://example.com/next.mq.md", "missing.mq.md", "%中.mq.md"] {
let tag = format!("<a href=\"{target}\" data-document-href=\"{target}\">目标</a>");
assert_eq!(document_links(&tag, &files, "entry.mq.md", &LinkMode::Live), tag);
}
}
}
fn percent_decode_document_path(value: &str) -> String {
let bytes = value.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i+2 < bytes.len() {
let hex = |b: u8| (b as char).to_digit(16).map(|v| v as u8);
if let (Some(a), Some(b)) = (hex(bytes[i+1]), hex(bytes[i+2])) {
out.push(a*16+b); i += 3; continue;
}
}
out.push(bytes[i]); i += 1;
}
String::from_utf8(out).unwrap_or_else(|_| value.to_string())
}
pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkMode) -> String {
let nav = nav_html(files, Some(rel), links);
let (status, status_label, out_text) = if vm.awaiting_input {
@@ -4124,10 +4220,11 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
} else {
vm.outline_html.clone()
};
let structure_html = document_links(&vm.structure_html, files, rel, links);
let structure_block = if outline_block.is_empty() {
format!(
r#"<div class="structure" id="structure">{structure}</div>"#,
structure = vm.structure_html
structure = structure_html
)
} else {
format!(
@@ -4135,7 +4232,7 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
<div class="structure" id="structure">{structure}</div>
{outline}
</div>"#,
structure = vm.structure_html,
structure = structure_html,
outline = outline_block,
)
};
+338
View File
@@ -0,0 +1,338 @@
//! Read-only presentation of link-shaped descriptions. No evaluation or fetching.
use crate::ast::{Arg, CallExpr, Expr, Literal, Module};
use crate::view::{html::escape, render::expr_display};
use pulldown_cmark::{html, Event, Options, Parser, Tag};
use std::collections::HashMap;
pub(crate) struct Span<'a> {
pub start: usize,
pub end: usize,
pub label: &'a str,
pub payload: &'a str,
}
/// Preserve quoted source data in executable spans and inline code in narration.
pub(crate) fn spans(text: &str, code: bool) -> Vec<Span<'_>> {
let bytes = text.as_bytes();
let mut found = Vec::new();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'\\' { i = (i + 2).min(bytes.len()); continue; }
if bytes[i] == b'\x60' || code && matches!(bytes[i], b'"' | b'\'') {
let quote = bytes[i];
let run = if quote == b'\x60' { bytes[i..].iter().take_while(|b| **b == quote).count() } else { 1 };
i += run;
while i < bytes.len() {
if bytes[i] == b'\\' { i = (i + 2).min(bytes.len()); }
else if bytes[i..].starts_with(&vec![quote; run]) { i += run; break; }
else { i += 1; }
}
continue;
}
if bytes[i] != b'[' || bytes.get(i + 1) == Some(&b'^')
|| i > 0 && bytes[i - 1] == b'!' {
i += 1; continue;
}
let start = i;
let mut j = i + 1;
let mut depth = 1;
while j < bytes.len() {
match bytes[j] {
b'\\' => { j += 2; continue; }
b'[' => depth += 1,
b']' => { depth -= 1; if depth == 0 { break; } }
_ => {}
}
j += 1;
}
if depth != 0 || bytes.get(j + 1) != Some(&b'(') { i += 1; continue; }
let label_end = j;
j += 2;
let payload_start = j;
depth = 1;
while j < bytes.len() {
match bytes[j] {
b'\\' => { j += 2; continue; }
b'"' | b'\'' | b'\x60' if code || j == payload_start
|| bytes.get(j.wrapping_sub(1)).is_some_and(|b| b" (=,[{:\t".contains(b)) => {
let quote = bytes[j]; j += 1;
while j < bytes.len() {
if bytes[j] == b'\\' { j += 2; }
else if bytes[j] == quote { j += 1; break; }
else { j += 1; }
}
continue;
}
b'(' => depth += 1,
b')' => { depth -= 1; if depth == 0 { break; } }
_ => {}
}
j += 1;
}
if depth == 0 {
found.push(Span { start, end: j + 1, label: &text[start + 1..label_end], payload: text[payload_start..j].trim() });
i = j + 1;
} else { i += 1; }
}
found
}
pub(crate) fn id(line: u32, at: usize) -> String { format!("logic-{line}-{at}") }
fn markdown(text: &str) -> String {
let parser = Parser::new_ext(text, Options::ENABLE_STRIKETHROUGH).map(|event| match event {
Event::Html(value) | Event::InlineHtml(value) => Event::Text(value),
Event::Start(Tag::Image { .. }) => Event::Html("<span class=\"logic-image-label\">".into()),
Event::End(pulldown_cmark::TagEnd::Image) => Event::Html("</span>".into()),
Event::Start(Tag::Link { dest_url, .. }) => Event::Html(format!("<span title=\"{}\">", escape(&dest_url)).into()),
Event::End(pulldown_cmark::TagEnd::Link) => Event::Html("</span>".into()),
other => other,
});
let mut rendered = String::new();
html::push_html(&mut rendered, parser);
rendered
}
fn label_html(label: &str) -> String {
let label = if label.is_empty() { "未命名内容" } else { label };
let value = markdown(label);
value.strip_prefix("<p>").and_then(|v| v.strip_suffix("</p>\n")).unwrap_or(&value).to_string()
}
fn safe_href(target: &str) -> bool {
let normalized: String = target.chars().filter(|c| !c.is_ascii_whitespace() && !c.is_control()).collect();
let lower = normalized.to_ascii_lowercase();
!lower.starts_with("javascript:") && !lower.starts_with("vbscript:")
&& !lower.starts_with("data:") && !lower.starts_with("file:")
}
fn destination(payload: &str) -> Option<String> {
let candidate = format!("[target]({payload})");
let target = Parser::new(&candidate).find_map(|event| match event {
Event::Start(Tag::Link { dest_url, .. }) => Some(dest_url.into_string()),
_ => None,
}).unwrap_or_else(|| payload.trim_matches(['<', '>']).to_string());
let scheme = target.split_once(':').is_some_and(|(scheme, _)|
scheme.starts_with(|c: char| c.is_ascii_alphabetic())
&& scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')));
let relative_path = target.contains('/') && !target.contains(['(', ')'])
&& !target.chars().any(char::is_whitespace)
&& target.starts_with(|c: char| c.is_alphabetic());
let looks_like_link = scheme || relative_path || target.starts_with('#') || target.starts_with('/')
|| target.starts_with("./") || target.starts_with("../")
|| target.starts_with("mailto:") || target.starts_with("tel:")
|| target.to_ascii_lowercase().starts_with("javascript:")
|| target.to_ascii_lowercase().starts_with("data:")
|| target.to_ascii_lowercase().starts_with("vbscript:")
|| [".mq.md", ".md", ".html", ".pdf", ".txt", ".json", ".svg", ".png"]
.iter().any(|ext| target.split(['?', '#']).next().unwrap_or("").ends_with(ext));
looks_like_link.then_some(target)
}
struct Payload { kind: &'static str, heading: &'static str, body: String, href: Option<String> }
fn payload(text: &str) -> Payload {
if text.trim().is_empty() {
return Payload { kind:"empty", heading:"待补充", body:"<p class=\"logic-empty\">待补充实际逻辑</p>".into(), href:None };
}
let expression = crate::parse::expr::parse_expr_prefer_var(text).ok();
if let Some(target) = destination(text).filter(|_| !matches!(expression, Some(Expr::List(_) | Expr::Map(_) | Expr::Literal(_)))) {
let body = if safe_href(&target) {
let external = target.starts_with("https://") || target.starts_with("http://") || target.starts_with("//");
let attributes = if external { " target=\"_blank\" rel=\"noopener noreferrer\"" } else { "" };
format!("<a class=\"logic-link-target\" href=\"{}\" data-document-href=\"{}\"{attributes}><span class=\"logic-link-address\">{}</span><span class=\"logic-link-open\">打开链接 ↗</span></a>", escape(&target), escape(&target), escape(&target))
} else {
format!("<p class=\"logic-link-address\">{}</p><p class=\"logic-hint\">此目标仅作为文字显示,不启用跳转。</p>", escape(&target))
};
return Payload { kind:"link", heading:"跳转链接", body, href:safe_href(&target).then_some(target) };
}
if text.starts_with(['[', '{']) {
if let Ok(value) = serde_json::from_str::<serde_json::Value>(text) {
return Payload { kind:"value", heading:"内容与值", body:json_html(&value, 0), href:None };
}
}
if let Some(expression) = expression {
let (kind, heading) = match expression {
Expr::Call(_) => ("call", "函数调用"),
Expr::List(_) | Expr::Map(_) | Expr::Literal(_) => ("value", "内容与值"),
Expr::Var(_) => ("reference", "引用"),
_ => ("expression", "表达式"),
};
return Payload { kind, heading, body:expression_html(&expression, 0), href:None };
}
Payload { kind:"content", heading:"内容说明", body:format!("<div class=\"logic-content\">{}</div>", markdown(text)), href:None }
}
/// JSON is document content here, never passed to the evaluator as an expression.
fn json_html(value: &serde_json::Value, depth: usize) -> String {
if depth > 5 { return format!("<code class=\"logic-expression\">{}</code>", escape(&value.to_string())); }
match value {
serde_json::Value::Array(values) => {
if values.is_empty() { return "<span class=\"logic-empty-value\">空列表</span>".into(); }
format!("<ol class=\"logic-values\">{}</ol>", values.iter()
.map(|v| format!("<li>{}</li>", json_html(v, depth + 1))).collect::<String>())
}
serde_json::Value::Object(values) => {
if values.is_empty() { return "<span class=\"logic-empty-value\">空记录</span>".into(); }
format!("<dl class=\"logic-arguments\">{}</dl>", values.iter()
.map(|(key, v)| format!("<div class=\"logic-argument\"><dt>{}</dt><dd>{}</dd></div>", escape(key), json_html(v, depth + 1))).collect::<String>())
}
serde_json::Value::String(value) => format!("<span class=\"logic-string\">{}</span>", escape(value)),
_ => format!("<code class=\"logic-expression\">{}</code>", escape(&value.to_string())),
}
}
fn call_name(call: &CallExpr) -> String {
if let Some(receiver) = &call.receiver { format!("{receiver}.{}", call.callee) }
else if let Some(path) = &call.path { path.join(".") }
else { call.callee.clone() }
}
fn expression_html(expression: &Expr, depth: usize) -> String {
if depth > 5 { return format!("<code class=\"logic-expression\">{}</code>", escape(&expr_display(expression))); }
match expression {
Expr::Call(call) => {
let name = call_name(call);
let mut out = format!("<div class=\"logic-call\"><code class=\"logic-call-name\" data-call-name=\"{}\">{}</code>", escape(&name), escape(&name));
if !call.pre_modifiers.is_empty() { out.push_str(&format!("<small class=\"logic-hint\">{}</small>", escape(&call.pre_modifiers.join(" ")))); }
if call.args.is_empty() { out.push_str("<p class=\"logic-no-args\">无需传入参数</p>"); }
else {
out.push_str("<dl class=\"logic-arguments\">");
for (index, argument) in call.args.iter().enumerate() {
let (name, value) = match argument {
Arg::Named { name, value } => (name.clone(), value),
Arg::Positional(value) => (format!("参数 {}", index + 1), value),
};
out.push_str(&format!("<div class=\"logic-argument\"><dt>{}</dt><dd>{}</dd></div>", escape(&name), expression_html(value, depth + 1)));
}
out.push_str("</dl>");
}
out.push_str("</div>"); out
}
Expr::Literal(Literal::Text(value)) =>
format!("<span class=\"logic-string\">{}</span>", escape(value)),
Expr::Literal(_) | Expr::Var(_) =>
format!("<code class=\"logic-expression\">{}</code>", escape(&expr_display(expression))),
Expr::List(values) => {
if values.is_empty() { return "<span class=\"logic-empty-value\">空列表</span>".into(); }
let rows = values.iter().map(|v| format!("<li>{}</li>", expression_html(v, depth + 1))).collect::<String>();
format!("<ol class=\"logic-values\">{rows}</ol>")
}
Expr::Map(values) => {
if values.is_empty() { return "<span class=\"logic-empty-value\">空记录</span>".into(); }
let rows = values.iter().map(|(key, value)| format!("<div class=\"logic-argument\"><dt>{}</dt><dd>{}</dd></div>", escape(key), expression_html(value, depth + 1))).collect::<String>();
format!("<dl class=\"logic-arguments\">{rows}</dl>")
}
Expr::Occluded { label, payload } => format!("<div class=\"logic-nested\"><span class=\"logic-nested-label\">{}</span>{}</div>", escape(label), payload.as_deref().map(|v|expression_html(v,depth+1)).unwrap_or_else(||"<span class=\"logic-empty-value\">待补充实际逻辑</span>".into())),
_ => format!("<code class=\"logic-expression\">{}</code>", escape(&expr_display(expression))),
}
}
pub(crate) fn source(line: u32, span: &Span<'_>, base: usize) -> String {
let id = id(line, base + span.start);
let item = payload(span.payload);
let attrs = format!("id=\"{id}-source\" data-logic-id=\"{id}\" data-line=\"{line}\" data-byte-start=\"{}\" data-byte-end=\"{}\" aria-describedby=\"{id}-note\"", base+span.start,base+span.end);
let label = label_html(span.label);
let mut out = if let Some(href) = item.href {
format!("<a href=\"{}\" data-document-href=\"{}\" class=\"occl-label logic-link-label mq-anchor\" {attrs}>{label}</a>", escape(&href), escape(&href))
} else {
format!("<button type=\"button\" class=\"occl-label mq-anchor\" {attrs} aria-controls=\"{id}-note\" title=\"查看{}(阅读不会执行)\">{label}</button>", item.heading)
};
if item.kind == "empty" { out.push_str("<span class=\"occl-stub\">待补充实际逻辑</span>"); }
out
}
pub(crate) fn note(line: u32, span: &Span<'_>, base: usize, executable: bool) -> String {
let id = id(line, base+span.start);
let item = payload(span.payload);
let hint = if executable { "源码说明 · 不是运行结果" } else { "文档引用 · 阅读不会执行" };
let original = if span.payload.is_empty() && executable { "待补充实际逻辑;当前空遮蔽返回 None。" } else { span.payload };
format!(r#"<details class="annot-chip annot-implementation" id="{id}-note" data-annot-id="{id}" data-annot-kind="implementation" data-logic-kind="{kind}" data-anchor-line="{line}" data-anchor-byte-start="{start}" data-anchor-byte-end="{end}"><summary class="annot-label"><span class="logic-kind">{heading}</span><span class="logic-note-label">{label}</span></summary><div class="annot-value logic-body">{body}<details class="logic-source"><summary>原始写法</summary><pre><code class="occl-code">{original}</code></pre></details></div><small class="logic-hint">{hint}</small></details>"#,
kind=item.kind, start=base+span.start, end=base+span.end, heading=item.heading,
label=label_html(span.label), body=item.body, original=escape(original))
}
pub(crate) struct Narrative {
pub markdown: String,
pub replacements: Vec<(String,String)>,
pub notes: String,
}
pub(crate) fn narrative(line: u32, text: &str, base: usize) -> Narrative {
let mut result = Narrative { markdown:String::new(), replacements:Vec::new(), notes:String::new() };
let mut prefix = format!("MQVIEWLINK{line}X{base}Q");
while text.contains(&prefix) { prefix.push('Q'); }
let mut cursor = 0;
for (index, span) in spans(text, false).into_iter().enumerate() {
let token = format!("{prefix}{index}END");
result.markdown.push_str(&text[cursor..span.start]);
result.markdown.push_str(&token);
result.replacements.push((token,source(line,&span,base)));
result.notes.push_str(&note(line,&span,base,false));
cursor=span.end;
}
result.markdown.push_str(&text[cursor..]);
result
}
pub(crate) fn replace(mut html: String, replacements: &[(String,String)]) -> String {
for (token,value) in replacements { html=html.replace(token,value); }
html
}
/// Link only unambiguous definitions in this document.
pub(crate) fn link_definitions(mut html: String, module: &Module) -> String {
fn walk(functions: &[crate::ast::Function], prefix:&str, names:&mut HashMap<String,Vec<u32>>) {
for function in functions {
let path=if prefix.is_empty(){function.name.clone()}else{format!("{prefix}.{}",function.name)};
names.entry(path.clone()).or_default().push(function.span.line);
if !prefix.is_empty(){names.entry(function.name.clone()).or_default().push(function.span.line);}
walk(&function.children,&path,names);
}
}
let mut names=HashMap::new();walk(&module.functions,"",&mut names);
for (name,lines) in names {
if lines.len()!=1 {continue;}
let escaped=escape(&name);
html=html.replace(&format!("<code class=\"logic-call-name\" data-call-name=\"{escaped}\">{escaped}</code>"),
&format!("<a class=\"logic-definition\" href=\"#fn-{}\" title=\"查看本页函数定义\"><code class=\"logic-call-name\">{escaped}</code><span aria-hidden=\"true\"> ↗</span></a>",lines[0]));
}
html
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn calls_and_collections_containing_urls_remain_structured_values() {
let call = payload("fetch(url=\"https://example.com/file.mq.md\", options={retry: 2})");
assert_eq!(call.kind, "call");
assert!(call.body.contains("logic-call-name") && call.body.contains("<dt>url</dt>"));
assert!(call.body.contains("<dt>options</dt>"));
assert!(!call.body.contains("logic-link-target"));
for text in ["[\"https://example.com\", 2]", "{\"url\": \"https://example.com\"}", "\"guide.mq.md\""] {
assert_eq!(payload(text).kind, "value", "{text}");
}
}
#[test]
fn balanced_scanning_preserves_inline_code_quotes_and_byte_anchors() {
let code = "\"[data](untouched)\" [操作](f(value=\")\", nested=g(2))) [空]()";
let found = spans(code, true);
assert_eq!(found.len(), 2);
assert_eq!(found[0].payload, "f(value=\")\", nested=g(2))");
assert_eq!(&code[found[0].start..found[0].end], "[操作](f(value=\")\", nested=g(2)))");
let narrative = "don't hide [链接](https://example.com/a(b)) or `[代码](opaque)`";
let found = spans(narrative, false);
assert_eq!(found.len(), 1);
assert_eq!(found[0].label, "链接");
}
#[test]
fn unsafe_targets_and_html_are_displayed_without_navigation_or_execution() {
for text in ["javascript:alert(1)", "data:text/html,<svg/onload=alert(1)>", "vbscript:evil"] {
let item = payload(text);
assert_eq!(item.kind, "link");
assert!(item.href.is_none());
assert!(!item.body.contains("<a "));
}
let item = payload("<script>alert(1)</script> beautiful prose");
assert!(!item.body.contains("<script>"));
assert!(item.body.contains("&lt;script&gt;"));
}
#[test]
fn markdown_link_titles_and_nested_parentheses_keep_the_destination() {
for (text, target) in [("https://example.com/a(b)", "https://example.com/a(b)"),
("<guide.mq.md> \"说明\"", "guide.mq.md"), ("#fn-7", "#fn-7")] {
assert_eq!(payload(text).href.as_deref(), Some(target));
}
}
}
+2 -1
View File
@@ -6,6 +6,7 @@ mod debug_api;
mod debug_page;
mod document;
mod html;
mod logic;
mod knowledge_present;
mod knowledge_reading;
mod notebook_api;
@@ -591,7 +592,7 @@ pub(crate) fn build_file_view_with_exec(
Ok(FileViewModel {
rel_path: rel.to_string(),
source,
structure_html: structure,
structure_html: html::document_links(&structure, &root.files, rel, &LinkMode::Live),
outline_html: outline,
stdout,
stderr,
+54
View File
@@ -212,3 +212,57 @@ body.reader-page .is-margin-note.annot-implementation > summary { font:15px/1.5
.reader-dialog .knowledge-table-wrap table { width:100%; border-collapse:collapse; font:12px/1.7 var(--sans); }
.reader-dialog .knowledge-table-wrap th,.reader-dialog .knowledge-table-wrap td { text-align:left; padding:8px 10px; border-bottom:1px solid var(--line); vertical-align:top; overflow-wrap:anywhere; }
.reader-run-summary { color:var(--olive); }.reader-dialog > details { margin:16px 0; }
/* Expanded details need reading room; collapsed neighbours keep their own height. */
body.reader-page .annot-chips:has(> .annot-implementation) { align-items:flex-start; }
body.reader-page .annot-implementation[open]:not(.is-margin-note) { flex-basis:100%; width:100%; }
body.reader-page .annot-implementation > summary { list-style:none; }
body.reader-page .annot-implementation > summary::-webkit-details-marker { display:none; }
body.reader-page .annot-implementation > summary::before { content:'›'; float:right; margin-left:12px; color:var(--gold); }
body.reader-page .annot-implementation[open] > summary::before { content:'⌄'; }
.logic-body pre { white-space:pre-wrap; overflow-wrap:anywhere; font:12px/1.7 var(--mono); margin:8px 0; }
@media(max-width:600px) {
body.reader-page .annot-chips:has(> .annot-implementation) { flex-direction:column; align-items:stretch; }
body.reader-page .annot-chips > .annot-implementation { width:100%; max-width:none; flex:none; }
}
/* Describe the intent in the sentence; read typed details beside it. */
body.reader-page a.occl-label { color:var(--olive); border-bottom:1px dotted var(--gold); text-decoration:none; padding:0 1px; }
body.reader-page a.occl-label:hover { background:var(--fill); }
.occl-label:focus-visible,.logic-definition:focus-visible,.logic-link-target:focus-visible { outline:2px solid var(--gold); outline-offset:4px; }
.logic-kind { display:block; font:10px/1.5 var(--sans); letter-spacing:.06em; color:var(--muted); }
.logic-note-label { font:15px/1.6 var(--serif); }
.logic-body { min-width:0; text-align:left; font:12px/1.7 var(--sans); color:var(--ink); overflow-wrap:anywhere; }
body.reader-page .annot-implementation .logic-body { display:block; white-space:normal; padding:8px 0 0; max-height:none; }
body.reader-page .annot-implementation.is-margin-note .logic-body { max-height:320px; overflow:auto; scrollbar-width:thin; }
.logic-call { border-left:2px solid var(--gold); padding:2px 0 2px 10px; }
.logic-call-name { color:var(--olive); font:600 12px/1.6 var(--mono); white-space:normal; overflow-wrap:anywhere; }
.logic-definition { color:var(--olive); text-decoration:none; border-bottom:1px dotted var(--gold); }
.logic-arguments { margin:8px 0 0; padding:0; }
.logic-argument { display:grid; grid-template-columns:minmax(45px,.7fr) minmax(0,1.3fr); gap:4px 8px; padding:5px 0; border-top:1px solid var(--line); }
.logic-argument dt { color:var(--muted); overflow-wrap:anywhere; font:11px/1.65 var(--mono); }
.logic-argument dd { margin:0; min-width:0; }
.logic-argument .logic-argument { display:block; }
.logic-string { white-space:pre-wrap; }
.logic-expression { white-space:pre-wrap; font:12px/1.7 var(--mono); color:var(--ink); }
.logic-values { padding-left:19px; margin:4px 0; }
.logic-values > li { margin:3px 0; padding-left:2px; }
.logic-no-args,.logic-empty-value { font-size:11px; color:var(--muted); }
.logic-body p { margin:5px 0; }
.logic-body .logic-link-target { display:block; border:1px solid var(--line); border-radius:7px; padding:9px 10px; color:var(--olive); text-decoration:none; background:var(--fill); }
.logic-link-address { display:block; font:11px/1.7 var(--mono); overflow-wrap:anywhere; }
.logic-link-open { display:block; margin-top:5px; font:11px/1.6 var(--sans); }
.logic-body .logic-source { margin-top:10px; border-top:1px solid var(--line); padding-top:6px; color:var(--muted); }
.logic-source > summary { cursor:pointer; font:10px/1.7 var(--sans); }
.logic-source pre { margin:5px 0 0; white-space:pre-wrap; overflow-wrap:anywhere; }
.logic-nested-label { color:var(--olive); }
.logic-content > :first-child { margin-top:0; }
.reader-dialog .logic-body { font-size:14px; }
.reader-dialog .logic-call-name { font-size:15px; }
.reader-dialog .logic-argument { grid-template-columns:minmax(70px,.6fr) minmax(0,1.4fr); padding:9px 0; }
.reader-dialog .logic-body .occl-code { white-space:pre-wrap; overflow-wrap:anywhere; font:12px/1.7 var(--mono); }
@media(max-width:600px) {
.logic-note-label { font-size:14px; }
.reader-dialog .logic-argument { grid-template-columns:minmax(55px,.6fr) minmax(0,1.4fr); }
}
+68 -7
View File
@@ -2,6 +2,28 @@
(function () {
'use strict';
var dialog, content, returnNodes = [], pending = false, toastTimer;
// User choices belong to the document, not to one temporary layout or DOM.
var disclosureChoices = new Map(), layoutToggles = new WeakMap();
function disclosureKey(node) {
var note=node.closest('.annot-implementation');
if(!note || !note.dataset.annotId) return null;
return note.dataset.annotId+(node===note ? '' : ':source');
}
function setDisclosure(node, open) {
if(node.open===open) return;
layoutToggles.set(node,open);
node.open=open;
}
function implementationOpen(note, margin) {
var key=disclosureKey(note);
return disclosureChoices.has(key) ? disclosureChoices.get(key) : margin;
}
function restoreDisclosures(root) {
root.querySelectorAll('.annot-implementation, .annot-implementation .logic-source').forEach(function(node){
var key=disclosureKey(node);
if(disclosureChoices.has(key)) setDisclosure(node,disclosureChoices.get(key));
});
}
function toast(message) {
var el = document.querySelector('.reader-toast');
el.textContent = message; el.hidden = false;
@@ -142,7 +164,7 @@
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; });
var exact = anchors.find(function (el) { return id && (el.dataset.logicId === 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')) {
@@ -191,7 +213,7 @@
band.classList.remove('is-keyed');
band.querySelectorAll('.annot-chip').forEach(function (chip) {
chip.classList.remove('is-margin-note');
if(chip.classList.contains('annot-implementation')) chip.open=false;
if(chip.classList.contains('annot-implementation')) setDisclosure(chip,implementationOpen(chip,false));
['left', 'top', 'width'].forEach(function (key) { chip.style.removeProperty(key); });
delete chip.dataset.readerAnchor; delete chip.dataset.readerSide;
});
@@ -401,7 +423,7 @@
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';
if(item.chip.classList.contains('annot-implementation')) item.chip.open=true;
if(item.chip.classList.contains('annot-implementation')) setDisclosure(item.chip,implementationOpen(item.chip,true));
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];
@@ -446,7 +468,15 @@
var choices = [];
if (structure && data.structure_html) {
structure.querySelectorAll('.call-picker,.loop-picker').forEach(function (el, i) { choices.push({index:i,value:el.value}); });
var destinations = new Map();
structure.querySelectorAll('a[data-document-href]').forEach(function (link) {
destinations.set(link.dataset.documentHref, link.getAttribute('href'));
});
structure.innerHTML = data.structure_html;
restoreDisclosures(structure);
structure.querySelectorAll('a[data-document-href]').forEach(function (link) {
if(destinations.has(link.dataset.documentHref)) link.setAttribute('href', destinations.get(link.dataset.documentHref));
});
if (window.marqdoInitDocument) window.marqdoInitDocument();
var pickers = structure.querySelectorAll('.call-picker,.loop-picker');
choices.forEach(function (choice) {
@@ -461,14 +491,33 @@
function init() {
dialog = document.getElementById('reader-dialog'); content = document.getElementById('reader-dialog-content');
dialog.addEventListener('close', function () { restorePanels(); refreshAnnotations(); });
// Capture native summary activation before other handlers can stop bubbling.
// Keyboard activation also produces a click; never cancel the native toggle.
document.addEventListener('click', function(ev) {
var summary=ev.target.closest('.annot-implementation > summary, .annot-implementation .logic-source > summary');
if(!summary || summary.closest('#reader-dialog')) return;
var node=summary.parentElement, key=disclosureKey(node);
if(key) disclosureChoices.set(key,!node.open);
refreshAnnotations();
}, true);
document.addEventListener('click', function (ev) {
var logic=ev.target.closest('[data-logic-id]');
var definition=ev.target.closest('.logic-definition');
if(definition && dialog.open) dialog.close();
var logic=ev.target.closest('button[data-logic-id]');
if(logic) {
ev.preventDefault();
var note=document.getElementById(logic.dataset.logicId+'-note');
openDialog('实际逻辑 · '+logic.textContent,'logic');
var hint=document.createElement('p');hint.className='knowledge-hint';hint.textContent='这里展示源码实现,阅读不会执行;运行结果另有标注。';content.appendChild(hint);
var code=document.createElement('pre');code.textContent=note ? note.querySelector('.annot-value').textContent : '此片段的逻辑详情暂不可用。';content.appendChild(code);return;
var kind=note && note.querySelector('.logic-kind');
openDialog((kind ? kind.textContent : '内容详情')+' · '+logic.textContent,'logic');
var hint=document.createElement('p');hint.className='knowledge-hint';hint.textContent='这里展示源码与说明,阅读不会执行;运行结果另有标注。';content.appendChild(hint);
var body=note && note.querySelector('.logic-body');
if(body) {
var copy=body.cloneNode(true);copy.classList.remove('annot-value');
content.appendChild(copy);
} else {
var fallback=document.createElement('p');fallback.textContent='此片段的详情暂不可用。';content.appendChild(fallback);
}
return;
}
var knowledge=ev.target.closest('.knowledge-explain, [data-knowledge-link]');
if(knowledge) {
@@ -483,6 +532,18 @@
if (ev.target.closest('.reader-brand')) { ev.preventDefault(); window.scrollTo({top:0,behavior:'auto'}); }
if (dialog.open && ev.target.closest('.outline-panel a')) { dialog.close(); }
});
document.addEventListener('toggle', function(ev) {
var node=ev.target;
if(!node.matches('.annot-implementation, .annot-implementation .logic-source') || node.closest('#reader-dialog')) return;
var expected=layoutToggles.get(node);
layoutToggles.delete(node);
// Layout writes can coalesce into one native toggle event. They must not
// become user choices or schedule another reset/measure cycle.
if(expected===node.open) return;
var key=disclosureKey(node);
if(key) disclosureChoices.set(key,node.open);
refreshAnnotations();
}, true);
function focusNote(ev, focus) {
var trigger=ev.target.closest('.annot-chip,[data-logic-id]');
if(!trigger || ev.relatedTarget && trigger.contains(ev.relatedTarget)) return;
+1 -1
View File
@@ -1761,7 +1761,7 @@ mod tests {
let module = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&module, src);
assert!(
html.contains("<a href=\"https://github.com/cflmy/marqdo\">仓库</a>"),
html.contains("href=\"https://github.com/cflmy/marqdo\"") && html.contains(">仓库</a>"),
"{html}"
);
assert!(html.contains("<code>code</code>"), "{html}");
+50
View File
@@ -0,0 +1,50 @@
// Reproduce user activation followed by real layout/observer and live DOM updates.
const assert=require('node:assert/strict');
const {chromium}=require(process.env.MARQDO_PLAYWRIGHT_MODULE||'playwright');
let browser;
(async()=>{
browser=await chromium.launch({headless:true,args:['--no-sandbox']});
const page=await browser.newPage({viewport:{width:1100,height:1000}});
const errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.route('https://**/*',r=>r.abort());
await page.goto(process.argv[2]);
await page.waitForTimeout(300);
for(const width of [1100,390,1440]){
await page.setViewportSize({width,height:1000});await page.waitForTimeout(200);
const note=page.locator('.annot-implementation:not(.is-margin-note)').first();
assert(await note.count(),'actual inline fallback at '+width);
const id=await note.getAttribute('data-annot-id');
const summary=note.locator(':scope > summary');
if(await note.evaluate(n=>n.open))await summary.click();
await summary.click();await page.waitForTimeout(300);
assert(await note.evaluate(n=>n.open),'click remains open after observer layout at '+width);
await page.evaluate(()=>{for(let i=0;i<5;i++)window.MarqdoReader.refreshAnnotations();});
await page.setViewportSize({width:width+15,height:980});await page.waitForTimeout(200);
assert(await note.evaluate(n=>n.open),'open choice survives resize at '+width);
const raw=note.locator('.logic-source');
if(await raw.count()){
if(!await raw.evaluate(n=>n.open))await raw.locator(':scope > summary').click();
await page.waitForTimeout(200);
assert(await note.evaluate(n=>n.open)&&await raw.evaluate(n=>n.open),'nested source stays readable');
}
await page.evaluate(()=>{
const structure=document.getElementById('structure');
const template=structure.cloneNode(true);
template.querySelectorAll('.annot-implementation,.logic-source').forEach(n=>n.open=false);
window.MarqdoReader.applyExecution({ok:true,page_token:window.MARQDO_VIEW_PAGE_TOKEN,structure_html:template.innerHTML});
});
await page.waitForTimeout(250);
const refreshed=page.locator('[data-annot-id="'+id+'"].annot-implementation');
assert(await refreshed.evaluate(n=>n.open),'live replacement preserves open choice');
if(await raw.count())assert(await refreshed.locator('.logic-source').evaluate(n=>n.open),'live replacement preserves raw source');
await refreshed.locator(':scope > summary').focus();await page.keyboard.press('Enter');
await page.waitForTimeout(250);assert.equal(await refreshed.evaluate(n=>n.open),false,'keyboard close persists');
await refreshed.locator(':scope > summary').focus();await page.keyboard.press('Space');
await page.waitForTimeout(250);assert(await refreshed.evaluate(n=>n.open),'keyboard open persists');
await refreshed.locator(':scope > summary').click();await page.waitForTimeout(150);
await page.evaluate(()=>window.MarqdoReader.refreshAnnotations());await page.waitForTimeout(150);
assert.equal(await refreshed.evaluate(n=>n.open),false,'explicit close persists');
}
assert.deepEqual(errors,[]);await browser.close();
console.log('disclosures: click, keyboard, nested source, repeated layout, resize and live replacement passed');
})().catch(async e=>{console.error(e);if(browser)await browser.close();process.exitCode=1;});
+88
View File
@@ -0,0 +1,88 @@
// Read typed details in the actual static/live reader without executing payloads.
const assert=require('node:assert/strict');
const {chromium}=require(process.env.MARQDO_PLAYWRIGHT_MODULE||'playwright');
let browser;
(async()=>{
browser=await chromium.launch({headless:true,args:['--no-sandbox']});
const context=await browser.newContext({viewport:{width:1440,height:1000}});
await context.route('https://**/*',r=>r.request().isNavigationRequest() ? r.fulfill({contentType:'text/html',body:'<h1>navigation reached</h1>'}) : r.abort());
const page=await context.newPage(),errors=[];
page.on('pageerror',e=>errors.push(e.message));
await page.goto(process.argv[2]);await page.waitForTimeout(250);
const label=text=>page.locator('#structure .occl-label').getByText(text,{exact:true});
const ids=await page.locator('#structure .occl-label').evaluateAll(ns=>ns.map(n=>n.dataset.logicId));
assert(ids.length>=10);assert.equal(new Set(ids).size,ids.length);
for(const id of ids)assert.equal(await page.locator('#'+id+'-note').count(),1,'one detail per description');
const callId=await label('函数与参数').getAttribute('data-logic-id');
const callNote=page.locator('#'+callId+'-note');
assert.equal(await callNote.getAttribute('data-logic-kind'),'call');
assert.deepEqual(await callNote.locator('.logic-arguments dt').allTextContents(),['单价','数量']);
const definition=await callNote.locator('.logic-definition').getAttribute('href');
await label('函数与参数').click();
assert(await page.locator('#reader-dialog').evaluate(n=>n.open));
assert(await page.locator('#reader-dialog .logic-arguments').isVisible());
assert.equal(await page.locator('#reader-dialog .logic-call-name').first().textContent(),'计算费用');
await page.locator('#reader-dialog .logic-source > summary').click();
assert((await page.locator('#reader-dialog pre').innerText()).includes('计算费用(单价=12, 数量=2)'));
await page.locator('#reader-dialog .logic-definition').click();
assert.equal(await page.locator('#reader-dialog').evaluate(n=>n.open),false);
assert.equal(new URL(page.url()).hash,definition);
const nestedId=await label('嵌套调用').getAttribute('data-logic-id');
assert.equal(await page.locator('#'+nestedId+'-note .logic-call-name').count(),2);
const listId=await label('列表内容').getAttribute('data-logic-id');
assert.deepEqual(await page.locator('#'+listId+'-note .logic-values li').allTextContents(),['1','2','3']);
const recordId=await label('记录内容').getAttribute('data-logic-id');
assert((await page.locator('#'+recordId+'-note .logic-body').textContent()).includes('茶'));
assert.equal(await page.locator('#structure .occl-stub').count(),1);
const repository=label('访问项目仓库');
assert.equal(await repository.evaluate(n=>n.tagName),'A');
const repoNote=page.locator('#'+await repository.getAttribute('data-logic-id')+'-note');
if(!await repoNote.evaluate(n=>n.open))await repoNote.locator(':scope > summary').click();
const popupPromise=context.waitForEvent('page');await repoNote.locator('.logic-link-target').click();
const popup=await popupPromise;await popup.waitForLoadState();
assert.equal(popup.url(),'https://github.com/cflmy/marqdo');await popup.close();
await label('跳到函数定义').click();assert.equal(new URL(page.url()).hash,definition);
await label('查看阅读示例').click();await page.waitForLoadState();
assert(page.url().includes('view-reading.mq.md'));
assert(await page.locator('#structure').getByText('购买两件商品',{exact:true}).count());
await page.goto(process.argv[2]);await page.waitForTimeout(200);
for(const width of [1920,1440,1100,1000,800,390]){
await page.setViewportSize({width,height:1000});await page.waitForTimeout(150);
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),'overflow '+width);
assert.deepEqual(await page.locator('.is-margin-note').evaluateAll(nodes=>{
const issues=[],rects=nodes.map(n=>n.getBoundingClientRect());
nodes.forEach((n,i)=>{
const r=rects[i];if(r.left<0||r.right>innerWidth)issues.push('offscreen');
const source=document.querySelector('[data-reader-source-anchor="'+n.dataset.readerAnchor+'"]');
if(!source||source.dataset.logicId!==n.dataset.annotId)issues.push('wrong source');
for(let j=i+1;j<rects.length;j++){const b=rects[j];if(r.left<b.right&&b.left<r.right&&r.top<b.bottom&&b.top<r.bottom)issues.push('overlap');}
});
if(innerWidth>=1440&&!nodes.length)issues.push('missing wide notes');
if(innerWidth<=1000&&nodes.length)issues.push('mobile margin');
return issues;
}),[],'precise and readable notes '+width);
}
const mobileNote=page.locator('#'+callId+'-note');
await mobileNote.locator(':scope > summary').click();
assert(await mobileNote.locator('.logic-body').isVisible());
await page.setViewportSize({width:430,height:1000});await page.waitForTimeout(150);
assert(await mobileNote.evaluate(n=>n.open),'manual disclosure survives layout');
if(process.env.MARQDO_SCREENSHOT_DIR){
await page.screenshot({path:process.env.MARQDO_SCREENSHOT_DIR+'/details-mobile.png',fullPage:true});
await page.setViewportSize({width:1440,height:1000});await page.waitForTimeout(200);
await page.locator('#structure .doc-prose').first().scrollIntoViewIfNeeded();
await page.screenshot({path:process.env.MARQDO_SCREENSHOT_DIR+'/details-desktop.png'});
await label('函数与参数').click();
await page.screenshot({path:process.env.MARQDO_SCREENSHOT_DIR+'/details-call.png'});
await page.keyboard.press('Escape');
}
const plainContext=await browser.newContext({javaScriptEnabled:false,viewport:{width:390,height:900}});
const plain=await plainContext.newPage();await plain.goto(process.argv[2]);
const note=plain.locator('#'+callId+'-note');await note.locator(':scope > summary').click();
assert(await note.locator('.logic-arguments').isVisible());
await note.locator('.logic-source > summary').click();assert((await note.locator('pre').innerText()).includes('计算费用'));
await plain.locator('#structure a.occl-label').getByText('查看阅读示例',{exact:true}).click();await plain.waitForLoadState();
assert(plain.url().includes('view-reading.mq.md'));await plainContext.close();
assert.deepEqual(errors,[]);await browser.close();
console.log('typed details: calls, values, real links, precise notes, responsive and no-JS passed');
})().catch(async e=>{console.error(e);if(browser)await browser.close();process.exitCode=1;});
+1 -1
View File
@@ -64,7 +64,7 @@ let browser;
// Read-only no-script fallback still exposes native details and real source text.
const context=await browser.newContext({javaScriptEnabled:false,viewport:{width:390,height:900}});
const plain=await context.newPage();await plain.goto(process.argv[2]);
const note=plain.locator('.annot-implementation').first();await note.locator('summary').click();
const note=plain.locator('.annot-implementation').first();await note.locator(':scope > summary').click();
assert(await note.locator('.annot-value').isVisible());
assert.equal(await plain.locator('.occl-stub').count(),1);
await context.close();
+17
View File
@@ -153,3 +153,20 @@ fn automatic_reader_marks_callable_modules_without_executing_tools_or_hiding_pro
assert!(html.contains(">fail</span>"), "a real entry failure was hidden");
assert!(!html.contains(">module</span>"));
}
#[test]
fn typed_details_keep_calls_links_and_content_readable_without_executing() {
let temp = Scratch::new();
let source = temp.0.join("details.mq.md");
fs::write(&source, include_str!("../examples/view-details.mq.md")).unwrap();
fs::write(temp.0.join("view-reading.mq.md"), "## next\n\nReturn *1*.\n").unwrap();
export(&temp.0, &temp.0.join("out"));
let html = fs::read_to_string(temp.0.join("out/pages/details.mq.md.html")).unwrap();
for fragment in ["data-logic-kind=\"call\"", "<dt>单价</dt>", "<dt>数量</dt>",
"class=\"logic-definition\"", "class=\"logic-values\"", "<dt>名称</dt>",
"data-logic-kind=\"empty\"", "待补充实际逻辑",
"href=\"view-reading.mq.md.html\"", "href=\"https://github.com/cflmy/marqdo\""] {
assert!(html.contains(fragment), "missing typed reading detail: {fragment}");
}
assert!(!html.contains("class=\"annot-chip annot-bind"), "reading acquired runtime results");
}