feat(writeback): image form  with view parity
Auto-persist image paths/URLs as Markdown images (validated extension); keep HTML comment for text. View and static export share styled source markers and output-card <img> rendering. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
9cf98a98b5
commit
f47a1e143a
8 files changed
+454
-52
No files matched your search
@@ -8,9 +8,11 @@
|
|||||||
|
|
||||||
## 定位
|
## 定位
|
||||||
|
|
||||||
**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` 的 `<!-- marqdo-out … -->` → `marqdo view` 在对应语句下显示 **output-card**。普通 Markdown 预览不显示该区域。
|
**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` → `marqdo view`(及静态 `view output`)在对应语句下显示 **output-card**,并在源码面用 **writeback** 样式标出块本身。
|
||||||
|
|
||||||
## 存储格式
|
## 存储格式(两种,可并存)
|
||||||
|
|
||||||
|
### 1. HTML 注释(文本 / 结构化输出)
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
*`n` = > len value=`xs` *
|
*`n` = > len value=`xs` *
|
||||||
@@ -30,11 +32,26 @@ pending
|
|||||||
-->
|
-->
|
||||||
```
|
```
|
||||||
|
|
||||||
- 注释内为 `marqdo-out`,可选后跟槽名(`ok` / `error` 等),**不存行号**
|
### 2. Markdown 图片(生成图 / 审计友好)
|
||||||
|
|
||||||
|
当 `value` **看起来像图片引用**(扩展名 `.png` / `.jpg` / `.jpeg` / `.gif` / `.webp` / `.svg` / …,或 `data:image/…`)时,`record` **自动**写成:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|

|
||||||
|

