From 58ec2172d619c3ef598b82799898ad6baaaa6d66 Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 15 Oct 2026 20:36:12 +0800 Subject: [PATCH] fix(view): mid-to-mid annot leaders and prose chip density Unify frame chip ids with marks, reorder chips under anchors, and draw SVG leaders from underline mid-bottom to chip mid-top so crowded bands stay readable. Co-authored-by: Cursor --- doc/design/view-document-annotations.md | 2 +- doc/design/view-prose-annot-gaps.md | 145 ++++++++++++ src/interp.rs | 69 +++++- src/view/annot.rs | 250 +++++++++++++++++++- src/view/document.rs | 172 +++++++++++++- src/view/html.rs | 288 +++++++++++++++++------- src/view/render.rs | 9 +- 7 files changed, 839 insertions(+), 96 deletions(-) create mode 100644 doc/design/view-prose-annot-gaps.md diff --git a/doc/design/view-document-annotations.md b/doc/design/view-document-annotations.md index de57fee..a148c69 100644 --- a/doc/design/view-document-annotations.md +++ b/doc/design/view-document-annotations.md @@ -4,7 +4,7 @@ |---|---| | 状态 | **Active** | | 日期 | 2026-10-15 | -| 相关 | [view.md](view.md) · [view-debug.md](view-debug.md) · [view-markup-surface.md](view-markup-surface.md) · [view-execution-trace.md](view-execution-trace.md) · [view-frame-selection.md](view-frame-selection.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) | +| 相关 | [view.md](view.md) · [view-debug.md](view-debug.md) · [view-markup-surface.md](view-markup-surface.md) · [view-execution-trace.md](view-execution-trace.md) · [view-frame-selection.md](view-frame-selection.md) · [view-prose-annot-gaps.md](view-prose-annot-gaps.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) | --- diff --git a/doc/design/view-prose-annot-gaps.md b/doc/design/view-prose-annot-gaps.md new file mode 100644 index 0000000..7d33d1f --- /dev/null +++ b/doc/design/view-prose-annot-gaps.md @@ -0,0 +1,145 @@ +# View:叙述面标注缺口(prose annot gaps) + +| | | +|---|---| +| 状态 | **Active** | +| 日期 | 2026-10-15 | +| 相关 | [view-document-annotations.md](view-document-annotations.md) · [view-static-interactive.md](view-static-interactive.md) · [view-frame-selection.md](view-frame-selection.md) · [view-execution-trace.md](view-execution-trace.md) | + +> **定位**:对既有文档面设计的**缺口专章**——写清用户可见的四类问题、根因(文件:行)与验收口径。不改写 ADR;不发明作者侧标注 DSL。 + +--- + +## 1. 为何「改了却几乎没变化」 + +| 原因 | 说明 | +|------|------| +| 错二进制 | PATH 上的 `marqdo` 可能仍是旧版(如 1.3.0);改动在源码 / `./target/debug/marqdo`。验收必须用 `cargo build && ./target/debug/marqdo view …` | +| Chip 被溢出藏掉 | 同 band 堆多帧 return/print/who;`MAX_VISIBLE_ANNOTS=4` 把当前帧的 `who` 打成 `annot-chip-overflow`(`display:none`);帧切换不重算溢出 | +| L-leader 几何错位 | `initAnnotLeaders` 里 `y0=0` 只在 `.annot-band` 顶画短折,**连不到**上方 underline;窄屏或 chip>4 时整段关掉 leaders | +| 旧静态快照 | gh-pages / 旧 `view output` 不会自动刷新 | + +--- + +## 2. 目标视觉语法(既有,不新造) + +锚定 [view-document-annotations.md](view-document-annotations.md) §3: + +``` +文本段…… `变量` …… **语句** …… *返回* + ━━━━━ + │ + └──→ 结果标注 chip +``` + +- underline:`mark.mq-anchor.mq-{decl|code|return}` +- band:段落下方 `.annot-band` → leaders + chips +- L-leader:CSS `border-left` + `border-bottom`(禁止 SVG) +- 公式/代码:[view-static-interactive.md](view-static-interactive.md) G3 **一层主视觉**;卡下不叠 Bind dump +- 帧:[view-frame-selection.md](view-frame-selection.md) **源码常显、只滤 chip**;默认末帧 + +--- + +## 3. 管线 + +```mermaid +flowchart LR + CLI["marqdo view / view output"] --> build["build_file_view"] + build --> cap["run_file_capture"] + cap --> annot["build_view_annots"] + annot --> doc["document::render_module_document"] + doc --> page["html.rs page_file"] + page --> js["initAnnotLeaders + initCallPickers"] +``` + +| 步骤 | 位置 | +|------|------| +| CLI / 导出 | `src/main.rs` · `src/view/mod.rs` · `src/view/output.rs` | +| Capture + Call 事件 | `src/interp.rs` | +| Annot 组装 | `src/view/annot.rs` `build_view_annots` | +| 文档面 HTML | `src/view/document.rs` | +| 卡片 chrome | `src/view/render.rs` `render_*_assign_card` | +| CSS / leader JS | `src/view/html.rs` | + +--- + +## 4. 四条用户问题 → 根因 → 验收 + +复现源:`public/00-welcome.mq.md` · `public/00-欢迎.mq.md` +对照金样:`tests/view/document-annot-demo.mq.md` · `tests/markup-v03/inc-prose.mq.md` + +### P1 — 叙述与代码同段时信息不显示 + +| | | +|---|---| +| 现象 | underline 在,chip / 连线弱或无 | +| 根因 | `html.rs` `initAnnotLeaders`:`y0=0` 相对 band;`document.rs` `MAX_VISIBLE_ANNOTS` 把当前帧 chip 溢出;PATH 旧 CLI | +| 目标 | 同 `inc-prose`:underline + L-leader(从锚点底到 chip)+ 可见 chip | +| 验收 | `./target/debug/marqdo view public/00-welcome.mq.md`:主文 `**greet…**` 与 `## greet` 体内均有可见 chip 与接到 underline 的 leader(宽屏) | + +### P2 — 函数内变量不显示 + +| | | +|---|---| +| 现象 | `` `who` `` 有浅蓝 underline,无值 chip | +| 根因 | bind chip 存在但带 `annot-chip-overflow`;`applyCallFrame` 只 `hidden` 非选中帧,不解除当前帧 overflow | +| 目标 | 选中调用帧时常显 `who` · `print` · `return` 各一枚 | +| 验收 | 切换「调用」下拉,三枚 chip 随帧变且默认可见(无需点 +N) | + +### P3 — ` ```text ` 渲染不一致 + +| | | +|---|---| +| 现象 | 变成内联 `text marqdo ext add…`,无卡片 | +| 根因 | Comment 围栏若进 `flush_para` → `join(" ")` → pulldown 当 inline code;应走 `render_narrative_fence` | +| 目标 | 与 bound python 同 `.code-card` chrome(badge + `pre.code-body`),**无** Run/foot | +| 验收 | welcome install 段:`data-lang="text"` + 两行 `marqdo ext add`;无 `text marqdo` | + +### P4 — 函数引用 / 代码卡未渲染 + +| | | +|---|---| +| 现象 | `**greet who=…**` 无结果;或 `hi` python 只见头/Run、不见源码 | +| 根因 | 同行多 Call 未与 BoldCode zip;或 Run 挤在 head;静态假 Run;错看 Debug 路径 | +| 目标 | 主文两 greet 各有 call chip(stdout 摘要);`hi` = `render_code_assign_card` head→body→foot;静态藏 Run | +| 验收 | 两枚 greet mark 均有非空 `data-annot-id`;`code-body` 含 `hello-from-python`;`MARQDO_VIEW_LIVE=false` 无 Run 按钮 | + +### call_id 语义(写死) + +| 位置 | call_id | +|------|---------| +| 主文 `**greet…**` 的 call chip | 入口帧(`# main` 的 call);结果为 stdout/返回摘要 | +| `## greet` 体内 print / who / return | callee 的 CallFrame id;跟函数标题旁 picker | + +--- + +## 5. 修复约定(实现红线) + +1. **帧感知密度**:band 内按选中 `call_id` 计可见 chip;默认末帧;同帧最多 4 枚常显;溢出只藏非当前帧或多余 kind。切换后客户端重算 overflow + `layoutAll()`。 +2. **Leader 容器**:提升到 `.doc-block`(prose + band);`y0` = 锚点底相对 block;按锚点 x 排序再画线。 +3. **卡片**:只复用 Browse `render_*_assign_card` / `render_narrative_fence` + `html.rs` `.code-*` / `.formula-card`;本波不改 Debug AST 路径(除非回归红)。 +4. **静态 Run**:`MARQDO_VIEW_LIVE=false` 时隐藏 Run,不留禁用假按钮(对齐 view-static-interactive D5)。 +5. **非目标**:不做 debug 断点;不发明作者标注 DSL;不用 SVG leader;不单独发版/推 gh-pages(除非另嘱)。 + +--- + +## 6. 验收命令 + +```bash +cargo build -q +./target/debug/marqdo version # 须为当前工作树版本 +./target/debug/marqdo view public/00-welcome.mq.md --no-open +./target/debug/marqdo view tests/view/document-annot-demo.mq.md --no-open +cargo test -q --lib view:: +``` + +--- + +## 7. 修订历史 + +| 日期 | 说明 | +|------|------| +| 2026-10-15 | 初稿:四问题、错二进制/溢出/leader 根因、帧感知密度与 leader 几何约定 | +| 2026-10-15 | L-leader 拥挤/消失:同跨度多帧 chip **共用 annot id**;可见 chip 按锚点 x 重排;leader 挂 doc-block | +| 2026-10-15 | L-leader 黑线碎段:JS `border*: "1.5px solid"` 无色覆盖 class → 改为 kind 色写入 shorthand;chip SSR/DOM 按锚点 L→R | +| 2026-10-15 | L-leader 改为 SVG:描述底边中点 → 轨道 → 短竖线 → 值 chip 顶边中点;chip 间距加宽 | diff --git a/src/interp.rs b/src/interp.rs index 8114438..757778b 100644 --- a/src/interp.rs +++ b/src/interp.rs @@ -652,7 +652,26 @@ impl Interpreter { &[("kind", "call"), ("callee", call.callee.as_str())], ); } - let _ = self.eval_call(module, fun, env, call)?; + let stdout_before = self.captured_stdout.len(); + let v = self.eval_call(module, fun, env, call)?; + if self.capture { + let (loop_id, iter) = self.loop_ctx(); + self.record_stmt_event(StmtEvent { + line: span.line, + kind: StmtEventKind::Call, + name: Some(call.callee.clone()), + value_after: Some(call_event_brief( + &v, + &self.captured_stdout, + stdout_before, + &call.callee, + )), + arm_index: None, + iter, + call_id: self.current_call_id(), + loop_id, + }); + } Ok(None) } Stmt::Expr { value, span } => { @@ -665,7 +684,30 @@ impl Interpreter { &[("kind", "expr")], ); } - let _ = self.eval_expr(module, fun, env, value)?; + let stdout_before = self.captured_stdout.len(); + let v = self.eval_expr(module, fun, env, value)?; + if self.capture { + let (loop_id, iter) = self.loop_ctx(); + let name = match value { + Expr::Call(c) => Some(c.callee.clone()), + _ => None, + }; + self.record_stmt_event(StmtEvent { + line: span.line, + kind: StmtEventKind::Call, + name: name.clone(), + value_after: Some(call_event_brief( + &v, + &self.captured_stdout, + stdout_before, + name.as_deref().unwrap_or("expr"), + )), + arm_index: None, + iter, + call_id: self.current_call_id(), + loop_id, + }); + } Ok(None) } Stmt::Branch { arms, span } => { @@ -1688,6 +1730,29 @@ fn brief_trace_val(v: &Value) -> String { } } +/// Prefer real result; else last stdout line emitted by the call; else callee name. +fn call_event_brief(v: &Value, stdout: &str, stdout_before: usize, callee: &str) -> String { + if !matches!(v, Value::None) { + return brief_trace_val(v); + } + if stdout.len() > stdout_before { + let delta = &stdout[stdout_before..]; + let line = delta + .trim_end() + .lines() + .last() + .unwrap_or(delta.trim_end()); + if !line.is_empty() { + return if line.chars().count() > 48 { + format!("{}…", line.chars().take(48).collect::()) + } else { + line.to_string() + }; + } + } + callee.to_string() +} + fn stmt_span(stmt: &Stmt) -> Span { match stmt { Stmt::Assign { span, .. } diff --git a/src/view/annot.rs b/src/view/annot.rs index 8ec363c..7f6d08a 100644 --- a/src/view/annot.rs +++ b/src/view/annot.rs @@ -33,7 +33,7 @@ pub enum AnnotKind { Return, #[allow(dead_code)] Call, - #[allow(dead_code)] + #[allow(dead_code)] // reserved for non-call BoldCode expr chips Expr, Branch, Loop, @@ -119,7 +119,9 @@ pub fn build_view_annots(module: &Module, source: &str, cap: &RunCapture) -> Vec ) }); let key = (*line, name.clone(), ev.call_id, ev.loop_id, ev.iter); - let mut value = ev.value_after.clone().unwrap_or_else(|| "?".into()); + let raw = ev.value_after.clone().unwrap_or_else(|| "?".into()); + let (value, detail) = abbreviate_bind_value(&raw); + let mut value = value; let count = assign_counts.get(&key).copied().unwrap_or(1); if count > 1 { value = format!("{value} · ×{count}"); @@ -132,7 +134,7 @@ pub fn build_view_annots(module: &Module, source: &str, cap: &RunCapture) -> Vec anchor_byte_end: end, label: name.clone(), value: brief_str(&value), - detail: ev.value_after.clone().unwrap_or_default(), + detail, arm_index: None, call_id: Some(ev.call_id), loop_id: ev.loop_id, @@ -352,6 +354,62 @@ pub fn build_view_annots(module: &Module, source: &str, cap: &RunCapture) -> Vec } } + // Call / expr events → chips; zip with BoldCode spans when several share a line. + let mut calls_by_line: HashMap> = HashMap::new(); + for ev in &cap.view_trace.events { + if ev.kind == StmtEventKind::Call { + calls_by_line.entry(ev.line).or_default().push(ev); + } + } + for (line, evs) in calls_by_line { + let text = lines + .get(line.saturating_sub(1) as usize) + .copied() + .unwrap_or(""); + let bold_spans: Vec<(usize, usize)> = scan_prose_line(text) + .into_iter() + .filter_map(|bit| match bit { + ProseBit::BoldCode { .. } => { + let start = bit_at(&bit); + Some((start, prose_bit_end(text, &bit))) + } + _ => None, + }) + .collect(); + for (i, ev) in evs.iter().enumerate() { + // One BoldCode on the line (e.g. print across call frames): share it. + // Several BoldCodes (e.g. two greets in main): zip by index. + let (start, end) = if bold_spans.is_empty() { + (None, None) + } else if bold_spans.len() == 1 { + let (s, e) = bold_spans[0]; + (Some(s), Some(e)) + } else { + bold_spans + .get(i) + .copied() + .map(|(s, e)| (Some(s), Some(e))) + .unwrap_or((None, None)) + }; + let value = ev.value_after.clone().unwrap_or_default(); + let label = ev.name.clone().unwrap_or_else(|| "call".into()); + out.push(ViewAnnot { + id: next_id("c"), + kind: AnnotKind::Call, + anchor_line: line, + anchor_byte_start: start, + anchor_byte_end: end, + label, + value: brief_str(&value), + detail: value, + arm_index: None, + call_id: Some(ev.call_id), + loop_id: ev.loop_id, + iter: ev.iter, + }); + } + } + // Call frames for picker (label = fn name). for fr in &cap.view_trace.calls { out.push(ViewAnnot { @@ -370,9 +428,167 @@ pub fn build_view_annots(module: &Module, source: &str, cap: &RunCapture) -> Vec }); } + // Param Decl sites in function body: bind chips from CallFrame args. + for fr in &cap.view_trace.calls { + let Some(fun) = find_fun_by_line(module, fr.fn_line) else { + continue; + }; + let body_lines = fun_stmt_lines(fun); + for (pname, pval) in parse_args_brief_pairs(&fr.args_brief) { + for (i, text) in lines.iter().enumerate() { + let line_no = (i + 1) as u32; + if !body_lines.contains(&line_no) { + continue; + } + for bit in scan_prose_line(text) { + if let ProseBit::Decl { name, at, .. } = &bit { + if name != &pname { + continue; + } + let end = prose_bit_end(text, &bit); + out.push(ViewAnnot { + id: next_id("p"), + kind: AnnotKind::Bind, + anchor_line: line_no, + anchor_byte_start: Some(*at), + anchor_byte_end: Some(end), + label: pname.clone(), + value: brief_str(&pval), + detail: format!("{pname}={pval}"), + arm_index: None, + call_id: Some(fr.call_id), + loop_id: None, + iter: None, + }); + } + } + } + } + } + + // Same prose span across call frames shares one id so + // matches the visible chip after frame filter (else L-leaders find no anchor). + unify_annot_ids_by_span(&mut out); + out } +fn unify_annot_ids_by_span(annots: &mut [ViewAnnot]) { + let mut first: HashMap<(u32, Option, Option, u8), String> = HashMap::new(); + for a in annots.iter_mut() { + if matches!(a.kind, AnnotKind::CallFrame | AnnotKind::LoopFrame) { + continue; + } + if a.anchor_byte_start.is_none() { + continue; + } + let tag = match a.kind { + AnnotKind::Bind => 1u8, + AnnotKind::Return => 2, + AnnotKind::Call | AnnotKind::Expr => 3, + AnnotKind::Branch => 4, + AnnotKind::Loop => 5, + AnnotKind::Writeback => 6, + AnnotKind::CallFrame | AnnotKind::LoopFrame => 0, + }; + let key = ( + a.anchor_line, + a.anchor_byte_start, + a.anchor_byte_end, + tag, + ); + if let Some(id) = first.get(&key) { + a.id = id.clone(); + } else { + first.insert(key, a.id.clone()); + } + } +} + +fn abbreviate_bind_value(raw: &str) -> (String, String) { + if raw.contains(" 96 { + let short: String = raw.chars().take(48).collect(); + return (format!("{short}…"), format!("{short}…")); + } + (raw.to_string(), raw.to_string()) +} + +fn parse_args_brief_pairs(brief: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + for part in brief.split(", ") { + if let Some((k, v)) = part.split_once('=') { + if !k.is_empty() { + out.push((k.to_string(), v.to_string())); + } + } + } + out +} + +fn find_fun_by_line(module: &Module, line: u32) -> Option<&Function> { + fn walk<'a>(fun: &'a Function, line: u32) -> Option<&'a Function> { + if fun.span.line == line { + return Some(fun); + } + for c in &fun.children { + if let Some(f) = walk(c, line) { + return Some(f); + } + } + None + } + for f in &module.functions { + if let Some(found) = walk(f, line) { + return Some(found); + } + } + None +} + +fn fun_stmt_lines(fun: &Function) -> std::collections::HashSet { + let mut s = std::collections::HashSet::new(); + fn walk_stmt(st: &Stmt, s: &mut std::collections::HashSet) { + let line = match st { + Stmt::Assign { span, .. } + | Stmt::Return { span, .. } + | Stmt::Call { span, .. } + | Stmt::Expr { span, .. } + | Stmt::Branch { span, .. } + | Stmt::While { span, .. } + | Stmt::ForEach { span, .. } => span.line, + }; + s.insert(line); + match st { + Stmt::Branch { arms, .. } => { + for arm in arms { + for b in &arm.body { + walk_stmt(b, s); + } + } + } + Stmt::While { body, .. } | Stmt::ForEach { body, .. } => { + for b in body { + walk_stmt(b, s); + } + } + _ => {} + } + } + for st in &fun.body { + walk_stmt(st, &mut s); + } + for c in &fun.children { + s.extend(fun_stmt_lines(c)); + } + s +} + /// Serialize ViewExecutionReport JSON for AI / page embed. pub fn view_execution_report_json(path: &str, ok: bool, cap: &RunCapture) -> String { use serde_json::{json, Map}; @@ -583,8 +799,10 @@ pub fn bit_kind_class(bit: &ProseBit) -> &'static str { /// Render annotation band HTML for a set of annots (already filtered to one block). /// -/// Chips with `iter` default to the **last** iteration per `loop_id` (SSR); the loop -/// picker toggles `hidden` / `is-frame-hidden` so only the selected iter is shown. +/// SSR defaults to the **last** call_id and **last** iteration per loop_id (matches +/// pickers). Overflow (`max_visible`) is counted only among chips visible in that +/// default frame — so `who` on the last greet call is not buried behind +N. +/// Client `applyCallFrame` recomputes overflow after switching. pub fn render_annot_band(annots: &[ViewAnnot], max_visible: usize) -> String { let annots: Vec<&ViewAnnot> = annots .iter() @@ -603,17 +821,35 @@ pub fn render_annot_band(annots: &[ViewAnnot], max_visible: usize) -> String { } } } + // Default call frame = max call_id among chips that carry one (last invocation). + let default_call_id: Option = annots.iter().filter_map(|a| a.call_id).max(); + // Left-to-right by anchor so chips sit under their underlines (avoids + // crossed L-leaders that look like “missing” lines when crowded). + let mut ordered: Vec<&ViewAnnot> = annots; + ordered.sort_by(|a, b| { + let sa = a.anchor_byte_start.unwrap_or(usize::MAX); + let sb = b.anchor_byte_start.unwrap_or(usize::MAX); + sa.cmp(&sb).then_with(|| a.id.cmp(&b.id)) + }); + let mut s = String::from(r#"
"#); + // Leaders live on the parent .doc-block (see initAnnotLeaders); keep a hook + // for keyed mode / a11y but geometry is computed against the block. s.push_str(r#""#); s.push_str(r#"
"#); let mut shown = 0usize; let mut overflow_count = 0usize; - for a in &annots { - let frame_miss = a + for a in &ordered { + let iter_miss = a .iter .zip(default_iter.get(&a.loop_id)) .map(|(i, d)| i != *d) .unwrap_or(false); + let call_miss = match (a.call_id, default_call_id) { + (Some(cid), Some(def)) if cid != def => true, + _ => false, + }; + let frame_miss = iter_miss || call_miss; let overflow = if frame_miss { false } else if shown >= max_visible { diff --git a/src/view/document.rs b/src/view/document.rs index b1e489b..3614e1c 100644 --- a/src/view/document.rs +++ b/src/view/document.rs @@ -110,9 +110,33 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot LineKind::Comment => { let text = l.text.trim_end_matches(['\r', '\n']); let trimmed = text.trim(); + // Unbound ```lang fences stay Comment in lex — render as code cards + // (same chrome as bound foreign), never join into a prose blob. + if crate::foreign::is_fence_opener(trimmed) + || (trimmed.starts_with("```") && !crate::foreign::is_fence_closer(trimmed)) + { + flush_para(&mut para, &mut out); + let (html, next) = render_narrative_fence(&lines, i); + out.push_str(&html); + i = next; + continue; + } + if crate::foreign::is_fence_closer(trimmed) { + // Orphan closer — skip. + flush_para(&mut para, &mut out); + i += 1; + continue; + } let bits = scan_prose_line(text); let is_stmt = stmt_lines.contains(&l.line_no); + let has_annots = by_line + .get(&l.line_no) + .map(|v| !v.is_empty()) + .unwrap_or(false); + // Decl alone stays in Markdown prose (keep links). Open a marked + // line block when there is executable prose, a stmt, or chips. let needs_annot = is_stmt + || has_annots || bits.iter().any(|b| { matches!(b, ProseBit::BoldCode { .. } | ProseBit::ItalicReturn { .. }) }); @@ -722,14 +746,24 @@ fn render_line_block( let trimmed = text.trim_start(); if bits.is_empty() { if let Some(rest) = trimmed.strip_prefix("> ") { + let aid = match_annot_for_line(annots) + .map(|a| a.id.as_str()) + .unwrap_or(""); s.push_str(&format!( - r#"
> {}
"#, - escape(rest) + r#"
> {rest}
"#, + line = line_no, + aid = escape(aid), + rest = escape(rest), )); } else if let Some(rest) = trimmed.strip_prefix('>') { + let aid = match_annot_for_line(annots) + .map(|a| a.id.as_str()) + .unwrap_or(""); s.push_str(&format!( - r#"
> {}
"#, - escape(rest.trim_start()) + r#"
> {rest}
"#, + line = line_no, + aid = escape(aid), + rest = escape(rest.trim_start()), )); } else { s.push_str(&format!( @@ -768,7 +802,8 @@ fn render_line_block( s } -/// Huge SVG / fenced code dumps make annot bands unreadable — keep those out of chips. +/// Huge SVG / fenced code dumps — prefer abbreviated chips from annot builder; +/// only drop if detail is still an unreadable dump. fn is_noisy_result_chip(a: &ViewAnnot) -> bool { if a.kind != crate::view::annot::AnnotKind::Bind { return false; @@ -777,6 +812,49 @@ fn is_noisy_result_chip(a: &ViewAnnot) -> bool { v.contains(" 96 } +fn match_annot_for_line<'a>(annots: &[&'a ViewAnnot]) -> Option<&'a ViewAnnot> { + annots.iter().copied().find(|a| { + matches!( + a.kind, + crate::view::annot::AnnotKind::Call + | crate::view::annot::AnnotKind::Bind + | crate::view::annot::AnnotKind::Return + ) + }) +} + +/// Unbound Markdown fence → same visual card as bound foreign (no Run chrome). +fn render_narrative_fence(lines: &[ClassifiedLine], start: usize) -> (String, usize) { + let opener = lines[start].text.trim_end_matches(['\r', '\n']).trim(); + let lang = crate::foreign::fence_lang(opener).unwrap_or_else(|| "text".into()); + let line_no = lines[start].line_no; + let mut body: Vec = Vec::new(); + let mut j = start + 1; + while j < lines.len() { + let t = lines[j].text.trim_end_matches(['\r', '\n']); + if crate::foreign::is_fence_closer(t.trim()) { + j += 1; + break; + } + body.push(t.to_string()); + j += 1; + } + let source = body.join("\n"); + let html = format!( + r#"
+
+ code + {lang} +
+
{src}
+
"#, + line = line_no, + lang = escape(&lang), + src = escape(&source), + ); + (html, j) +} + /// Render prose with markers stripped; show surface inner text only. fn render_prose_with_marks( line_no: u32, @@ -1244,4 +1322,88 @@ mod tests { "{html}" ); } + + #[test] + fn narrative_text_fence_renders_as_code_card() { + let src = r#"# main + +```text +marqdo ext add web +marqdo ext add quantum +``` + +> print text=ok +"#; + let module = crate::parse::parse_source(src).unwrap(); + let html = render_module_document(&module, src, &[]); + assert!( + html.contains(r#"data-lang="text""#) && html.contains("code-body"), + "text fence should be a code card: {html}" + ); + assert!( + html.contains("marqdo ext add web\nmarqdo ext add quantum"), + "fence body newlines preserved: {html}" + ); + assert!( + !html.contains("text marqdo"), + "must not collapse fence into inline code: {html}" + ); + } + + #[test] + fn prose_calls_and_param_decl_get_chips() { + let src = r#"# main + +Try **greet who="a"** and **greet who="b"**. + +## greet + +When we meet `who`, we **print text="Hi, `who`!"** and close with*None*. +"#; + let module = crate::parse::parse_source(src).unwrap(); + let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); + let annots = build_view_annots(&module, src, &cap); + assert!( + annots + .iter() + .filter(|a| a.kind == crate::view::annot::AnnotKind::Call) + .count() + >= 3, + "expected greet×2 + print call events: {:?}", + cap.view_trace.events + ); + assert!( + annots.iter().any(|a| { + a.kind == crate::view::annot::AnnotKind::Bind && a.label == "who" + }), + "param Decl bind missing: {annots:?}" + ); + let html = render_module_document(&module, src, &annots); + assert!(html.contains("annot-call"), "{html}"); + assert!(html.contains("annot-bind"), "{html}"); + assert!(html.contains("Hi, a!") || html.contains("Hi, b!"), "{html}"); + // Dual greet call sites each get a non-empty annot id. + let greet_ids: Vec<_> = html + .match_indices("mq-code") + .filter(|_| true) + .collect(); + assert!( + html.matches(r#"data-annot-id="c"#).count() >= 2 + || html.contains(r#"data-annot-id="c"#), + "expected call annot ids on greet marks: {html}" + ); + let _ = greet_ids; + // Last-frame who bind must not be buried in overflow (frame-aware density). + assert!( + !html.contains(r#"annot-bind annot-chip-overflow"#) + || html.contains(r#"annot-label">who"#), + "who bind should be visible for default (last) call frame: {html}" + ); + // Prefer: no overflow on bind chips when last frame has ≤4 chips. + let bind_overflow = html.matches("annot-bind annot-chip-overflow").count(); + assert_eq!( + bind_overflow, 0, + "default frame who/print/return must not overflow: {html}" + ); + } } diff --git a/src/view/html.rs b/src/view/html.rs index 6c445ed..459bdae 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -382,6 +382,20 @@ li.doc-list-meta { margin-left: -1.25rem; } .doc-block { position: relative; margin: 0.55rem 0 0.85rem; } +.doc-block > .annot-leaders { + position: absolute; + inset: 0; + pointer-events: none; + overflow: visible; + z-index: 1; /* below .annot-chips */ +} +.doc-block > .annot-leaders svg { + position: absolute; + left: 0; + top: 0; + overflow: visible; +} +.doc-block.is-keyed > .annot-leaders { display: none; } .doc-block.doc-exec[style*="--doc-indent"] { margin-left: calc(var(--doc-indent, 1) * 1.5rem); } @@ -466,38 +480,26 @@ ul.doc-loop, ol.doc-branch { .mq-anchor.is-focus { background: rgba(0,0,0,0.04); } .annot-band { position: relative; - margin: 0.35rem 0 0.15rem; + margin: 0.55rem 0 0.15rem; min-height: 1.6rem; - padding-top: 0.55rem; -} -.annot-leaders { - position: absolute; - inset: 0; - pointer-events: none; - overflow: visible; + padding-top: 1.15rem; /* room for mid→mid leaders (rail + stub) */ + z-index: 1; } +/* Band-local leaders kept for keyed fallback; geometry uses .doc-block > .annot-leaders */ +.annot-band > .annot-leaders { display: none; } .annot-leader { - position: absolute; - box-sizing: border-box; - border-left: 1.5px solid var(--line-strong); - border-bottom: 1.5px solid var(--line-strong); - border-color: #8e8e93; + fill: none; + stroke-width: 1.5; + stroke-linecap: round; + stroke-linejoin: round; pointer-events: none; } -.annot-leader.annot-bind { border-color: #5ac8fa; } -.annot-leader.annot-return { border-color: #30d158; } -.annot-leader.annot-code, -.annot-leader.annot-call, -.annot-leader.annot-expr { border-color: #ff9f0a; } -.annot-leader.annot-branch { border-color: #bf5af2; } -.annot-leader.annot-loop { border-color: #64d2ff; } -.annot-leader.annot-writeback { border-color: #8e8e93; } .annot-chips { display: flex; flex-wrap: wrap; - gap: 0.4rem 0.55rem; + gap: 0.45rem 0.7rem; position: relative; - z-index: 1; + z-index: 3; /* chips above leaders */ } .annot-chip { display: inline-flex; @@ -531,9 +533,9 @@ ul.doc-loop, ol.doc-branch { .annot-chip.annot-branch { border-left-color: #bf5af2; } .annot-chip.annot-loop { border-left-color: #64d2ff; } .annot-chip.annot-writeback { border-left-color: #8e8e93; } -.annot-chip-overflow { display: none; } -.annot-band.is-expanded .annot-chip-overflow:not([hidden]):not(.is-frame-hidden) { - display: inline-flex; +.annot-chip.annot-chip-overflow { display: none !important; } +.annot-band.is-expanded .annot-chip.annot-chip-overflow:not([hidden]):not(.is-frame-hidden) { + display: inline-flex !important; } .annot-label { color: var(--muted); font-weight: 600; } .annot-value { color: var(--ink); word-break: break-word; } @@ -546,17 +548,17 @@ ul.doc-loop, ol.doc-branch { padding: 0.22rem 0.45rem; cursor: pointer; } -.annot-band.is-keyed .annot-leaders { display: none; } -.annot-band.is-keyed .annot-chip::before { +.annot-band.is-keyed .annot-chip::before, +.doc-block.is-keyed .annot-chip::before { content: attr(data-annot-key) " "; color: var(--muted); } @media (max-width: 640px) { .annot-band { padding-top: 0.25rem; } - .annot-leaders { display: none; } + .doc-block > .annot-leaders { display: none; } } @media (prefers-reduced-motion: reduce) { - .annot-leaders { display: none; } + .doc-block > .annot-leaders { display: none; } } .badge { display: inline-block; @@ -1340,6 +1342,16 @@ ul.doc-loop, ol.doc-branch { align-items: center; gap: 0.4rem; } +.code-foot { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.45rem 0.65rem; + padding: 0.5rem 0.85rem; + border-top: 1px solid var(--line); + background: #fafafa; +} +.code-foot .code-actions { margin-left: auto; } .code-cmd { min-width: 9rem; max-width: 16rem; @@ -1376,6 +1388,7 @@ ul.doc-loop, ol.doc-branch { background: #1e1e1e; color: #d4d4d4; font: 0.82rem/1.45 var(--mono); + min-height: 2.4rem; } .code-body code { font: inherit; @@ -1579,17 +1592,23 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { function initForeignCards() {{ var live = !!window.MARQDO_VIEW_LIVE; document.querySelectorAll(".code-card").forEach(function (card) {{ + var foot = card.querySelector(".code-foot"); var btn = card.querySelector(".code-run"); var cmd = card.querySelector(".code-cmd"); var out = card.querySelector(".code-out"); var body = card.querySelector(".code-body code"); - if (!btn || !out || !body) return; + // Narrative ```text``` cards have no Run chrome — leave as-is. + if (!btn) return; if (!live) {{ - btn.disabled = true; - btn.title = "Run is available in live marqdo view"; - if (cmd) cmd.disabled = true; + // Static: hide fake Run (view-static-interactive D5 / view-prose-annot-gaps P4). + if (foot) foot.hidden = true; + else {{ + btn.hidden = true; + if (cmd) cmd.hidden = true; + }} return; }} + if (!out || !body) return; btn.addEventListener("click", function () {{ btn.disabled = true; out.hidden = false; @@ -2280,6 +2299,45 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { }}); }} + var MAX_VISIBLE_ANNOTS = 4; + + function setFrameHidden(el, hide) {{ + el.hidden = !!hide; + if (hide) el.classList.add("is-frame-hidden"); + else el.classList.remove("is-frame-hidden"); + }} + + /** After frame filter: overflow only among chips visible in the selected frame. */ + function recomputeAnnotOverflow(scope) {{ + var root = scope || document.getElementById("structure") || document; + root.querySelectorAll("[data-annot-band]").forEach(function (band) {{ + band.classList.remove("is-expanded"); + var chips = band.querySelectorAll(".annot-chip"); + var visible = []; + chips.forEach(function (chip) {{ + chip.classList.remove("annot-chip-overflow"); + if (chip.hidden || chip.classList.contains("is-frame-hidden")) return; + visible.push(chip); + }}); + var overflow = 0; + visible.forEach(function (chip, i) {{ + if (i >= MAX_VISIBLE_ANNOTS) {{ + chip.classList.add("annot-chip-overflow"); + overflow++; + }} + }}); + var more = band.querySelector("[data-annot-more]"); + if (more) {{ + if (overflow > 0) {{ + more.hidden = false; + more.textContent = "+" + overflow; + }} else {{ + more.hidden = true; + }} + }} + }}); + }} + /** Source structure always stays visible; only chips + arm classes follow the frame. */ function initCallPickers() {{ document.querySelectorAll(".call-picker").forEach(function (sel) {{ @@ -2295,7 +2353,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { root.querySelectorAll(".annot-chip[data-call-id]").forEach(function (chip) {{ var cid = String(chip.getAttribute("data-call-id") || ""); if (!allowed[cid]) return; - chip.hidden = cid !== callId; + setFrameHidden(chip, cid !== callId); }}); var trace = readViewTrace(); applyParamChipValues(fnName, callId, trace); @@ -2318,6 +2376,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { }}); }}); }} + recomputeAnnotOverflow(root); initAnnotLeaders(); }} if (sel.dataset.bound !== "1") {{ @@ -2328,12 +2387,6 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { }}); }} - function setFrameHidden(el, hide) {{ - el.hidden = !!hide; - if (hide) el.classList.add("is-frame-hidden"); - else el.classList.remove("is-frame-hidden"); - }} - function initLoopPickers() {{ document.querySelectorAll(".loop-picker").forEach(function (sel) {{ function apply() {{ @@ -2355,6 +2408,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { if (lid && loopId && String(lid) !== loopId) return; setFrameHidden(chip, String(chipIter) !== iter); }}); + recomputeAnnotOverflow(scope); initAnnotLeaders(); }} if (sel.dataset.bound !== "1") {{ @@ -2365,6 +2419,26 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { }}); }} + function ensureBlockLeaders(block) {{ + var leaders = block.querySelector(":scope > .annot-leaders"); + if (!leaders) {{ + leaders = document.createElement("div"); + leaders.className = "annot-leaders"; + leaders.setAttribute("aria-hidden", "true"); + block.insertBefore(leaders, block.firstChild); + }} + return leaders; + }} + + function leaderColor(kind) {{ + if (kind === "bind") return "#5ac8fa"; + if (kind === "return") return "#30d158"; + if (kind === "call" || kind === "expr" || kind === "code") return "#ff9f0a"; + if (kind === "branch") return "#bf5af2"; + if (kind === "loop") return "#64d2ff"; + return "#8e8e93"; + }} + function initAnnotLeaders() {{ var bands = document.querySelectorAll("[data-annot-band]"); if (!bands.length) return; @@ -2372,68 +2446,122 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { var narrow = window.matchMedia && window.matchMedia("(max-width: 640px)").matches; function layoutBand(band) {{ - var leaders = band.querySelector(".annot-leaders"); - var chips = band.querySelectorAll(".annot-chip:not(.annot-chip-overflow):not([hidden]):not(.is-frame-hidden)"); - if (!leaders) return; + var block = band.closest(".doc-block"); + if (!block) return; + var leaders = ensureBlockLeaders(block); leaders.innerHTML = ""; - if (reduce || narrow || chips.length > 4) {{ - band.classList.add("is-keyed"); - chips.forEach(function (chip, i) {{ - chip.setAttribute("data-annot-key", String(i + 1)); - }}); - return; - }} - band.classList.remove("is-keyed"); - var bandRect = band.getBoundingClientRect(); + var chipsEl = band.querySelector(".annot-chips"); + var chips = Array.prototype.slice.call( + band.querySelectorAll(".annot-chip:not(.annot-chip-overflow):not([hidden]):not(.is-frame-hidden)") + ); + // Pair chips with anchors; reorder DOM left→right under underlines so + // L-leaders do not cross (crowded reverse order looked like missing lines). + var items = []; chips.forEach(function (chip) {{ - if (chip.hidden || chip.classList.contains("is-frame-hidden")) return; var id = chip.getAttribute("data-annot-id") || ""; var kind = chip.getAttribute("data-annot-kind") || ""; var anchor = id - ? document.querySelector('.mq-anchor[data-annot-id="' + id + '"]') + ? (block.querySelector('.mq-anchor[data-annot-id="' + id + '"]') + || document.querySelector('.mq-anchor[data-annot-id="' + id + '"]')) : null; + // Fallback: match mark kind on this block (frame chips may share a span). if (!anchor) {{ - var block = band.closest(".doc-block"); - anchor = block ? block.querySelector(".mq-anchor") : null; + var cls = kind === "bind" ? "mq-decl" + : kind === "return" ? "mq-return" + : (kind === "call" || kind === "expr" || kind === "code") ? "mq-code" + : ""; + if (cls) anchor = block.querySelector(".mq-anchor." + cls); }} if (!anchor) return; - var a = anchor.getBoundingClientRect(); - var c = chip.getBoundingClientRect(); - var x0 = a.left + a.width / 2 - bandRect.left; - var y0 = 0; - var x1 = c.left + Math.min(12, c.width / 2) - bandRect.left; - var y1 = c.top - bandRect.top + c.height / 2; - var left = Math.min(x0, x1); - var width = Math.max(2, Math.abs(x1 - x0)); - var height = Math.max(2, y1 - y0); - var el = document.createElement("div"); - el.className = "annot-leader annot-" + kind; - el.style.left = left + "px"; - el.style.top = y0 + "px"; - el.style.width = width + "px"; - el.style.height = height + "px"; - if (x1 < x0) {{ - el.style.borderLeft = "none"; - el.style.borderRight = "1.5px solid"; - el.style.borderBottom = "1.5px solid"; - }} - leaders.appendChild(el); + if (id) anchor.setAttribute("data-annot-id", id); + items.push({{ + chip: chip, + anchor: anchor, + kind: kind, + x: anchor.getBoundingClientRect().left + }}); }}); + items.sort(function (a, b) {{ return a.x - b.x; }}); + if (chipsEl && items.length) {{ + items.forEach(function (it) {{ chipsEl.appendChild(it.chip); }}); + var more = band.querySelector("[data-annot-more]"); + if (more) chipsEl.appendChild(more); + }} + if (reduce || narrow || items.length > MAX_VISIBLE_ANNOTS) {{ + block.classList.add("is-keyed"); + band.classList.add("is-keyed"); + items.forEach(function (it, i) {{ + it.chip.setAttribute("data-annot-key", String(i + 1)); + }}); + return; + }} + block.classList.remove("is-keyed"); + band.classList.remove("is-keyed"); + // Mid-bottom of mark → mid-top of chip: vertical, horizontal rail, short stub. + var blockRect = block.getBoundingClientRect(); + var bw = Math.max(1, block.offsetWidth); + var bh = Math.max(1, block.offsetHeight); + var svgNS = "http://www.w3.org/2000/svg"; + var svg = document.createElementNS(svgNS, "svg"); + svg.setAttribute("width", String(bw)); + svg.setAttribute("height", String(bh)); + svg.setAttribute("viewBox", "0 0 " + bw + " " + bh); + svg.setAttribute("aria-hidden", "true"); + items.forEach(function (it) {{ + var a = it.anchor.getBoundingClientRect(); + var c = it.chip.getBoundingClientRect(); + var x0 = a.left + a.width / 2 - blockRect.left; + var y0 = a.bottom - blockRect.top + 1; + var x1 = c.left + c.width / 2 - blockRect.left; + var y1 = c.top - blockRect.top; + if (y1 < y0 + 8) {{ + y1 = y0 + 12; + }} + // Short stub into chip top-center; rail sits above that. + var stub = Math.min(10, Math.max(6, (y1 - y0) * 0.28)); + var yRail = y1 - stub; + if (yRail < y0 + 4) {{ + yRail = (y0 + y1) / 2; + }} + var path = document.createElementNS(svgNS, "path"); + path.setAttribute("class", "annot-leader annot-" + it.kind); + path.setAttribute("stroke", leaderColor(it.kind)); + // Orthogonal: down from mark mid → across → short down to chip mid. + path.setAttribute( + "d", + "M " + x0.toFixed(1) + " " + y0.toFixed(1) + + " L " + x0.toFixed(1) + " " + yRail.toFixed(1) + + " L " + x1.toFixed(1) + " " + yRail.toFixed(1) + + " L " + x1.toFixed(1) + " " + y1.toFixed(1) + ); + svg.appendChild(path); + }}); + leaders.appendChild(svg); }} function layoutAll() {{ bands.forEach(layoutBand); }} layoutAll(); + // Second pass after fonts/layout settle (first paint often has zero chip width). + requestAnimationFrame(function () {{ layoutAll(); }}); + if (document.documentElement.dataset.annotLeadersRo === "1") return; + document.documentElement.dataset.annotLeadersRo = "1"; if (typeof ResizeObserver !== "undefined") {{ var ro = new ResizeObserver(function () {{ layoutAll(); }}); - bands.forEach(function (b) {{ ro.observe(b); }}); + bands.forEach(function (b) {{ + ro.observe(b); + var blk = b.closest(".doc-block"); + if (blk) ro.observe(blk); + }}); var surface = document.querySelector(".document-surface"); if (surface) ro.observe(surface); }} window.addEventListener("resize", layoutAll); document.querySelectorAll("[data-annot-more]").forEach(function (btn) {{ + if (btn.dataset.bound === "1") return; + btn.dataset.bound = "1"; btn.addEventListener("click", function () {{ var band = btn.closest("[data-annot-band]"); if (!band) return; @@ -2443,6 +2571,8 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { }}); }}); document.querySelectorAll(".annot-chip").forEach(function (chip) {{ + if (chip.dataset.focusBound === "1") return; + chip.dataset.focusBound = "1"; chip.addEventListener("mouseenter", function () {{ var id = chip.getAttribute("data-annot-id"); if (!id) return; diff --git a/src/view/render.rs b/src/view/render.rs index 2237f8a..081cf3a 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -1259,12 +1259,14 @@ fn render_stmt( code `{name}` = {lang} +
+
{src}
+
-
{src}
"#, lang = lang, @@ -1526,6 +1528,7 @@ pub(crate) fn render_formula_assign_card(name: &str, tex: &str) -> String { } /// Foreign code assign card for document surface embedding (single visual layer). +/// Head → body → foot(actions) so the source is never collapsed under the Run row. pub(crate) fn render_code_assign_card(name: &str, lang: &str, source: &str) -> String { let placeholder = escape(&crate::foreign::default_cmd_display(lang)); format!( @@ -1534,12 +1537,14 @@ pub(crate) fn render_code_assign_card(name: &str, lang: &str, source: &str) -> S code {name} {lang} + +
{src}
+
-
{src}
"#, lang = escape(lang),