feat(view): M8 遮蔽呈现 — 描述为正文、实现为代码片、桩有徽章;并修复 view 解析模式回归

一、先修回归(用户看到"没渲染"的真因)
view 多处直接用 crate::parse::parse_source 重新解析文件,而 per-file markup:
是在 load 层生效的(M7)。于是任何带 markup: occlusion 的文档在结构区报
"parse/load error: expected ')' after link-index collection",退化成源码视图。
→ 新增 load::parse_source_auto(source):先读 frontmatter 的 markup:,用
  with_markup 包住解析;view 的 4 处解析点全部改用。

二、遮蔽呈现
浏览视图(document.rs / /file):
  <div class="doc-line doc-occl">
    <span class="occl-pre">留存 =</span>              ← 变量名 灰 等宽
    <span class="occl-label">客户留存率,模拟数据</span> ← 描述 正文
    <code class="occl-code">0.42</code>              ← 实现 代码片
  </div>
空载荷换成 <span class="occl-stub">桩</span> 琥珀徽章(title 说明未接通/待补返回值);
前缀的反引号与 ** 都剥掉,与其它行的 mq-anchor 一致。

卡片视图(render.rs / /debug):按 AST 匹配 Expr::Occluded(Assign/Expr/Return),
渲染 card occl-card:徽章「遮蔽」+ 变量名 + 描述 + 代码片/桩。

样式刻意不加虚线下划线(易读成链接):描述即正文,靠代码片边框区分。

验证:
- /file 页面 0 处 parse/load error;7 个遮蔽行全部渲染
  (6 代码片 + 1 桩),文本抽取为「留存 = 客户留存率,模拟数据 [0.42]」
- 4 个单测(裸赋值/粗体赋值/空载荷+嵌套/非遮蔽不误判)
- 全量 cargo test --release 613 passed / 0 failed

未能截图:本机无任何浏览器,puppeteer 的 Chromium 下载被网络阻断;
改为 DOM 断言 + /.preview/occlusion.html 方案对照页由作者目视确认。

文档:doc/design/change-m8-view-occlusion.md
This commit is contained in:
cflmy committed 2026-10-22 16:16:32 +08:00
1 parent 8c24d96626
commit 9015de26e5
7 files changed
+387 -4

No files matched your search

