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 <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-10-15 20:36:12 +08:00
1 parent 66926e9e0a
commit 58ec2172d6
7 files changed
+839 -96

No files matched your search

+243 -7
View File
@@ -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<u32, Vec<&crate::capture::StmtEvent>> = 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 <mark data-annot-id>
// 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<usize>, Option<usize>, 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("<svg") {
return ("svg".into(), "svg".into());
}
if raw.contains("```") {
return ("code".into(), "code".into());
}
if raw.chars().count() > 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<u32> {
let mut s = std::collections::HashSet::new();
fn walk_stmt(st: &Stmt, s: &mut std::collections::HashSet<u32>) {
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<u32> = 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#"<div class="annot-band" data-annot-band>"#);
// 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#"<div class="annot-leaders" aria-hidden="true"></div>"#);
s.push_str(r#"<div class="annot-chips">"#);
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 {
+167 -5
View File
@@ -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 <code> 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#"<div class="doc-line doc-call"><span class="mq-call-gt">&gt;</span> {}</div>"#,
escape(rest)
r#"<div class="doc-line doc-call"><span class="mq-call-gt">&gt;</span> <mark class="mq-anchor mq-code" data-line="{line}" data-annot-id="{aid}">{rest}</mark></div>"#,
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#"<div class="doc-line doc-call"><span class="mq-call-gt">&gt;</span> {}</div>"#,
escape(rest.trim_start())
r#"<div class="doc-line doc-call"><span class="mq-call-gt">&gt;</span> <mark class="mq-anchor mq-code" data-line="{line}" data-annot-id="{aid}">{rest}</mark></div>"#,
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("<svg") || v.contains("```") || v.chars().count() > 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<String> = 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#"<div class="doc-block doc-exec" data-line="{line}"><div class="card code-card" data-lang="{lang}">
<div class="code-head">
<span class="badge">code</span>
<span class="code-lang">{lang}</span>
</div>
<pre class="code-body"><code class="language-{lang}">{src}</code></pre>
</div></div>"#,
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("<code>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</span>"#),
"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}"
);
}
}
+209 -79
View File
@@ -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;
+7 -2
View File
@@ -1259,12 +1259,14 @@ fn render_stmt(
<span class="badge">code</span>
<code class="expr">`{name}` =</code>
<span class="code-lang">{lang}</span>
</div>
<pre class="code-body"><code class="language-{lang}">{src}</code></pre>
<div class="code-foot">
<div class="code-actions">
<input type="text" class="code-cmd" placeholder="{placeholder}" spellcheck="false" autocomplete="off"/>
<button type="button" class="code-run">Run</button>
</div>
</div>
<pre class="code-body"><code class="language-{lang}">{src}</code></pre>
<pre class="code-out" hidden></pre>
</div>"#,
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
<span class="badge">code</span>
<span class="code-name">{name}</span>
<span class="code-lang">{lang}</span>
</div>
<pre class="code-body"><code class="language-{lang}">{src}</code></pre>
<div class="code-foot">
<div class="code-actions">
<input type="text" class="code-cmd" placeholder="{placeholder}" spellcheck="false" autocomplete="off"/>
<button type="button" class="code-run">Run</button>
</div>
</div>
<pre class="code-body"><code class="language-{lang}">{src}</code></pre>
<pre class="code-out" hidden></pre>
</div>"#,
lang = escape(lang),