|
||||||
|
```
|
||||||
|
|
||||||
|
- 普通 Markdown 预览即可看见图;view / 静态站额外加 writeback 标记与 output-card 中的 `<img>`。
|
||||||
|
- 非图片路径仍走注释块;把非图片硬写成 `` 时扫描会忽略(校验失败)。
|
||||||
|
- `list` / `scan_path` 结果带 `kind`: `comment` | `image`。
|
||||||
|
|
||||||
|
### 共用规则
|
||||||
|
|
||||||
|
- 标记字为 `marqdo-out`,可选后跟槽名(`ok` / `error` 等),**不存行号**
|
||||||
- 默认在**调用行下方**插入或替换紧邻**无键**块
|
- 默认在**调用行下方**插入或替换紧邻**无键**块
|
||||||
- `at_end=true`:替换文件末尾的**无键**块
|
- `at_end=true`:替换文件末尾的**无键**块
|
||||||
- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽(智能体单步用父调用行,即 `step` 语句下方);`ensure` 在缺失时写入占位且不覆盖已有正文。命名槽互不覆盖,也不使用文件末尾单块。
|
- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽;`ensure` 在缺失时写入占位且不覆盖已有正文
|
||||||
- `line=` / `行=`:显式锚点行号。子任务 / 异步写回必须带上,否则会锚到子任务内部调用行。主机侧有全局互斥锁,写前从磁盘重读入口源,避免并发写互相覆盖。
|
- `line=` / `行=`:显式锚点行号;主机侧有全局互斥锁
|
||||||
|
|
||||||
### 替换跨度与空行
|
### 替换跨度与空行
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -11,7 +11,7 @@ Persist run output in .mq.md (Jupyter-style writeback)
|
|||||||
+ `key`=None
|
+ `key`=None
|
||||||
+ `line`=None
|
+ `line`=None
|
||||||
|
|
||||||
Write `value` to `<!-- marqdo-out … -->` in the entry file. Default: insert or replace the block immediately below the call; `at_end=true` replaces the unkeyed EOF block. With `key=` (e.g. `ok` / `error`), replace or create that named slot only — slots do not overwrite each other. Optional `line=` anchors the block under that source line (needed when writing from a subtask).
|
Write `value` into the entry file. Image-like values (`.png` / `.svg` / … or `data:image/…`) become `` (or ``); other values use `<!-- marqdo-out … -->`. Default: insert or replace the block immediately below the call; `at_end=true` replaces the unkeyed EOF block. With `key=` (e.g. `ok` / `error`), replace or create that named slot only — slots do not overwrite each other. Optional `line=` anchors the block under that source line (needed when writing from a subtask).
|
||||||
|
|
||||||
*> host_writeback_record value=`value` at_end=`at_end` key=`key` line=`line`*
|
*> host_writeback_record value=`value` at_end=`at_end` key=`key` line=`line`*
|
||||||
|
|
||||||
@@ -51,6 +51,6 @@ List all output blocks in the entry file (includes `key` when named).
|
|||||||
## scan_path
|
## scan_path
|
||||||
+ `path`
|
+ `path`
|
||||||
|
|
||||||
List `<!-- marqdo-out … -->` slots in any file (workbook inspection).
|
List writeback slots in any file (HTML comment and `` image forms; workbook inspection).
|
||||||
|
|
||||||
*> host_writeback_scan_path path=`path`*
|
*> host_writeback_scan_path path=`path`*
|
||||||
+2
-2
@@ -11,7 +11,7 @@ description: 将运行结果写回 .mq.md(Jupyter 式自写回)
|
|||||||
+ `键`=None
|
+ `键`=None
|
||||||
+ `行`=None
|
+ `行`=None
|
||||||
|
|
||||||
在入口文件中写入 `<!-- marqdo-out … -->`。默认在调用行下方插入或替换;`末尾=true` 时替换无键末尾块。带 `键=`(如 `ok` / `error` / `成功` / `失败`)时只更新该命名槽,互不覆盖。可选 `行=` 锚定到指定源码行(子任务写回时需要)。
|
在入口文件中写入自写回块:若 `值` 像图片路径/URL(`.png` / `.svg` / … 或 `data:image/…`)则写成 ``,否则写成 `<!-- marqdo-out … -->`。默认在调用行下方插入或替换;`末尾=true` 时替换无键末尾块。带 `键=`(如 `ok` / `error` / `成功` / `失败`)时只更新该命名槽,互不覆盖。可选 `行=` 锚定到指定源码行(子任务写回时需要)。
|
||||||
|
|
||||||
*> host_writeback_record value=`值` at_end=`末尾` key=`键` line=`行`*
|
*> host_writeback_record value=`值` at_end=`末尾` key=`键` line=`行`*
|
||||||
|
|
||||||
@@ -51,6 +51,6 @@ description: 将运行结果写回 .mq.md(Jupyter 式自写回)
|
|||||||
## 扫描路径
|
## 扫描路径
|
||||||
+ `路径`
|
+ `路径`
|
||||||
|
|
||||||
扫描任意文件中的 `<!-- marqdo-out … -->` 槽(工作簿观察)。
|
扫描任意文件中的自写回槽(注释块与 `` 图片;工作簿观察)。
|
||||||
|
|
||||||
*> host_writeback_scan_path path=`路径`*
|
*> host_writeback_scan_path path=`路径`*
|
||||||
+244
-26
@@ -1,7 +1,11 @@
|
|||||||
//! Jupyter-style output persistence in `.mq.md` (`<!-- marqdo-out … -->`).
|
//! Jupyter-style output persistence in `.mq.md`.
|
||||||
//!
|
//!
|
||||||
//! Optional **named slots**: `<!-- marqdo-out ok -->` / `<!-- marqdo-out error -->`
|
//! Two surface forms (both scanned / replaced):
|
||||||
//! so success and failure results do not overwrite each other.
|
//! - HTML comment: `<!-- marqdo-out … -->` (text / structured output)
|
||||||
|
//! - Markdown image: `` (image refs; validated)
|
||||||
|
//!
|
||||||
|
//! Optional **named slots**: `marqdo-out ok` / `marqdo-out error` so success and
|
||||||
|
//! failure results do not overwrite each other.
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
@@ -14,14 +18,30 @@ const MAGIC: &str = "marqdo-out";
|
|||||||
/// Serialize all writeback file mutations (sync + subtask writers).
|
/// Serialize all writeback file mutations (sync + subtask writers).
|
||||||
static WRITEBACK_LOCK: Mutex<()> = Mutex::new(());
|
static WRITEBACK_LOCK: Mutex<()> = Mutex::new(());
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum BlockKind {
|
||||||
|
Comment,
|
||||||
|
Image,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
struct BlockSpan {
|
struct BlockSpan {
|
||||||
start: usize,
|
start: usize,
|
||||||
end: usize,
|
end: usize,
|
||||||
|
/// Comment body text, or image URL/path for [`BlockKind::Image`].
|
||||||
body: String,
|
body: String,
|
||||||
start_line: u32,
|
start_line: u32,
|
||||||
/// Named slot from header (`marqdo-out ok` → `ok`); `None` = legacy unkeyed.
|
/// Named slot from header (`marqdo-out ok` → `ok`); `None` = legacy unkeyed.
|
||||||
key: Option<String>,
|
key: Option<String>,
|
||||||
|
kind: BlockKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// View-facing writeback piece under a statement line.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct WritebackEntry {
|
||||||
|
pub key: Option<String>,
|
||||||
|
pub body: String,
|
||||||
|
pub is_image: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn display_value(v: &Value) -> String {
|
fn display_value(v: &Value) -> String {
|
||||||
@@ -119,13 +139,71 @@ fn line_number_at(source: &str, byte: usize) -> u32 {
|
|||||||
+ 1
|
+ 1
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_block(body: &str, key: Option<&str>) -> String {
|
fn format_comment_block(body: &str, key: Option<&str>) -> String {
|
||||||
match key {
|
match key {
|
||||||
Some(k) => format!("<!-- {MAGIC} {k}\n{body}\n-->"),
|
Some(k) => format!("<!-- {MAGIC} {k}\n{body}\n-->"),
|
||||||
None => format!("<!-- {MAGIC}\n{body}\n-->"),
|
None => format!("<!-- {MAGIC}\n{body}\n-->"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn format_image_block(url: &str, key: Option<&str>) -> String {
|
||||||
|
match key {
|
||||||
|
Some(k) => format!(""),
|
||||||
|
None => format!(""),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn format_block_for_value(body: &str, key: Option<&str>) -> Result<String, String> {
|
||||||
|
if looks_like_image_ref(body) {
|
||||||
|
validate_image_ref(body)?;
|
||||||
|
Ok(format_image_block(body.trim(), key))
|
||||||
|
} else {
|
||||||
|
Ok(format_comment_block(body, key))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when `s` looks like a path/URL that should persist as ``.
|
||||||
|
pub fn looks_like_image_ref(s: &str) -> bool {
|
||||||
|
validate_image_ref(s).is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accept local/relative paths and http(s) URLs with a known image extension,
|
||||||
|
/// or `data:image/…` URIs.
|
||||||
|
pub fn validate_image_ref(s: &str) -> Result<(), String> {
|
||||||
|
let t = s.trim().trim_matches('"').trim_matches('\'');
|
||||||
|
if t.is_empty() {
|
||||||
|
return Err("writeback image: empty path".into());
|
||||||
|
}
|
||||||
|
if t.starts_with("data:image/") {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
// Strip query/fragment for extension check.
|
||||||
|
let no_query = t.split_once('?').map(|(p, _)| p).unwrap_or(t);
|
||||||
|
let path_part = no_query.split_once('#').map(|(p, _)| p).unwrap_or(no_query);
|
||||||
|
let file = path_part.rsplit('/').next().unwrap_or(path_part);
|
||||||
|
// Require a real extension (reject bare names like `svg` / `png`).
|
||||||
|
let Some((stem, ext)) = file.rsplit_once('.') else {
|
||||||
|
return Err(format!(
|
||||||
|
"writeback image: path needs an image extension (got `{t}`)"
|
||||||
|
));
|
||||||
|
};
|
||||||
|
if stem.is_empty() {
|
||||||
|
return Err(format!("writeback image: invalid file name `{t}`"));
|
||||||
|
}
|
||||||
|
let ext = ext.to_ascii_lowercase();
|
||||||
|
const OK: &[&str] = &[
|
||||||
|
"png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "avif", "tif", "tiff",
|
||||||
|
];
|
||||||
|
if OK.contains(&ext.as_str()) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(format!(
|
||||||
|
"writeback image: not an image path/URL (got `{t}`; need .{})",
|
||||||
|
OK.join("/.")
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn parse_header_key(header: &str) -> Option<String> {
|
fn parse_header_key(header: &str) -> Option<String> {
|
||||||
let mut parts = header.split_whitespace();
|
let mut parts = header.split_whitespace();
|
||||||
let first = parts.next()?;
|
let first = parts.next()?;
|
||||||
@@ -160,11 +238,43 @@ fn parse_one_block(block: &str, start_byte: usize, source: &str) -> Option<Block
|
|||||||
body,
|
body,
|
||||||
start_line: line_number_at(source, start_byte),
|
start_line: line_number_at(source, start_byte),
|
||||||
key,
|
key,
|
||||||
|
kind: BlockKind::Comment,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `` on a single source line.
|
||||||
|
fn parse_image_line(line: &str, line_start: usize, source: &str) -> Option<BlockSpan> {
|
||||||
|
let trimmed = line.trim();
|
||||||
|
let rest = trimmed.strip_prefix("?;
|
||||||
|
let alt = rest[..alt_end].trim();
|
||||||
|
if !alt.split_whitespace().any(|t| t == MAGIC) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let key = parse_header_key(alt);
|
||||||
|
let after_alt = &rest[alt_end + 2..];
|
||||||
|
let url_end = after_alt.rfind(')')?;
|
||||||
|
let url = after_alt[..url_end].trim();
|
||||||
|
if url.is_empty() || validate_image_ref(url).is_err() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
// Span covers the trimmed image on its line (indent kept outside).
|
||||||
|
let trim_start = line.find(trimmed).unwrap_or(0);
|
||||||
|
let start = line_start + trim_start;
|
||||||
|
let end = start + trimmed.len();
|
||||||
|
Some(BlockSpan {
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
body: url.to_string(),
|
||||||
|
start_line: line_number_at(source, start),
|
||||||
|
key,
|
||||||
|
kind: BlockKind::Image,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn scan_blocks(source: &str) -> Vec<BlockSpan> {
|
fn scan_blocks(source: &str) -> Vec<BlockSpan> {
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
|
// HTML comment blocks
|
||||||
let mut i = 0usize;
|
let mut i = 0usize;
|
||||||
while i < source.len() {
|
while i < source.len() {
|
||||||
let rest = &source[i..];
|
let rest = &source[i..];
|
||||||
@@ -186,6 +296,16 @@ fn scan_blocks(source: &str) -> Vec<BlockSpan> {
|
|||||||
}
|
}
|
||||||
i = abs + end_rel + 3;
|
i = abs + end_rel + 3;
|
||||||
}
|
}
|
||||||
|
// Image writebacks (line-oriented)
|
||||||
|
let mut line_start = 0usize;
|
||||||
|
for line in source.split_inclusive('\n') {
|
||||||
|
let content = line.trim_end_matches(['\r', '\n']);
|
||||||
|
if let Some(b) = parse_image_line(content, line_start, source) {
|
||||||
|
out.push(b);
|
||||||
|
}
|
||||||
|
line_start += line.len();
|
||||||
|
}
|
||||||
|
out.sort_by_key(|b| b.start);
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -323,7 +443,7 @@ fn find_keyed_in_cluster(source: &str, after_line: u32, key: &str) -> Option<Blo
|
|||||||
/// Replace keyed block under `anchor` line, or insert into that cluster (not EOF).
|
/// Replace keyed block under `anchor` line, or insert into that cluster (not EOF).
|
||||||
fn replace_or_insert_keyed_at(source: &str, anchor: u32, key: &str, body: &str) -> Result<String, String> {
|
fn replace_or_insert_keyed_at(source: &str, anchor: u32, key: &str, body: &str) -> Result<String, String> {
|
||||||
let key = normalize_slot_key(key);
|
let key = normalize_slot_key(key);
|
||||||
let block = format_block(body, Some(&key));
|
let block = format_block_for_value(body, Some(&key))?;
|
||||||
if let Some(existing) = find_keyed_in_cluster(source, anchor, &key) {
|
if let Some(existing) = find_keyed_in_cluster(source, anchor, &key) {
|
||||||
return Ok(splice_block(source, existing.start, existing.end, &block));
|
return Ok(splice_block(source, existing.start, existing.end, &block));
|
||||||
}
|
}
|
||||||
@@ -438,13 +558,13 @@ pub fn record(
|
|||||||
let stripped = find_eof_block(&source)
|
let stripped = find_eof_block(&source)
|
||||||
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
|
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
|
||||||
.unwrap_or_else(|| source.clone());
|
.unwrap_or_else(|| source.clone());
|
||||||
append_eof(&stripped, &format_block(&body, None))
|
append_eof(&stripped, &format_block_for_value(&body, None)?)
|
||||||
} else {
|
} else {
|
||||||
let line = anchor.ok_or_else(|| "writeback: missing anchor line".to_string())?;
|
let line = anchor.ok_or_else(|| "writeback: missing anchor line".to_string())?;
|
||||||
let stripped = find_adjacent_block(&source, line)
|
let stripped = find_adjacent_block(&source, line)
|
||||||
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
|
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
|
||||||
.unwrap_or_else(|| source.clone());
|
.unwrap_or_else(|| source.clone());
|
||||||
insert_after_line(&stripped, line, &format_block(&body, None))?
|
insert_after_line(&stripped, line, &format_block_for_value(&body, None)?)?
|
||||||
};
|
};
|
||||||
persist(ctx, &next)?;
|
persist(ctx, &next)?;
|
||||||
Ok(Value::Text(body.clone()))
|
Ok(Value::Text(body.clone()))
|
||||||
@@ -549,10 +669,15 @@ fn slots_from_source(source: &str) -> Value {
|
|||||||
.map(|b| {
|
.map(|b| {
|
||||||
let anchor = anchor_line_above(source, b.start_line);
|
let anchor = anchor_line_above(source, b.start_line);
|
||||||
let at_eof = b.key.is_none() && is_eof_block(source, &b);
|
let at_eof = b.key.is_none() && is_eof_block(source, &b);
|
||||||
|
let kind = match b.kind {
|
||||||
|
BlockKind::Comment => "comment",
|
||||||
|
BlockKind::Image => "image",
|
||||||
|
};
|
||||||
let mut entries = vec![
|
let mut entries = vec![
|
||||||
("line".into(), Value::Int(anchor as i64)),
|
("line".into(), Value::Int(anchor as i64)),
|
||||||
("body".into(), Value::Text(b.body)),
|
("body".into(), Value::Text(b.body)),
|
||||||
("at_end".into(), Value::Bool(at_eof)),
|
("at_end".into(), Value::Bool(at_eof)),
|
||||||
|
("kind".into(), Value::Text(kind.into())),
|
||||||
];
|
];
|
||||||
if let Some(k) = b.key {
|
if let Some(k) = b.key {
|
||||||
entries.push(("key".into(), Value::Text(k)));
|
entries.push(("key".into(), Value::Text(k)));
|
||||||
@@ -584,29 +709,49 @@ pub fn ensure_slot(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Map statement line → body for adjacent blocks (keyed slots included under their anchor).
|
/// Structured writebacks keyed by the statement line above the block cluster.
|
||||||
pub fn writeback_map(source: &str) -> HashMap<u32, String> {
|
pub fn writeback_entries(source: &str) -> HashMap<u32, Vec<WritebackEntry>> {
|
||||||
let mut map = HashMap::new();
|
let mut map: HashMap<u32, Vec<WritebackEntry>> = HashMap::new();
|
||||||
for b in scan_blocks(source) {
|
for b in scan_blocks(source) {
|
||||||
let anchor = anchor_line_above(source, b.start_line);
|
let anchor = if b.key.is_none() && is_eof_block(source, &b) {
|
||||||
let piece = match &b.key {
|
0
|
||||||
Some(k) => format!("[{k}]\n{}", b.body),
|
|
||||||
None => b.body.clone(),
|
|
||||||
};
|
|
||||||
if b.key.is_none() && is_eof_block(source, &b) {
|
|
||||||
map.insert(0, piece);
|
|
||||||
} else {
|
} else {
|
||||||
map.entry(anchor)
|
anchor_line_above(source, b.start_line)
|
||||||
.and_modify(|e| {
|
};
|
||||||
e.push_str("\n\n");
|
let entry = WritebackEntry {
|
||||||
e.push_str(&piece);
|
key: b.key.clone(),
|
||||||
})
|
body: b.body.clone(),
|
||||||
.or_insert(piece);
|
is_image: b.kind == BlockKind::Image,
|
||||||
}
|
};
|
||||||
|
map.entry(anchor).or_default().push(entry);
|
||||||
}
|
}
|
||||||
map
|
map
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Map statement line → combined body for adjacent blocks (keyed slots included).
|
||||||
|
/// Image slots are encoded as a markdown image line so view/static can render `<img>`.
|
||||||
|
pub fn writeback_map(source: &str) -> HashMap<u32, String> {
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
for (anchor, entries) in writeback_entries(source) {
|
||||||
|
let mut pieces = Vec::new();
|
||||||
|
for e in entries {
|
||||||
|
let content = if e.is_image {
|
||||||
|
format!("", e.body)
|
||||||
|
} else {
|
||||||
|
e.body
|
||||||
|
};
|
||||||
|
let piece = match &e.key {
|
||||||
|
Some(k) => format!("[{k}]\n{content}"),
|
||||||
|
None => content,
|
||||||
|
};
|
||||||
|
pieces.push(piece);
|
||||||
|
}
|
||||||
|
map.insert(anchor, pieces.join("\n\n"));
|
||||||
|
}
|
||||||
|
map
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -614,7 +759,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn parse_and_insert_adjacent() {
|
fn parse_and_insert_adjacent() {
|
||||||
let src = "# main\n\n**x = 1**\n";
|
let src = "# main\n\n**x = 1**\n";
|
||||||
let block = format_block("1", None);
|
let block = format_comment_block("1", None);
|
||||||
let next = insert_after_line(src, 3, &block).unwrap();
|
let next = insert_after_line(src, 3, &block).unwrap();
|
||||||
assert!(next.contains("marqdo-out"));
|
assert!(next.contains("marqdo-out"));
|
||||||
assert!(!next.contains("@line"));
|
assert!(!next.contains("@line"));
|
||||||
@@ -625,6 +770,79 @@ mod tests {
|
|||||||
assert!(!replaced.contains("marqdo-out"));
|
assert!(!replaced.contains("marqdo-out"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn image_writeback_scan_and_format() {
|
||||||
|
assert!(looks_like_image_ref("plot.svg"));
|
||||||
|
assert!(looks_like_image_ref("https://ex.com/a.PNG"));
|
||||||
|
assert!(looks_like_image_ref("data:image/png;base64,xx"));
|
||||||
|
assert!(looks_like_image_ref("plots/a.svg?v=1"));
|
||||||
|
assert!(!looks_like_image_ref("readme.txt"));
|
||||||
|
assert!(!looks_like_image_ref("42"));
|
||||||
|
assert!(!looks_like_image_ref("svg")); // bare name, not an extension
|
||||||
|
assert!(!looks_like_image_ref(".svg"));
|
||||||
|
let block = format_image_block("out/plot.svg", Some("ok"));
|
||||||
|
assert_eq!(block, "");
|
||||||
|
let src = "# main\n\n**x = 1**\n\n\n> print text=tail\n";
|
||||||
|
let blocks = scan_blocks(src);
|
||||||
|
assert_eq!(blocks.len(), 1);
|
||||||
|
assert_eq!(blocks[0].kind, BlockKind::Image);
|
||||||
|
assert_eq!(blocks[0].body, "out/plot.svg");
|
||||||
|
assert_eq!(blocks[0].key.as_deref(), Some("ok"));
|
||||||
|
let map = writeback_map(src);
|
||||||
|
assert_eq!(
|
||||||
|
map.get(&3).map(|s| s.as_str()),
|
||||||
|
Some("[ok]\n")
|
||||||
|
);
|
||||||
|
// Invalid image URL in marqdo-out alt → not a writeback slot
|
||||||
|
let bad = "# main\n\n\n";
|
||||||
|
assert!(scan_blocks(bad).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unkeyed_comment_and_image_replace_each_other() {
|
||||||
|
let src = "# main\n\n**x = 1**\n<!-- marqdo-out\nold\n-->\n\n> print text=tail\n";
|
||||||
|
let line = 3u32;
|
||||||
|
let to_image = {
|
||||||
|
let stripped = find_adjacent_block(src, line)
|
||||||
|
.map(|b| strip_span(src, b.start, span_end_including_nl(src, b.end)))
|
||||||
|
.unwrap_or_else(|| src.to_string());
|
||||||
|
insert_after_line(
|
||||||
|
&stripped,
|
||||||
|
line,
|
||||||
|
&format_block_for_value("fig.svg", None).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
assert!(to_image.contains(""));
|
||||||
|
assert!(!to_image.contains("<!-- marqdo-out"));
|
||||||
|
let blocks = scan_blocks(&to_image);
|
||||||
|
assert_eq!(blocks.len(), 1);
|
||||||
|
assert_eq!(blocks[0].kind, BlockKind::Image);
|
||||||
|
|
||||||
|
let to_text = {
|
||||||
|
let stripped = find_adjacent_block(&to_image, line)
|
||||||
|
.map(|b| strip_span(&to_image, b.start, span_end_including_nl(&to_image, b.end)))
|
||||||
|
.unwrap_or_else(|| to_image.clone());
|
||||||
|
insert_after_line(
|
||||||
|
&stripped,
|
||||||
|
line,
|
||||||
|
&format_block_for_value("hello", None).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
assert!(to_text.contains("<!-- marqdo-out\nhello\n-->"));
|
||||||
|
assert!(!to_text.contains("![marqdo-out]"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn record_format_picks_image_for_svg_path() {
|
||||||
|
let s = format_block_for_value("figs/a.svg", None).unwrap();
|
||||||
|
assert_eq!(s, "");
|
||||||
|
let t = format_block_for_value("hello", None).unwrap();
|
||||||
|
assert!(t.contains("<!-- marqdo-out"));
|
||||||
|
assert!(format_block_for_value("notes.txt", None).unwrap().contains("<!--"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn writeback_map_uses_line_above() {
|
fn writeback_map_uses_line_above() {
|
||||||
let src = "# main\n\n**x = 1**\n<!-- marqdo-out\n42\n-->\n\n> print text=tail\n";
|
let src = "# main\n\n**x = 1**\n<!-- marqdo-out\n42\n-->\n\n> print text=tail\n";
|
||||||
@@ -671,7 +889,7 @@ mod tests {
|
|||||||
let stripped = find_adjacent_block(s, line)
|
let stripped = find_adjacent_block(s, line)
|
||||||
.map(|b| strip_span(s, b.start, span_end_including_nl(s, b.end)))
|
.map(|b| strip_span(s, b.start, span_end_including_nl(s, b.end)))
|
||||||
.unwrap_or_else(|| s.to_string());
|
.unwrap_or_else(|| s.to_string());
|
||||||
insert_after_line(&stripped, line, &format_block(body, None)).unwrap()
|
insert_after_line(&stripped, line, &format_comment_block(body, None)).unwrap()
|
||||||
};
|
};
|
||||||
let once = strip_insert(src, "a");
|
let once = strip_insert(src, "a");
|
||||||
let twice = strip_insert(&once, "b");
|
let twice = strip_insert(&once, "b");
|
||||||
|
|||||||
@@ -292,9 +292,25 @@ fn breaks_comment_paragraph(trimmed: &str) -> bool {
|
|||||||
if trimmed.starts_with('+') {
|
if trimmed.starts_with('+') {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
if is_image_writeback_line(trimmed) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `` — image writeback surface (see stdlib-writeback).
|
||||||
|
pub fn is_image_writeback_line(trimmed: &str) -> bool {
|
||||||
|
let t = trimmed.trim();
|
||||||
|
let Some(rest) = t.strip_prefix(" else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let alt = rest[..alt_end].trim();
|
||||||
|
alt.split_whitespace().any(|tok| tok == "marqdo-out")
|
||||||
|
}
|
||||||
|
|
||||||
fn looks_like_ordered_list_item(trimmed: &str) -> bool {
|
fn looks_like_ordered_list_item(trimmed: &str) -> bool {
|
||||||
let mut chars = trimmed.chars();
|
let mut chars = trimmed.chars();
|
||||||
let mut saw_digit = false;
|
let mut saw_digit = false;
|
||||||
@@ -382,6 +398,9 @@ pub fn classify_source(source: &str) -> Vec<ClassifiedLine> {
|
|||||||
in_writeback = false;
|
in_writeback = false;
|
||||||
}
|
}
|
||||||
LineKind::Writeback
|
LineKind::Writeback
|
||||||
|
} else if is_image_writeback_line(trimmed) {
|
||||||
|
in_comment_paragraph = false;
|
||||||
|
LineKind::Writeback
|
||||||
} else {
|
} else {
|
||||||
match base {
|
match base {
|
||||||
LineKind::Blank => {
|
LineKind::Blank => {
|
||||||
@@ -547,6 +566,17 @@ mod tests {
|
|||||||
assert_eq!(lines[3].kind, LineKind::Writeback);
|
assert_eq!(lines[3].kind, LineKind::Writeback);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn image_writeback_line_classified() {
|
||||||
|
assert!(is_image_writeback_line(""));
|
||||||
|
assert!(is_image_writeback_line(""));
|
||||||
|
assert!(!is_image_writeback_line(""));
|
||||||
|
let src = "# main\n\n**x = 1**\n\n\n> print text=x\n";
|
||||||
|
let lines = classify_source(src);
|
||||||
|
let img = lines.iter().find(|l| l.text.contains("marqdo-out]")).unwrap();
|
||||||
|
assert_eq!(img.kind, LineKind::Writeback, "{:?}", lines);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn paragraph_comment_keeps_backtick_continuation() {
|
fn paragraph_comment_keeps_backtick_continuation() {
|
||||||
let src = "采用了\n`.mq.md`的双层后缀\n\n> print text=ok\n";
|
let src = "采用了\n`.mq.md`的双层后缀\n\n> print text=ok\n";
|
||||||
|
|||||||
+6
-10
@@ -101,6 +101,10 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
|
|||||||
}
|
}
|
||||||
LineKind::Writeback => {
|
LineKind::Writeback => {
|
||||||
flush_para(&mut para, &mut out);
|
flush_para(&mut para, &mut out);
|
||||||
|
out.push_str(&crate::view::render::render_writeback_source_line(
|
||||||
|
l.line_no,
|
||||||
|
l.text.trim_end_matches(['\r', '\n']),
|
||||||
|
));
|
||||||
i += 1;
|
i += 1;
|
||||||
}
|
}
|
||||||
LineKind::Comment => {
|
LineKind::Comment => {
|
||||||
@@ -313,11 +317,7 @@ fn render_table_block(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(body) = writebacks.get(&first_line) {
|
if let Some(body) = writebacks.get(&first_line) {
|
||||||
html.push_str(&format!(
|
html.push_str(&crate::view::render::render_output_card(first_line, body));
|
||||||
r#"<div class="card output-card" id="wb-{line}"><pre class="output-body">{}</pre></div>"#,
|
|
||||||
escape(body),
|
|
||||||
line = first_line
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
html.push_str("</div>");
|
html.push_str("</div>");
|
||||||
(html, i)
|
(html, i)
|
||||||
@@ -746,11 +746,7 @@ fn render_line_block(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(body) = writeback_body {
|
if let Some(body) = writeback_body {
|
||||||
s.push_str(&format!(
|
s.push_str(&crate::view::render::render_output_card(line_no, body));
|
||||||
r#"<div class="card output-card" id="wb-{line}"><pre class="output-body">{}</pre></div>"#,
|
|
||||||
escape(body),
|
|
||||||
line = line_no
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formula/code cards are the single visual truth — do not stack Bind chips
|
// Formula/code cards are the single visual truth — do not stack Bind chips
|
||||||
|
|||||||
@@ -972,6 +972,9 @@ ul.doc-loop, ol.doc-branch {
|
|||||||
border-left: 3px solid #2563eb;
|
border-left: 3px solid #2563eb;
|
||||||
background: #f8fafc;
|
background: #f8fafc;
|
||||||
}
|
}
|
||||||
|
.output-card.output-card-image {
|
||||||
|
border-left-color: #0d9488;
|
||||||
|
}
|
||||||
.output-card .wb-badges {
|
.output-card .wb-badges {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
@@ -987,6 +990,58 @@ ul.doc-loop, ol.doc-branch {
|
|||||||
white-space: pre-wrap;
|
white-space: pre-wrap;
|
||||||
color: #0f172a;
|
color: #0f172a;
|
||||||
}
|
}
|
||||||
|
.wb-figure {
|
||||||
|
margin: 0.5rem 0 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.wb-image {
|
||||||
|
display: block;
|
||||||
|
max-width: 100%;
|
||||||
|
height: auto;
|
||||||
|
border-radius: 6px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
.wb-image-url {
|
||||||
|
margin: 0.35rem 0 0;
|
||||||
|
font: 0.75rem/1.35 var(--mono);
|
||||||
|
color: var(--muted);
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
.doc-writeback {
|
||||||
|
margin: 0.35rem 0;
|
||||||
|
padding: 0.4rem 0.55rem;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px dashed #94a3b8;
|
||||||
|
background: #f1f5f9;
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.4rem 0.65rem;
|
||||||
|
align-items: baseline;
|
||||||
|
}
|
||||||
|
.doc-writeback[data-wb-kind="image"] {
|
||||||
|
border-color: #0d9488;
|
||||||
|
background: #f0fdfa;
|
||||||
|
}
|
||||||
|
.wb-source-badge {
|
||||||
|
font: 0.68rem/1.2 var(--sans);
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: #334155;
|
||||||
|
background: #e2e8f0;
|
||||||
|
padding: 0.12rem 0.4rem;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
.doc-writeback[data-wb-kind="image"] .wb-source-badge {
|
||||||
|
background: #ccfbf1;
|
||||||
|
color: #115e59;
|
||||||
|
}
|
||||||
|
.wb-source-text {
|
||||||
|
font: 0.82rem/1.4 var(--mono);
|
||||||
|
color: #0f172a;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
.wb-outline {
|
.wb-outline {
|
||||||
margin-top: 0.75rem;
|
margin-top: 0.75rem;
|
||||||
padding-top: 0.75rem;
|
padding-top: 0.75rem;
|
||||||
|
|||||||
+93
-7
@@ -1070,17 +1070,89 @@ fn stmt_end_line(stmt: &Stmt) -> u32 {
|
|||||||
|
|
||||||
fn output_card(line: u32, writebacks: &HashMap<u32, String>) -> String {
|
fn output_card(line: u32, writebacks: &HashMap<u32, String>) -> String {
|
||||||
match writebacks.get(&line) {
|
match writebacks.get(&line) {
|
||||||
Some(body) => {
|
Some(body) => render_output_card(line, body),
|
||||||
let badges = writeback_badges(body);
|
|
||||||
format!(
|
|
||||||
r#"<div class="card output-card" id="wb-{line}"><div class="wb-badges">{badges}</div><pre class="output-body">{}</pre></div>"#,
|
|
||||||
escape(body)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
None => String::new(),
|
None => String::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Live view + static site: text `<pre>` and/or `<img>` for image writebacks.
|
||||||
|
pub fn render_output_card(line: u32, combined: &str) -> String {
|
||||||
|
if combined.trim().is_empty() {
|
||||||
|
return String::new();
|
||||||
|
}
|
||||||
|
let badges = writeback_badges(combined);
|
||||||
|
let mut body_html = String::new();
|
||||||
|
let mut buf_text = String::new();
|
||||||
|
let flush_text = |buf: &mut String, out: &mut String| {
|
||||||
|
if buf.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
out.push_str(&format!(
|
||||||
|
r#"<pre class="output-body">{}</pre>"#,
|
||||||
|
escape(buf.trim_end())
|
||||||
|
));
|
||||||
|
buf.clear();
|
||||||
|
};
|
||||||
|
for line_s in combined.lines() {
|
||||||
|
let t = line_s.trim();
|
||||||
|
if let Some(url) = extract_md_image_url(t) {
|
||||||
|
flush_text(&mut buf_text, &mut body_html);
|
||||||
|
body_html.push_str(&format!(
|
||||||
|
r#"<figure class="wb-figure"><img class="wb-image" src="{src}" alt="writeback"/><figcaption class="wb-image-url">{cap}</figcaption></figure>"#,
|
||||||
|
src = escape(&url),
|
||||||
|
cap = escape(&url),
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
if !buf_text.is_empty() {
|
||||||
|
buf_text.push('\n');
|
||||||
|
}
|
||||||
|
buf_text.push_str(line_s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush_text(&mut buf_text, &mut body_html);
|
||||||
|
let has_img = body_html.contains("wb-image");
|
||||||
|
format!(
|
||||||
|
r#"<div class="card output-card{img_cls}" id="wb-{line}" data-wb="1"><div class="wb-badges">{badges}</div>{body}</div>"#,
|
||||||
|
line = line,
|
||||||
|
img_cls = if has_img { " output-card-image" } else { "" },
|
||||||
|
badges = badges,
|
||||||
|
body = body_html,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_md_image_url(line: &str) -> Option<String> {
|
||||||
|
let t = line.trim();
|
||||||
|
let rest = t.strip_prefix("?;
|
||||||
|
let after = &rest[alt_end + 2..];
|
||||||
|
let url_end = after.rfind(')')?;
|
||||||
|
let url = after[..url_end].trim();
|
||||||
|
if url.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(url.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Document-surface marker for a writeback source line (comment or image).
|
||||||
|
pub fn render_writeback_source_line(line_no: u32, text: &str) -> String {
|
||||||
|
let trimmed = text.trim();
|
||||||
|
let is_image = trimmed.starts_with("![") && trimmed.contains("marqdo-out");
|
||||||
|
let kind = if is_image { "image" } else { "comment" };
|
||||||
|
let label = if is_image {
|
||||||
|
"writeback · image"
|
||||||
|
} else {
|
||||||
|
"writeback"
|
||||||
|
};
|
||||||
|
format!(
|
||||||
|
r#"<div class="doc-block doc-writeback" data-line="{line}" data-wb-kind="{kind}"><span class="wb-source-badge">{label}</span><code class="wb-source-text">{text}</code></div>"#,
|
||||||
|
line = line_no,
|
||||||
|
kind = kind,
|
||||||
|
label = label,
|
||||||
|
text = escape(trimmed),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn writeback_badges(body: &str) -> String {
|
fn writeback_badges(body: &str) -> String {
|
||||||
let mut keys = Vec::new();
|
let mut keys = Vec::new();
|
||||||
for line in body.lines() {
|
for line in body.lines() {
|
||||||
@@ -1739,6 +1811,20 @@ mod tests {
|
|||||||
assert!(html.contains(">xs<") || html.contains("vars-name\">xs"), "{html}");
|
assert!(html.contains(">xs<") || html.contains("vars-name\">xs"), "{html}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn output_card_renders_image_writeback() {
|
||||||
|
let html = render_output_card(3, "[ok]\n");
|
||||||
|
assert!(html.contains("output-card-image"), "{html}");
|
||||||
|
assert!(html.contains(r#"src="plots/a.svg""#), "{html}");
|
||||||
|
assert!(html.contains("wb-ok") || html.contains(">ok<"), "{html}");
|
||||||
|
let text = render_output_card(1, "plain-42");
|
||||||
|
assert!(text.contains("output-body"), "{text}");
|
||||||
|
assert!(!text.contains("wb-image"), "{text}");
|
||||||
|
let src = render_writeback_source_line(4, "");
|
||||||
|
assert!(src.contains(r#"data-wb-kind="image""#), "{src}");
|
||||||
|
assert!(src.contains("writeback · image"), "{src}");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn structure_marks_inferred_params() {
|
fn structure_marks_inferred_params() {
|
||||||
let src = include_str!("../../tests/markup-v03/inc-prose.mq.md");
|
let src = include_str!("../../tests/markup-v03/inc-prose.mq.md");
|
||||||
|
|||||||
Reference in new issue
Block a user