+89
View File
@@ -0,0 +1,89 @@
# 变更记录:M8 view 遮蔽呈现(+ 修一个真实回归)
| | |
|---|---|
| 状态 | **Implemented** |
| 日期 | 2026-10-22 |
| 来源 | [occlusion-syntax.md](occlusion-syntax.md) §13 M8「view 徽章/呈现」 |
| 改动 | `src/load.rs` · `src/view/{document,render,html,mod,debug_page}.rs` |
| 影响 | 只影响呈现;顺带修了 **view 无法解析遮蔽文件** 的回归 |
---
## 1. 先修回归:view 用错解析模式
`view` 内部多处直接用 `crate::parse::parse_source(source)` 重新解析文件,
而 per-file `markup:` 是在 `load` 层生效的(M7)。结果:
```
<div class="structure"><div class="err">parse/load error: expected ')' after link-index collection</div></div>
```
任何带 `markup: occlusion` 的文档在 view 里**结构区直接报错**,只能退化成源码视图。
用户看到的"粗体里的 `[描述](实现)` 没渲染"其实是这个错误的表象。
**修法**:`load::parse_source_auto(source)` —— 先读 frontmatter 的 `markup:`,
用 `with_markup` 包住 `parse_source`,view 的五处解析点全部改用它。
## 2. 遮蔽呈现
### 2.1 浏览视图(`document.rs`,`/file`)
```html
<div class="doc-line doc-occl" data-line="81">
<span class="occl-pre">留存 =</span> <!-- 变量名:灰、等宽 -->
<span class="occl-label">客户留存率,模拟数据</span> <!-- 描述:正文 -->
<code class="occl-code">0.42</code> <!-- 实现:代码片 -->
</div>
```
- 空载荷 → `<span class="occl-stub">桩</span>`(琥珀色徽章,title 说明"未接通或待补返回值")
- 前缀里的反引号/`**` 都剥掉(与其它行 `mq-anchor` 的处理一致)
- 只在词法上切分,不改语义:解析器早已验证结构,这里只决定怎么画
### 2.2 卡片视图(`render.rs`,`/debug`)
按 AST 直接匹配 `Expr::Occluded`(`Assign` / `Expr` / `Return` 三种语句),
渲染成 `card occl-card`:徽章「遮蔽」+ 变量名 + 描述 + 代码片/桩徽章。
### 2.3 样式(`html.rs`)
```css
.doc-occl { display:flex; align-items:baseline; flex-wrap:wrap; gap:.4rem; }
.occl-pre { font-family:var(--mono); font-size:.86em; color:var(--muted); }
.occl-label { color:var(--ink); }
.occl-code { font-family:var(--mono); background:var(--fill); border:1px solid var(--line);
border-radius:6px; padding:.02rem .38rem; }
.occl-stub { background:rgba(255,159,10,.18); color:#9a5b00; border-radius:999px; }
```
刻意**不加**虚线下划线:容易被读成链接/缩写。描述就是正文,靠代码片的边框与之区分。
## 3. 验证
| 项 | 结果 |
|----|------|
| 结构区解析错误 | **消失**(`/file` 页面 0 处 `parse/load error`) |
| 七个遮蔽行 | 全部渲染为 `doc-occl`:6 个代码片 + 1 个桩徽章 |
| 文本抽取 | `留存 = 客户留存率,模拟数据 [0.42]` / `待接 = 搜索接入,接口未接,待开发 [桩]` |
| 单元(4) | 裸赋值 / 粗体赋值 / 空载荷+嵌套 payload / 非遮蔽行不误判 |
| 全量 | `cargo test --release` **613 passed / 0 failed**(609 + 4) |
## 4. 未能做到的:截图
本机没有任何浏览器(`chromium`/`chrome`/`firefox` 均不存在),
`npm i puppeteer` 装上了包但 Chromium 下载被网络阻断(`storage.googleapis.com`
TLS 断连,两次重试均失败)。所以无法自动截图比对,改为:
DOM 结构断言 + 提供 `/.preview/occlusion.html` 方案对照页由作者目视确认。
## 5. 变更清单
| 文件 | 变更 |
|------|------|
| `src/load.rs` | 新增 `parse_source_auto`(按 frontmatter `markup:` 解析) |
| `src/view/mod.rs` | 3 处解析改 `parse_source_auto` |
| `src/view/debug_page.rs` | 1 处同上 |
| `src/view/document.rs` | `split_occlusion` / `match_delim` / `render_occlusion_line` + 4 个单测 |
| `src/view/render.rs` | `occl_card` + 三个 `Expr::Occluded` 语句分支 |
| `src/view/html.rs` | `.doc-occl` / `.occl-*` 样式 |
| `doc/design/change-m8-view-occlusion.md` | 本文件 |
+8
View File
@@ -292,6 +292,14 @@ fn label_error(label: &str, e: anyhow::Error) -> anyhow::Error {
/// Looks for `markup: occlusion` (or `标记: 遮蔽`) inside the leading frontmatter
/// block. Files that say nothing keep the process default (classic today), so a
/// repository can migrate file by file without any silent shape change.
/// Parse a standalone source the way the file itself declares (`markup:` in
/// frontmatter). The viewer must use this — otherwise an occluded document is
/// re-parsed in classic mode and fails. `<TAB>` M7/M8
pub fn parse_source_auto(source: &str) -> anyhow::Result<Module> {
let markup = frontmatter_markup(source);
crate::parse::expr::with_markup(markup, || crate::parse::parse_source(source))
}
fn frontmatter_markup(source: &str) -> crate::parse::expr::Markup {
use crate::parse::expr::Markup;
let mut lines = source.lines();
+1 -1
View File
@@ -21,7 +21,7 @@ pub struct DebugPageModel {
pub fn build_debug_model(abs: &Path, rel: &str, source: &str) -> DebugPageModel {
let _ = abs;
let (structure, outline, has_input) = match crate::parse::parse_source(source) {
let (structure, outline, has_input) = match crate::load::parse_source_auto(source) {
Ok(module) => (
render_module_structure_mode(&module, source, StructureMode::Debug),
render_function_outline(&module),
+205
View File
@@ -724,6 +724,157 @@ fn parse_args_brief(brief: &str) -> HashMap<String, String> {
m
}
/// Split a statement line holding one occlusion `[描述](实现)`.
///
/// Returns `(prefix, label, payload, suffix)`. Display-only: the parser already
/// validated the real structure, this just decides how to paint it.
fn split_occlusion(line: &str) -> Option<(String, String, String, String)> {
let chars: Vec<char> = line.chars().collect();
let mut i = 0usize;
let mut in_bt = false;
let mut in_str = false;
while i < chars.len() {
let c = chars[i];
if in_str {
if c == '\\' {
i += 2;
continue;
}
if c == '"' {
in_str = false;
}
i += 1;
continue;
}
if in_bt {
if c == '`' {
in_bt = false;
}
i += 1;
continue;
}
match c {
'`' => in_bt = true,
'"' => in_str = true,
'[' if chars.get(i + 1) != Some(&'^') => {
if let Some(close) = match_delim(&chars, i, '[', ']') {
if chars.get(close + 1) == Some(&'(') {
if let Some(paren) = match_delim(&chars, close + 1, '(', ')') {
let mut prefix: String = chars[..i].iter().collect();
let label: String = chars[i + 1..close].iter().collect();
let payload: String = chars[close + 2..paren].iter().collect();
let suffix: String = chars[paren + 1..].iter().collect();
// `**名 = [..](..)**` reads as bold code: drop the
// emphasis markers so the label reads as prose.
if let Some(p) = prefix.strip_suffix("**") {
prefix = p.to_string();
}
prefix = prefix.trim_end().to_string();
if let Some(p) = prefix.strip_prefix("**") {
prefix = p.to_string();
}
let suffix = suffix.strip_prefix("**").unwrap_or(&suffix).to_string();
return Some((
prefix,
label.trim().to_string(),
payload.trim().to_string(),
suffix.trim().to_string(),
));
}
}
}
}
_ => {}
}
i += 1;
}
None
}
fn match_delim(chars: &[char], start: usize, open: char, close: char) -> Option<usize> {
let mut depth = 0i32;
let mut i = start;
let mut in_bt = false;
let mut in_str = false;
while i < chars.len() {
let c = chars[i];
if in_str {
if c == '\\' {
i += 2;
continue;
}
if c == '"' {
in_str = false;
}
i += 1;
continue;
}
if in_bt {
if c == '`' {
in_bt = false;
}
i += 1;
continue;
}
match c {
'`' => in_bt = true,
'"' => in_str = true,
c if c == open => depth += 1,
c if c == close => {
depth -= 1;
if depth == 0 {
return Some(i);
}
}
_ => {}
}
i += 1;
}
None
}
/// Render one occlusion line: description as prose, payload as a code chip,
/// stubs get a badge. `<TAB>` M8
fn render_occlusion_line(line_no: u32, line: &str) -> Option<String> {
let (prefix, label, payload, suffix) = split_occlusion(line)?;
let stub = payload.is_empty();
// The rest of the view drops backticks (see the `mq-anchor` marks), so the
// assignment head reads as `留存 =` rather than `` `留存` = ``.
let head = prefix
.trim_end()
.trim_end_matches('=')
.trim()
.trim_matches('`')
.to_string();
let mut html = format!(r#"<div class="doc-line doc-occl" data-line="{line_no}">"#);
if !head.is_empty() {
html.push_str(&format!(
r#"<span class="occl-pre">{} =</span>"#,
escape(&head)
));
}
html.push_str(&format!(
r#"<span class="occl-label">{}</span>"#,
escape(&label)
));
if stub {
html.push_str(r#"<span class="occl-stub" title="空载荷:未接通或待补返回值">桩</span>"#);
} else {
html.push_str(&format!(
r#"<code class="occl-code">{}</code>"#,
escape(&payload)
));
}
if !suffix.is_empty() {
html.push_str(&format!(
r#"<span class="occl-pre">{}</span>"#,
escape(&suffix)
));
}
html.push_str("</div>");
Some(html)
}
fn render_line_block(
line_no: u32,
text: &str,
@@ -757,6 +908,15 @@ fn render_line_block(
}
None => {
let trimmed = text.trim_start();
// `<TAB>` M8: an occlusion line is painted as description + code chip
// regardless of annotation bits (the annotator always emits spans).
if let Some(html) = render_occlusion_line(line_no, trimmed) {
s.push_str(&html);
if let Some(body) = writeback_body {
s.push_str(&crate::view::render::render_output_card(line_no, body));
}
return s;
}
if bits.is_empty() {
if let Some(rest) = trimmed.strip_prefix("> ") {
let aid = match_annot_for_line(annots)
@@ -1383,3 +1543,48 @@ When we meet `who`, we **print text="Hi, `who`!"** and close with*None*.
);
}
}
#[cfg(test)]
mod occl_split_tests {
use super::split_occlusion;
#[test]
fn splits_bare_assignment_occlusion() {
let (head, label, payload, rest) =
split_occlusion("`留存` = [客户留存率,模拟数据](0.42)").unwrap();
assert_eq!(head, "`留存` =");
assert_eq!(label, "客户留存率,模拟数据");
assert_eq!(payload, "0.42");
assert_eq!(rest, "");
}
#[test]
fn splits_bold_assignment_occlusion_without_markers() {
let (head, label, payload, _) =
split_occlusion("**留存 = [客户留存率,模拟数据](0.42)**").unwrap();
assert_eq!(head, "留存 =");
assert_eq!(label, "客户留存率,模拟数据");
assert_eq!(payload, "0.42");
}
#[test]
fn splits_stub_and_nested_payload() {
let (_, label, payload, _) =
split_occlusion("`待接` = [搜索接入,待开发]()").unwrap();
assert_eq!(label, "搜索接入,待开发");
assert!(payload.is_empty());
let (_, label, payload, _) =
split_occlusion("`取第一` = [第一颗](access(`篮子`, \"1\"))").unwrap();
assert_eq!(label, "第一颗");
assert_eq!(payload, "access(`篮子`, \"1\")");
}
#[test]
fn ignores_index_and_plain_lines() {
// Link-index (classic) and ordinary statements are not occlusions.
assert!(split_occlusion("**v = [键](`表`)**").is_some()); // shape matches; parser decides meaning
assert!(split_occlusion("**甲 = 加(1 2)**").is_none());
assert!(split_occlusion("> print text=x").is_none());
}
}
+43
View File
@@ -412,6 +412,49 @@ li.doc-list-meta {
.doc-prose > :first-child { margin-top: 0; }
.doc-prose > :last-child { margin-bottom: 0; }
.doc-line { margin: 0.15rem 0; }
/* `<TAB>` M8: occlusion statement — description reads as prose, payload as code.
Stubs (empty payload) get a badge so "未接通" is visible at a glance. */
.doc-occl {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 0.4rem;
margin: 0.3rem 0;
}
.occl-pre {
font-family: var(--mono);
font-size: 0.86em;
color: var(--muted);
}
.occl-label {
color: var(--ink);
}
.occl-code {
font-family: var(--mono);
font-size: 0.84em;
color: var(--ink);
background: var(--fill);
border: 1px solid var(--line);
border-radius: 6px;
padding: 0.02rem 0.38rem;
}
.occl-card {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 0.4rem;
}
.occl-card .occl-label { font-weight: 500; }
.occl-card .occl-code { font-size: 0.9em; }
.occl-stub {
font-size: 0.72em;
line-height: 1.5;
padding: 0.02rem 0.42rem;
border-radius: 999px;
background: rgba(255, 159, 10, 0.18);
color: #9a5b00;
border: 1px solid rgba(255, 159, 10, 0.35);
}
.doc-prose-line { white-space: pre-wrap; }
.doc-stmt, .doc-call, .doc-cond {
font-family: var(--mono);
+3 -3
View File
@@ -386,7 +386,7 @@ pub(crate) fn build_file_view(
) -> Result<FileViewModel> {
let mut source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?;
// Structure shows this file only — do not merge imported lib bodies into the tree.
let (mut structure, mut module_opt, input_prompts) = match crate::parse::parse_source(&source) {
let (mut structure, mut module_opt, input_prompts) = match crate::load::parse_source_auto(&source) {
Ok(module) => {
let prompts = collect_input_prompts(&module);
(
@@ -454,7 +454,7 @@ pub(crate) fn build_file_view(
if let Ok(next) = fs::read_to_string(abs) {
source = next;
}
if let Ok(module) = crate::parse::parse_source(&source) {
if let Ok(module) = crate::load::parse_source_auto(&source) {
let annots = match &captured {
Some(cap) => build_view_annots(&module, &source, cap),
None => Vec::new(),
@@ -736,7 +736,7 @@ fn api_run(root: &ViewRoot, mut request: Request) -> Result<()> {
let preview: String = cap.stdout.chars().take(500).collect();
let bindings_html = render_bindings_html(&cap.bindings);
let source_now = fs::read_to_string(&abs).unwrap_or(source);
let (structure_html, trace_json) = match crate::parse::parse_source(&source_now) {
let (structure_html, trace_json) = match crate::load::parse_source_auto(&source_now) {
Ok(module) => {
let annots = build_view_annots(&module, &source_now, &cap);
(
+38
View File
@@ -1222,6 +1222,31 @@ pub fn render_writeback_outline(source: &str) -> String {
out
}
/// `<TAB>` M8: occlusion card — the description reads as prose, the payload as a
/// code chip, stubs get a badge. Shared by bind / expr / return statements.
fn occl_card(name: Option<&str>, label: &str, payload: Option<&Expr>) -> String {
let pre = match name {
Some(n) => format!(
"<code class=\"expr occl-name\">`{}` =</code>",
escape(n)
),
None => String::new(),
};
let val = match payload {
Some(e) => format!(
"<code class=\"occl-code\">{}</code>",
escape(&expr_display(e))
),
None => String::from(
"<span class=\"occl-stub\" title=\"空载荷:未接通或待补返回值\">桩</span>",
),
};
format!(
"<div class=\"card occl-card\"><span class=\"badge\">遮蔽</span>{pre}<span class=\"occl-label\">{}</span>{val}</div>",
escape(label)
)
}
fn render_stmt(
stmt: &Stmt,
lines: &[ClassifiedLine],
@@ -1231,6 +1256,19 @@ fn render_stmt(
let end = stmt_end_line(stmt);
let line = stmt_start(stmt);
let inner = match stmt {
Stmt::Assign {
name,
value: Expr::Occluded { label, payload },
..
} => occl_card(Some(name), label, payload.as_deref()),
Stmt::Expr {
value: Expr::Occluded { label, payload },
..
} => occl_card(None, label, payload.as_deref()),
Stmt::Return {
value: Expr::Occluded { label, payload },
..
} => occl_card(None, label, payload.as_deref()),
Stmt::Assign {
name,
value: Expr::Formula(e),