diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 236b436..dfd0735 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 7615799..b910e1a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 / 亮点 diff --git a/Cargo.lock b/Cargo.lock index 73d6b66..cc963b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index be4169d..7bcd33d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/README.md b/README.md index 07e8022..93a3ff7 100644 --- a/README.md +++ b/README.md @@ -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 —— 知识即可执行。** diff --git a/crates/marqdo-wasm/Cargo.toml b/crates/marqdo-wasm/Cargo.toml index 327c5d1..2be80c0 100644 --- a/crates/marqdo-wasm/Cargo.toml +++ b/crates/marqdo-wasm/Cargo.toml @@ -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)" diff --git a/debian/changelog b/debian/changelog index 8c97d17..37890d2 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,9 @@ +marqdo (2.7.1-1ppa1) noble; urgency=medium + + * Release 2.7.1; see the reviewed upstream CHANGELOG. + + -- Marqdo Maintainers 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. diff --git a/doc/releases/v2.7.1.md b/doc/releases/v2.7.1.md new file mode 100644 index 0000000..5165175 --- /dev/null +++ b/doc/releases/v2.7.1.md @@ -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. diff --git a/examples/view-details.mq.md b/examples/view-details.mq.md new file mode 100644 index 0000000..2f13656 --- /dev/null +++ b/examples/view-details.mq.md @@ -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 后,可以直接按件数计算。这一示例只处理简单乘法,未包含税费、折扣或金额舍入规则,实际项目应根据业务补齐这些约定。 + +在确认输入符合业务要求之后,返回 *[按件数计算](单价 * 数量)*,调用方便得到了本次购买的总费用。 diff --git a/src/browser_session.rs b/src/browser_session.rs index a163860..4bb3e76 100644 --- a/src/browser_session.rs +++ b/src/browser_session.rs @@ -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(); diff --git a/src/view/document.rs b/src/view/document.rs index 9d0e366..2679739 100644 --- a/src/view/document.rs +++ b/src/view/document.rs @@ -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::>() - .join(" "); - let source_anchors=para.iter().skip(1).map(|(line,_)|format!(r#""#)).collect::(); + let source_anchors = para.iter().skip(1).map(|(line,_)| + format!(r#""#)).collect::(); + 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::>().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(&[], ¬es); out.push_str(&format!( - r#"
{source_anchors}
{md}
"#, - line = first_line, - md = md + r#"
{source_anchors}
{md}
{band}
"# )); }; @@ -218,7 +219,7 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot } flush_para(&mut para, &mut out); out.push_str(""); - 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 = 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(""); - for c in &cells { - html.push_str(&format!("{}", escape(c))); - } + for cell in &rendered { html.push_str(&format!("{cell}")); } html.push_str(""); 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(""); - for c in &cells { - html.push_str(&format!("{}", escape(c))); - } + for cell in &cells { html.push_str(&format!("{}", escape(cell))); } html.push_str(""); } continue; } html.push_str(""); - for c in &cells { - html.push_str(&format!("{}", escape(c))); - } + for cell in &rendered { html.push_str(&format!("{cell}")); } html.push_str(""); } - if header_done { - html.push_str(""); - } + if header_done { html.push_str(""); } html.push_str(""); - // 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 = 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 = 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, ¬es)); 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, ¬es)); // Body: following lines with greater indent until next sibling. i += 1; @@ -622,7 +598,7 @@ fn render_surface_line( if head.trim() == "*" { return r#"else"#.into(); } - format!(r#"{}"#, escape(head)) + format!(r#"{}"#, 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 { /// 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> { - 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::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#""#,escape(label))); - if span.payload.is_empty() { - html.push_str(r#"待补充实际逻辑"#); - } + 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#"
实际逻辑 · {label}{payload}源码说明 · 不是运行结果
"#,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("仓库"), + html.contains("href=\"https://github.com/cflmy/marqdo\"") && html.contains(">仓库") && 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(">指南")); + assert!(html.contains("emphasis")); + 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\"")); } diff --git a/src/view/html.rs b/src/view/html.rs index 98cebd7..1c577c5 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -4012,6 +4012,102 @@ body.notebook-page .wb-source-text { color: var(--nb-text); } "# } + +/// 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(""", "\"").replace("'", "'") + .replace("<", "<").replace(">", ">").replace("&", "&") + } + let mut out = String::new(); + let mut rest = source; + while let Some(start) = 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#"打开"#; + let live = document_links(tag, &files, "docs/entry.mq.md", &LinkMode::Live); + assert!(live.contains("href=\"/file?path=read%20me.mq.md&stdin=a&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&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!("目标"); + 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#"
{structure}
"#, - 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
{structure}
{outline} "#, - structure = vm.structure_html, + structure = structure_html, outline = outline_block, ) }; diff --git a/src/view/logic.rs b/src/view/logic.rs new file mode 100644 index 0000000..a3707d4 --- /dev/null +++ b/src/view/logic.rs @@ -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> { + 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("".into()), + Event::End(pulldown_cmark::TagEnd::Image) => Event::Html("".into()), + Event::Start(Tag::Link { dest_url, .. }) => Event::Html(format!("", escape(&dest_url)).into()), + Event::End(pulldown_cmark::TagEnd::Link) => Event::Html("".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("

