diff --git a/CHANGELOG.md b/CHANGELOG.md index 04cd976..a9fb687 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Added -- **foreign 拥有视图会话**:新增 `foreign.session kernels= cells=`,返回 foreign 会话句柄;`view` 只消费 `会话` 绑定,不再识别 `内核表` / `会话表` 保留名。没有 `会话` 时,view cells 使用无状态一次性执行,不创建内核。清除输出已接通 `/api/session/clear`,普通 view 与 foreign cells 共用,并由 Execution 面板的 Clear 按钮清除页面输出;无 `会话` 的 view 在 Run All 时执行整个文档并回写 Execution(不再空转);静态导出与动态 view 共用同一套 View 外壳和按钮布局;静态页面执行按钮点击显示“静态页面无法真实执行”,不伪造成功;移除 `In []` / `Out []` 与 Notebook 品牌;没有新增 CLI 或第二个交互模式。 +- **foreign 拥有视图会话**:新增 `foreign.session kernels= cells=`,返回 foreign 会话句柄;`view` 只消费 `会话` 绑定,不再识别 `内核表` / `会话表` 保留名。没有 `会话` 时,view cells 使用无状态一次性执行,不创建内核。清除输出已接通 `/api/session/clear`,普通 view 与 foreign cells 共用,并由 Execution 面板的 Clear 按钮清除页面输出;无 `会话` 的 view 在 Run All 时执行整个文档并回写 Execution(不再空转);静态导出与动态 view 共用同一套 View 外壳和按钮布局;静态页面执行按钮点击显示“静态页面无法真实执行”,不伪造成功;静态导出会实际执行代码单元并把 stdout/stderr 注入代码卡,失败也显示真实错误;移除 `In []` / `Out []` 与 Notebook 品牌;没有新增 CLI 或第二个交互模式。 ### Fixed diff --git a/public/features/19-foreign-view-cells.mq.md b/public/features/19-foreign-view-cells.mq.md index 525c7eb..1152aa2 100644 --- a/public/features/19-foreign-view-cells.mq.md +++ b/public/features/19-foreign-view-cells.mq.md @@ -166,7 +166,6 @@ Cells in view. Named kernels and a cell order are ordinary bound tables, not fen | 独立复核 | 复核 | read the JSON report | ``` -`会话` = > foreign.session kernels=`分析内核` cells=`分析单元` `marqdo view` consumes the foreign-owned `会话` handle and renders Run All, Step, per-cell kernel switching, a journal, dirty reload and a state panel. Without that handle, cells are stateless one-shot runs. There is no separate interactive command; `marqdo run` still executes the same file as one program. diff --git a/public/features/19-外联视图单元.mq.md b/public/features/19-外联视图单元.mq.md index 165736f..4bbd46c 100644 --- a/public/features/19-外联视图单元.mq.md +++ b/public/features/19-外联视图单元.mq.md @@ -166,7 +166,6 @@ view 中的单元。命名内核和单元顺序都是普通绑定表,不是 fe | 独立复核 | 复核 | 读取 JSON 报告 | ``` -`会话` = > foreign.session kernels=`分析内核` cells=`分析单元` `marqdo view` 消费 foreign 拥有的 `会话` 句柄,渲染 Run All、Step、切换内核、journal、dirty reload 和状态面板。没有该句柄时,单元是无状态的一次性运行。没有单独的交互命令;`marqdo run` 仍把同一份文件当单个程序执行。 diff --git a/src/view/output.rs b/src/view/output.rs index 659f1ed..eb9eaf1 100644 --- a/src/view/output.rs +++ b/src/view/output.rs @@ -1,11 +1,14 @@ //! Static HTML export: `marqdo view output`. +use std::collections::HashMap; use std::fs; use std::path::PathBuf; use anyhow::{Context, Result}; -use crate::view::html::{page_file, page_index, LinkMode}; +use crate::host::foreign_doc::DocumentSession; +use crate::value::Value; +use crate::view::html::{escape, page_file, page_index, LinkMode}; use crate::view::{build_file_view, build_root, ViewRoot}; pub struct OutputOptions { @@ -14,6 +17,138 @@ pub struct OutputOptions { pub no_exec: bool, } +#[derive(Debug, Clone)] +struct StaticCellOutput { + ok: bool, + text: String, +} + +fn value_text(v: &Value) -> Option { + match v { + Value::Text(s) => Some(s.clone()), + Value::None => None, + _ => v.reveal_text().map(|s| s.to_string()), + } +} + +fn value_bool(v: &Value) -> Option { + match v { + Value::Bool(b) => Some(*b), + _ => None, + } +} + +fn record_field(record: &Value, key: &str) -> Option { + match record { + Value::Map(entries) => entries + .iter() + .find(|(k, _)| k == key) + .map(|(_, v)| v.clone()), + _ => None, + } +} + +/// Run the document's cells at export time and keep their real outputs. This +/// is what makes a static page show foreign results instead of just source. +fn static_cell_outputs(root: &ViewRoot, abs: &std::path::Path) -> HashMap { + let mut out = HashMap::new(); + let Ok(mut session) = DocumentSession::open(abs, &root.root) else { + return out; + }; + for cell in session.order.clone() { + let record = match session.run_cell(&cell, None) { + Ok(record) => record, + Err(error) => { + out.insert( + cell, + StaticCellOutput { + ok: false, + text: error, + }, + ); + continue; + } + }; + let ok = record_field(&record, "ok") + .and_then(|v| value_bool(&v)) + .unwrap_or(false); + let mut parts = Vec::new(); + if let Some(stdout) = record_field(&record, "stdout").and_then(|v| value_text(&v)) { + if !stdout.is_empty() { + parts.push(stdout); + } + } + if let Some(stderr) = record_field(&record, "stderr").and_then(|v| value_text(&v)) { + if !stderr.is_empty() { + parts.push(format!("[stderr]\n{stderr}")); + } + } + if let Some(error) = record_field(&record, "error").and_then(|v| value_text(&v)) { + if !error.is_empty() { + parts.push(error); + } + } + let mut meta = Vec::new(); + if let Some(code) = + record_field(&record, "code").and_then(|v| match v { + Value::Int(n) => Some(n), + _ => None, + }) + { + if code != 0 { + meta.push(format!("exit {code}")); + } + } + if let Some(ms) = + record_field(&record, "ms").and_then(|v| match v { + Value::Int(n) => Some(n), + _ => None, + }) + { + if ms > 0 { + meta.push(format!("{ms}ms")); + } + } + if !meta.is_empty() { + parts.push(format!("— {}", meta.join(" · "))); + } + let text = if parts.is_empty() { + "(no output)".to_string() + } else { + parts.join("\n\n") + }; + out.insert(cell, StaticCellOutput { ok, text }); + } + session.close(); + out +} + +/// Inject static cell outputs into code cards without running client JS. +fn inject_cell_outputs(html: &str, outputs: &HashMap) -> String { + let mut html = html.to_string(); + for (name, out) in outputs { + let marker = format!(r#"data-code-name="{name}""#); + let Some(pos) = html.find(&marker) else { + continue; + }; + let tail = &html[pos..]; + let Some(out_pos) = tail.find(r#""#) else { + continue; + }; + let abs_pos = pos + out_pos; + let replacement = if out.ok { + format!(r#"
{}
"#, escape(&out.text)) + } else { + format!(r#"
{}
"#, escape(&out.text)) + }; + html.replace_range( + abs_pos..abs_pos + r#""#.len(), + &replacement, + ); + } + html +} + pub fn write_static(opts: OutputOptions) -> Result<()> { let root = build_root(&opts.path)?; fs::create_dir_all(&opts.out_dir) @@ -48,7 +183,15 @@ pub fn write_static(opts: OutputOptions) -> Result<()> { let links = LinkMode::Static { from: Some(rel.clone()), }; - let html = page_file(&root.files, &rel, &vm, &links); + let cell_outputs = if opts.no_exec { + HashMap::new() + } else { + static_cell_outputs(&root, &abs) + }; + let html = inject_cell_outputs( + &page_file(&root.files, &rel, &vm, &links), + &cell_outputs, + ); let out_file = pages_root.join(format!("{rel}.html")); if let Some(parent) = out_file.parent() { fs::create_dir_all(parent)?; @@ -57,11 +200,14 @@ pub fn write_static(opts: OutputOptions) -> Result<()> { if first_page_html.is_none() { // index.html = first file (same content, links rooted at OUT_DIR) - first_page_html = Some(page_file( - &root.files, - &rel, - &vm, - &LinkMode::Static { from: None }, + first_page_html = Some(inject_cell_outputs( + &page_file( + &root.files, + &rel, + &vm, + &LinkMode::Static { from: None }, + ), + &cell_outputs, )); } } @@ -85,3 +231,18 @@ fn resolve_abs(root: &ViewRoot, rel: &str) -> Result { let abs = root.root.join(rel); Ok(abs.canonicalize().unwrap_or(abs)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn injects_visible_static_cell_outputs() { + let html = r#"
"#; + let mut outputs = HashMap::new(); + outputs.insert("a".to_string(), StaticCellOutput { ok: true, text: "42".into() }); + let html = inject_cell_outputs(html, &outputs); + assert!(html.contains(r#"
42
"#), "{html}"); + assert!(!html.contains("hidden"), "{html}"); + } +}