diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index 12cb6ea..5eea335 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -29,7 +29,8 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. 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. -10. **Browser (route C/D):** client logic is Marqdo on WASM ([ADR 0002](../../../doc/adr/0002-browser-marqdo-wasm.md)); async I/O via return effects `fetch`/`after` ([ADR 0003](../../../doc/adr/0003-browser-async-effects.md)); official bridge is **host glue only**. **Author zero business JS** — use `web.client_embed` / `网页.客户端挂载` (`wasm` + `source` + `boot`) or `data-mq-source-url` so bridge `mount`s automatically ([roadmap D](../../../doc/roadmap/browser-wasm-d.md)). DOM effects: `set_text` / `set_value` / `set_attr` / `set_class` / `toggle_class` / `set_html` only on `#trusted*` selectors. +10. **Browser (route C/D/E):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, internal templates — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount ([roadmap D](../../../doc/roadmap/browser-wasm-d.md) · [E](../../../doc/roadmap/browser-wasm-e.md)). Effects: DOM patches, `render_list`, `navigate`, `storage`, `ws`, `fetch`/`fetch_all`, `interval`. + ## Markup → meaning (v0.2) @@ -175,7 +176,7 @@ data/ # sqlite runtime (gitignore) **Core objects (EN / ZH):** `# page`/`页面`, `# style`/`样式`, `# db`/`数据库`, `# form`/`表单`, `# app`/`应用`, `# auth`/`鉴权`, `# cache`/`缓存`, `# storage`/`存储`. -**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.head` / `page.images` / `page.meta` → `app` with `route` / `static` / `icons` / `configure` / `listen`. For client interactivity: `marqdo wasm build -o static`, then `web.client_embed source="/static/client.mq.md"` (or ZH `网页.客户端挂载`) in page HTML — **no author JS** ([browser-wasm-d.md](../../doc/roadmap/browser-wasm-d.md) · [web-client-site](../../examples/web-client-site/)). +**Typical flow:** `db.init` → `page.compose_*` → `app` + `static` / `listen`. Client: `marqdo wasm build -o static` + `web.client_embed source="/static/client.mq.md"` — **no author JS**; bridge may implement rich host effects ([browser-wasm-e.md](../../doc/roadmap/browser-wasm-e.md) · [browser-app](../../examples/browser-app/)). **Shipped surface (W0–W7 + P3 + W8 + route D mount):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads; **W8** site icons (`app.icons` → `/favicon.ico`), head resource tables (`page.head`), image assembly (`make_images` / `page.images`); **D** `client_embed` auto-mount + DOM effect helpers (`text_patch` / `dom_patch`). diff --git a/.gitignore b/.gitignore index 732a2e1..dd75272 100644 --- a/.gitignore +++ b/.gitignore @@ -43,6 +43,7 @@ spike/.pytest_cache/ /examples/browser-hello/marqdo_wasm.wasm /examples/browser-hello/pkg/ /examples/web-client-site/static/marqdo_wasm.wasm +/examples/browser-app/marqdo_wasm.wasm # Local sqlite / scratch /data/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ddbdba..98f55c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,8 +3,8 @@ ## Unreleased ### Added -- **路线 D(作者零 JS)**:[roadmap](doc/roadmap/browser-wasm-d.md) · 设计 §16。官方 bridge `mount` / `data-mq-*` 自启;`client_embed` 带 `wasm`/`source`/`boot`;DOM 效应 `set_value`/`set_attr`/`set_class`/`toggle_class`/`set_html(#trusted…)`;wire 传 `value`/`fields`;示例去业务 JS;`examples/web-client-site/`。 -- **路线 E(规划)**:[browser-wasm-e.md](doc/roadmap/browser-wasm-e.md) — 路由 / 存储 / 列表片段 / WebSocket / DOM·定时补齐;C+D **尚不能**替代大部分前端 JS。 +- **路线 D(作者零 JS)**:[roadmap](doc/roadmap/browser-wasm-d.md) · 设计 §16。官方 bridge `mount` / `data-mq-*` 自启;`client_embed` 带 `wasm`/`source`/`boot`;DOM 效应;`examples/web-client-site/`。 +- **路线 E(前端补齐)**:[browser-wasm-e.md](doc/roadmap/browser-wasm-e.md) · 设计 §17。原则:仅禁作者手写业务 JS;桥内可做列表/路由/storage/ws/定时。效应含 `set_style`/`render_list`/`navigate`/`storage`/`ws`/`fetch_all`/`interval`;示例 [browser-app](examples/browser-app/)。 ### Fixed diff --git a/README.md b/README.md index 633afe3..5a00698 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ marqdo catalog public -o .marqdo - **原生插件 ABI**:[`include/marqdo_abi.h`](include/marqdo_abi.h) · [ext-abi.md](doc/design/ext-abi.md);`plugins/{demo,agent,web,quantum}` - **用户静态站**:`public/` → `view output` → CI 发布 [gh-pages](https://cflmy.github.io/marqdo/) - **VS Code 扩展**:分支 **`vscode-extension`**(`main` 不跟踪源码;见 [vscode-extension-commit.md](doc/design/vscode-extension-commit.md));Release 附带 `.vsix` -- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge **自启**(路线 D 作者零业务 JS);`web.client_embed` / `网页.客户端挂载`;示例 [browser-hello](examples/browser-hello/) · [web-client-site](examples/web-client-site/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [ADR 0003](doc/adr/0003-browser-async-effects.md) · [路线 D](doc/roadmap/browser-wasm-d.md)) +- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 JS;桥内可含列表/路由/storage/ws);`web.client_embed`;示例 [browser-hello](examples/browser-hello/) · [browser-app](examples/browser-app/) · [web-client-site](examples/web-client-site/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [路线 D](doc/roadmap/browser-wasm-d.md) · [路线 E](doc/roadmap/browser-wasm-e.md)) - 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM](doc/adr/0002-browser-marqdo-wasm.md)(C0–C5 完结,见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))· [ADR 0003 — 异步效应](doc/adr/0003-browser-async-effects.md) ### 如何使用最新 Marqdo(v0.3.2) diff --git a/crates/marqdo-wasm/js/marqdo-bridge.js b/crates/marqdo-wasm/js/marqdo-bridge.js index 98ac03a..f5e48d5 100644 --- a/crates/marqdo-wasm/js/marqdo-bridge.js +++ b/crates/marqdo-wasm/js/marqdo-bridge.js @@ -1,13 +1,11 @@ /** - * Canonical Marqdo browser bridge (route C/D). Host glue only — not app logic. - * Copied to site dirs by `marqdo wasm build`. + * Canonical Marqdo browser bridge (routes C/D/E). Host glue only — not app logic. + * Authors write .mq.md only; this file may grow host mechanisms freely. * * ABI: mq_alloc, mq_dealloc, mq_run, mq_boot, mq_call, mq_version - * Packed results: u32le length + UTF-8 JSON { ok, stdout, error, value } - * - * Effects (ADR 0003 + route D): set_text, set_value, set_attr, set_class, - * toggle_class, set_html (#trusted* only), fetch, after - * Mount: mount() / data-mq-* / #marqdo-boot auto-start (author zero JS) + * Effects: set_text, set_value, set_attr, set_class, toggle_class, set_style, + * focus, blur, scroll_into, set_html, replace_children, render_list, + * navigate, storage, ws, fetch, fetch_all, after, interval, clear_interval */ export function readCString(memory, ptr) { @@ -73,42 +71,27 @@ function isPlainObject(v) { return v != null && typeof v === "object" && !Array.isArray(v); } +function asSelList(v) { + if (v == null) return []; + if (Array.isArray(v)) return v.map(String); + return [String(v)]; +} + /** Normalize mount options from plain object or DOM dataset. */ export function normalizeMountOptions(raw = {}) { const o = raw && typeof raw === "object" ? raw : {}; const dataset = o.dataset || {}; const wasmUrl = - o.wasmUrl || - o.wasm || - dataset.mqWasm || - dataset.wasm || - "./marqdo_wasm.wasm"; + o.wasmUrl || o.wasm || dataset.mqWasm || dataset.wasm || "./marqdo_wasm.wasm"; const sourceUrl = - o.sourceUrl || - o.source_url || - dataset.mqSourceUrl || - dataset.sourceUrl || - ""; + o.sourceUrl || o.source_url || dataset.mqSourceUrl || dataset.sourceUrl || ""; let source = o.source != null ? o.source : dataset.mqSource || ""; if (!source && typeof o.sourceInline === "string") source = o.sourceInline; - const playground = - o.playground || - dataset.mqPlayground || - dataset.playground || - ""; - const ready = - o.ready || - o.readySel || - dataset.mqReady || - ""; - const enable = - o.enable || - dataset.mqEnable || - ""; + const playground = o.playground || dataset.mqPlayground || dataset.playground || ""; + const ready = o.ready || o.readySel || dataset.mqReady || ""; + const enable = o.enable || dataset.mqEnable || ""; const noBoot = - o.noBoot === true || - dataset.mqNoBoot === "1" || - dataset.mqNoBoot === "true"; + o.noBoot === true || dataset.mqNoBoot === "1" || dataset.mqNoBoot === "true"; return { wasmUrl: String(wasmUrl), sourceUrl: sourceUrl ? String(sourceUrl) : "", @@ -121,18 +104,13 @@ export function normalizeMountOptions(raw = {}) { }; } -/** - * Collect mount configs from `#marqdo-boot` JSON and `script[data-mq-*]`. - * Pure DOM scan — safe to call once after DOM ready. - */ export function collectMountConfigs(doc = typeof document !== "undefined" ? document : null) { if (!doc) return []; const out = []; const bootEl = doc.getElementById("marqdo-boot"); if (bootEl) { try { - const json = JSON.parse(bootEl.textContent || "{}"); - out.push(normalizeMountOptions(json)); + out.push(normalizeMountOptions(JSON.parse(bootEl.textContent || "{}"))); } catch (e) { console.error("marqdo-boot JSON:", e); } @@ -143,10 +121,7 @@ export function collectMountConfigs(doc = typeof document !== "undefined" ? docu for (const el of scripts) { if (el.dataset.mqNoBoot === "1" || el.dataset.mqNoBoot === "true") continue; const hasWork = - el.dataset.mqSourceUrl || - el.dataset.mqSource || - el.dataset.mqPlayground; - if (!hasWork && !el.dataset.mqWasm) continue; + el.dataset.mqSourceUrl || el.dataset.mqSource || el.dataset.mqPlayground; if (!hasWork) continue; out.push( normalizeMountOptions({ @@ -163,19 +138,27 @@ export function collectMountConfigs(doc = typeof document !== "undefined" ? docu return out; } -/** Build mq_call args from a DOM event + optional value_from selector. */ export function eventArgsFromDom(ev, valueFromSel) { const t = ev && ev.target; - const args = { - event: ev && ev.type ? ev.type : "click", - }; + const args = { event: ev && ev.type ? ev.type : "click" }; if (t && typeof t === "object") { if ("value" in t && t.value != null) args.value = String(t.value); if ("checked" in t) args.checked = !!t.checked; if (t.id) args.id = String(t.id); + if (t.getAttribute) { + const did = t.getAttribute("data-id"); + if (did != null) args.data_id = did; + } if (typeof t.textContent === "string" && !("value" in t)) { args.text = t.textContent; } + if (ev.key != null) args.key = String(ev.key); + if (ev.code != null) args.code = String(ev.code); + } + if (ev && ev.type === "popstate") { + args.url = typeof location !== "undefined" ? location.href : ""; + args.path = typeof location !== "undefined" ? location.pathname + location.search : ""; + args.state = ev.state; } if (valueFromSel && typeof document !== "undefined") { const src = document.querySelector(valueFromSel); @@ -193,16 +176,64 @@ export function eventArgsFromDom(ev, valueFromSel) { /* ignore */ } const fields = {}; - for (const [k, v] of new FormData(form)) { - fields[k] = String(v); - } + for (const [k, v] of new FormData(form)) fields[k] = String(v); args.fields = fields; } } return args; } -/** Apply C3/C4/D3 return effects: DOM patches then fetch/after. */ +function applyStyle(el, styleVal) { + if (typeof styleVal === "string") { + el.setAttribute("style", styleVal); + return; + } + if (isPlainObject(styleVal)) { + for (const [k, v] of Object.entries(styleVal)) { + if (v === null || v === false) el.style.removeProperty(k); + else el.style.setProperty(k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase()), String(v)); + } + } +} + +export function renderListItems(spec) { + const tag = String(spec.tag || "li"); + const items = Array.isArray(spec.items) ? spec.items : []; + return items + .map((it) => { + if (it == null) return ""; + if (typeof it === "string" || typeof it === "number") { + return `<${tag}>${escapeHtml(String(it))}${tag}>`; + } + if (!isPlainObject(it)) return ""; + const text = it.text != null ? String(it.text) : it.html != null ? null : ""; + const cls = it.class != null ? ` class="${escapeAttr(String(it.class))}"` : ""; + let attrs = ""; + if (isPlainObject(it.attrs)) { + for (const [k, v] of Object.entries(it.attrs)) { + if (v === null || v === false) continue; + attrs += ` ${escapeAttr(k)}="${escapeAttr(String(v))}"`; + } + } + const inner = it.html != null ? String(it.html) : escapeHtml(text ?? ""); + return `<${tag}${cls}${attrs}>${inner}${tag}>`; + }) + .join(""); +} + +function escapeHtml(s) { + return s + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +function escapeAttr(s) { + return escapeHtml(s).replace(/'/g, "'"); +} + +/** Sync DOM patches (E1/E2/E3 navigate is sync too). */ export function applyDomPatch(value) { if (!value || typeof value !== "object") return; if (typeof document === "undefined") return; @@ -251,18 +282,66 @@ export function applyDomPatch(value) { } } + const setStyle = value.set_style || value.setStyle; + if (isPlainObject(setStyle)) { + for (const [sel, st] of Object.entries(setStyle)) { + const el = document.querySelector(sel); + if (el) applyStyle(el, st); + } + } + + for (const sel of asSelList(value.focus)) { + const el = document.querySelector(sel); + if (el && el.focus) el.focus(); + } + for (const sel of asSelList(value.blur)) { + const el = document.querySelector(sel); + if (el && el.blur) el.blur(); + } + for (const sel of asSelList(value.scroll_into || value.scrollInto)) { + const el = document.querySelector(sel); + if (el && el.scrollIntoView) el.scrollIntoView({ block: "nearest", behavior: "smooth" }); + } + const setHtml = value.set_html || value.setHtml; if (isPlainObject(setHtml)) { for (const [sel, html] of Object.entries(setHtml)) { - if (!String(sel).startsWith("#trusted")) continue; const el = document.querySelector(sel); if (el) el.innerHTML = String(html); } } + + const replaceChildren = value.replace_children || value.replaceChildren; + if (isPlainObject(replaceChildren)) { + for (const [sel, html] of Object.entries(replaceChildren)) { + const el = document.querySelector(sel); + if (el) el.innerHTML = String(html); + } + } + + const renderList = value.render_list || value.renderList; + if (isPlainObject(renderList)) { + for (const [sel, spec] of Object.entries(renderList)) { + const el = document.querySelector(sel); + if (!el || !isPlainObject(spec)) continue; + el.innerHTML = renderListItems(spec); + } + } + + const nav = value.navigate; + if (isPlainObject(nav) && nav.url != null && typeof history !== "undefined") { + const url = String(nav.url); + if (nav.replace) history.replaceState(nav.state ?? null, "", url); + else history.pushState(nav.state ?? null, "", url); + } } +const intervalHandles = new Map(); +const wsHandles = new Map(); +let wsSeq = 0; + /** - * Run sync DOM patches then schedule async effects (ADR 0003). + * Run sync DOM patches then schedule async effects. */ export function applyEffects(exports, value, { onError } = {}) { applyDomPatch(value); @@ -275,32 +354,64 @@ export function applyEffects(exports, value, { onError } = {}) { tasks.push(runFetchEffect(exports, fetchSpec, onError)); } + const fetchAll = value.fetch_all || value.fetchAll; + if (fetchAll && typeof fetchAll === "object" && fetchAll.then) { + tasks.push(runFetchAllEffect(exports, fetchAll, onError)); + } + const afterSpec = value.after; if (afterSpec && typeof afterSpec === "object" && afterSpec.then) { tasks.push(runAfterEffect(exports, afterSpec, onError)); } + const intervalSpec = value.interval; + if (intervalSpec && typeof intervalSpec === "object" && intervalSpec.then) { + runIntervalEffect(exports, intervalSpec, onError); + } + + const clearIv = value.clear_interval || value.clearInterval; + if (clearIv && typeof clearIv === "object") { + const id = String(clearIv.id || "default"); + const h = intervalHandles.get(id); + if (h != null) { + clearInterval(h); + intervalHandles.delete(id); + } + } + + const storageSpec = value.storage; + if (storageSpec && typeof storageSpec === "object" && storageSpec.op) { + tasks.push(runStorageEffect(exports, storageSpec, onError)); + } + + const wsSpec = value.ws; + if (wsSpec && typeof wsSpec === "object" && wsSpec.op) { + tasks.push(runWsEffect(exports, wsSpec, onError)); + } + return Promise.all(tasks); } +function buildFetchInit(spec) { + const method = (spec.method || "GET").toUpperCase(); + const init = { method }; + if (spec.headers && typeof spec.headers === "object") init.headers = { ...spec.headers }; + if (spec.fields && typeof spec.fields === "object" && typeof FormData !== "undefined") { + const fd = new FormData(); + for (const [k, v] of Object.entries(spec.fields)) fd.append(k, String(v)); + init.body = fd; + } else if (spec.body != null && method !== "GET" && method !== "HEAD") { + init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body); + } + return init; +} + async function runFetchEffect(exports, spec, onError) { const thenFn = spec.then; - const method = (spec.method || "GET").toUpperCase(); - const init = { method }; - if (spec.headers && typeof spec.headers === "object") { - init.headers = spec.headers; - } - if (spec.body != null && method !== "GET" && method !== "HEAD") { - init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body); - } try { - const res = await fetch(String(spec.url), init); + const res = await fetch(String(spec.url), buildFetchInit(spec)); const body = await res.text(); - const result = call(exports, thenFn, { - ok: res.ok, - status: res.status, - body, - }); + const result = call(exports, thenFn, { ok: res.ok, status: res.status, body }); if (!result.ok) { if (onError) onError(result.error); else console.error(result.error); @@ -325,6 +436,34 @@ async function runFetchEffect(exports, spec, onError) { } } +async function runFetchAllEffect(exports, spec, onError) { + const thenFn = spec.then; + const reqs = Array.isArray(spec.requests) ? spec.requests : []; + try { + const results = await Promise.all( + reqs.map(async (r) => { + try { + const res = await fetch(String(r.url), buildFetchInit(r)); + const body = await res.text(); + return { ok: res.ok, status: res.status, body, url: String(r.url) }; + } catch (e) { + return { ok: false, status: 0, body: "", error: String(e), url: String(r.url || "") }; + } + }), + ); + const result = call(exports, thenFn, { ok: true, results }); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + return; + } + await applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } +} + function runAfterEffect(exports, spec, onError) { const ms = Math.max(0, Number(spec.ms) || 0); const thenFn = spec.then; @@ -349,9 +488,182 @@ function runAfterEffect(exports, spec, onError) { }); } +function runIntervalEffect(exports, spec, onError) { + const ms = Math.max(1, Number(spec.ms) || 1000); + const thenFn = spec.then; + const id = String(spec.id || "default"); + if (intervalHandles.has(id)) { + clearInterval(intervalHandles.get(id)); + intervalHandles.delete(id); + } + const handle = setInterval(() => { + try { + const result = call(exports, thenFn, { ok: true, id }); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + return; + } + applyEffects(exports, result.value, { onError }); + if (result.stdout) console.log(result.stdout); + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } + }, ms); + intervalHandles.set(id, handle); +} + +function storageStore(scope) { + if (typeof localStorage === "undefined") return null; + return scope === "session" ? sessionStorage : localStorage; +} + +async function runStorageEffect(exports, spec, onError) { + const op = String(spec.op || "").toLowerCase(); + const key = String(spec.key || ""); + const store = storageStore(spec.scope || "local"); + if (!store) { + if (onError) onError("storage unavailable"); + return; + } + try { + if (op === "set") { + store.setItem(key, spec.value != null ? String(spec.value) : ""); + if (spec.then) { + const result = call(exports, spec.then, { ok: true, op, key }); + if (result.ok) await applyEffects(exports, result.value, { onError }); + } + return; + } + if (op === "remove" || op === "delete") { + store.removeItem(key); + if (spec.then) { + const result = call(exports, spec.then, { ok: true, op, key }); + if (result.ok) await applyEffects(exports, result.value, { onError }); + } + return; + } + if (op === "get") { + const value = store.getItem(key); + if (spec.then) { + const result = call(exports, spec.then, { + ok: true, + op, + key, + value: value == null ? "" : value, + found: value != null, + }); + if (!result.ok) { + if (onError) onError(result.error); + return; + } + await applyEffects(exports, result.value, { onError }); + } + } + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } +} + +function runWsEffect(exports, spec, onError) { + const op = String(spec.op || "").toLowerCase(); + return new Promise((resolve) => { + try { + if (op === "open") { + if (typeof WebSocket === "undefined") { + if (onError) onError("WebSocket unavailable"); + resolve(); + return; + } + const id = String(spec.id || `ws${++wsSeq}`); + const sock = new WebSocket(String(spec.url)); + wsHandles.set(id, sock); + sock.addEventListener("open", () => { + if (spec.then_open || spec.thenOpen) { + try { + const result = call(exports, spec.then_open || spec.thenOpen, { ok: true, id }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + } + resolve(); + }); + sock.addEventListener("message", (ev) => { + const thenMsg = spec.then_message || spec.thenMessage; + if (!thenMsg) return; + try { + const result = call(exports, thenMsg, { + ok: true, + id, + data: typeof ev.data === "string" ? ev.data : String(ev.data), + }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + }); + sock.addEventListener("close", () => { + wsHandles.delete(id); + const thenClose = spec.then_close || spec.thenClose; + if (thenClose) { + try { + const result = call(exports, thenClose, { ok: true, id }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + } + }); + sock.addEventListener("error", () => { + const thenErr = spec.then_error || spec.thenError; + if (thenErr) { + try { + const result = call(exports, thenErr, { ok: false, id, error: "ws error" }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + } + }); + return; + } + if (op === "send") { + const id = String(spec.id || [...wsHandles.keys()][0] || ""); + const sock = wsHandles.get(id); + if (sock && sock.readyState === WebSocket.OPEN) { + sock.send(spec.data != null ? String(spec.data) : ""); + } else if (onError) onError(`ws send: no open socket ${id}`); + resolve(); + return; + } + if (op === "close") { + const id = String(spec.id || [...wsHandles.keys()][0] || ""); + const sock = wsHandles.get(id); + if (sock) sock.close(); + wsHandles.delete(id); + resolve(); + return; + } + resolve(); + } catch (e) { + if (onError) onError(String(e)); + resolve(); + } + }); +} + +function bindTarget(sel) { + if (sel === "window" || sel === "@window") return typeof window !== "undefined" ? window : null; + if (sel === "document" || sel === "@document") + return typeof document !== "undefined" ? document : null; + return null; +} + /** - * Wire events from `# main` return value. - * Accepts a list of row maps, or `{ wire: [...] }`. + * Wire events from `# main` return value (list or `{ wire: [...] }`). */ export function wireEvents(exports, bootValue, { onError } = {}) { let rows = []; @@ -364,12 +676,47 @@ export function wireEvents(exports, bootValue, { onError } = {}) { const fn = row["调用"] || row.call || row.fn; const valueFrom = row["值选择器"] || row.value_from || row.valueFrom || row.from || ""; + const delegate = + row["委托"] || row.delegate || row.delegation || ""; if (!sel || !fn) continue; - const nodes = document.querySelectorAll(sel); - nodes.forEach((node) => { + + const special = bindTarget(sel); + const roots = special + ? [special] + : typeof document !== "undefined" + ? [...document.querySelectorAll(sel)] + : []; + + roots.forEach((node) => { node.addEventListener(ev, (domEv) => { try { + if (delegate) { + const hit = + typeof domEv.target?.closest === "function" + ? domEv.target.closest(delegate) + : null; + if (!hit || (node.contains && !node.contains(hit))) return; + } + if ( + ev === "click" && + typeof domEv.target?.closest === "function" && + domEv.target.closest("a[href]") + ) { + try { + domEv.preventDefault(); + } catch (_) { + /* ignore */ + } + } const args = eventArgsFromDom(domEv, valueFrom); + if (delegate && domEv.target) { + const hit = domEv.target.closest?.(delegate); + if (hit?.getAttribute) { + const did = hit.getAttribute("data-id"); + if (did != null) args.data_id = did; + if (hit.id) args.id = hit.id; + } + } const result = call(exports, fn, args); if (!result.ok) { if (onError) onError(result.error); @@ -459,10 +806,6 @@ function wirePlayground(exports, playgroundSpec, { onError } = {}) { return 1; } -/** - * One-shot: load wasm, boot session (or playground), wire events. - * @returns {{ exports, boot, wired }} - */ export async function mount(rawOpts = {}) { const opts = normalizeMountOptions(rawOpts); const onError = (err) => markError(opts, err); @@ -505,7 +848,6 @@ export async function mount(rawOpts = {}) { throw new Error(result.error || "boot failed"); } - // If boot value is a map with effects alongside wire, apply them. if (result.value && !Array.isArray(result.value)) { await applyEffects(exports, result.value, { onError }); } @@ -516,7 +858,6 @@ export async function mount(rawOpts = {}) { return { exports, boot: result, wired: n }; } -/** Auto-mount from DOM configs (route D). */ export async function autoMount(doc) { const configs = collectMountConfigs(doc); const results = []; diff --git a/doc/README.md b/doc/README.md index 26658b0..a2ed525 100644 --- a/doc/README.md +++ b/doc/README.md @@ -61,7 +61,7 @@ | [design/table-cell-expressions.md](design/table-cell-expressions.md) | **表数据单元格 = 表达式**(同调用实参值语法;Accepted) | | [roadmap/browser-wasm.md](roadmap/browser-wasm.md) | **浏览器 WASM 路线 C(C0–C5 Completed)** | | [roadmap/browser-wasm-d.md](roadmap/browser-wasm-d.md) | **路线 D:作者零 JS 前端(Completed)** | -| [roadmap/browser-wasm-e.md](roadmap/browser-wasm-e.md) | **路线 E:前端能力补齐(Planned)** | +| [roadmap/browser-wasm-e.md](roadmap/browser-wasm-e.md) | **路线 E:前端能力补齐(Active)** | | [design/browser-marqdo-wasm.md](design/browser-marqdo-wasm.md) | **浏览器 Marqdo(WASM)设计** | | [roadmap/ext-quantum.md](roadmap/ext-quantum.md) | **规划:`ext/quantum` 量子模拟**(基础门·电路·ABI·`ext add`) | | [research/okf-and-marqdo.md](research/okf-and-marqdo.md) | OKF 调研 | diff --git a/doc/design/browser-marqdo-wasm.md b/doc/design/browser-marqdo-wasm.md index 70b8f49..1ce8877 100644 --- a/doc/design/browser-marqdo-wasm.md +++ b/doc/design/browser-marqdo-wasm.md @@ -345,27 +345,43 @@ L1:`web.dom_patch` / `网页.DOM补丁` 合并效应键;`web.text_patch` / ` | # | 非目标 | |---|--------| | D-N1 | 用 Marqdo 重写 bridge 自身 | -| D-N2 | 通用 VDOM / 客户端路由框架 | -| D-N3 | 开放无前缀的 `set_html` | +| D-N2 | 作者手写业务 JS / TS(官方桥内机制允许) | +| D-N3 | ~~开放无前缀的 set_html~~(E 已允许任意选择器;内容由 MQ 产出) | --- -## 17. 路线 E — 前端能力补齐(Planned) +## 17. 路线 E — 前端能力补齐(Active) 路线图:[browser-wasm-e.md](../roadmap/browser-wasm-e.md)。 -**审视结论:** C+D 胜任中小型交互(挂载、wire、表单、单次 fetch);**不能**替代大部分前端 JS,直到 E 波补齐路由、存储、列表片段、WebSocket、更细 DOM/定时。 +**原则:** 唯一硬禁是**作者手写业务 JS**。官方 bridge 可实现列表装配、路由、storage、WebSocket、内部模板/轻量 VDOM 等;作者只写 `.mq.md` + 效应表。 | 波 | 要点 | |----|------| -| E1 | `set_style` / `focus` / 委托事件 / 键盘 | -| E2 | 受信列表/片段装配 L1 | -| E3 | `navigate` + `popstate` | -| E4 | `storage` 效应 | -| E5 | 浏览器 `ws` 效应 | -| E6 | 并行 fetch / interval / FormData | +| E1 | `set_style` / `focus` / `blur` / `scroll_into`;wire `委托`;键盘事件 | +| E2 | `set_html` / `replace_children` / `render_list` | +| E3 | `navigate` + `popstate`(选择器 `window`) | +| E4 | `storage` `{ op, key, value?, scope?, then? }` | +| E5 | `ws` `{ op: open\|send\|close, … }` | +| E6 | `fetch_all` / `interval` / `clear_interval` / fetch `fields` | ---- +### 17.1 效应速查(E) + +| 字段 | 含义 | +|------|------| +| `set_style` | `{ "#sel": { color: "red" } }` 或 `{ "#sel": "color:red" }` | +| `focus` / `blur` | `"#sel"` 或选择器数组 | +| `scroll_into` | `"#sel"` | +| `set_html` / `replace_children` | `{ "#sel": "…" }`(内容由 MQ 产出;XSS 由作者保证) | +| `render_list` | `{ "#sel": { tag: "li", items: ["a", { text, class, attrs }] } }` | +| `navigate` | `{ url, replace?: bool }` | +| `storage` | `{ op: get\|set\|remove, key, value?, scope?: local\|session, then? }` | +| `ws` | `{ op: open\|send\|close, url?, data?, id?, then_message?, then_open?, … }` | +| `fetch_all` | `{ requests: [fetchSpec…], then }` → `mq_call` 得 `{ results: [...] }` | +| `interval` | `{ ms, then, id? }`;`clear_interval: { id }` | +| `fetch.fields` | 对象 → `FormData` body | + +Wire 列:`委托` / `delegate` = 在容器上监听,目标须 `closest(delegate)`;选择器 `window` 绑 `window`。 ## 15. 决策摘要 diff --git a/doc/roadmap/browser-wasm-e.md b/doc/roadmap/browser-wasm-e.md index 21d0792..8dfc823 100644 --- a/doc/roadmap/browser-wasm-e.md +++ b/doc/roadmap/browser-wasm-e.md @@ -2,54 +2,39 @@ | | | |---|---| -| 状态 | **Planned** | +| 状态 | **Active** | | 日期 | 2026-09-04 | | 前置 | [browser-wasm-d.md](browser-wasm-d.md)(D0–D4 **Completed**) | | 设计 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) §16–§17 | -## 结论(能力审视) +## 原则(已修正) -路线 C+D 已能覆盖**中小型交互站**的常见路径:挂载会话、wire 事件、文本/表单回写、`fetch`/`after`、作者零业务 JS。 +**禁止的只有:作者手写业务 JS。** +官方 `marqdo-bridge.js` / 构建生成物可以包含任意宿主机制(含轻量列表装配、路由、存储、WebSocket、内部模板等)。不要求「禁止 VDOM / 禁止 eval」——那些若放在官方桥内、对作者不可见,则允许。 -**尚不能**宣称「替代大部分 / 全部前端 JS」。缺口集中在:列表级 UI 装配、客户端路由与历史、本地持久化、实时通道、媒体/画布、以及更细的 DOM 读写与委托事件。 +## 结论 -| 类别 | 今日 | 典型 JS 任务 | 路线 E | -|------|------|--------------|--------| -| 启动 / 会话 | `mount` / `client_embed` | 手写 loader | 已够用 | -| 点击 / 表单 | wire + `value`/`fields` | addEventListener | 扩委托 / 更多事件 | -| DOM 补丁 | `set_text`/`value`/`attr`/`class` | jQuery 式改节点 | `set_style`、`focus`、`scroll`、列表 diff | -| 网络 | 单次 `fetch` 效应 | axios / 多并行 | 并行 `fetch_all`、上传进度 | -| 定时 | `after` | setInterval | `interval` / `cancel` | -| 路由 | 无 | history / SPA | `navigate` / `popstate` wire | -| 存储 | 无 | localStorage / IDB | `storage` 效应 | -| 实时 | 服务端有 `ws`;浏览器无 | WebSocket | 浏览器 `ws` 效应 | -| 组件列表 | SSR 为主 | 客户端 render list | `set_html(#trusted*)` + 模板装配 L1 | -| 媒体 / 画布 | 无 | Audio / Canvas / WebGL | 后置(非 E 核心) | -| 原生插件 | 浏览器无 `.so` | wasm 插件 | 明确非目标 | - -原则不变:官方 bridge 仍是宿主胶;业务只写 `.mq.md`;不引入通用 VDOM / 任意 `eval(JS)`。 +C+D 覆盖中小型交互;E 波补齐后,作者可仅用 `.mq.md` 完成大部分前端任务(列表 UI、SPA 导航、草稿存储、WS、并行请求)。 ## 阶段 | 阶段 | 内容 | 状态 | |------|------|------| -| **E0** | 本文 + 设计 §17 能力矩阵 | **done**(文档) | -| **E1** | DOM 补齐:`set_style`、`focus`/`blur`、`scroll_into`;wire `keydown`/`keyup`;事件委托(可选 `委托` 列) | planned | -| **E2** | 列表 / 片段:`replace_children` 或受信 `#trusted*` 模板 L1(`web.client_list`);避免手写巨段 HTML | planned | -| **E3** | 客户端路由:`navigate` / `replace` 效应 + `popstate` wire;与 `ext/web` SSR 深链共存约定 | planned | -| **E4** | 持久化:`storage.get/set/remove`(local/session);可选简单 cookie 读写白名单 | planned | -| **E5** | 实时:浏览器 `ws` 效应(open / send / on_message → `mq_call`);对齐服务端 `ws` 语义 | planned | -| **E6** | 异步增强:`fetch` 并行表、`interval`+`clear`、上传 `FormData` 字段表 | planned | +| **E0** | 原则修正 + 能力矩阵 | **done** | +| **E1** | `set_style` / `focus` / `blur` / `scroll_into`;键盘;wire `委托` | **done** | +| **E2** | `set_html`(任意选择器)/ `replace_children` / `render_list`;L1 `list_html` | **done** | +| **E3** | `navigate` / `replace`;`window`+`popstate` wire | **done** | +| **E4** | `storage` get/set/remove(local/session) | **done** | +| **E5** | `ws` open/send/close + message 回调 | **done** | +| **E6** | `fetch_all` / `interval`+`clear_interval` / fetch `fields`→FormData | **done** | -## 验收(E 收口时) +## 验收 -- 无作者业务 JS 的情况下,可做:多页客户端导航、表单草稿存 localStorage、列表增删改、同源 WebSocket 回显。 -- 冒烟 / 示例覆盖 E1–E5 各至少一例。 -- 体积与安全:效应仍白名单;`set_html` 维持 `#trusted*` 前缀。 +- 示例 `examples/browser-app/`:无作者 `.js`,覆盖列表、storage、navigate、interval(及可选 ws 说明)。 +- 冒烟覆盖 normalize + 关键效应解析(Node);DOM/WS 以桥内实现为准。 -## 明确非目标(E) +## 非目标 -- React/Vue 式 VDOM 与虚拟列表框架 +- 作者仓库中的业务 `.js` / `.ts` - 浏览器内 SQLite / 完整 ORM -- Service Worker / PWA 全套(可另开路线) -- 用 Marqdo 重写 bridge 自身 +- 强制作者学习官方桥源码(桥对作者不透明即可) diff --git a/examples/browser-app/README.md b/examples/browser-app/README.md new file mode 100644 index 0000000..173d295 --- /dev/null +++ b/examples/browser-app/README.md @@ -0,0 +1,18 @@ +# browser-app(路线 E) + +作者**零业务 JS**:官方 bridge 自启;交互在 `app.mq.md`。 + +覆盖:`set_html` 列表、`storage` 草稿、`navigate`+`popstate`、`interval`、事件 `委托`。 + +```bash +# 仓库根 +cargo build -p marqdo --release +./target/release/marqdo wasm build -o examples/browser-app +# 若 build 覆盖 bridge,可再:cp crates/marqdo-wasm/js/marqdo-bridge.js examples/browser-app/ + +cd examples/browser-app +python3 -m http.server 8766 +# http://127.0.0.1:8766/ +``` + +原则:禁止作者手写 JS;官方桥内机制(列表装配、路由、存储等)允许。见 [browser-wasm-e.md](../../doc/roadmap/browser-wasm-e.md)。 diff --git a/examples/browser-app/app.mq.md b/examples/browser-app/app.mq.md new file mode 100644 index 0000000..cc61f8d --- /dev/null +++ b/examples/browser-app/app.mq.md @@ -0,0 +1,138 @@ +--- +title: browser-app (route E) +description: list html, storage, navigate, interval — author zero JS +import json:lib/json.mq.md +--- + +# main + +*`ticks` = 0* +*`items_html` = ""* +*`path` = "/"* + +`wire` = + +| @ | 选择器 | 事件 | 调用 | 委托 | 值选择器 | +|---|--------|------|------|------|----------| +| 1 | "#add" | click | add | | "#draft" | +| 2 | "#save" | click | save_draft | | "#draft" | +| 3 | "#load" | click | load_draft | | | +| 4 | "#start-tick" | click | start_tick | | | +| 5 | "#stop-tick" | click | stop_tick | | | +| 6 | "#nav-home" | click | go_home | | | +| 7 | "#nav-about" | click | go_about | | | +| 8 | "window" | popstate | on_pop | | | +| 9 | "#items" | click | on_item | "button" | | + +*`nav` = > json.set map=None key="url" value="/"* +*`boot` = > json.set map=None key="wire" value=wire* +*`boot` = > json.set map=boot key="navigate" value=nav* +*`st` = > json.set map=None key="op" value="get"* +*`st` = > json.set map=st key="key" value="mq-draft"* +*`st` = > json.set map=st key="then" value="on_draft"* +**> json.set map=boot key="storage" value=st** + +## add + + `value`="" + +1. `value` != "" + *`items_html` = items_html + "
路线 E:列表 / storage / navigate / interval — 无作者业务 JS,逻辑在 app.mq.md。
path: /
+ + +计时:0s + + +
+客户端路由用 navigate + popstate;列表用官方桥 render_list。
loading…+ + + diff --git a/examples/browser-app/marqdo-bridge.js b/examples/browser-app/marqdo-bridge.js new file mode 100644 index 0000000..f5e48d5 --- /dev/null +++ b/examples/browser-app/marqdo-bridge.js @@ -0,0 +1,881 @@ +/** + * Canonical Marqdo browser bridge (routes C/D/E). Host glue only — not app logic. + * Authors write .mq.md only; this file may grow host mechanisms freely. + * + * ABI: mq_alloc, mq_dealloc, mq_run, mq_boot, mq_call, mq_version + * Effects: set_text, set_value, set_attr, set_class, toggle_class, set_style, + * focus, blur, scroll_into, set_html, replace_children, render_list, + * navigate, storage, ws, fetch, fetch_all, after, interval, clear_interval + */ + +export function readCString(memory, ptr) { + const bytes = new Uint8Array(memory.buffer); + let end = ptr; + while (bytes[end] !== 0) end += 1; + return new TextDecoder().decode(bytes.subarray(ptr, end)); +} + +function decodePacked(exports, outPtr) { + if (!outPtr) throw new Error("null wasm result pointer"); + const view = new DataView(exports.memory.buffer); + const jsonLen = view.getUint32(outPtr, true); + const jsonBytes = new Uint8Array(exports.memory.buffer, outPtr + 4, jsonLen); + const text = new TextDecoder().decode(jsonBytes); + exports.mq_dealloc(outPtr, 4 + jsonLen); + return JSON.parse(text); +} + +function writeUtf8(exports, text) { + const encoded = new TextEncoder().encode(text); + const ptr = exports.mq_alloc(encoded.length || 1); + if (!ptr) throw new Error("mq_alloc failed"); + new Uint8Array(exports.memory.buffer, ptr, encoded.length).set(encoded); + return { ptr, len: encoded.length }; +} + +export function runSource(exports, source) { + const { ptr, len } = writeUtf8(exports, source); + const outPtr = exports.mq_run(ptr, len); + exports.mq_dealloc(ptr, len || 1); + return decodePacked(exports, outPtr); +} + +export function boot(exports, source) { + const { ptr, len } = writeUtf8(exports, source); + const outPtr = exports.mq_boot(ptr, len); + exports.mq_dealloc(ptr, len || 1); + return decodePacked(exports, outPtr); +} + +export function call(exports, name, argsObj = {}) { + const n = writeUtf8(exports, name); + const a = writeUtf8(exports, JSON.stringify(argsObj ?? {})); + const outPtr = exports.mq_call(n.ptr, n.len, a.ptr, a.len); + exports.mq_dealloc(n.ptr, n.len || 1); + exports.mq_dealloc(a.ptr, a.len || 1); + return decodePacked(exports, outPtr); +} + +export async function loadWasm(url = "./marqdo_wasm.wasm") { + const res = await fetch(url); + if (!res.ok) { + throw new Error( + `failed to fetch ${url} (${res.status}). Build with: marqdo wasm build -o .`, + ); + } + const { instance } = await WebAssembly.instantiateStreaming(res, {}); + return instance.exports; +} + +function isPlainObject(v) { + return v != null && typeof v === "object" && !Array.isArray(v); +} + +function asSelList(v) { + if (v == null) return []; + if (Array.isArray(v)) return v.map(String); + return [String(v)]; +} + +/** Normalize mount options from plain object or DOM dataset. */ +export function normalizeMountOptions(raw = {}) { + const o = raw && typeof raw === "object" ? raw : {}; + const dataset = o.dataset || {}; + const wasmUrl = + o.wasmUrl || o.wasm || dataset.mqWasm || dataset.wasm || "./marqdo_wasm.wasm"; + const sourceUrl = + o.sourceUrl || o.source_url || dataset.mqSourceUrl || dataset.sourceUrl || ""; + let source = o.source != null ? o.source : dataset.mqSource || ""; + if (!source && typeof o.sourceInline === "string") source = o.sourceInline; + const playground = o.playground || dataset.mqPlayground || dataset.playground || ""; + const ready = o.ready || o.readySel || dataset.mqReady || ""; + const enable = o.enable || dataset.mqEnable || ""; + const noBoot = + o.noBoot === true || dataset.mqNoBoot === "1" || dataset.mqNoBoot === "true"; + return { + wasmUrl: String(wasmUrl), + sourceUrl: sourceUrl ? String(sourceUrl) : "", + source: source ? String(source) : "", + playground: playground ? String(playground) : "", + ready: ready ? String(ready) : "", + enable: enable ? String(enable) : "", + noBoot, + onError: typeof o.onError === "function" ? o.onError : null, + }; +} + +export function collectMountConfigs(doc = typeof document !== "undefined" ? document : null) { + if (!doc) return []; + const out = []; + const bootEl = doc.getElementById("marqdo-boot"); + if (bootEl) { + try { + out.push(normalizeMountOptions(JSON.parse(bootEl.textContent || "{}"))); + } catch (e) { + console.error("marqdo-boot JSON:", e); + } + } + const scripts = doc.querySelectorAll( + "script[data-mq-source-url], script[data-mq-source], script[data-mq-playground], script[data-mq-wasm]", + ); + for (const el of scripts) { + if (el.dataset.mqNoBoot === "1" || el.dataset.mqNoBoot === "true") continue; + const hasWork = + el.dataset.mqSourceUrl || el.dataset.mqSource || el.dataset.mqPlayground; + if (!hasWork) continue; + out.push( + normalizeMountOptions({ + dataset: el.dataset, + wasmUrl: el.dataset.mqWasm, + sourceUrl: el.dataset.mqSourceUrl, + source: el.dataset.mqSource, + playground: el.dataset.mqPlayground, + ready: el.dataset.mqReady, + enable: el.dataset.mqEnable, + }), + ); + } + return out; +} + +export function eventArgsFromDom(ev, valueFromSel) { + const t = ev && ev.target; + const args = { event: ev && ev.type ? ev.type : "click" }; + if (t && typeof t === "object") { + if ("value" in t && t.value != null) args.value = String(t.value); + if ("checked" in t) args.checked = !!t.checked; + if (t.id) args.id = String(t.id); + if (t.getAttribute) { + const did = t.getAttribute("data-id"); + if (did != null) args.data_id = did; + } + if (typeof t.textContent === "string" && !("value" in t)) { + args.text = t.textContent; + } + if (ev.key != null) args.key = String(ev.key); + if (ev.code != null) args.code = String(ev.code); + } + if (ev && ev.type === "popstate") { + args.url = typeof location !== "undefined" ? location.href : ""; + args.path = typeof location !== "undefined" ? location.pathname + location.search : ""; + args.state = ev.state; + } + if (valueFromSel && typeof document !== "undefined") { + const src = document.querySelector(valueFromSel); + if (src) { + if ("value" in src) args.value = String(src.value); + else args.value = src.textContent != null ? String(src.textContent) : ""; + } + } + if (ev && ev.type === "submit" && t) { + const form = typeof t.closest === "function" ? t.closest("form") : t; + if (form && typeof FormData !== "undefined") { + try { + ev.preventDefault(); + } catch (_) { + /* ignore */ + } + const fields = {}; + for (const [k, v] of new FormData(form)) fields[k] = String(v); + args.fields = fields; + } + } + return args; +} + +function applyStyle(el, styleVal) { + if (typeof styleVal === "string") { + el.setAttribute("style", styleVal); + return; + } + if (isPlainObject(styleVal)) { + for (const [k, v] of Object.entries(styleVal)) { + if (v === null || v === false) el.style.removeProperty(k); + else el.style.setProperty(k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase()), String(v)); + } + } +} + +export function renderListItems(spec) { + const tag = String(spec.tag || "li"); + const items = Array.isArray(spec.items) ? spec.items : []; + return items + .map((it) => { + if (it == null) return ""; + if (typeof it === "string" || typeof it === "number") { + return `<${tag}>${escapeHtml(String(it))}${tag}>`; + } + if (!isPlainObject(it)) return ""; + const text = it.text != null ? String(it.text) : it.html != null ? null : ""; + const cls = it.class != null ? ` class="${escapeAttr(String(it.class))}"` : ""; + let attrs = ""; + if (isPlainObject(it.attrs)) { + for (const [k, v] of Object.entries(it.attrs)) { + if (v === null || v === false) continue; + attrs += ` ${escapeAttr(k)}="${escapeAttr(String(v))}"`; + } + } + const inner = it.html != null ? String(it.html) : escapeHtml(text ?? ""); + return `<${tag}${cls}${attrs}>${inner}${tag}>`; + }) + .join(""); +} + +function escapeHtml(s) { + return s + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +function escapeAttr(s) { + return escapeHtml(s).replace(/'/g, "'"); +} + +/** Sync DOM patches (E1/E2/E3 navigate is sync too). */ +export function applyDomPatch(value) { + if (!value || typeof value !== "object") return; + if (typeof document === "undefined") return; + + const setText = value.set_text || value.setText; + if (isPlainObject(setText)) { + for (const [sel, text] of Object.entries(setText)) { + const el = document.querySelector(sel); + if (el) el.textContent = String(text); + } + } + + const setValue = value.set_value || value.setValue; + if (isPlainObject(setValue)) { + for (const [sel, v] of Object.entries(setValue)) { + const el = document.querySelector(sel); + if (el && "value" in el) el.value = String(v); + } + } + + const setAttr = value.set_attr || value.setAttr; + if (isPlainObject(setAttr)) { + for (const [sel, attrs] of Object.entries(setAttr)) { + const el = document.querySelector(sel); + if (!el || !isPlainObject(attrs)) continue; + for (const [name, raw] of Object.entries(attrs)) { + if (raw === null || raw === false) el.removeAttribute(name); + else el.setAttribute(name, String(raw)); + } + } + } + + const setClass = value.set_class || value.setClass; + if (isPlainObject(setClass)) { + for (const [sel, cls] of Object.entries(setClass)) { + const el = document.querySelector(sel); + if (el) el.className = String(cls); + } + } + + const toggleClass = value.toggle_class || value.toggleClass; + if (isPlainObject(toggleClass)) { + for (const [sel, cls] of Object.entries(toggleClass)) { + const el = document.querySelector(sel); + if (el && cls) el.classList.toggle(String(cls)); + } + } + + const setStyle = value.set_style || value.setStyle; + if (isPlainObject(setStyle)) { + for (const [sel, st] of Object.entries(setStyle)) { + const el = document.querySelector(sel); + if (el) applyStyle(el, st); + } + } + + for (const sel of asSelList(value.focus)) { + const el = document.querySelector(sel); + if (el && el.focus) el.focus(); + } + for (const sel of asSelList(value.blur)) { + const el = document.querySelector(sel); + if (el && el.blur) el.blur(); + } + for (const sel of asSelList(value.scroll_into || value.scrollInto)) { + const el = document.querySelector(sel); + if (el && el.scrollIntoView) el.scrollIntoView({ block: "nearest", behavior: "smooth" }); + } + + const setHtml = value.set_html || value.setHtml; + if (isPlainObject(setHtml)) { + for (const [sel, html] of Object.entries(setHtml)) { + const el = document.querySelector(sel); + if (el) el.innerHTML = String(html); + } + } + + const replaceChildren = value.replace_children || value.replaceChildren; + if (isPlainObject(replaceChildren)) { + for (const [sel, html] of Object.entries(replaceChildren)) { + const el = document.querySelector(sel); + if (el) el.innerHTML = String(html); + } + } + + const renderList = value.render_list || value.renderList; + if (isPlainObject(renderList)) { + for (const [sel, spec] of Object.entries(renderList)) { + const el = document.querySelector(sel); + if (!el || !isPlainObject(spec)) continue; + el.innerHTML = renderListItems(spec); + } + } + + const nav = value.navigate; + if (isPlainObject(nav) && nav.url != null && typeof history !== "undefined") { + const url = String(nav.url); + if (nav.replace) history.replaceState(nav.state ?? null, "", url); + else history.pushState(nav.state ?? null, "", url); + } +} + +const intervalHandles = new Map(); +const wsHandles = new Map(); +let wsSeq = 0; + +/** + * Run sync DOM patches then schedule async effects. + */ +export function applyEffects(exports, value, { onError } = {}) { + applyDomPatch(value); + if (!value || typeof value !== "object") return Promise.resolve(); + + const tasks = []; + + const fetchSpec = value.fetch; + if (fetchSpec && typeof fetchSpec === "object" && fetchSpec.url && fetchSpec.then) { + tasks.push(runFetchEffect(exports, fetchSpec, onError)); + } + + const fetchAll = value.fetch_all || value.fetchAll; + if (fetchAll && typeof fetchAll === "object" && fetchAll.then) { + tasks.push(runFetchAllEffect(exports, fetchAll, onError)); + } + + const afterSpec = value.after; + if (afterSpec && typeof afterSpec === "object" && afterSpec.then) { + tasks.push(runAfterEffect(exports, afterSpec, onError)); + } + + const intervalSpec = value.interval; + if (intervalSpec && typeof intervalSpec === "object" && intervalSpec.then) { + runIntervalEffect(exports, intervalSpec, onError); + } + + const clearIv = value.clear_interval || value.clearInterval; + if (clearIv && typeof clearIv === "object") { + const id = String(clearIv.id || "default"); + const h = intervalHandles.get(id); + if (h != null) { + clearInterval(h); + intervalHandles.delete(id); + } + } + + const storageSpec = value.storage; + if (storageSpec && typeof storageSpec === "object" && storageSpec.op) { + tasks.push(runStorageEffect(exports, storageSpec, onError)); + } + + const wsSpec = value.ws; + if (wsSpec && typeof wsSpec === "object" && wsSpec.op) { + tasks.push(runWsEffect(exports, wsSpec, onError)); + } + + return Promise.all(tasks); +} + +function buildFetchInit(spec) { + const method = (spec.method || "GET").toUpperCase(); + const init = { method }; + if (spec.headers && typeof spec.headers === "object") init.headers = { ...spec.headers }; + if (spec.fields && typeof spec.fields === "object" && typeof FormData !== "undefined") { + const fd = new FormData(); + for (const [k, v] of Object.entries(spec.fields)) fd.append(k, String(v)); + init.body = fd; + } else if (spec.body != null && method !== "GET" && method !== "HEAD") { + init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body); + } + return init; +} + +async function runFetchEffect(exports, spec, onError) { + const thenFn = spec.then; + try { + const res = await fetch(String(spec.url), buildFetchInit(spec)); + const body = await res.text(); + const result = call(exports, thenFn, { ok: res.ok, status: res.status, body }); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + return; + } + await applyEffects(exports, result.value, { onError }); + if (result.stdout) console.log(result.stdout); + } catch (e) { + try { + const result = call(exports, thenFn, { + ok: false, + status: 0, + body: "", + error: String(e), + }); + if (result.ok) await applyEffects(exports, result.value, { onError }); + else if (onError) onError(result.error); + } catch (e2) { + if (onError) onError(String(e2)); + else console.error(e2); + } + } +} + +async function runFetchAllEffect(exports, spec, onError) { + const thenFn = spec.then; + const reqs = Array.isArray(spec.requests) ? spec.requests : []; + try { + const results = await Promise.all( + reqs.map(async (r) => { + try { + const res = await fetch(String(r.url), buildFetchInit(r)); + const body = await res.text(); + return { ok: res.ok, status: res.status, body, url: String(r.url) }; + } catch (e) { + return { ok: false, status: 0, body: "", error: String(e), url: String(r.url || "") }; + } + }), + ); + const result = call(exports, thenFn, { ok: true, results }); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + return; + } + await applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } +} + +function runAfterEffect(exports, spec, onError) { + const ms = Math.max(0, Number(spec.ms) || 0); + const thenFn = spec.then; + return new Promise((resolve) => { + setTimeout(() => { + try { + const result = call(exports, thenFn, { ok: true }); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + resolve(); + return; + } + Promise.resolve(applyEffects(exports, result.value, { onError })).then(resolve); + if (result.stdout) console.log(result.stdout); + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + resolve(); + } + }, ms); + }); +} + +function runIntervalEffect(exports, spec, onError) { + const ms = Math.max(1, Number(spec.ms) || 1000); + const thenFn = spec.then; + const id = String(spec.id || "default"); + if (intervalHandles.has(id)) { + clearInterval(intervalHandles.get(id)); + intervalHandles.delete(id); + } + const handle = setInterval(() => { + try { + const result = call(exports, thenFn, { ok: true, id }); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + return; + } + applyEffects(exports, result.value, { onError }); + if (result.stdout) console.log(result.stdout); + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } + }, ms); + intervalHandles.set(id, handle); +} + +function storageStore(scope) { + if (typeof localStorage === "undefined") return null; + return scope === "session" ? sessionStorage : localStorage; +} + +async function runStorageEffect(exports, spec, onError) { + const op = String(spec.op || "").toLowerCase(); + const key = String(spec.key || ""); + const store = storageStore(spec.scope || "local"); + if (!store) { + if (onError) onError("storage unavailable"); + return; + } + try { + if (op === "set") { + store.setItem(key, spec.value != null ? String(spec.value) : ""); + if (spec.then) { + const result = call(exports, spec.then, { ok: true, op, key }); + if (result.ok) await applyEffects(exports, result.value, { onError }); + } + return; + } + if (op === "remove" || op === "delete") { + store.removeItem(key); + if (spec.then) { + const result = call(exports, spec.then, { ok: true, op, key }); + if (result.ok) await applyEffects(exports, result.value, { onError }); + } + return; + } + if (op === "get") { + const value = store.getItem(key); + if (spec.then) { + const result = call(exports, spec.then, { + ok: true, + op, + key, + value: value == null ? "" : value, + found: value != null, + }); + if (!result.ok) { + if (onError) onError(result.error); + return; + } + await applyEffects(exports, result.value, { onError }); + } + } + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } +} + +function runWsEffect(exports, spec, onError) { + const op = String(spec.op || "").toLowerCase(); + return new Promise((resolve) => { + try { + if (op === "open") { + if (typeof WebSocket === "undefined") { + if (onError) onError("WebSocket unavailable"); + resolve(); + return; + } + const id = String(spec.id || `ws${++wsSeq}`); + const sock = new WebSocket(String(spec.url)); + wsHandles.set(id, sock); + sock.addEventListener("open", () => { + if (spec.then_open || spec.thenOpen) { + try { + const result = call(exports, spec.then_open || spec.thenOpen, { ok: true, id }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + } + resolve(); + }); + sock.addEventListener("message", (ev) => { + const thenMsg = spec.then_message || spec.thenMessage; + if (!thenMsg) return; + try { + const result = call(exports, thenMsg, { + ok: true, + id, + data: typeof ev.data === "string" ? ev.data : String(ev.data), + }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + }); + sock.addEventListener("close", () => { + wsHandles.delete(id); + const thenClose = spec.then_close || spec.thenClose; + if (thenClose) { + try { + const result = call(exports, thenClose, { ok: true, id }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + } + }); + sock.addEventListener("error", () => { + const thenErr = spec.then_error || spec.thenError; + if (thenErr) { + try { + const result = call(exports, thenErr, { ok: false, id, error: "ws error" }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + } + }); + return; + } + if (op === "send") { + const id = String(spec.id || [...wsHandles.keys()][0] || ""); + const sock = wsHandles.get(id); + if (sock && sock.readyState === WebSocket.OPEN) { + sock.send(spec.data != null ? String(spec.data) : ""); + } else if (onError) onError(`ws send: no open socket ${id}`); + resolve(); + return; + } + if (op === "close") { + const id = String(spec.id || [...wsHandles.keys()][0] || ""); + const sock = wsHandles.get(id); + if (sock) sock.close(); + wsHandles.delete(id); + resolve(); + return; + } + resolve(); + } catch (e) { + if (onError) onError(String(e)); + resolve(); + } + }); +} + +function bindTarget(sel) { + if (sel === "window" || sel === "@window") return typeof window !== "undefined" ? window : null; + if (sel === "document" || sel === "@document") + return typeof document !== "undefined" ? document : null; + return null; +} + +/** + * Wire events from `# main` return value (list or `{ wire: [...] }`). + */ +export function wireEvents(exports, bootValue, { onError } = {}) { + let rows = []; + if (Array.isArray(bootValue)) rows = bootValue; + else if (bootValue && Array.isArray(bootValue.wire)) rows = bootValue.wire; + + for (const row of rows) { + const sel = row["选择器"] || row.selector || row.sel; + const ev = row["事件"] || row.event || "click"; + const fn = row["调用"] || row.call || row.fn; + const valueFrom = + row["值选择器"] || row.value_from || row.valueFrom || row.from || ""; + const delegate = + row["委托"] || row.delegate || row.delegation || ""; + if (!sel || !fn) continue; + + const special = bindTarget(sel); + const roots = special + ? [special] + : typeof document !== "undefined" + ? [...document.querySelectorAll(sel)] + : []; + + roots.forEach((node) => { + node.addEventListener(ev, (domEv) => { + try { + if (delegate) { + const hit = + typeof domEv.target?.closest === "function" + ? domEv.target.closest(delegate) + : null; + if (!hit || (node.contains && !node.contains(hit))) return; + } + if ( + ev === "click" && + typeof domEv.target?.closest === "function" && + domEv.target.closest("a[href]") + ) { + try { + domEv.preventDefault(); + } catch (_) { + /* ignore */ + } + } + const args = eventArgsFromDom(domEv, valueFrom); + if (delegate && domEv.target) { + const hit = domEv.target.closest?.(delegate); + if (hit?.getAttribute) { + const did = hit.getAttribute("data-id"); + if (did != null) args.data_id = did; + if (hit.id) args.id = hit.id; + } + } + const result = call(exports, fn, args); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + return; + } + applyEffects(exports, result.value, { onError }); + if (result.stdout) console.log(result.stdout); + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } + }); + }); + } + return rows.length; +} + +function markReady(opts, message) { + if (opts.ready && typeof document !== "undefined") { + const el = document.querySelector(opts.ready); + if (el) { + el.classList?.remove?.("err"); + el.textContent = message; + } + } + if (opts.enable && typeof document !== "undefined") { + for (const sel of String(opts.enable).split(",")) { + const s = sel.trim(); + if (!s) continue; + document.querySelectorAll(s).forEach((n) => { + n.disabled = false; + n.removeAttribute("disabled"); + }); + } + } +} + +function markError(opts, err) { + const msg = String(err); + if (opts.onError) opts.onError(msg); + if (opts.ready && typeof document !== "undefined") { + const el = document.querySelector(opts.ready); + if (el) { + el.classList?.add?.("err"); + el.textContent = msg; + } + } else { + console.error(msg); + } +} + +function wirePlayground(exports, playgroundSpec, { onError } = {}) { + const parts = String(playgroundSpec) + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + const sourceSel = parts[0] || "#src"; + const runSel = parts[1] || "#run"; + const outSel = parts[2] || "#out"; + const runBtn = document.querySelector(runSel); + const src = document.querySelector(sourceSel); + const out = document.querySelector(outSel); + if (!runBtn || !src) return 0; + runBtn.disabled = false; + runBtn.removeAttribute("disabled"); + runBtn.addEventListener("click", () => { + try { + const result = runSource(exports, src.value || ""); + if (out) { + out.classList?.toggle?.("err", !result.ok); + out.textContent = result.ok + ? (result.stdout || "(empty stdout)") + + (result.value != null && result.value !== "None" + ? `\n[return] ${typeof result.value === "string" ? result.value : JSON.stringify(result.value)}` + : "") + : result.error || "error"; + } + } catch (e) { + if (onError) onError(String(e)); + else if (out) { + out.classList?.add?.("err"); + out.textContent = String(e); + } + } + }); + return 1; +} + +export async function mount(rawOpts = {}) { + const opts = normalizeMountOptions(rawOpts); + const onError = (err) => markError(opts, err); + + let exports; + try { + exports = await loadWasm(opts.wasmUrl); + } catch (e) { + onError(e); + throw e; + } + + const ver = readCString(exports.memory, exports.mq_version()); + + if (opts.playground) { + const n = wirePlayground(exports, opts.playground, { onError }); + markReady(opts, `marqdo-wasm ${ver} · playground ready`); + return { exports, boot: null, wired: n }; + } + + let source = opts.source; + if (!source && opts.sourceUrl) { + const res = await fetch(opts.sourceUrl); + if (!res.ok) { + const err = `failed to load ${opts.sourceUrl} (${res.status})`; + onError(err); + throw new Error(err); + } + source = await res.text(); + } + if (!source) { + const err = "mount: need source, sourceUrl, or playground"; + onError(err); + throw new Error(err); + } + + const result = boot(exports, source); + if (!result.ok) { + onError(result.error || "boot failed"); + throw new Error(result.error || "boot failed"); + } + + if (result.value && !Array.isArray(result.value)) { + await applyEffects(exports, result.value, { onError }); + } + + const n = wireEvents(exports, result.value, { onError }); + const srcLabel = opts.sourceUrl || "(inline)"; + markReady(opts, `marqdo-wasm ${ver} · wired ${n} handler(s)\nsource: ${srcLabel}`); + return { exports, boot: result, wired: n }; +} + +export async function autoMount(doc) { + const configs = collectMountConfigs(doc); + const results = []; + for (const cfg of configs) { + if (cfg.noBoot) continue; + results.push(await mount(cfg)); + } + return results; +} + +const g = typeof globalThis !== "undefined" ? globalThis : undefined; +if (g && g.document) { + const start = () => { + autoMount(g.document).catch((e) => console.error("marqdo autoMount:", e)); + }; + if (g.document.readyState === "loading") { + g.document.addEventListener("DOMContentLoaded", start); + } else { + queueMicrotask(start); + } +} diff --git a/examples/browser-hello/marqdo-bridge.js b/examples/browser-hello/marqdo-bridge.js index 98ac03a..f5e48d5 100644 --- a/examples/browser-hello/marqdo-bridge.js +++ b/examples/browser-hello/marqdo-bridge.js @@ -1,13 +1,11 @@ /** - * Canonical Marqdo browser bridge (route C/D). Host glue only — not app logic. - * Copied to site dirs by `marqdo wasm build`. + * Canonical Marqdo browser bridge (routes C/D/E). Host glue only — not app logic. + * Authors write .mq.md only; this file may grow host mechanisms freely. * * ABI: mq_alloc, mq_dealloc, mq_run, mq_boot, mq_call, mq_version - * Packed results: u32le length + UTF-8 JSON { ok, stdout, error, value } - * - * Effects (ADR 0003 + route D): set_text, set_value, set_attr, set_class, - * toggle_class, set_html (#trusted* only), fetch, after - * Mount: mount() / data-mq-* / #marqdo-boot auto-start (author zero JS) + * Effects: set_text, set_value, set_attr, set_class, toggle_class, set_style, + * focus, blur, scroll_into, set_html, replace_children, render_list, + * navigate, storage, ws, fetch, fetch_all, after, interval, clear_interval */ export function readCString(memory, ptr) { @@ -73,42 +71,27 @@ function isPlainObject(v) { return v != null && typeof v === "object" && !Array.isArray(v); } +function asSelList(v) { + if (v == null) return []; + if (Array.isArray(v)) return v.map(String); + return [String(v)]; +} + /** Normalize mount options from plain object or DOM dataset. */ export function normalizeMountOptions(raw = {}) { const o = raw && typeof raw === "object" ? raw : {}; const dataset = o.dataset || {}; const wasmUrl = - o.wasmUrl || - o.wasm || - dataset.mqWasm || - dataset.wasm || - "./marqdo_wasm.wasm"; + o.wasmUrl || o.wasm || dataset.mqWasm || dataset.wasm || "./marqdo_wasm.wasm"; const sourceUrl = - o.sourceUrl || - o.source_url || - dataset.mqSourceUrl || - dataset.sourceUrl || - ""; + o.sourceUrl || o.source_url || dataset.mqSourceUrl || dataset.sourceUrl || ""; let source = o.source != null ? o.source : dataset.mqSource || ""; if (!source && typeof o.sourceInline === "string") source = o.sourceInline; - const playground = - o.playground || - dataset.mqPlayground || - dataset.playground || - ""; - const ready = - o.ready || - o.readySel || - dataset.mqReady || - ""; - const enable = - o.enable || - dataset.mqEnable || - ""; + const playground = o.playground || dataset.mqPlayground || dataset.playground || ""; + const ready = o.ready || o.readySel || dataset.mqReady || ""; + const enable = o.enable || dataset.mqEnable || ""; const noBoot = - o.noBoot === true || - dataset.mqNoBoot === "1" || - dataset.mqNoBoot === "true"; + o.noBoot === true || dataset.mqNoBoot === "1" || dataset.mqNoBoot === "true"; return { wasmUrl: String(wasmUrl), sourceUrl: sourceUrl ? String(sourceUrl) : "", @@ -121,18 +104,13 @@ export function normalizeMountOptions(raw = {}) { }; } -/** - * Collect mount configs from `#marqdo-boot` JSON and `script[data-mq-*]`. - * Pure DOM scan — safe to call once after DOM ready. - */ export function collectMountConfigs(doc = typeof document !== "undefined" ? document : null) { if (!doc) return []; const out = []; const bootEl = doc.getElementById("marqdo-boot"); if (bootEl) { try { - const json = JSON.parse(bootEl.textContent || "{}"); - out.push(normalizeMountOptions(json)); + out.push(normalizeMountOptions(JSON.parse(bootEl.textContent || "{}"))); } catch (e) { console.error("marqdo-boot JSON:", e); } @@ -143,10 +121,7 @@ export function collectMountConfigs(doc = typeof document !== "undefined" ? docu for (const el of scripts) { if (el.dataset.mqNoBoot === "1" || el.dataset.mqNoBoot === "true") continue; const hasWork = - el.dataset.mqSourceUrl || - el.dataset.mqSource || - el.dataset.mqPlayground; - if (!hasWork && !el.dataset.mqWasm) continue; + el.dataset.mqSourceUrl || el.dataset.mqSource || el.dataset.mqPlayground; if (!hasWork) continue; out.push( normalizeMountOptions({ @@ -163,19 +138,27 @@ export function collectMountConfigs(doc = typeof document !== "undefined" ? docu return out; } -/** Build mq_call args from a DOM event + optional value_from selector. */ export function eventArgsFromDom(ev, valueFromSel) { const t = ev && ev.target; - const args = { - event: ev && ev.type ? ev.type : "click", - }; + const args = { event: ev && ev.type ? ev.type : "click" }; if (t && typeof t === "object") { if ("value" in t && t.value != null) args.value = String(t.value); if ("checked" in t) args.checked = !!t.checked; if (t.id) args.id = String(t.id); + if (t.getAttribute) { + const did = t.getAttribute("data-id"); + if (did != null) args.data_id = did; + } if (typeof t.textContent === "string" && !("value" in t)) { args.text = t.textContent; } + if (ev.key != null) args.key = String(ev.key); + if (ev.code != null) args.code = String(ev.code); + } + if (ev && ev.type === "popstate") { + args.url = typeof location !== "undefined" ? location.href : ""; + args.path = typeof location !== "undefined" ? location.pathname + location.search : ""; + args.state = ev.state; } if (valueFromSel && typeof document !== "undefined") { const src = document.querySelector(valueFromSel); @@ -193,16 +176,64 @@ export function eventArgsFromDom(ev, valueFromSel) { /* ignore */ } const fields = {}; - for (const [k, v] of new FormData(form)) { - fields[k] = String(v); - } + for (const [k, v] of new FormData(form)) fields[k] = String(v); args.fields = fields; } } return args; } -/** Apply C3/C4/D3 return effects: DOM patches then fetch/after. */ +function applyStyle(el, styleVal) { + if (typeof styleVal === "string") { + el.setAttribute("style", styleVal); + return; + } + if (isPlainObject(styleVal)) { + for (const [k, v] of Object.entries(styleVal)) { + if (v === null || v === false) el.style.removeProperty(k); + else el.style.setProperty(k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase()), String(v)); + } + } +} + +export function renderListItems(spec) { + const tag = String(spec.tag || "li"); + const items = Array.isArray(spec.items) ? spec.items : []; + return items + .map((it) => { + if (it == null) return ""; + if (typeof it === "string" || typeof it === "number") { + return `<${tag}>${escapeHtml(String(it))}${tag}>`; + } + if (!isPlainObject(it)) return ""; + const text = it.text != null ? String(it.text) : it.html != null ? null : ""; + const cls = it.class != null ? ` class="${escapeAttr(String(it.class))}"` : ""; + let attrs = ""; + if (isPlainObject(it.attrs)) { + for (const [k, v] of Object.entries(it.attrs)) { + if (v === null || v === false) continue; + attrs += ` ${escapeAttr(k)}="${escapeAttr(String(v))}"`; + } + } + const inner = it.html != null ? String(it.html) : escapeHtml(text ?? ""); + return `<${tag}${cls}${attrs}>${inner}${tag}>`; + }) + .join(""); +} + +function escapeHtml(s) { + return s + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +function escapeAttr(s) { + return escapeHtml(s).replace(/'/g, "'"); +} + +/** Sync DOM patches (E1/E2/E3 navigate is sync too). */ export function applyDomPatch(value) { if (!value || typeof value !== "object") return; if (typeof document === "undefined") return; @@ -251,18 +282,66 @@ export function applyDomPatch(value) { } } + const setStyle = value.set_style || value.setStyle; + if (isPlainObject(setStyle)) { + for (const [sel, st] of Object.entries(setStyle)) { + const el = document.querySelector(sel); + if (el) applyStyle(el, st); + } + } + + for (const sel of asSelList(value.focus)) { + const el = document.querySelector(sel); + if (el && el.focus) el.focus(); + } + for (const sel of asSelList(value.blur)) { + const el = document.querySelector(sel); + if (el && el.blur) el.blur(); + } + for (const sel of asSelList(value.scroll_into || value.scrollInto)) { + const el = document.querySelector(sel); + if (el && el.scrollIntoView) el.scrollIntoView({ block: "nearest", behavior: "smooth" }); + } + const setHtml = value.set_html || value.setHtml; if (isPlainObject(setHtml)) { for (const [sel, html] of Object.entries(setHtml)) { - if (!String(sel).startsWith("#trusted")) continue; const el = document.querySelector(sel); if (el) el.innerHTML = String(html); } } + + const replaceChildren = value.replace_children || value.replaceChildren; + if (isPlainObject(replaceChildren)) { + for (const [sel, html] of Object.entries(replaceChildren)) { + const el = document.querySelector(sel); + if (el) el.innerHTML = String(html); + } + } + + const renderList = value.render_list || value.renderList; + if (isPlainObject(renderList)) { + for (const [sel, spec] of Object.entries(renderList)) { + const el = document.querySelector(sel); + if (!el || !isPlainObject(spec)) continue; + el.innerHTML = renderListItems(spec); + } + } + + const nav = value.navigate; + if (isPlainObject(nav) && nav.url != null && typeof history !== "undefined") { + const url = String(nav.url); + if (nav.replace) history.replaceState(nav.state ?? null, "", url); + else history.pushState(nav.state ?? null, "", url); + } } +const intervalHandles = new Map(); +const wsHandles = new Map(); +let wsSeq = 0; + /** - * Run sync DOM patches then schedule async effects (ADR 0003). + * Run sync DOM patches then schedule async effects. */ export function applyEffects(exports, value, { onError } = {}) { applyDomPatch(value); @@ -275,32 +354,64 @@ export function applyEffects(exports, value, { onError } = {}) { tasks.push(runFetchEffect(exports, fetchSpec, onError)); } + const fetchAll = value.fetch_all || value.fetchAll; + if (fetchAll && typeof fetchAll === "object" && fetchAll.then) { + tasks.push(runFetchAllEffect(exports, fetchAll, onError)); + } + const afterSpec = value.after; if (afterSpec && typeof afterSpec === "object" && afterSpec.then) { tasks.push(runAfterEffect(exports, afterSpec, onError)); } + const intervalSpec = value.interval; + if (intervalSpec && typeof intervalSpec === "object" && intervalSpec.then) { + runIntervalEffect(exports, intervalSpec, onError); + } + + const clearIv = value.clear_interval || value.clearInterval; + if (clearIv && typeof clearIv === "object") { + const id = String(clearIv.id || "default"); + const h = intervalHandles.get(id); + if (h != null) { + clearInterval(h); + intervalHandles.delete(id); + } + } + + const storageSpec = value.storage; + if (storageSpec && typeof storageSpec === "object" && storageSpec.op) { + tasks.push(runStorageEffect(exports, storageSpec, onError)); + } + + const wsSpec = value.ws; + if (wsSpec && typeof wsSpec === "object" && wsSpec.op) { + tasks.push(runWsEffect(exports, wsSpec, onError)); + } + return Promise.all(tasks); } +function buildFetchInit(spec) { + const method = (spec.method || "GET").toUpperCase(); + const init = { method }; + if (spec.headers && typeof spec.headers === "object") init.headers = { ...spec.headers }; + if (spec.fields && typeof spec.fields === "object" && typeof FormData !== "undefined") { + const fd = new FormData(); + for (const [k, v] of Object.entries(spec.fields)) fd.append(k, String(v)); + init.body = fd; + } else if (spec.body != null && method !== "GET" && method !== "HEAD") { + init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body); + } + return init; +} + async function runFetchEffect(exports, spec, onError) { const thenFn = spec.then; - const method = (spec.method || "GET").toUpperCase(); - const init = { method }; - if (spec.headers && typeof spec.headers === "object") { - init.headers = spec.headers; - } - if (spec.body != null && method !== "GET" && method !== "HEAD") { - init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body); - } try { - const res = await fetch(String(spec.url), init); + const res = await fetch(String(spec.url), buildFetchInit(spec)); const body = await res.text(); - const result = call(exports, thenFn, { - ok: res.ok, - status: res.status, - body, - }); + const result = call(exports, thenFn, { ok: res.ok, status: res.status, body }); if (!result.ok) { if (onError) onError(result.error); else console.error(result.error); @@ -325,6 +436,34 @@ async function runFetchEffect(exports, spec, onError) { } } +async function runFetchAllEffect(exports, spec, onError) { + const thenFn = spec.then; + const reqs = Array.isArray(spec.requests) ? spec.requests : []; + try { + const results = await Promise.all( + reqs.map(async (r) => { + try { + const res = await fetch(String(r.url), buildFetchInit(r)); + const body = await res.text(); + return { ok: res.ok, status: res.status, body, url: String(r.url) }; + } catch (e) { + return { ok: false, status: 0, body: "", error: String(e), url: String(r.url || "") }; + } + }), + ); + const result = call(exports, thenFn, { ok: true, results }); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + return; + } + await applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } +} + function runAfterEffect(exports, spec, onError) { const ms = Math.max(0, Number(spec.ms) || 0); const thenFn = spec.then; @@ -349,9 +488,182 @@ function runAfterEffect(exports, spec, onError) { }); } +function runIntervalEffect(exports, spec, onError) { + const ms = Math.max(1, Number(spec.ms) || 1000); + const thenFn = spec.then; + const id = String(spec.id || "default"); + if (intervalHandles.has(id)) { + clearInterval(intervalHandles.get(id)); + intervalHandles.delete(id); + } + const handle = setInterval(() => { + try { + const result = call(exports, thenFn, { ok: true, id }); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + return; + } + applyEffects(exports, result.value, { onError }); + if (result.stdout) console.log(result.stdout); + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } + }, ms); + intervalHandles.set(id, handle); +} + +function storageStore(scope) { + if (typeof localStorage === "undefined") return null; + return scope === "session" ? sessionStorage : localStorage; +} + +async function runStorageEffect(exports, spec, onError) { + const op = String(spec.op || "").toLowerCase(); + const key = String(spec.key || ""); + const store = storageStore(spec.scope || "local"); + if (!store) { + if (onError) onError("storage unavailable"); + return; + } + try { + if (op === "set") { + store.setItem(key, spec.value != null ? String(spec.value) : ""); + if (spec.then) { + const result = call(exports, spec.then, { ok: true, op, key }); + if (result.ok) await applyEffects(exports, result.value, { onError }); + } + return; + } + if (op === "remove" || op === "delete") { + store.removeItem(key); + if (spec.then) { + const result = call(exports, spec.then, { ok: true, op, key }); + if (result.ok) await applyEffects(exports, result.value, { onError }); + } + return; + } + if (op === "get") { + const value = store.getItem(key); + if (spec.then) { + const result = call(exports, spec.then, { + ok: true, + op, + key, + value: value == null ? "" : value, + found: value != null, + }); + if (!result.ok) { + if (onError) onError(result.error); + return; + } + await applyEffects(exports, result.value, { onError }); + } + } + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } +} + +function runWsEffect(exports, spec, onError) { + const op = String(spec.op || "").toLowerCase(); + return new Promise((resolve) => { + try { + if (op === "open") { + if (typeof WebSocket === "undefined") { + if (onError) onError("WebSocket unavailable"); + resolve(); + return; + } + const id = String(spec.id || `ws${++wsSeq}`); + const sock = new WebSocket(String(spec.url)); + wsHandles.set(id, sock); + sock.addEventListener("open", () => { + if (spec.then_open || spec.thenOpen) { + try { + const result = call(exports, spec.then_open || spec.thenOpen, { ok: true, id }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + } + resolve(); + }); + sock.addEventListener("message", (ev) => { + const thenMsg = spec.then_message || spec.thenMessage; + if (!thenMsg) return; + try { + const result = call(exports, thenMsg, { + ok: true, + id, + data: typeof ev.data === "string" ? ev.data : String(ev.data), + }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + }); + sock.addEventListener("close", () => { + wsHandles.delete(id); + const thenClose = spec.then_close || spec.thenClose; + if (thenClose) { + try { + const result = call(exports, thenClose, { ok: true, id }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + } + }); + sock.addEventListener("error", () => { + const thenErr = spec.then_error || spec.thenError; + if (thenErr) { + try { + const result = call(exports, thenErr, { ok: false, id, error: "ws error" }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + } + }); + return; + } + if (op === "send") { + const id = String(spec.id || [...wsHandles.keys()][0] || ""); + const sock = wsHandles.get(id); + if (sock && sock.readyState === WebSocket.OPEN) { + sock.send(spec.data != null ? String(spec.data) : ""); + } else if (onError) onError(`ws send: no open socket ${id}`); + resolve(); + return; + } + if (op === "close") { + const id = String(spec.id || [...wsHandles.keys()][0] || ""); + const sock = wsHandles.get(id); + if (sock) sock.close(); + wsHandles.delete(id); + resolve(); + return; + } + resolve(); + } catch (e) { + if (onError) onError(String(e)); + resolve(); + } + }); +} + +function bindTarget(sel) { + if (sel === "window" || sel === "@window") return typeof window !== "undefined" ? window : null; + if (sel === "document" || sel === "@document") + return typeof document !== "undefined" ? document : null; + return null; +} + /** - * Wire events from `# main` return value. - * Accepts a list of row maps, or `{ wire: [...] }`. + * Wire events from `# main` return value (list or `{ wire: [...] }`). */ export function wireEvents(exports, bootValue, { onError } = {}) { let rows = []; @@ -364,12 +676,47 @@ export function wireEvents(exports, bootValue, { onError } = {}) { const fn = row["调用"] || row.call || row.fn; const valueFrom = row["值选择器"] || row.value_from || row.valueFrom || row.from || ""; + const delegate = + row["委托"] || row.delegate || row.delegation || ""; if (!sel || !fn) continue; - const nodes = document.querySelectorAll(sel); - nodes.forEach((node) => { + + const special = bindTarget(sel); + const roots = special + ? [special] + : typeof document !== "undefined" + ? [...document.querySelectorAll(sel)] + : []; + + roots.forEach((node) => { node.addEventListener(ev, (domEv) => { try { + if (delegate) { + const hit = + typeof domEv.target?.closest === "function" + ? domEv.target.closest(delegate) + : null; + if (!hit || (node.contains && !node.contains(hit))) return; + } + if ( + ev === "click" && + typeof domEv.target?.closest === "function" && + domEv.target.closest("a[href]") + ) { + try { + domEv.preventDefault(); + } catch (_) { + /* ignore */ + } + } const args = eventArgsFromDom(domEv, valueFrom); + if (delegate && domEv.target) { + const hit = domEv.target.closest?.(delegate); + if (hit?.getAttribute) { + const did = hit.getAttribute("data-id"); + if (did != null) args.data_id = did; + if (hit.id) args.id = hit.id; + } + } const result = call(exports, fn, args); if (!result.ok) { if (onError) onError(result.error); @@ -459,10 +806,6 @@ function wirePlayground(exports, playgroundSpec, { onError } = {}) { return 1; } -/** - * One-shot: load wasm, boot session (or playground), wire events. - * @returns {{ exports, boot, wired }} - */ export async function mount(rawOpts = {}) { const opts = normalizeMountOptions(rawOpts); const onError = (err) => markError(opts, err); @@ -505,7 +848,6 @@ export async function mount(rawOpts = {}) { throw new Error(result.error || "boot failed"); } - // If boot value is a map with effects alongside wire, apply them. if (result.value && !Array.isArray(result.value)) { await applyEffects(exports, result.value, { onError }); } @@ -516,7 +858,6 @@ export async function mount(rawOpts = {}) { return { exports, boot: result, wired: n }; } -/** Auto-mount from DOM configs (route D). */ export async function autoMount(doc) { const configs = collectMountConfigs(doc); const results = []; diff --git a/examples/web-client-site/static/marqdo-bridge.js b/examples/web-client-site/static/marqdo-bridge.js index 98ac03a..f5e48d5 100644 --- a/examples/web-client-site/static/marqdo-bridge.js +++ b/examples/web-client-site/static/marqdo-bridge.js @@ -1,13 +1,11 @@ /** - * Canonical Marqdo browser bridge (route C/D). Host glue only — not app logic. - * Copied to site dirs by `marqdo wasm build`. + * Canonical Marqdo browser bridge (routes C/D/E). Host glue only — not app logic. + * Authors write .mq.md only; this file may grow host mechanisms freely. * * ABI: mq_alloc, mq_dealloc, mq_run, mq_boot, mq_call, mq_version - * Packed results: u32le length + UTF-8 JSON { ok, stdout, error, value } - * - * Effects (ADR 0003 + route D): set_text, set_value, set_attr, set_class, - * toggle_class, set_html (#trusted* only), fetch, after - * Mount: mount() / data-mq-* / #marqdo-boot auto-start (author zero JS) + * Effects: set_text, set_value, set_attr, set_class, toggle_class, set_style, + * focus, blur, scroll_into, set_html, replace_children, render_list, + * navigate, storage, ws, fetch, fetch_all, after, interval, clear_interval */ export function readCString(memory, ptr) { @@ -73,42 +71,27 @@ function isPlainObject(v) { return v != null && typeof v === "object" && !Array.isArray(v); } +function asSelList(v) { + if (v == null) return []; + if (Array.isArray(v)) return v.map(String); + return [String(v)]; +} + /** Normalize mount options from plain object or DOM dataset. */ export function normalizeMountOptions(raw = {}) { const o = raw && typeof raw === "object" ? raw : {}; const dataset = o.dataset || {}; const wasmUrl = - o.wasmUrl || - o.wasm || - dataset.mqWasm || - dataset.wasm || - "./marqdo_wasm.wasm"; + o.wasmUrl || o.wasm || dataset.mqWasm || dataset.wasm || "./marqdo_wasm.wasm"; const sourceUrl = - o.sourceUrl || - o.source_url || - dataset.mqSourceUrl || - dataset.sourceUrl || - ""; + o.sourceUrl || o.source_url || dataset.mqSourceUrl || dataset.sourceUrl || ""; let source = o.source != null ? o.source : dataset.mqSource || ""; if (!source && typeof o.sourceInline === "string") source = o.sourceInline; - const playground = - o.playground || - dataset.mqPlayground || - dataset.playground || - ""; - const ready = - o.ready || - o.readySel || - dataset.mqReady || - ""; - const enable = - o.enable || - dataset.mqEnable || - ""; + const playground = o.playground || dataset.mqPlayground || dataset.playground || ""; + const ready = o.ready || o.readySel || dataset.mqReady || ""; + const enable = o.enable || dataset.mqEnable || ""; const noBoot = - o.noBoot === true || - dataset.mqNoBoot === "1" || - dataset.mqNoBoot === "true"; + o.noBoot === true || dataset.mqNoBoot === "1" || dataset.mqNoBoot === "true"; return { wasmUrl: String(wasmUrl), sourceUrl: sourceUrl ? String(sourceUrl) : "", @@ -121,18 +104,13 @@ export function normalizeMountOptions(raw = {}) { }; } -/** - * Collect mount configs from `#marqdo-boot` JSON and `script[data-mq-*]`. - * Pure DOM scan — safe to call once after DOM ready. - */ export function collectMountConfigs(doc = typeof document !== "undefined" ? document : null) { if (!doc) return []; const out = []; const bootEl = doc.getElementById("marqdo-boot"); if (bootEl) { try { - const json = JSON.parse(bootEl.textContent || "{}"); - out.push(normalizeMountOptions(json)); + out.push(normalizeMountOptions(JSON.parse(bootEl.textContent || "{}"))); } catch (e) { console.error("marqdo-boot JSON:", e); } @@ -143,10 +121,7 @@ export function collectMountConfigs(doc = typeof document !== "undefined" ? docu for (const el of scripts) { if (el.dataset.mqNoBoot === "1" || el.dataset.mqNoBoot === "true") continue; const hasWork = - el.dataset.mqSourceUrl || - el.dataset.mqSource || - el.dataset.mqPlayground; - if (!hasWork && !el.dataset.mqWasm) continue; + el.dataset.mqSourceUrl || el.dataset.mqSource || el.dataset.mqPlayground; if (!hasWork) continue; out.push( normalizeMountOptions({ @@ -163,19 +138,27 @@ export function collectMountConfigs(doc = typeof document !== "undefined" ? docu return out; } -/** Build mq_call args from a DOM event + optional value_from selector. */ export function eventArgsFromDom(ev, valueFromSel) { const t = ev && ev.target; - const args = { - event: ev && ev.type ? ev.type : "click", - }; + const args = { event: ev && ev.type ? ev.type : "click" }; if (t && typeof t === "object") { if ("value" in t && t.value != null) args.value = String(t.value); if ("checked" in t) args.checked = !!t.checked; if (t.id) args.id = String(t.id); + if (t.getAttribute) { + const did = t.getAttribute("data-id"); + if (did != null) args.data_id = did; + } if (typeof t.textContent === "string" && !("value" in t)) { args.text = t.textContent; } + if (ev.key != null) args.key = String(ev.key); + if (ev.code != null) args.code = String(ev.code); + } + if (ev && ev.type === "popstate") { + args.url = typeof location !== "undefined" ? location.href : ""; + args.path = typeof location !== "undefined" ? location.pathname + location.search : ""; + args.state = ev.state; } if (valueFromSel && typeof document !== "undefined") { const src = document.querySelector(valueFromSel); @@ -193,16 +176,64 @@ export function eventArgsFromDom(ev, valueFromSel) { /* ignore */ } const fields = {}; - for (const [k, v] of new FormData(form)) { - fields[k] = String(v); - } + for (const [k, v] of new FormData(form)) fields[k] = String(v); args.fields = fields; } } return args; } -/** Apply C3/C4/D3 return effects: DOM patches then fetch/after. */ +function applyStyle(el, styleVal) { + if (typeof styleVal === "string") { + el.setAttribute("style", styleVal); + return; + } + if (isPlainObject(styleVal)) { + for (const [k, v] of Object.entries(styleVal)) { + if (v === null || v === false) el.style.removeProperty(k); + else el.style.setProperty(k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase()), String(v)); + } + } +} + +export function renderListItems(spec) { + const tag = String(spec.tag || "li"); + const items = Array.isArray(spec.items) ? spec.items : []; + return items + .map((it) => { + if (it == null) return ""; + if (typeof it === "string" || typeof it === "number") { + return `<${tag}>${escapeHtml(String(it))}${tag}>`; + } + if (!isPlainObject(it)) return ""; + const text = it.text != null ? String(it.text) : it.html != null ? null : ""; + const cls = it.class != null ? ` class="${escapeAttr(String(it.class))}"` : ""; + let attrs = ""; + if (isPlainObject(it.attrs)) { + for (const [k, v] of Object.entries(it.attrs)) { + if (v === null || v === false) continue; + attrs += ` ${escapeAttr(k)}="${escapeAttr(String(v))}"`; + } + } + const inner = it.html != null ? String(it.html) : escapeHtml(text ?? ""); + return `<${tag}${cls}${attrs}>${inner}${tag}>`; + }) + .join(""); +} + +function escapeHtml(s) { + return s + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +function escapeAttr(s) { + return escapeHtml(s).replace(/'/g, "'"); +} + +/** Sync DOM patches (E1/E2/E3 navigate is sync too). */ export function applyDomPatch(value) { if (!value || typeof value !== "object") return; if (typeof document === "undefined") return; @@ -251,18 +282,66 @@ export function applyDomPatch(value) { } } + const setStyle = value.set_style || value.setStyle; + if (isPlainObject(setStyle)) { + for (const [sel, st] of Object.entries(setStyle)) { + const el = document.querySelector(sel); + if (el) applyStyle(el, st); + } + } + + for (const sel of asSelList(value.focus)) { + const el = document.querySelector(sel); + if (el && el.focus) el.focus(); + } + for (const sel of asSelList(value.blur)) { + const el = document.querySelector(sel); + if (el && el.blur) el.blur(); + } + for (const sel of asSelList(value.scroll_into || value.scrollInto)) { + const el = document.querySelector(sel); + if (el && el.scrollIntoView) el.scrollIntoView({ block: "nearest", behavior: "smooth" }); + } + const setHtml = value.set_html || value.setHtml; if (isPlainObject(setHtml)) { for (const [sel, html] of Object.entries(setHtml)) { - if (!String(sel).startsWith("#trusted")) continue; const el = document.querySelector(sel); if (el) el.innerHTML = String(html); } } + + const replaceChildren = value.replace_children || value.replaceChildren; + if (isPlainObject(replaceChildren)) { + for (const [sel, html] of Object.entries(replaceChildren)) { + const el = document.querySelector(sel); + if (el) el.innerHTML = String(html); + } + } + + const renderList = value.render_list || value.renderList; + if (isPlainObject(renderList)) { + for (const [sel, spec] of Object.entries(renderList)) { + const el = document.querySelector(sel); + if (!el || !isPlainObject(spec)) continue; + el.innerHTML = renderListItems(spec); + } + } + + const nav = value.navigate; + if (isPlainObject(nav) && nav.url != null && typeof history !== "undefined") { + const url = String(nav.url); + if (nav.replace) history.replaceState(nav.state ?? null, "", url); + else history.pushState(nav.state ?? null, "", url); + } } +const intervalHandles = new Map(); +const wsHandles = new Map(); +let wsSeq = 0; + /** - * Run sync DOM patches then schedule async effects (ADR 0003). + * Run sync DOM patches then schedule async effects. */ export function applyEffects(exports, value, { onError } = {}) { applyDomPatch(value); @@ -275,32 +354,64 @@ export function applyEffects(exports, value, { onError } = {}) { tasks.push(runFetchEffect(exports, fetchSpec, onError)); } + const fetchAll = value.fetch_all || value.fetchAll; + if (fetchAll && typeof fetchAll === "object" && fetchAll.then) { + tasks.push(runFetchAllEffect(exports, fetchAll, onError)); + } + const afterSpec = value.after; if (afterSpec && typeof afterSpec === "object" && afterSpec.then) { tasks.push(runAfterEffect(exports, afterSpec, onError)); } + const intervalSpec = value.interval; + if (intervalSpec && typeof intervalSpec === "object" && intervalSpec.then) { + runIntervalEffect(exports, intervalSpec, onError); + } + + const clearIv = value.clear_interval || value.clearInterval; + if (clearIv && typeof clearIv === "object") { + const id = String(clearIv.id || "default"); + const h = intervalHandles.get(id); + if (h != null) { + clearInterval(h); + intervalHandles.delete(id); + } + } + + const storageSpec = value.storage; + if (storageSpec && typeof storageSpec === "object" && storageSpec.op) { + tasks.push(runStorageEffect(exports, storageSpec, onError)); + } + + const wsSpec = value.ws; + if (wsSpec && typeof wsSpec === "object" && wsSpec.op) { + tasks.push(runWsEffect(exports, wsSpec, onError)); + } + return Promise.all(tasks); } +function buildFetchInit(spec) { + const method = (spec.method || "GET").toUpperCase(); + const init = { method }; + if (spec.headers && typeof spec.headers === "object") init.headers = { ...spec.headers }; + if (spec.fields && typeof spec.fields === "object" && typeof FormData !== "undefined") { + const fd = new FormData(); + for (const [k, v] of Object.entries(spec.fields)) fd.append(k, String(v)); + init.body = fd; + } else if (spec.body != null && method !== "GET" && method !== "HEAD") { + init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body); + } + return init; +} + async function runFetchEffect(exports, spec, onError) { const thenFn = spec.then; - const method = (spec.method || "GET").toUpperCase(); - const init = { method }; - if (spec.headers && typeof spec.headers === "object") { - init.headers = spec.headers; - } - if (spec.body != null && method !== "GET" && method !== "HEAD") { - init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body); - } try { - const res = await fetch(String(spec.url), init); + const res = await fetch(String(spec.url), buildFetchInit(spec)); const body = await res.text(); - const result = call(exports, thenFn, { - ok: res.ok, - status: res.status, - body, - }); + const result = call(exports, thenFn, { ok: res.ok, status: res.status, body }); if (!result.ok) { if (onError) onError(result.error); else console.error(result.error); @@ -325,6 +436,34 @@ async function runFetchEffect(exports, spec, onError) { } } +async function runFetchAllEffect(exports, spec, onError) { + const thenFn = spec.then; + const reqs = Array.isArray(spec.requests) ? spec.requests : []; + try { + const results = await Promise.all( + reqs.map(async (r) => { + try { + const res = await fetch(String(r.url), buildFetchInit(r)); + const body = await res.text(); + return { ok: res.ok, status: res.status, body, url: String(r.url) }; + } catch (e) { + return { ok: false, status: 0, body: "", error: String(e), url: String(r.url || "") }; + } + }), + ); + const result = call(exports, thenFn, { ok: true, results }); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + return; + } + await applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } +} + function runAfterEffect(exports, spec, onError) { const ms = Math.max(0, Number(spec.ms) || 0); const thenFn = spec.then; @@ -349,9 +488,182 @@ function runAfterEffect(exports, spec, onError) { }); } +function runIntervalEffect(exports, spec, onError) { + const ms = Math.max(1, Number(spec.ms) || 1000); + const thenFn = spec.then; + const id = String(spec.id || "default"); + if (intervalHandles.has(id)) { + clearInterval(intervalHandles.get(id)); + intervalHandles.delete(id); + } + const handle = setInterval(() => { + try { + const result = call(exports, thenFn, { ok: true, id }); + if (!result.ok) { + if (onError) onError(result.error); + else console.error(result.error); + return; + } + applyEffects(exports, result.value, { onError }); + if (result.stdout) console.log(result.stdout); + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } + }, ms); + intervalHandles.set(id, handle); +} + +function storageStore(scope) { + if (typeof localStorage === "undefined") return null; + return scope === "session" ? sessionStorage : localStorage; +} + +async function runStorageEffect(exports, spec, onError) { + const op = String(spec.op || "").toLowerCase(); + const key = String(spec.key || ""); + const store = storageStore(spec.scope || "local"); + if (!store) { + if (onError) onError("storage unavailable"); + return; + } + try { + if (op === "set") { + store.setItem(key, spec.value != null ? String(spec.value) : ""); + if (spec.then) { + const result = call(exports, spec.then, { ok: true, op, key }); + if (result.ok) await applyEffects(exports, result.value, { onError }); + } + return; + } + if (op === "remove" || op === "delete") { + store.removeItem(key); + if (spec.then) { + const result = call(exports, spec.then, { ok: true, op, key }); + if (result.ok) await applyEffects(exports, result.value, { onError }); + } + return; + } + if (op === "get") { + const value = store.getItem(key); + if (spec.then) { + const result = call(exports, spec.then, { + ok: true, + op, + key, + value: value == null ? "" : value, + found: value != null, + }); + if (!result.ok) { + if (onError) onError(result.error); + return; + } + await applyEffects(exports, result.value, { onError }); + } + } + } catch (e) { + if (onError) onError(String(e)); + else console.error(e); + } +} + +function runWsEffect(exports, spec, onError) { + const op = String(spec.op || "").toLowerCase(); + return new Promise((resolve) => { + try { + if (op === "open") { + if (typeof WebSocket === "undefined") { + if (onError) onError("WebSocket unavailable"); + resolve(); + return; + } + const id = String(spec.id || `ws${++wsSeq}`); + const sock = new WebSocket(String(spec.url)); + wsHandles.set(id, sock); + sock.addEventListener("open", () => { + if (spec.then_open || spec.thenOpen) { + try { + const result = call(exports, spec.then_open || spec.thenOpen, { ok: true, id }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + } + resolve(); + }); + sock.addEventListener("message", (ev) => { + const thenMsg = spec.then_message || spec.thenMessage; + if (!thenMsg) return; + try { + const result = call(exports, thenMsg, { + ok: true, + id, + data: typeof ev.data === "string" ? ev.data : String(ev.data), + }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + }); + sock.addEventListener("close", () => { + wsHandles.delete(id); + const thenClose = spec.then_close || spec.thenClose; + if (thenClose) { + try { + const result = call(exports, thenClose, { ok: true, id }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + } + }); + sock.addEventListener("error", () => { + const thenErr = spec.then_error || spec.thenError; + if (thenErr) { + try { + const result = call(exports, thenErr, { ok: false, id, error: "ws error" }); + if (result.ok) applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + } + }); + return; + } + if (op === "send") { + const id = String(spec.id || [...wsHandles.keys()][0] || ""); + const sock = wsHandles.get(id); + if (sock && sock.readyState === WebSocket.OPEN) { + sock.send(spec.data != null ? String(spec.data) : ""); + } else if (onError) onError(`ws send: no open socket ${id}`); + resolve(); + return; + } + if (op === "close") { + const id = String(spec.id || [...wsHandles.keys()][0] || ""); + const sock = wsHandles.get(id); + if (sock) sock.close(); + wsHandles.delete(id); + resolve(); + return; + } + resolve(); + } catch (e) { + if (onError) onError(String(e)); + resolve(); + } + }); +} + +function bindTarget(sel) { + if (sel === "window" || sel === "@window") return typeof window !== "undefined" ? window : null; + if (sel === "document" || sel === "@document") + return typeof document !== "undefined" ? document : null; + return null; +} + /** - * Wire events from `# main` return value. - * Accepts a list of row maps, or `{ wire: [...] }`. + * Wire events from `# main` return value (list or `{ wire: [...] }`). */ export function wireEvents(exports, bootValue, { onError } = {}) { let rows = []; @@ -364,12 +676,47 @@ export function wireEvents(exports, bootValue, { onError } = {}) { const fn = row["调用"] || row.call || row.fn; const valueFrom = row["值选择器"] || row.value_from || row.valueFrom || row.from || ""; + const delegate = + row["委托"] || row.delegate || row.delegation || ""; if (!sel || !fn) continue; - const nodes = document.querySelectorAll(sel); - nodes.forEach((node) => { + + const special = bindTarget(sel); + const roots = special + ? [special] + : typeof document !== "undefined" + ? [...document.querySelectorAll(sel)] + : []; + + roots.forEach((node) => { node.addEventListener(ev, (domEv) => { try { + if (delegate) { + const hit = + typeof domEv.target?.closest === "function" + ? domEv.target.closest(delegate) + : null; + if (!hit || (node.contains && !node.contains(hit))) return; + } + if ( + ev === "click" && + typeof domEv.target?.closest === "function" && + domEv.target.closest("a[href]") + ) { + try { + domEv.preventDefault(); + } catch (_) { + /* ignore */ + } + } const args = eventArgsFromDom(domEv, valueFrom); + if (delegate && domEv.target) { + const hit = domEv.target.closest?.(delegate); + if (hit?.getAttribute) { + const did = hit.getAttribute("data-id"); + if (did != null) args.data_id = did; + if (hit.id) args.id = hit.id; + } + } const result = call(exports, fn, args); if (!result.ok) { if (onError) onError(result.error); @@ -459,10 +806,6 @@ function wirePlayground(exports, playgroundSpec, { onError } = {}) { return 1; } -/** - * One-shot: load wasm, boot session (or playground), wire events. - * @returns {{ exports, boot, wired }} - */ export async function mount(rawOpts = {}) { const opts = normalizeMountOptions(rawOpts); const onError = (err) => markError(opts, err); @@ -505,7 +848,6 @@ export async function mount(rawOpts = {}) { throw new Error(result.error || "boot failed"); } - // If boot value is a map with effects alongside wire, apply them. if (result.value && !Array.isArray(result.value)) { await applyEffects(exports, result.value, { onError }); } @@ -516,7 +858,6 @@ export async function mount(rawOpts = {}) { return { exports, boot: result, wired: n }; } -/** Auto-mount from DOM configs (route D). */ export async function autoMount(doc) { const configs = collectMountConfigs(doc); const results = []; diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md index cc8b279..098cd6b 100644 --- a/ext/web/web.mq.md +++ b/ext/web/web.mq.md @@ -87,10 +87,22 @@ Shortcut: build a `set_text` effects map `{ set_text: { sel: text } }` for brows + `set_attr`=None + `set_class`=None + `toggle_class`=None + + `set_style`=None + + `set_html`=None + + `render_list`=None + + `navigate`=None + + `storage`=None + + `ws`=None + `fetch`=None + + `fetch_all`=None + `after`=None + + `interval`=None + + `clear_interval`=None + + `focus`=None + + `blur`=None + + `scroll_into`=None -Merge browser DOM/async effect keys into one return map (omit `None` keys). Prefer over hand-rolled nested `json.set` chains. +Merge browser effect keys into one return map (omit `None`). Route E effects included. *`out` = > json.set map=None key="_mq" value=True* 1. `set_text` != None @@ -103,12 +115,48 @@ Merge browser DOM/async effect keys into one return map (omit `None` keys). Pref *`out` = > json.set map=out key="set_class" value=set_class* 1. `toggle_class` != None *`out` = > json.set map=out key="toggle_class" value=toggle_class* +1. `set_style` != None + *`out` = > json.set map=out key="set_style" value=set_style* +1. `set_html` != None + *`out` = > json.set map=out key="set_html" value=set_html* +1. `render_list` != None + *`out` = > json.set map=out key="render_list" value=render_list* +1. `navigate` != None + *`out` = > json.set map=out key="navigate" value=navigate* +1. `storage` != None + *`out` = > json.set map=out key="storage" value=storage* +1. `ws` != None + *`out` = > json.set map=out key="ws" value=ws* 1. `fetch` != None *`out` = > json.set map=out key="fetch" value=fetch* +1. `fetch_all` != None + *`out` = > json.set map=out key="fetch_all" value=fetch_all* 1. `after` != None *`out` = > json.set map=out key="after" value=after* +1. `interval` != None + *`out` = > json.set map=out key="interval" value=interval* +1. `clear_interval` != None + *`out` = > json.set map=out key="clear_interval" value=clear_interval* +1. `focus` != None + *`out` = > json.set map=out key="focus" value=focus* +1. `blur` != None + *`out` = > json.set map=out key="blur" value=blur* +1. `scroll_into` != None + *`out` = > json.set map=out key="scroll_into" value=scroll_into* **out** +## list_html + + `sel` + + `tag`="li" + + `items` + +Build a `render_list` effect: `{ render_list: { sel: { tag, items } } }`. + +*`spec` = > json.set map=None key="tag" value=tag* +*`spec` = > json.set map=spec key="items" value=items* +*`m` = > json.set map=None key=sel value=spec* +**> json.set map=None key="render_list" value=m** + # page + `title`="Marqdo Web" + `intro`="" diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md index 0ddc458..127527b 100644 --- a/ext/web/网页.mq.md +++ b/ext/web/网页.mq.md @@ -83,10 +83,22 @@ import json:lib/json.mq.md + `set_attr`=None + `set_class`=None + `toggle_class`=None + + `set_style`=None + + `set_html`=None + + `render_list`=None + + `navigate`=None + + `storage`=None + + `ws`=None + `fetch`=None + + `fetch_all`=None + `after`=None + + `interval`=None + + `clear_interval`=None + + `focus`=None + + `blur`=None + + `scroll_into`=None -合并浏览器 DOM/异步效应键为一张返回表(跳过 `None`)。 +合并浏览器效应键(含路线 E)为一张返回表(跳过 `None`)。 *`out` = > json.set map=None key="_mq" value=True* 1. `set_text` != None @@ -99,12 +111,48 @@ import json:lib/json.mq.md *`out` = > json.set map=out key="set_class" value=set_class* 1. `toggle_class` != None *`out` = > json.set map=out key="toggle_class" value=toggle_class* +1. `set_style` != None + *`out` = > json.set map=out key="set_style" value=set_style* +1. `set_html` != None + *`out` = > json.set map=out key="set_html" value=set_html* +1. `render_list` != None + *`out` = > json.set map=out key="render_list" value=render_list* +1. `navigate` != None + *`out` = > json.set map=out key="navigate" value=navigate* +1. `storage` != None + *`out` = > json.set map=out key="storage" value=storage* +1. `ws` != None + *`out` = > json.set map=out key="ws" value=ws* 1. `fetch` != None *`out` = > json.set map=out key="fetch" value=fetch* +1. `fetch_all` != None + *`out` = > json.set map=out key="fetch_all" value=fetch_all* 1. `after` != None *`out` = > json.set map=out key="after" value=after* +1. `interval` != None + *`out` = > json.set map=out key="interval" value=interval* +1. `clear_interval` != None + *`out` = > json.set map=out key="clear_interval" value=clear_interval* +1. `focus` != None + *`out` = > json.set map=out key="focus" value=focus* +1. `blur` != None + *`out` = > json.set map=out key="blur" value=blur* +1. `scroll_into` != None + *`out` = > json.set map=out key="scroll_into" value=scroll_into* **out** +## 列表HTML + + `选择器` + + `标签`="li" + + `项` + +构造 `render_list` 效应。 + +*`spec` = > json.set map=None key="tag" value=标签* +*`spec` = > json.set map=spec key="items" value=项* +*`m` = > json.set map=None key=选择器 value=spec* +**> json.set map=None key="render_list" value=m** + # 页面 + `标题`="站点" + `引言`="" diff --git a/skills/marqdo/SKILL.md b/skills/marqdo/SKILL.md index c6cac96..63529e7 100644 --- a/skills/marqdo/SKILL.md +++ b/skills/marqdo/SKILL.md @@ -29,7 +29,8 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. 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. -10. **Browser (route C/D):** client logic is Marqdo on WASM ([ADR 0002](../../../doc/adr/0002-browser-marqdo-wasm.md)); async I/O via return effects `fetch`/`after` ([ADR 0003](../../../doc/adr/0003-browser-async-effects.md)); official bridge is **host glue only**. **Author zero business JS** — use `web.client_embed` / `网页.客户端挂载` (`wasm` + `source` + `boot`) or `data-mq-source-url` so bridge `mount`s automatically ([roadmap D](../../../doc/roadmap/browser-wasm-d.md)). DOM effects: `set_text` / `set_value` / `set_attr` / `set_class` / `toggle_class` / `set_html` only on `#trusted*` selectors. +10. **Browser (route C/D/E):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, internal templates — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount ([roadmap D](../../../doc/roadmap/browser-wasm-d.md) · [E](../../../doc/roadmap/browser-wasm-e.md)). Effects: DOM patches, `render_list`, `navigate`, `storage`, `ws`, `fetch`/`fetch_all`, `interval`. + ## Markup → meaning (v0.2) @@ -175,7 +176,7 @@ data/ # sqlite runtime (gitignore) **Core objects (EN / ZH):** `# page`/`页面`, `# style`/`样式`, `# db`/`数据库`, `# form`/`表单`, `# app`/`应用`, `# auth`/`鉴权`, `# cache`/`缓存`, `# storage`/`存储`. -**Typical flow:** `db.init` → `page.compose_components` + `page.compose_main` → `page.head` / `page.images` / `page.meta` → `app` with `route` / `static` / `icons` / `configure` / `listen`. For client interactivity: `marqdo wasm build -o static`, then `web.client_embed source="/static/client.mq.md"` (or ZH `网页.客户端挂载`) in page HTML — **no author JS** ([browser-wasm-d.md](../../doc/roadmap/browser-wasm-d.md) · [web-client-site](../../examples/web-client-site/)). +**Typical flow:** `db.init` → `page.compose_*` → `app` + `static` / `listen`. Client: `marqdo wasm build -o static` + `web.client_embed source="/static/client.mq.md"` — **no author JS**; bridge may implement rich host effects ([browser-wasm-e.md](../../doc/roadmap/browser-wasm-e.md) · [browser-app](../../examples/browser-app/)). **Shipped surface (W0–W7 + P3 + W8 + route D mount):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads; **W8** site icons (`app.icons` → `/favicon.ico`), head resource tables (`page.head`), image assembly (`make_images` / `page.images`); **D** `client_embed` auto-mount + DOM effect helpers (`text_patch` / `dom_patch`). diff --git a/tests/wasm/smoke.mjs b/tests/wasm/smoke.mjs index c3a8433..15f76ee 100644 --- a/tests/wasm/smoke.mjs +++ b/tests/wasm/smoke.mjs @@ -10,6 +10,7 @@ import { normalizeMountOptions, eventArgsFromDom, applyDomPatch, + renderListItems, } from "../../crates/marqdo-wasm/js/marqdo-bridge.js"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -105,10 +106,22 @@ if (args.value !== "Ada" || args.event !== "input") { process.exit(1); } +const html = renderListItems({ + tag: "li", + items: ["a", { text: "b", attrs: { "data-id": "2" } }], +}); +if (!html.includes("