feat(foreign): pass Marqdo values into multi-kernel view sessions
foreign.session accepts a values table and initializes each kernel from ordinary Marqdo values. The static walkthrough now uses two kernels and a shared 订单 value instead of redefining orders inside Python. Static pages embed the session summary so kernel controls and Clean stay visible.
This commit is contained in:
1 parent
15362cb048
commit
9b269f6447
7 files changed
+164
-61
No files matched your search
@@ -152,6 +152,7 @@ in input order. Raises with the failing index after all workers finish.
|
||||
## session
|
||||
+ `kernels`=None
|
||||
+ `cells`=None
|
||||
+ `values`=None
|
||||
|
||||
Declare a document view session. `kernels` and `cells` are ordinary tables:
|
||||
kernels are `|名称|语言|命令|` (ZH or EN), cells are `|单元|内核|`.
|
||||
@@ -162,6 +163,7 @@ view has no persistent kernel state.
|
||||
**p = > table.put in=`p` at="kind" value="foreign-session"**
|
||||
**p = > table.put in=`p` at="kernels" value=`kernels`**
|
||||
**p = > table.put in=`p` at="cells" value=`cells`**
|
||||
**p = > table.put in=`p` at="values" value=`values`**
|
||||
*p*
|
||||
|
||||
## session_open
|
||||
|
||||
@@ -150,6 +150,7 @@ JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回
|
||||
## 会话
|
||||
+ `内核表`=None
|
||||
+ `单元表`=None
|
||||
+ `值表`=None
|
||||
|
||||
声明文档视图会话。内核表和单元表都是普通表格;返回一个 foreign 会话句柄,
|
||||
供 view 消费。没有这个句柄时,view 的 cells 是无状态的。
|
||||
@@ -158,6 +159,7 @@ JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回
|
||||
**p = > table.put in=`p` at="kind" value="foreign-session"**
|
||||
**p = > table.put in=`p` at="kernels" value=`内核表`**
|
||||
**p = > table.put in=`p` at="cells" value=`单元表`**
|
||||
**p = > table.put in=`p` at="values" value=`值表`**
|
||||
*p*
|
||||
|
||||
## 会话开启
|
||||
|
||||
@@ -71,27 +71,23 @@ View cells share state.
|
||||
| @ | 名称 | 语言 |
|
||||
|---|------|------|
|
||||
| 1 | 分析 | python |
|
||||
| 2 | 复核 | python |
|
||||
|
||||
`分析单元` =
|
||||
|
||||
| @ | 单元 | 内核 |
|
||||
|---|------|------|
|
||||
| 1 | 准备 | 分析 |
|
||||
| 2 | 计算 | 分析 |
|
||||
| 1 | 计算 | 分析 |
|
||||
| 2 | 复核 | 复核 |
|
||||
|
||||
`会话` = > foreign.session kernels=`分析内核` cells=`分析单元`
|
||||
`初始值` =
|
||||
|
||||
`准备` =
|
||||
```python
|
||||
orders = [
|
||||
{"区域": "华东", "金额": 120},
|
||||
{"区域": "华东", "金额": 300},
|
||||
{"区域": "华南", "金额": 90},
|
||||
{"区域": "华南", "金额": 140},
|
||||
{"区域": "华北", "金额": 220},
|
||||
{"区域": "西部", "金额": 80},
|
||||
]
|
||||
```
|
||||
| 内核 | 名称 | 值 |
|
||||
|------|------|----|
|
||||
| 分析 | orders | `订单` |
|
||||
| 复核 | orders | `订单` |
|
||||
|
||||
`会话` = > foreign.session kernels=`分析内核` cells=`分析单元` values=`初始值`
|
||||
|
||||
`计算` =
|
||||
```python
|
||||
@@ -121,10 +117,21 @@ print(json.dumps({
|
||||
}, ensure_ascii=False))
|
||||
```
|
||||
|
||||
`查看` consumes the `会话` handle. Run All runs `准备` then `计算` in the same Python kernel; the static export runs the same cells at build time and embeds their real outputs.
|
||||
`复核` =
|
||||
```python
|
||||
import json
|
||||
|
||||
print(json.dumps({
|
||||
"kernel": "复核",
|
||||
"count": len(orders),
|
||||
"total": round(sum(float(row["金额"]) for row in orders), 2),
|
||||
}, ensure_ascii=False))
|
||||
```
|
||||
|
||||
`查看` consumes the `会话` handle. Run All runs `计算` in the `分析` kernel and `复核` in the `复核` kernel; the static export runs the same cells and embeds their real outputs.
|
||||
|
||||
The important language point:
|
||||
|
||||
Tables are values passed to `foreign.session`. Kernel state lives in `foreign`. View only renders the handle and its cells. `run` still executes the same document as a program.
|
||||
The `初始值` table passes the same Marqdo `订单` value into both kernels. Kernel state lives in `foreign`. View only renders the handle and its cells. `run` still executes the same document as a program.
|
||||
|
||||
There is no separate notebook CLI, no stdin requirement in this example, and no hidden language switch.
|
||||
@@ -71,27 +71,23 @@ view 单元共享状态。
|
||||
| @ | 名称 | 语言 |
|
||||
|---|------|------|
|
||||
| 1 | 分析 | python |
|
||||
| 2 | 复核 | python |
|
||||
|
||||
`分析单元` =
|
||||
|
||||
| @ | 单元 | 内核 |
|
||||
|---|------|------|
|
||||
| 1 | 准备 | 分析 |
|
||||
| 2 | 计算 | 分析 |
|
||||
| 1 | 计算 | 分析 |
|
||||
| 2 | 复核 | 复核 |
|
||||
|
||||
`会话` = > 外联.会话 内核表=`分析内核` 单元表=`分析单元`
|
||||
`初始值` =
|
||||
|
||||
`准备` =
|
||||
```python
|
||||
orders = [
|
||||
{"区域": "华东", "金额": 120},
|
||||
{"区域": "华东", "金额": 300},
|
||||
{"区域": "华南", "金额": 90},
|
||||
{"区域": "华南", "金额": 140},
|
||||
{"区域": "华北", "金额": 220},
|
||||
{"区域": "西部", "金额": 80},
|
||||
]
|
||||
```
|
||||
| 内核 | 名称 | 值 |
|
||||
|------|------|----|
|
||||
| 分析 | orders | `订单` |
|
||||
| 复核 | orders | `订单` |
|
||||
|
||||
`会话` = > 外联.会话 内核表=`分析内核` 单元表=`分析单元` 值表=`初始值`
|
||||
|
||||
`计算` =
|
||||
```python
|
||||
@@ -121,10 +117,21 @@ print(json.dumps({
|
||||
}, ensure_ascii=False))
|
||||
```
|
||||
|
||||
`查看` 消费 `会话` 句柄。Run All 会在同一个 Python 内核里先跑 `准备` 再跑 `计算`;静态导出在构建时走同一批单元,并把真实输出嵌入页面。
|
||||
`复核` =
|
||||
```python
|
||||
import json
|
||||
|
||||
print(json.dumps({
|
||||
"kernel": "复核",
|
||||
"count": len(orders),
|
||||
"total": round(sum(float(row["金额"]) for row in orders), 2),
|
||||
}, ensure_ascii=False))
|
||||
```
|
||||
|
||||
`查看` 消费 `会话` 句柄。Run All 在 `分析` 内核执行 `计算`,在 `复核` 内核执行 `复核`;静态导出走同一批单元,并把真实输出嵌入页面。
|
||||
|
||||
语言上的重点:
|
||||
|
||||
表是值,传给 `外联.会话`。内核态归 `外联` 管理。view 只渲染句柄和单元。`run` 仍然把同一份文档当程序执行。
|
||||
`初始值` 表把同一个 Marqdo `订单` 值传给两个内核。内核态归 `外联` 管理。view 只渲染句柄和单元。`run` 仍然把同一份文档当程序执行。
|
||||
|
||||
没有单独的 notebook CLI,这个示例不依赖 stdin,也没有隐藏的语言切换。
|
||||
+37
-7
@@ -165,14 +165,21 @@ fn table_rows(v: &Value) -> Result<Vec<HashMap<String, Value>>, String> {
|
||||
|
||||
fn plan_tables(
|
||||
bindings: &HashMap<String, Value>,
|
||||
) -> Result<(Option<Vec<HashMap<String, Value>>>, Option<Vec<HashMap<String, Value>>>), String> {
|
||||
) -> Result<
|
||||
(
|
||||
Option<Vec<HashMap<String, Value>>>,
|
||||
Option<Vec<HashMap<String, Value>>>,
|
||||
Option<Vec<HashMap<String, Value>>>,
|
||||
),
|
||||
String,
|
||||
> {
|
||||
let Some(plan) = bindings.get("会话") else {
|
||||
return Ok((None, None));
|
||||
return Ok((None, None, None));
|
||||
};
|
||||
let Value::Map(fields) = plan else {
|
||||
// `会话` is also a common low-level session id binding (e.g. from
|
||||
// foreign.session_open). It is not a view plan; leave cells stateless.
|
||||
return Ok((None, None));
|
||||
return Ok((None, None, None));
|
||||
};
|
||||
let field = |name: &str| {
|
||||
fields
|
||||
@@ -192,7 +199,11 @@ fn plan_tables(
|
||||
Some(Value::None) | None => None,
|
||||
Some(v) => Some(table_rows(&v)?),
|
||||
};
|
||||
Ok((kernels, cells))
|
||||
let values = match field("values") {
|
||||
Some(Value::None) | None => None,
|
||||
Some(v) => Some(table_rows(&v)?),
|
||||
};
|
||||
Ok((kernels, cells, values))
|
||||
}
|
||||
|
||||
fn col_value<'a>(row: &'a HashMap<String, Value>, names: &[&str]) -> Option<&'a Value> {
|
||||
@@ -311,7 +322,7 @@ impl DocumentSession {
|
||||
collect_cells(&entry.body, &mut cells, &mut seen)?;
|
||||
let declarations = capture_bindings(path, root, &module, &source)?;
|
||||
|
||||
let (plan_kernels, plan_cells) = plan_tables(&declarations)?;
|
||||
let (plan_kernels, plan_cells, plan_values) = plan_tables(&declarations)?;
|
||||
let persistent = matches!(
|
||||
declarations.get("会话"),
|
||||
Some(Value::Map(fields))
|
||||
@@ -411,7 +422,7 @@ impl DocumentSession {
|
||||
host.entry_path = Some(path.to_path_buf());
|
||||
host.entry_source = Some(source);
|
||||
|
||||
Ok(Self {
|
||||
let mut session = Self {
|
||||
path: path.to_path_buf(),
|
||||
root: root.to_path_buf(),
|
||||
persistent,
|
||||
@@ -425,7 +436,26 @@ impl DocumentSession {
|
||||
host,
|
||||
kernel_sessions: HashMap::new(),
|
||||
seq: 0,
|
||||
})
|
||||
};
|
||||
if let Some(rows) = plan_values {
|
||||
for row in rows {
|
||||
let kernel = col_text(&row, &["内核", "Kernel", "kernel"])
|
||||
.ok_or_else(|| "foreign.session values: missing 内核/Kernel".to_string())?;
|
||||
let name = col_text(&row, &["名称", "Name", "name"])
|
||||
.ok_or_else(|| "foreign.session values: missing 名称/Name".to_string())?;
|
||||
let value = col_value(&row, &["值", "Value", "value", "数据"])
|
||||
.ok_or_else(|| format!("foreign.session values[{name}]: missing 值/Value"))?
|
||||
.clone();
|
||||
let id = session.ensure_kernel_session(&kernel)?;
|
||||
foreign_session::set(
|
||||
&mut session.host,
|
||||
&Value::Text(id),
|
||||
&Value::Text(name),
|
||||
&value,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Re-read the document, preserving kernels/state/journal. Changed cells become dirty.
|
||||
|
||||
+36
-4
@@ -3692,6 +3692,34 @@ body.notebook-page .stdin-form button {
|
||||
});
|
||||
});
|
||||
}
|
||||
function renderStaticSummary(s) {
|
||||
if (!s) return;
|
||||
state.persistent = !!s.persistent;
|
||||
state.kernels = s.kernels || [];
|
||||
state.cells = {};
|
||||
(s.cells || []).forEach(function (c) { state.cells[c.name] = c; });
|
||||
(s.cells || []).forEach(function (c) {
|
||||
var el = card(c.name);
|
||||
if (!el) return;
|
||||
badge(el, c.status, c.status === "clean");
|
||||
if (!state.persistent) {
|
||||
ensureKernel(el, false);
|
||||
return;
|
||||
}
|
||||
var sel = ensureKernel(el, true);
|
||||
var opts = state.kernels.filter(function (k) { return k.lang === c.lang; }).map(function (k) { return k.name; });
|
||||
if (!opts.length) opts = [c.kernel];
|
||||
sel.innerHTML = "";
|
||||
opts.forEach(function (n) {
|
||||
var o = document.createElement("option");
|
||||
o.value = n; o.textContent = n;
|
||||
if (n === c.kernel) o.selected = true;
|
||||
sel.appendChild(o);
|
||||
});
|
||||
sel.disabled = true;
|
||||
sel.title = "Static export: kernel fixed to " + c.kernel;
|
||||
});
|
||||
}
|
||||
function openSession() {
|
||||
var bar = document.getElementById("notebook-bar");
|
||||
if (bar) bar.hidden = false;
|
||||
@@ -3804,10 +3832,14 @@ body.notebook-page .stdin-form button {
|
||||
staticNotice();
|
||||
});
|
||||
});
|
||||
document.querySelectorAll(".code-card").forEach(function (el) {
|
||||
ensureKernel(el, false);
|
||||
bindClean(el);
|
||||
});
|
||||
if (window.MARQDO_STATIC_SESSION) {
|
||||
renderStaticSummary(window.MARQDO_STATIC_SESSION);
|
||||
} else {
|
||||
document.querySelectorAll(".code-card").forEach(function (el) {
|
||||
ensureKernel(el, false);
|
||||
});
|
||||
}
|
||||
document.querySelectorAll(".code-card").forEach(bindClean);
|
||||
status("static export · preview only");
|
||||
return;
|
||||
}
|
||||
|
||||
+41
-18
@@ -50,18 +50,18 @@ fn record_field(record: &Value, key: &str) -> Option<Value> {
|
||||
|
||||
/// 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(
|
||||
fn static_page_data(
|
||||
root: &ViewRoot,
|
||||
abs: &std::path::Path,
|
||||
stdin: &str,
|
||||
) -> HashMap<String, StaticCellOutput> {
|
||||
) -> (HashMap<String, StaticCellOutput>, Option<Value>) {
|
||||
let mut out = HashMap::new();
|
||||
let Ok(mut session) = DocumentSession::open(abs, &root.root) else {
|
||||
return out;
|
||||
return (out, None);
|
||||
};
|
||||
let Ok(summary) = session.run_all_with_stdin(false, Some(stdin)) else {
|
||||
session.close();
|
||||
return out;
|
||||
return (out, None);
|
||||
};
|
||||
let records = match &summary {
|
||||
Value::Map(entries) => entries
|
||||
@@ -123,8 +123,9 @@ fn static_cell_outputs(
|
||||
out.insert(cell, StaticCellOutput { ok, text });
|
||||
}
|
||||
}
|
||||
let view_summary = session.summary();
|
||||
session.close();
|
||||
out
|
||||
(out, Some(view_summary))
|
||||
}
|
||||
|
||||
/// Inject static cell outputs into code cards without running client JS.
|
||||
@@ -153,6 +154,22 @@ fn inject_cell_outputs(html: &str, outputs: &HashMap<String, StaticCellOutput>)
|
||||
html
|
||||
}
|
||||
|
||||
fn inject_static_session(html: &str, summary: Option<&Value>) -> String {
|
||||
let Some(summary) = summary else {
|
||||
return html.to_string();
|
||||
};
|
||||
let Ok(json) = crate::host::json::value_to_json(summary) else {
|
||||
return html.to_string();
|
||||
};
|
||||
let Ok(json) = serde_json::to_string(&json) else {
|
||||
return html.to_string();
|
||||
};
|
||||
let line = format!(
|
||||
"window.MARQDO_VIEW_LIVE = false;\nwindow.MARQDO_STATIC_SESSION = {json};"
|
||||
);
|
||||
html.replace("window.MARQDO_VIEW_LIVE = false;", &line)
|
||||
}
|
||||
|
||||
pub fn write_static(opts: OutputOptions) -> Result<()> {
|
||||
let root = build_root(&opts.path)?;
|
||||
fs::create_dir_all(&opts.out_dir)
|
||||
@@ -187,14 +204,17 @@ pub fn write_static(opts: OutputOptions) -> Result<()> {
|
||||
let links = LinkMode::Static {
|
||||
from: Some(rel.clone()),
|
||||
};
|
||||
let cell_outputs = if opts.no_exec {
|
||||
HashMap::new()
|
||||
let (cell_outputs, static_summary) = if opts.no_exec {
|
||||
(HashMap::new(), None)
|
||||
} else {
|
||||
static_cell_outputs(&root, &abs, &vm.preset_stdin)
|
||||
static_page_data(&root, &abs, &vm.preset_stdin)
|
||||
};
|
||||
let html = inject_cell_outputs(
|
||||
&page_file(&root.files, &rel, &vm, &links),
|
||||
&cell_outputs,
|
||||
let html = inject_static_session(
|
||||
&inject_cell_outputs(
|
||||
&page_file(&root.files, &rel, &vm, &links),
|
||||
&cell_outputs,
|
||||
),
|
||||
static_summary.as_ref(),
|
||||
);
|
||||
let out_file = pages_root.join(format!("{rel}.html"));
|
||||
if let Some(parent) = out_file.parent() {
|
||||
@@ -204,14 +224,17 @@ 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(inject_cell_outputs(
|
||||
&page_file(
|
||||
&root.files,
|
||||
&rel,
|
||||
&vm,
|
||||
&LinkMode::Static { from: None },
|
||||
first_page_html = Some(inject_static_session(
|
||||
&inject_cell_outputs(
|
||||
&page_file(
|
||||
&root.files,
|
||||
&rel,
|
||||
&vm,
|
||||
&LinkMode::Static { from: None },
|
||||
),
|
||||
&cell_outputs,
|
||||
),
|
||||
&cell_outputs,
|
||||
static_summary.as_ref(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user