").and_then(|v| v.strip_suffix("

\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 { + 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 } +fn payload(text: &str) -> Payload { + if text.trim().is_empty() { + return Payload { kind:"empty", heading:"待补充", body:"

待补充实际逻辑

".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!("{}打开链接 ↗", escape(&target), escape(&target), escape(&target)) + } else { + format!("

此目标仅作为文字显示,不启用跳转。

", 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::(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!("
{}
", 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!("{}", escape(&value.to_string())); } + match value { + serde_json::Value::Array(values) => { + if values.is_empty() { return "空列表".into(); } + format!("
    {}
", values.iter() + .map(|v| format!("
  • {}
  • ", json_html(v, depth + 1))).collect::()) + } + serde_json::Value::Object(values) => { + if values.is_empty() { return "空记录".into(); } + format!("
    {}
    ", values.iter() + .map(|(key, v)| format!("
    {}
    {}
    ", escape(key), json_html(v, depth + 1))).collect::()) + } + serde_json::Value::String(value) => format!("{}", escape(value)), + _ => format!("{}", 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!("{}", escape(&expr_display(expression))); } + match expression { + Expr::Call(call) => { + let name = call_name(call); + let mut out = format!("
    {}", escape(&name), escape(&name)); + if !call.pre_modifiers.is_empty() { out.push_str(&format!("{}", escape(&call.pre_modifiers.join(" ")))); } + if call.args.is_empty() { out.push_str("

    无需传入参数

    "); } + else { + out.push_str("
    "); + 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!("
    {}
    {}
    ", escape(&name), expression_html(value, depth + 1))); + } + out.push_str("
    "); + } + out.push_str("
    "); out + } + Expr::Literal(Literal::Text(value)) => + format!("{}", escape(value)), + Expr::Literal(_) | Expr::Var(_) => + format!("{}", escape(&expr_display(expression))), + Expr::List(values) => { + if values.is_empty() { return "空列表".into(); } + let rows = values.iter().map(|v| format!("
  • {}
  • ", expression_html(v, depth + 1))).collect::(); + format!("
      {rows}
    ") + } + Expr::Map(values) => { + if values.is_empty() { return "空记录".into(); } + let rows = values.iter().map(|(key, value)| format!("
    {}
    {}
    ", escape(key), expression_html(value, depth + 1))).collect::(); + format!("
    {rows}
    ") + } + Expr::Occluded { label, payload } => format!("
    {}{}
    ", escape(label), payload.as_deref().map(|v|expression_html(v,depth+1)).unwrap_or_else(||"待补充实际逻辑".into())), + _ => format!("{}", 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!("{label}", escape(&href), escape(&href)) + } else { + format!("", item.heading) + }; + if item.kind == "empty" { out.push_str("待补充实际逻辑"); } + 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#"
    {heading}{label}
    {body}
    原始写法
    {original}
    {hint}
    "#, + 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(¬e(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>) { + 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!("{escaped}"), + &format!("{escaped} ↗",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("
    url
    ")); + assert!(call.body.contains("
    options
    ")); + 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,", "vbscript:evil"] { + let item = payload(text); + assert_eq!(item.kind, "link"); + assert!(item.href.is_none()); + assert!(!item.body.contains("alert(1) beautiful prose"); + assert!(!item.body.contains(""), "{html}" ); assert!(html.contains("code"), "{html}"); diff --git a/tests/view/disclosures.browser.cjs b/tests/view/disclosures.browser.cjs new file mode 100644 index 0000000..8a85585 --- /dev/null +++ b/tests/view/disclosures.browser.cjs @@ -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;}); diff --git a/tests/view/payloads.browser.cjs b/tests/view/payloads.browser.cjs new file mode 100644 index 0000000..0177101 --- /dev/null +++ b/tests/view/payloads.browser.cjs @@ -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:'

    navigation reached

    '}) : 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=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;}); diff --git a/tests/view/readability.browser.cjs b/tests/view/readability.browser.cjs index 642b8f9..2c597ca 100644 --- a/tests/view/readability.browser.cjs +++ b/tests/view/readability.browser.cjs @@ -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(); diff --git a/tests/view_readability.rs b/tests/view_readability.rs index 516bf30..08d2292 100644 --- a/tests/view_readability.rs +++ b/tests/view_readability.rs @@ -153,3 +153,20 @@ fn automatic_reader_marks_callable_modules_without_executing_tools_or_hiding_pro assert!(html.contains(">fail"), "a real entry failure was hidden"); assert!(!html.contains(">module")); } + +#[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\"", "
    单价
    ", "
    数量
    ", + "class=\"logic-definition\"", "class=\"logic-values\"", "
    名称
    ", + "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"); +}