fix(web): admin layout, ext add native, keyframes; document quoted CSS ratios
Widen admin main/table display, ensure marqdo ext add builds/copies the native plugin before mq install, and emit valid @keyframes from style tables. Prefer quoted cells like "16/9" for CSS values that contain /. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
416914a346
commit
2079577314
12 files changed
+354
-148
No files matched your search
@@ -24,7 +24,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.
|
||||
4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`+` params** (under heading), **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**, `**…**` = return.
|
||||
5. **Identifiers use backticks** — params `` + `name` ``. **Exemptions:** foreach `` - [item](coll) ``; footnote `` name[^key] ``; **inside italic `*…*` / bold `**…**`**, bare ids are **variables** (Python-style unified namespace) and method-call receivers are bare too. **Drop the backticks on value-expression variable names and method receivers inside `*…*` / `**…**`** — they are redundant once the `*…*`/`**…**` markers mark the segment as code: `*分类 = 分类[^苹果]*`, `**n * 2**`, `*p = > page.主体装配 组件=home*`. **Text literals must be quoted**: `*a = > text.split value=src sep=","*`. Backticks **still required** where a bare word is *not* a variable in **standalone `>` calls** (bare = text there): `` > str `n` ``, `` > `obj`.method ``. **No trailing space** inside `*…*` / `**…**` wrapped code: the closing marker must touch the last token directly (`*a = 1*`, `**n**`), never `` *a = 1 * ``.
|
||||
6. **Structure lines are not wrapped in italics.** `#` `>` `+` `-` `|` lines stand alone; use `*…*` only for general statements (bindings / expressions).
|
||||
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed.
|
||||
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults / table cells**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed. Numeric ratios that must stay text use quotes (`"1/5"`, `"16/9"`); bare `1/5` is division.
|
||||
8. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed.
|
||||
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
|
||||
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Fixed
|
||||
- **Admin UI**:主区取消 `max-width:56rem` 限制,表格外包可横向滚动的 `.table-wrap`,单元格完整展示并自动换行;表单加宽且 textarea 可随内容增高。
|
||||
- **`marqdo ext add`**:安装含原生插件的扩展时**先**定位/自动 `cargo build` 再拷贝 `.mq.md`,避免只装上文稿、运行时报 `native plugin not found`;扩大 `.so` 搜索路径。
|
||||
- **`web_style` / 样式装配**:正确输出 `@keyframes` 块(停点为嵌套规则,不再写成 `0%: opacity: 0`)。
|
||||
- **样式表含 `/` 的值**:文档明确**引号优先**(`"16/9"`、`"1/5"`);不引入靠空格消歧的表单元格比率折叠。
|
||||
|
||||
## v0.3.1 — 2026-08-29
|
||||
|
||||
### Highlights
|
||||
|
||||
+11
-4
@@ -52,14 +52,21 @@ Future optional ext domains get their own subdirs (e.g. `ext/web/`, `ext/quantum
|
||||
| `web` | `web/web.mq.md`, `web/网页.mq.md`, **`native/libweb.so`** — 见 [ext-web.md](ext-web.md) · [roadmap](../roadmap/ext-web.md) |
|
||||
| `quantum` | `quantum/quantum.mq.md`, `quantum/量子.mq.md`, **`native/libquantum.so`** — 见 [ext-quantum.md](ext-quantum.md) · [roadmap](../roadmap/ext-quantum.md) |
|
||||
|
||||
`add agent` copies the built native plugin into `MARQDO_EXT/native/`. Build it first:
|
||||
`add agent` / `add web` / `add quantum` **先定位原生插件**,再复制 `.mq.md`:
|
||||
|
||||
1. 在 `CARGO_TARGET_DIR`、`target/{debug,release}`、源码 `ext` 旁的 `target/`、可执行文件旁等路径查找 `lib{name}.so`(或 `.dll` / `.dylib`)
|
||||
2. 找不到则自动执行 `cargo build -p marqdo_plugin_{name}`,再安装到 `MARQDO_EXT/native/`
|
||||
3. 写入 `{name}.plugin` 绝对路径提示,供 `plugin.native_path` 解析
|
||||
|
||||
这样不会出现「只装了 `.mq.md`、运行时报 native plugin not found」的半安装状态。
|
||||
|
||||
```bash
|
||||
cargo build -p marqdo_plugin_agent
|
||||
marqdo ext add agent
|
||||
# 推荐:在仓库根目录
|
||||
marqdo ext add web
|
||||
# 等价于找到或编好 libweb.so 后拷入 ~/.marqdo/ext/native/
|
||||
```
|
||||
|
||||
Without install, runtime resolves the plugin via `plugin.native_path name=agent` (see [ext-abi.md](ext-abi.md)): `MARQDO_AGENT_PLUGIN` → `CARGO_TARGET_DIR/{debug,release}/` → cwd `target/…` → beside `marqdo` binary → `MARQDO_EXT/native/`.
|
||||
Without a prior install, runtime still resolves via `plugin.native_path name=web` (see [ext-abi.md](ext-abi.md)): `MARQDO_WEB_PLUGIN` → `CARGO_TARGET_DIR/{debug,release}/` → cwd `target/…` → beside `marqdo` binary → `MARQDO_EXT/native/`.
|
||||
|
||||
## Tests
|
||||
|
||||
|
||||
@@ -268,7 +268,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
|
||||
| **首列表头 `@` / `行` / `row`** | **行向** `List` of `Map`(标记列不进入字段;任意数据行数) |
|
||||
| 重复表头 | 诊断错误 |
|
||||
|
||||
**数据单元格是表达式**(与调用实参值语法相同:裸词、数字、`` `var` ``、算术、引号串;URL / `gpt-4o-mini` 等按路径·连字符折叠为文本)。表头仍是键名文本。细则:[table-cell-expressions.md](table-cell-expressions.md)。
|
||||
**数据单元格是表达式**(与调用实参值语法相同:裸词、数字、`` `var` ``、算术、引号串;URL / `gpt-4o-mini` 等按路径·连字符折叠为文本;含 `/` 的 CSS 比率等请用引号 `"1/5"`,裸 `1/5` 为除法)。表头仍是键名文本。细则:[table-cell-expressions.md](table-cell-expressions.md)。
|
||||
|
||||
```markdown
|
||||
*`k` = secret *
|
||||
|
||||
@@ -44,10 +44,11 @@ v1 把 GFM 数据单元格一律收成 **字面量**(`Int` / `Text`)。结
|
||||
| `` `api_key` `` | 变量引用 |
|
||||
| `` `a` + `b` `` | 普通表达式 |
|
||||
| `True` / `假` / `None` | 布尔 / 空 |
|
||||
| `"https://…"` / `".marqdo/x"` | 引号字符串(可含 `/`、插值) |
|
||||
| `"https://…"` / `".marqdo/x"` / `"1/5"` / `"16/9"` | 引号字符串(可含 `/`、插值;**CSS 比率等含 `/` 的值请用引号**,勿依赖空格消歧) |
|
||||
| `https://api.openai.com/v1` | **路径折叠**:无空格的 `Text/Text/…` 除法链收成整段文本(同调用实参) |
|
||||
| `gpt-4o-mini` | **连字符散文**:不拆成减法(同调用实参) |
|
||||
| `` /about ``、`` /chat/completions `` | 以 `/` 开头的路径散文 → 整段文本 |
|
||||
| `1/5` | **整数除法**(同表达式 / 调用实参;今日整除得 `0`)——要文本请写 `"1/5"` |
|
||||
| 空单元格 | 空文本 `""` |
|
||||
|
||||
### 2.2 表头仍是键名文本
|
||||
@@ -111,9 +112,10 @@ v1 把 GFM 数据单元格一律收成 **字面量**(`Int` / `Text`)。结
|
||||
|--------|------|
|
||||
| 纯中文/英文词、整数 | **不变** |
|
||||
| `gpt-4o-mini`、URL、`/path` | **不变**(折叠规则与调用实参一致) |
|
||||
| 真正要做除法 / 减法 | 用空格或括号:`` `n` / 2 ``、`` `a` - 1 ``;或先在表外算再 `` `x` `` 填入 |
|
||||
| 真正要做除法 / 减法 | 裸写 `1/5` 或空格/括号:`` `n` / 2 ``、`` `a` - 1 ``;或先在表外算再 `` `x` `` 填入 |
|
||||
| CSS / 含 `/` 的散文值 | **引号优先**:`"1/5"`、`"16/9"`、`"image/png"`(不靠空格把算术「关掉」) |
|
||||
|
||||
破坏性:几乎无。唯一需注意的是「想在单元格里写算术且两侧是裸词」——与调用实参同一套消歧。
|
||||
破坏性:几乎无。唯一需注意的是「想在单元格里写算术且两侧是裸词」——与调用实参同一套消歧;含 `/` 的**文本**一律用引号。
|
||||
|
||||
---
|
||||
|
||||
@@ -132,6 +134,7 @@ v1 把 GFM 数据单元格一律收成 **字面量**(`Int` / `Text`)。结
|
||||
|----|------|
|
||||
| 金样 | 横表单元格 `` `var` `` 读环境;竖表旧金样全绿 |
|
||||
| 路径 | `https://…`、`/chat/completions`、`gpt-4o-mini` 仍为文本 |
|
||||
| 含 `/` 文本 | 表单元格用引号:`"1/5"`、`"16/9"`;裸 `1/5` 为除法 |
|
||||
| 扩展 | `ext/ai/llm` 构造可用表写入运行时字段,去掉无必要的 `json.set` 链 |
|
||||
| 文档 | 本页 + roadmap T5 + markdown-mapping §9 同步 |
|
||||
|
||||
|
||||
+5
-2
@@ -24,8 +24,11 @@ Load the ABI v2 `web` plugin once.
|
||||
Assemble a GFM style table into a CSS string. Two shapes are accepted:
|
||||
`|选择器|属性|值|` rule rows (arbitrary selectors; rows sharing a selector are
|
||||
merged, and a leading `|媒体|` column groups rows into `@media` blocks), or
|
||||
`|属性|值|` property rows wrapped as `.name { … }`. Styles stay as data tables,
|
||||
`make_style` turns them into CSS — 样式即数据、装配即函数.
|
||||
`|属性|值|` property rows wrapped as `.name { … }`. Selectors starting with
|
||||
`@keyframes name` emit keyframe blocks (`属性` = stop `from`/`to`/`N%`,
|
||||
`值` = `prop: val` or use `@keyframes name from` + normal 属性/值). Quote CSS
|
||||
values that contain `/` (e.g. `"16/9"`, `"1/5"`); bare `1/5` is integer division.
|
||||
Styles stay as data tables, `make_style` turns them into CSS — 样式即数据、装配即函数.
|
||||
|
||||
> ensure_plugin
|
||||
**> web_style name=`name` table=`table`**
|
||||
|
||||
@@ -24,6 +24,9 @@ import sys:lib/sys.mq.md
|
||||
把 GFM 样式表装配成一段 CSS 文本。支持两种表形:
|
||||
`|选择器|属性|值|` 规则行(选择器任意,同一选择器多行合并成一条规则;
|
||||
加 `|媒体|` 列即可分组进 `@media` 块),或 `|属性|值|` 属性行(按 `.名 { … }` 包裹)。
|
||||
选择器以 `@keyframes 名` 开头时输出关键帧块(`属性` 为停点 `from`/`to`/`N%`,
|
||||
`值` 写 `opacity: 0` 等声明;也可用 `@keyframes 名 from` + 普通属性/值)。
|
||||
含 `/` 的 CSS 值请加引号(如 `"16/9"`、`"1/5"`),否则按表达式除法求值。
|
||||
样式即数据、装配即函数 —— 主题模块据此把样式表拼成完整样式表。
|
||||
|
||||
> 确保插件
|
||||
|
||||
+16
-23
@@ -1211,16 +1211,6 @@ fn flash_html(flash: Option<&str>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn truncate_cell(s: &str, max: usize) -> String {
|
||||
let mut it = s.chars();
|
||||
let head: String = it.by_ref().take(max).collect();
|
||||
if it.next().is_some() {
|
||||
format!("{head}…")
|
||||
} else {
|
||||
head
|
||||
}
|
||||
}
|
||||
|
||||
fn admin_shell(st: &AppState, title: &str, active: Option<&str>, inner: &str) -> String {
|
||||
let tables = st
|
||||
.db_url
|
||||
@@ -1270,7 +1260,7 @@ fn admin_shell(st: &AppState, title: &str, active: Option<&str>, inner: &str) ->
|
||||
<style>
|
||||
:root {{ --ink:#1c1917; --muted:#78716c; --paper:#fafaf9; --line:#e7e5e4; --accent:#0f766e; --ok:#166534; --err:#b91c1c; --side:#f5f5f4; }}
|
||||
* {{ box-sizing:border-box; }}
|
||||
body {{ margin:0; font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; background:var(--paper); color:var(--ink); min-height:100vh; display:grid; grid-template-columns:14rem 1fr; }}
|
||||
body {{ margin:0; font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; background:var(--paper); color:var(--ink); min-height:100vh; display:grid; grid-template-columns:14rem minmax(0,1fr); }}
|
||||
@media (max-width:720px) {{ body {{ grid-template-columns:1fr; }} .admin-nav {{ border-right:0; border-bottom:1px solid var(--line); }} }}
|
||||
.admin-nav {{ background:var(--side); border-right:1px solid var(--line); padding:1.1rem 1rem 1.5rem; }}
|
||||
.admin-nav .brand {{ display:block; font-weight:600; font-size:1.05rem; margin-bottom:1rem; color:var(--ink); }}
|
||||
@@ -1280,7 +1270,7 @@ body {{ margin:0; font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; backgro
|
||||
.admin-nav .nav-label {{ margin:1.1rem 0 .35rem; font-size:.75rem; text-transform:uppercase; letter-spacing:.04em; color:var(--muted); }}
|
||||
.admin-nav .nav-foot {{ margin-top:1.5rem; font-size:.9rem; }}
|
||||
.admin-nav .muted {{ color:var(--muted); font-size:.9rem; }}
|
||||
.admin-main {{ padding:1.25rem 1.5rem 2rem; max-width:56rem; }}
|
||||
.admin-main {{ padding:1.25rem 1.5rem 2rem; min-width:0; width:100%; max-width:none; overflow-x:auto; }}
|
||||
.admin-main h1 {{ margin:0 0 .35rem; font-size:1.65rem; }}
|
||||
.crumbs {{ color:var(--muted); font-size:.85rem; margin-bottom:1rem; }}
|
||||
.crumbs a {{ color:var(--muted); }}
|
||||
@@ -1290,21 +1280,23 @@ body {{ margin:0; font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; backgro
|
||||
.btn:hover {{ filter:brightness(1.05); }}
|
||||
.btn-muted {{ background:#78716c; }}
|
||||
.btn-ghost {{ background:transparent; color:var(--accent)!important; border:1px solid var(--line); }}
|
||||
table.data {{ width:100%; border-collapse:collapse; background:#fff; border:1px solid var(--line); border-radius:6px; overflow:hidden; }}
|
||||
table.data th,table.data td {{ border-bottom:1px solid var(--line); padding:.55rem .7rem; text-align:left; vertical-align:top; font-size:.92rem; }}
|
||||
table.data th {{ background:#f5f5f4; font-weight:600; }}
|
||||
.table-wrap {{ width:100%; overflow-x:auto; -webkit-overflow-scrolling:touch; border:1px solid var(--line); border-radius:6px; background:#fff; }}
|
||||
table.data {{ width:100%; min-width:100%; border-collapse:collapse; background:#fff; }}
|
||||
table.data th,table.data td {{ border-bottom:1px solid var(--line); padding:.55rem .7rem; text-align:left; vertical-align:top; font-size:.92rem; word-break:break-word; overflow-wrap:anywhere; white-space:pre-wrap; }}
|
||||
table.data th {{ background:#f5f5f4; font-weight:600; white-space:nowrap; }}
|
||||
table.data tr:last-child td {{ border-bottom:0; }}
|
||||
table.data .actions {{ white-space:nowrap; }}
|
||||
table.data .actions {{ white-space:nowrap; overflow-wrap:normal; word-break:normal; }}
|
||||
.empty {{ background:#fff; border:1px dashed var(--line); border-radius:6px; padding:2rem 1.25rem; text-align:center; color:var(--muted); }}
|
||||
.empty strong {{ display:block; color:var(--ink); margin-bottom:.35rem; font-size:1.05rem; }}
|
||||
.flash {{ padding:.65rem .85rem; border-radius:4px; margin:0 0 1rem; }}
|
||||
.flash.ok {{ background:#ecfdf5; color:var(--ok); border:1px solid #a7f3d0; }}
|
||||
.flash.err {{ background:#fef2f2; color:var(--err); border:1px solid #fecaca; }}
|
||||
.danger {{ color:var(--err); }}
|
||||
.site-form {{ max-width:28rem; margin-top:.5rem; }}
|
||||
.site-form {{ max-width:min(48rem,100%); width:100%; margin-top:.5rem; }}
|
||||
.site-form form {{ display:grid; gap:.85rem; }}
|
||||
.site-form label {{ display:grid; gap:.25rem; font-size:.9rem; }}
|
||||
.site-form input,.site-form textarea {{ padding:.5rem .6rem; border:1px solid var(--line); border-radius:4px; font:inherit; background:#fff; }}
|
||||
.site-form input,.site-form textarea {{ padding:.5rem .6rem; border:1px solid var(--line); border-radius:4px; font:inherit; background:#fff; width:100%; box-sizing:border-box; }}
|
||||
.site-form textarea {{ min-height:8rem; resize:vertical; field-sizing:content; }}
|
||||
.site-form input[readonly] {{ background:#f5f5f4; color:var(--muted); }}
|
||||
.site-form .err {{ color:var(--err); font-size:.85rem; }}
|
||||
.site-form .actions {{ display:flex; gap:.75rem; align-items:center; flex-wrap:wrap; }}
|
||||
@@ -1363,14 +1355,14 @@ async fn admin_home(
|
||||
"<div class=\"empty\"><strong>No tables</strong>Initialize a table via <code>db.init</code> / <code>数据库.初始化</code>.</div>",
|
||||
);
|
||||
} else {
|
||||
inner.push_str("<table class=\"data\"><thead><tr><th>Table</th><th></th></tr></thead><tbody>");
|
||||
inner.push_str("<div class=\"table-wrap\"><table class=\"data\"><thead><tr><th>Table</th><th></th></tr></thead><tbody>");
|
||||
for t in &tables {
|
||||
inner.push_str(&format!(
|
||||
"<tr><td><a href=\"/admin/{t}\">{t}</a></td><td class=\"actions\"><a class=\"btn\" href=\"/admin/{t}/new\">New</a></td></tr>",
|
||||
t = esc(t)
|
||||
));
|
||||
}
|
||||
inner.push_str("</tbody></table>");
|
||||
inner.push_str("</tbody></table></div>");
|
||||
}
|
||||
Html(admin_shell(&st, "Admin", None, &inner)).into_response()
|
||||
}
|
||||
@@ -1433,7 +1425,7 @@ async fn admin_table(
|
||||
esc(&table)
|
||||
));
|
||||
} else {
|
||||
inner.push_str("<table class=\"data\"><thead><tr>");
|
||||
inner.push_str("<div class=\"table-wrap\"><table class=\"data\"><thead><tr>");
|
||||
for c in &cols {
|
||||
inner.push_str(&format!("<th>{}</th>", esc(c)));
|
||||
}
|
||||
@@ -1450,7 +1442,8 @@ async fn admin_table(
|
||||
other => other.to_string(),
|
||||
})
|
||||
.unwrap_or_default();
|
||||
inner.push_str(&format!("<td>{}</td>", esc(&truncate_cell(&cell, 80))));
|
||||
// Show full cell text; CSS wraps / table-wrap scrolls when needed.
|
||||
inner.push_str(&format!("<td>{}</td>", esc(&cell)));
|
||||
}
|
||||
let id = m
|
||||
.get("id")
|
||||
@@ -1468,7 +1461,7 @@ async fn admin_table(
|
||||
}
|
||||
inner.push_str("</tr>");
|
||||
}
|
||||
inner.push_str("</tbody></table>");
|
||||
inner.push_str("</tbody></table></div>");
|
||||
}
|
||||
Html(admin_shell(&st, &table, Some(&table), &inner)).into_response()
|
||||
}
|
||||
|
||||
+238
-109
@@ -310,13 +310,16 @@ pub fn normalize_slot(name: &str) -> String {
|
||||
|
||||
/// Style table → CSS text.
|
||||
///
|
||||
/// Three table shapes are supported:
|
||||
/// Table shapes:
|
||||
/// 1. Rule rows `|媒体|选择器|属性|值|` — rows grouped by `媒体` emit
|
||||
/// `@media { … }` blocks; rows sharing a selector are merged into one rule.
|
||||
/// 2. Rule rows `|选择器|属性|值|` — each row emits `selector { prop: value; }`,
|
||||
/// rows sharing a selector are merged into one rule. `selector` may be any
|
||||
/// CSS selector (`aside.side`, `ul.side-nav a:hover`).
|
||||
/// 3. Plain property rows `|属性|值|` — emitted as `.name { prop: value; }`.
|
||||
/// 4. **`@keyframes`** — selector `@keyframes name` (optional stop in the
|
||||
/// selector: `@keyframes name from`) or stop in the `属性` column:
|
||||
/// `|@keyframes fade|from|opacity: 0|` → nested keyframe rules.
|
||||
///
|
||||
/// Examples (rule shape):
|
||||
/// ```text
|
||||
@@ -327,8 +330,9 @@ pub fn normalize_slot(name: &str) -> String {
|
||||
/// | 选择器 | 属性 | 值 |
|
||||
/// |--------|------|-----|
|
||||
/// | aside.side | padding | 2rem 1.25rem |
|
||||
/// | aside.side | background | #f5f5f4 |
|
||||
/// | ul.side-nav a:hover | color | var(--accent) |
|
||||
/// | @keyframes pulse | 0% | opacity: 0 |
|
||||
/// | @keyframes pulse | 100% | opacity: 1 |
|
||||
/// | @keyframes pulse from | opacity | 0 |
|
||||
/// ```
|
||||
pub fn as_css_named(name: &str, table: &Value) -> String {
|
||||
let name = normalize_ref(name);
|
||||
@@ -338,9 +342,6 @@ pub fn as_css_named(name: &str, table: &Value) -> String {
|
||||
let mut out = String::new();
|
||||
match table {
|
||||
Value::Object(m) => {
|
||||
// Column-first table object: `{选择器:[…], 属性:[…], 值:[…], 媒体:[…]}`
|
||||
// (how GFM tables reach the plugin). Row-major maps (one rule per map)
|
||||
// are handled too: if 选择器 is a scalar, treat it as a single row.
|
||||
let sels = pick(m, SEL_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let props = pick(m, PROP_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let vals = pick(m, VAL_KEYS).map(as_str_list).unwrap_or_default();
|
||||
@@ -359,117 +360,201 @@ pub fn as_css_named(name: &str, table: &Value) -> String {
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
// Group by media then selector; or plain `.name { … }` when no selectors.
|
||||
let mut by_media: Vec<(String, Vec<(String, Vec<String>)>)> = Vec::new();
|
||||
let mut plain: Vec<String> = Vec::new();
|
||||
for (media, sel, p, v) in rows {
|
||||
if p.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let decl = format!(" {p}: {v};");
|
||||
if !media.is_empty() {
|
||||
let group = match by_media.iter_mut().find(|(mq, _)| *mq == media) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
by_media.push((media.clone(), Vec::new()));
|
||||
let (_, g) = by_media.last_mut().unwrap();
|
||||
g
|
||||
}
|
||||
};
|
||||
push_rule(group, &sel, decl);
|
||||
} else if !sel.is_empty() {
|
||||
let group = match by_media.iter_mut().find(|(mq, _)| mq.is_empty()) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
by_media.push((String::new(), Vec::new()));
|
||||
let (_, g) = by_media.last_mut().unwrap();
|
||||
g
|
||||
}
|
||||
};
|
||||
push_rule(group, &sel, decl);
|
||||
} else {
|
||||
plain.push(decl);
|
||||
}
|
||||
}
|
||||
for (media, rules) in by_media {
|
||||
if media.is_empty() {
|
||||
for (sel, decls) in rules {
|
||||
out.push_str(&format!("{} {{\n{}\n}}\n", sel, decls.join("\n")));
|
||||
}
|
||||
} else {
|
||||
let inner = rules
|
||||
.iter()
|
||||
.map(|(sel, decls)| format!("{} {{\n{}\n}}", sel, decls.join("\n")))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
out.push_str(&format!("@media {} {{\n{}\n}}\n", media, inner));
|
||||
}
|
||||
}
|
||||
if !plain.is_empty() {
|
||||
out.push_str(&format!(".{} {{\n{}\n}}\n", name, plain.join("\n")));
|
||||
}
|
||||
emit_css_rows(&rows, &name, &mut out);
|
||||
}
|
||||
Value::Array(rows) => {
|
||||
// Group rule rows by media query and selector; plain rows as `.name { … }`.
|
||||
let mut by_media: Vec<(String, Vec<(String, Vec<String>)>)> = Vec::new();
|
||||
let mut plain: Vec<String> = Vec::new();
|
||||
for row in rows {
|
||||
let Some(m) = row.as_object() else { continue };
|
||||
let media = pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default();
|
||||
let sel = pick(m, SEL_KEYS).map(cell_str).unwrap_or_default();
|
||||
let p = pick(m, PROP_KEYS).map(cell_str).unwrap_or_default();
|
||||
let v = pick(m, VAL_KEYS).map(cell_str).unwrap_or_default();
|
||||
if p.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let decl = format!(" {p}: {v};");
|
||||
if !media.is_empty() {
|
||||
let group = match by_media.iter_mut().find(|(mq, _)| *mq == media) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
by_media.push((media.clone(), Vec::new()));
|
||||
let (_, g) = by_media.last_mut().unwrap();
|
||||
g
|
||||
}
|
||||
};
|
||||
push_rule(group, &sel, decl);
|
||||
} else if !sel.is_empty() {
|
||||
let group = match by_media.iter_mut().find(|(mq, _)| mq.is_empty()) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
by_media.push((String::new(), Vec::new()));
|
||||
let (_, g) = by_media.last_mut().unwrap();
|
||||
g
|
||||
}
|
||||
};
|
||||
push_rule(group, &sel, decl);
|
||||
} else {
|
||||
plain.push(decl);
|
||||
}
|
||||
}
|
||||
for (media, rules) in by_media {
|
||||
if media.is_empty() {
|
||||
for (sel, decls) in rules {
|
||||
out.push_str(&format!("{} {{\n{}\n}}\n", sel, decls.join("\n")));
|
||||
}
|
||||
} else {
|
||||
let inner = rules
|
||||
.iter()
|
||||
.map(|(sel, decls)| format!("{} {{\n{}\n}}", sel, decls.join("\n")))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
out.push_str(&format!("@media {} {{\n{}\n}}\n", media, inner));
|
||||
}
|
||||
}
|
||||
if !plain.is_empty() {
|
||||
out.push_str(&format!(".{} {{\n{}\n}}\n", name, plain.join("\n")));
|
||||
}
|
||||
let rows: Vec<(String, String, String, String)> = rows
|
||||
.iter()
|
||||
.filter_map(|row| {
|
||||
let m = row.as_object()?;
|
||||
Some((
|
||||
pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default(),
|
||||
pick(m, SEL_KEYS).map(cell_str).unwrap_or_default(),
|
||||
pick(m, PROP_KEYS).map(cell_str).unwrap_or_default(),
|
||||
pick(m, VAL_KEYS).map(cell_str).unwrap_or_default(),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
emit_css_rows(&rows, &name, &mut out);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Parse `@keyframes name` or `@keyframes name stop` from a selector cell.
|
||||
fn parse_keyframes_sel(sel: &str) -> Option<(String, Option<String>)> {
|
||||
let t = sel.trim();
|
||||
if t.len() < 10 || !t[..10].eq_ignore_ascii_case("@keyframes") {
|
||||
return None;
|
||||
}
|
||||
let rest = t[10..].trim();
|
||||
if rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// First token = animation name; optional second = keyframe stop.
|
||||
let mut parts = rest.split_whitespace();
|
||||
let anim = parts.next()?.to_string();
|
||||
let stop = parts.next().map(|s| s.to_string());
|
||||
Some((anim, stop))
|
||||
}
|
||||
|
||||
fn is_keyframe_stop(s: &str) -> bool {
|
||||
let t = s.trim();
|
||||
if t.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if t.eq_ignore_ascii_case("from") || t.eq_ignore_ascii_case("to") {
|
||||
return true;
|
||||
}
|
||||
// 0%, 50%, 100.5%, etc.
|
||||
let stripped = t.trim_end_matches('%');
|
||||
!stripped.is_empty()
|
||||
&& stripped
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_digit() || c == '.')
|
||||
&& t.ends_with('%')
|
||||
}
|
||||
|
||||
fn keyframe_decl_lines(css_prop: &str, value: &str) -> Vec<String> {
|
||||
// Value may be a full declaration (`opacity: 0`) or bare value when the
|
||||
// CSS property lived in the selector form `@keyframes name from` + 属性.
|
||||
let v = value.trim().trim_end_matches(';').trim();
|
||||
if v.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
if v.contains(':') {
|
||||
v.split(';')
|
||||
.map(|p| p.trim())
|
||||
.filter(|p| !p.is_empty())
|
||||
.map(|p| format!(" {p};"))
|
||||
.collect()
|
||||
} else if !css_prop.is_empty() && !is_keyframe_stop(css_prop) {
|
||||
// `@keyframes name from` + 属性=opacity + 值=0
|
||||
vec![format!(" {css_prop}: {v};")]
|
||||
} else {
|
||||
// Bare value — prefer `opacity: 0` in the 值 column.
|
||||
vec![format!(" {v};")]
|
||||
}
|
||||
}
|
||||
|
||||
fn push_keyframe(
|
||||
groups: &mut Vec<(String, Vec<(String, Vec<String>)>)>,
|
||||
anim: &str,
|
||||
stop: &str,
|
||||
decls: Vec<String>,
|
||||
) {
|
||||
if anim.is_empty() || stop.is_empty() || decls.is_empty() {
|
||||
return;
|
||||
}
|
||||
let anim_group = match groups.iter_mut().find(|(n, _)| n == anim) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
groups.push((anim.to_string(), Vec::new()));
|
||||
&mut groups.last_mut().unwrap().1
|
||||
}
|
||||
};
|
||||
match anim_group.iter_mut().find(|(s, _)| s == stop) {
|
||||
Some((_, d)) => d.extend(decls),
|
||||
None => anim_group.push((stop.to_string(), decls)),
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_css_rows(rows: &[(String, String, String, String)], class_name: &str, out: &mut String) {
|
||||
let mut by_media: Vec<(String, Vec<(String, Vec<String>)>)> = Vec::new();
|
||||
let mut by_keyframes: Vec<(String, Vec<(String, Vec<String>)>)> = Vec::new();
|
||||
let mut plain: Vec<String> = Vec::new();
|
||||
|
||||
for (media, sel, p, v) in rows {
|
||||
let media = media.trim();
|
||||
let sel = sel.trim();
|
||||
let p = p.trim();
|
||||
let v = v.trim();
|
||||
|
||||
if let Some((anim, stop_in_sel)) = parse_keyframes_sel(sel) {
|
||||
let stop_from_sel = stop_in_sel.is_some();
|
||||
let (stop, prop_for_decl) = match stop_in_sel {
|
||||
Some(s) => (s, p.to_string()),
|
||||
None => {
|
||||
// 属性 = keyframe stop (from / to / N%); 值 = declaration(s)
|
||||
if !is_keyframe_stop(p) {
|
||||
continue;
|
||||
}
|
||||
(p.to_string(), String::new())
|
||||
}
|
||||
};
|
||||
let decls = if stop_from_sel {
|
||||
keyframe_decl_lines(&prop_for_decl, v)
|
||||
} else {
|
||||
keyframe_decl_lines("", v)
|
||||
};
|
||||
let decls = if decls.is_empty() && !v.is_empty() && !prop_for_decl.is_empty() {
|
||||
keyframe_decl_lines(&prop_for_decl, v)
|
||||
} else {
|
||||
decls
|
||||
};
|
||||
push_keyframe(&mut by_keyframes, &anim, &stop, decls);
|
||||
continue;
|
||||
}
|
||||
|
||||
if p.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let decl = format!(" {p}: {v};");
|
||||
if !media.is_empty() {
|
||||
let group = match by_media.iter_mut().find(|(mq, _)| *mq == media) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
by_media.push((media.to_string(), Vec::new()));
|
||||
let (_, g) = by_media.last_mut().unwrap();
|
||||
g
|
||||
}
|
||||
};
|
||||
push_rule(group, sel, decl);
|
||||
} else if !sel.is_empty() {
|
||||
let group = match by_media.iter_mut().find(|(mq, _)| mq.is_empty()) {
|
||||
Some((_, g)) => g,
|
||||
None => {
|
||||
by_media.push((String::new(), Vec::new()));
|
||||
let (_, g) = by_media.last_mut().unwrap();
|
||||
g
|
||||
}
|
||||
};
|
||||
push_rule(group, sel, decl);
|
||||
} else {
|
||||
plain.push(decl);
|
||||
}
|
||||
}
|
||||
|
||||
for (media, rules) in by_media {
|
||||
if media.is_empty() {
|
||||
for (sel, decls) in rules {
|
||||
out.push_str(&format!("{} {{\n{}\n}}\n", sel, decls.join("\n")));
|
||||
}
|
||||
} else {
|
||||
let inner = rules
|
||||
.iter()
|
||||
.map(|(sel, decls)| format!("{} {{\n{}\n}}", sel, decls.join("\n")))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
out.push_str(&format!("@media {} {{\n{}\n}}\n", media, inner));
|
||||
}
|
||||
}
|
||||
for (anim, stops) in by_keyframes {
|
||||
out.push_str(&format!("@keyframes {} {{\n", anim));
|
||||
for (stop, decls) in stops {
|
||||
out.push_str(&format!(" {} {{\n", stop));
|
||||
out.push_str(&decls.join("\n"));
|
||||
out.push('\n');
|
||||
out.push_str(" }\n");
|
||||
}
|
||||
out.push_str("}\n");
|
||||
}
|
||||
if !plain.is_empty() {
|
||||
out.push_str(&format!(".{} {{\n{}\n}}\n", class_name, plain.join("\n")));
|
||||
}
|
||||
}
|
||||
|
||||
/// Push `decl` under `sel` into a `(selector, declarations)` group list,
|
||||
/// merging declarations when the selector already exists.
|
||||
fn push_rule(groups: &mut Vec<(String, Vec<String>)>, sel: &str, decl: String) {
|
||||
@@ -614,3 +699,47 @@ fn meta_text(v: &Value) -> String {
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod css_tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn keyframes_stop_in_prop() {
|
||||
let t = json!([
|
||||
{"选择器": "@keyframes pulse", "属性": "0%", "值": "opacity: 0"},
|
||||
{"选择器": "@keyframes pulse", "属性": "100%", "值": "opacity: 1"},
|
||||
]);
|
||||
let css = as_css_named("anim", &t);
|
||||
assert!(css.contains("@keyframes pulse {"), "{css}");
|
||||
assert!(css.contains("0% {"), "{css}");
|
||||
assert!(css.contains("opacity: 0;"), "{css}");
|
||||
assert!(css.contains("100% {"), "{css}");
|
||||
assert!(!css.contains("0%: opacity"), "{css}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyframes_stop_in_selector() {
|
||||
let t = json!([
|
||||
{"选择器": "@keyframes fade from", "属性": "opacity", "值": "0"},
|
||||
{"选择器": "@keyframes fade to", "属性": "opacity", "值": "1"},
|
||||
]);
|
||||
let css = as_css_named("anim", &t);
|
||||
assert!(css.contains("@keyframes fade {"), "{css}");
|
||||
assert!(css.contains("from {"), "{css}");
|
||||
assert!(css.contains("opacity: 0;"), "{css}");
|
||||
assert!(css.contains("to {"), "{css}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn media_still_works() {
|
||||
let t = json!([
|
||||
{"媒体": "(max-width: 800px)", "选择器": ".x", "属性": "color", "值": "red"},
|
||||
]);
|
||||
let css = as_css_named("x", &t);
|
||||
assert!(css.contains("@media (max-width: 800px)"), "{css}");
|
||||
assert!(css.contains(".x {"), "{css}");
|
||||
assert!(css.contains("color: red;"), "{css}");
|
||||
}
|
||||
}
|
||||
+54
-4
@@ -194,6 +194,11 @@ fn find_native_plugin(short: &str) -> Result<PathBuf> {
|
||||
let base = PathBuf::from(h);
|
||||
candidates.push(base.join("native").join(&name));
|
||||
candidates.push(base.join(&name));
|
||||
// MARQDO_EXT_SOURCE often points at repo `ext/`; native libs live in sibling target/.
|
||||
if let Some(repo) = base.parent() {
|
||||
candidates.push(repo.join("target").join("debug").join(&name));
|
||||
candidates.push(repo.join("target").join("release").join(&name));
|
||||
}
|
||||
}
|
||||
// Honor CARGO_TARGET_DIR (sandbox / custom target roots) before cwd/target.
|
||||
if let Ok(td) = env::var("CARGO_TARGET_DIR") {
|
||||
@@ -205,6 +210,15 @@ fn find_native_plugin(short: &str) -> Result<PathBuf> {
|
||||
candidates.push(cwd.join("target").join("debug").join(&name));
|
||||
candidates.push(cwd.join("target").join("release").join(&name));
|
||||
candidates.push(cwd.join("ext").join("native").join(&name));
|
||||
// Walk up looking for a Cargo workspace target/ (run from a subdir).
|
||||
let mut dir = cwd.clone();
|
||||
for _ in 0..6 {
|
||||
candidates.push(dir.join("target").join("debug").join(&name));
|
||||
candidates.push(dir.join("target").join("release").join(&name));
|
||||
if !dir.pop() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(exe) = env::current_exe() {
|
||||
if let Some(dir) = exe.parent() {
|
||||
@@ -213,6 +227,7 @@ fn find_native_plugin(short: &str) -> Result<PathBuf> {
|
||||
candidates.push(dir.join(&name));
|
||||
// target/debug/deps → target/debug
|
||||
candidates.push(dir.join("..").join(&name));
|
||||
candidates.push(dir.join("..").join("release").join(&name));
|
||||
}
|
||||
}
|
||||
for p in &candidates {
|
||||
@@ -221,8 +236,35 @@ fn find_native_plugin(short: &str) -> Result<PathBuf> {
|
||||
}
|
||||
}
|
||||
bail!(
|
||||
"cannot find native plugin `{name}` (run `cargo build -p marqdo_plugin_{short}`, or `marqdo ext add {short}`, or set {env_key})"
|
||||
"cannot find native plugin `{name}` (run `cargo build -p marqdo_plugin_{short}`, or set {env_key})"
|
||||
)
|
||||
}
|
||||
|
||||
/// Locate a built native plugin, or `cargo build -p …` once then look again.
|
||||
fn ensure_native_plugin(crate_name: &str) -> Result<PathBuf> {
|
||||
let short = native_short_name(crate_name);
|
||||
if let Ok(p) = find_native_plugin(short) {
|
||||
return Ok(p);
|
||||
}
|
||||
println!(
|
||||
"native plugin for `{short}` not found; building `{crate_name}` (debug)…"
|
||||
);
|
||||
let status = std::process::Command::new("cargo")
|
||||
.args(["build", "-p", crate_name])
|
||||
.status()
|
||||
.with_context(|| format!("spawn cargo build -p {crate_name}"))?;
|
||||
if !status.success() {
|
||||
bail!(
|
||||
"cargo build -p {crate_name} failed (status {status}); build the plugin then re-run `marqdo ext add {short}`"
|
||||
);
|
||||
}
|
||||
find_native_plugin(short).with_context(|| {
|
||||
format!(
|
||||
"built `{crate_name}` but still cannot find {}; set {} to the .so/.dll path",
|
||||
native_lib_filename(short),
|
||||
native_env_var(short)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn add_ext(id: &str) -> Result<()> {
|
||||
@@ -240,6 +282,14 @@ pub fn add_ext(id: &str) -> Result<()> {
|
||||
fs::create_dir_all(&root)
|
||||
.with_context(|| format!("create install root {}", root.display()))?;
|
||||
|
||||
// Preflight native binary *before* copying .mq.md so a missing .so does not
|
||||
// leave a half-installed tree that fails at `plugin.native_path` / load time.
|
||||
let native_src = if let Some(crate_name) = pkg.native_crate {
|
||||
Some(ensure_native_plugin(crate_name)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
for f in pkg.mq_files {
|
||||
let src = find_source_file(f)?;
|
||||
let dest = root.join(f);
|
||||
@@ -252,10 +302,9 @@ pub fn add_ext(id: &str) -> Result<()> {
|
||||
println!("installed {}", dest.display());
|
||||
}
|
||||
|
||||
if let Some(crate_name) = pkg.native_crate {
|
||||
if let (Some(crate_name), Some(src)) = (pkg.native_crate, native_src) {
|
||||
let short = native_short_name(crate_name);
|
||||
let lib_name = native_lib_filename(short);
|
||||
let src = find_native_plugin(short)?;
|
||||
let native_dir = root.join("native");
|
||||
fs::create_dir_all(&native_dir)?;
|
||||
let dest = native_dir.join(&lib_name);
|
||||
@@ -270,7 +319,8 @@ pub fn add_ext(id: &str) -> Result<()> {
|
||||
fs::write(&hint, abs.to_string_lossy().as_bytes())?;
|
||||
println!("wrote {}", hint.display());
|
||||
println!(
|
||||
"hint: import works via install root; set {}={} if load_native needs it",
|
||||
"hint: `plugin.native_path name={short}` resolves via {}; or set {}={}",
|
||||
dest.display(),
|
||||
native_env_var(short),
|
||||
abs.display()
|
||||
);
|
||||
|
||||
+3
-1
@@ -182,7 +182,9 @@ fn structure_collection_cell_expr() {
|
||||
gpt-4o-mini
|
||||
https://api.openai.com/v1
|
||||
/chat/completions
|
||||
sk-live",
|
||||
sk-live
|
||||
1/5
|
||||
16/9",
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -33,3 +33,13 @@ description: Data cells evaluate like call-arg values (`var`, paths, hyphen pros
|
||||
| 1 | user | `secret` |
|
||||
|
||||
> print text=`rec`[^1][^content]
|
||||
|
||||
`ratios` =
|
||||
|
||||
| r |
|
||||
|---|
|
||||
| "1/5" |
|
||||
| "16/9" |
|
||||
|
||||
> print text=`ratios`[^1]
|
||||
> print text=`ratios`[^2]
|
||||
Reference in new issue
Block a user