feat(wasm): route D zero-author-JS frontend + plan route E
Auto-mount via bridge mount/data-mq and client_embed; expand DOM/form effects; drop hello loader JS; add web-client-site. Document that C+D cover mid-size interactivity but not most JS apps—route E covers routing, storage, lists, WebSocket, and richer DOM/timers. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
4c27c8afeb
commit
a9d30cdf4a
30 files changed
+1769
-213
No files matched your search
@@ -1,6 +1,6 @@
|
||||
# browser-hello(WASM C1–C3)
|
||||
# browser-hello(WASM C1–C4 / 路线 D)
|
||||
|
||||
浏览器内跑 Marqdo(路线 C)。
|
||||
浏览器内跑 Marqdo。**无作者业务 JS**——只保留官方 `marqdo-bridge.js`(`marqdo wasm build` 拷贝)。
|
||||
|
||||
```bash
|
||||
# 仓库根目录
|
||||
@@ -13,9 +13,9 @@ python3 -m http.server 8765
|
||||
|
||||
| 页 | 说明 |
|
||||
|----|------|
|
||||
| [/](http://127.0.0.1:8765/) | C1:编辑源码 → `mq_run` 打印 |
|
||||
| [/interact.html](http://127.0.0.1:8765/interact.html) | C3:`counter.mq.md` 交互表 → 点击改 DOM |
|
||||
| [/fetch.html](http://127.0.0.1:8765/fetch.html) | C4:`fetch` / `after` 效应续体 |
|
||||
| [/](http://127.0.0.1:8765/) | playground:`data-mq-playground` + textarea → `mq_run` |
|
||||
| [/interact.html](http://127.0.0.1:8765/interact.html) | `counter.mq.md` wire → 点击改 DOM |
|
||||
| [/fetch.html](http://127.0.0.1:8765/fetch.html) | `fetch` / `after` 效应 |
|
||||
| [/form.html](http://127.0.0.1:8765/form.html) | `input` + `value` / `set_class`(D3) |
|
||||
|
||||
- `marqdo-bridge.js`:官方宿主桥(`boot` / `call` / `wireEvents` / `applyEffects`)
|
||||
- 业务源码只有 `.mq.md`;异步见 [ADR 0003](../../doc/adr/0003-browser-async-effects.md)
|
||||
自启方式:脚本上的 `data-mq-source-url` / `data-mq-playground`,或 `#marqdo-boot` JSON。详见 [browser-wasm-d.md](../../doc/roadmap/browser-wasm-d.md)。
|
||||
@@ -69,11 +69,18 @@
|
||||
</head>
|
||||
<body>
|
||||
<h1>Marqdo</h1>
|
||||
<p class="lead">C4:返回 <code>fetch</code> / <code>after</code> 效应,由官方 bridge 续体回调(ADR 0003)。业务只在 <code>fetch.mq.md</code>。<a href="./interact.html">计数器</a> · <a href="./">打印</a></p>
|
||||
<p class="lead">C4/D:返回 <code>fetch</code> / <code>after</code> 效应;bridge 自启(ADR 0003)。业务只在 <code>fetch.mq.md</code>。<a href="./interact.html">计数器</a> · <a href="./form.html">表单</a> · <a href="./">打印</a></p>
|
||||
<div id="status">idle</div>
|
||||
<button id="load" type="button" disabled>请求 UUID</button>
|
||||
<button id="ping" class="secondary" type="button" disabled>延迟 pong</button>
|
||||
<pre id="log">loading…</pre>
|
||||
<script type="module" src="./fetch.js"></script>
|
||||
<script
|
||||
type="module"
|
||||
src="./marqdo-bridge.js"
|
||||
data-mq-wasm="./marqdo_wasm.wasm"
|
||||
data-mq-source-url="./fetch.mq.md"
|
||||
data-mq-ready="#log"
|
||||
data-mq-enable="#load,#ping"
|
||||
></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,52 +0,0 @@
|
||||
import {
|
||||
applyDomPatch,
|
||||
boot,
|
||||
loadWasm,
|
||||
readCString,
|
||||
wireEvents,
|
||||
} from "./marqdo-bridge.js";
|
||||
|
||||
async function main() {
|
||||
const log = document.getElementById("log");
|
||||
const loadBtn = document.getElementById("load");
|
||||
const pingBtn = document.getElementById("ping");
|
||||
|
||||
let exports;
|
||||
try {
|
||||
exports = await loadWasm("./marqdo_wasm.wasm");
|
||||
} catch (e) {
|
||||
log.classList.add("err");
|
||||
log.textContent = String(e);
|
||||
return;
|
||||
}
|
||||
|
||||
const srcRes = await fetch("./fetch.mq.md");
|
||||
if (!srcRes.ok) {
|
||||
log.classList.add("err");
|
||||
log.textContent = `failed to load fetch.mq.md (${srcRes.status})`;
|
||||
return;
|
||||
}
|
||||
const source = await srcRes.text();
|
||||
const result = boot(exports, source);
|
||||
if (!result.ok) {
|
||||
log.classList.add("err");
|
||||
log.textContent = result.error || "boot failed";
|
||||
return;
|
||||
}
|
||||
|
||||
const n = wireEvents(exports, result.value, {
|
||||
onError: (err) => {
|
||||
log.classList.add("err");
|
||||
log.textContent = err;
|
||||
},
|
||||
});
|
||||
applyDomPatch({ set_text: { "#status": "idle" } });
|
||||
|
||||
const ver = readCString(exports.memory, exports.mq_version());
|
||||
log.classList.remove("err");
|
||||
log.textContent = `marqdo-wasm ${ver} · wired ${n} · ADR 0003 effects\nsource: fetch.mq.md`;
|
||||
loadBtn.disabled = false;
|
||||
pingBtn.disabled = false;
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,76 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-Hans">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Marqdo · 表单 (D3)</title>
|
||||
<style>
|
||||
:root {
|
||||
--ink: #1a1f1c;
|
||||
--paper: #e8efe6;
|
||||
--accent: #2f6f4e;
|
||||
--muted: #5a6b60;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif;
|
||||
color: var(--ink);
|
||||
background:
|
||||
radial-gradient(700px 400px at 100% 20%, #d0e0d4 0%, transparent 50%),
|
||||
linear-gradient(165deg, #f3f7f2, var(--paper));
|
||||
padding: 2rem clamp(1rem, 4vw, 3rem);
|
||||
}
|
||||
h1 {
|
||||
font-family: "IBM Plex Serif", "Noto Serif SC", serif;
|
||||
font-weight: 600;
|
||||
font-size: clamp(1.6rem, 3vw, 2.2rem);
|
||||
margin: 0 0 0.35rem;
|
||||
}
|
||||
.lead { color: var(--muted); margin: 0 0 1.25rem; max-width: 38rem; }
|
||||
label { display: block; font-size: 0.85rem; color: var(--muted); margin: 0.75rem 0 0.35rem; }
|
||||
input[type="text"] {
|
||||
width: min(24rem, 100%);
|
||||
padding: 0.5rem 0.75rem;
|
||||
border: 1px solid #b7c7bb;
|
||||
background: rgba(255,255,255,0.75);
|
||||
font: inherit;
|
||||
}
|
||||
#echo {
|
||||
margin-top: 1rem;
|
||||
font-size: 1.25rem;
|
||||
min-height: 1.5em;
|
||||
}
|
||||
#echo.hi { color: var(--accent); font-weight: 600; }
|
||||
pre {
|
||||
margin-top: 1.5rem;
|
||||
width: min(42rem, 100%);
|
||||
padding: 0.9rem 1rem;
|
||||
background: #122018;
|
||||
color: #d7eadc;
|
||||
overflow: auto;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.err { color: #ffb4a8; }
|
||||
a { color: var(--accent); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Marqdo</h1>
|
||||
<p class="lead">D3:<code>input</code> 事件把 <code>value</code> 传入 Marqdo;<code>set_value</code> / <code>set_class</code> / <code>set_attr</code> 回写 DOM。业务只在 <code>form.mq.md</code>。<a href="./interact.html">计数器</a> · <a href="./">打印</a></p>
|
||||
<label for="name">名字</label>
|
||||
<input id="name" type="text" placeholder="输入…" disabled />
|
||||
<div id="echo">(等待输入)</div>
|
||||
<pre id="log">loading…</pre>
|
||||
<script
|
||||
type="module"
|
||||
src="./marqdo-bridge.js"
|
||||
data-mq-wasm="./marqdo_wasm.wasm"
|
||||
data-mq-source-url="./form.mq.md"
|
||||
data-mq-ready="#log"
|
||||
data-mq-enable="#name"
|
||||
></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,34 @@
|
||||
---
|
||||
title: browser form (D3)
|
||||
description: input wire passes value; set_text / set_class / set_attr effects
|
||||
import json:lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`wire` =
|
||||
|
||||
| @ | 选择器 | 事件 | 调用 |
|
||||
|---|--------|------|------|
|
||||
| 1 | "#name" | input | on_input |
|
||||
|
||||
**`wire`**
|
||||
|
||||
## on_input
|
||||
+ `value`=""
|
||||
+ `event`=""
|
||||
|
||||
1. `value` != ""
|
||||
*`label` = "你好," + value*
|
||||
*`t` = > json.set map=None key="#echo" value=label*
|
||||
*`ret` = > json.set map=None key="set_text" value=t*
|
||||
*`c` = > json.set map=None key="#echo" value="hi"*
|
||||
*`ret` = > json.set map=ret key="set_class" value=c*
|
||||
*`attrs` = > json.set map=None key="data-name" value=value*
|
||||
*`a` = > json.set map=None key="#echo" value=attrs*
|
||||
**> json.set map=ret key="set_attr" value=a**
|
||||
2. *
|
||||
*`t` = > json.set map=None key="#echo" value="(等待输入)"*
|
||||
*`ret` = > json.set map=None key="set_text" value=t*
|
||||
*`c` = > json.set map=None key="#echo" value=""*
|
||||
**> json.set map=ret key="set_class" value=c**
|
||||
@@ -67,7 +67,7 @@
|
||||
</head>
|
||||
<body>
|
||||
<h1>Marqdo</h1>
|
||||
<p class="lead">浏览器内 WASM 解释器(路线 C / C1):源码是 <code>.mq.md</code>,无业务手写 JS。<a href="./interact.html">交互示例 (C3)</a></p>
|
||||
<p class="lead">浏览器内 WASM(路线 C/D):源码是 <code>.mq.md</code>,官方 bridge 自启 playground,无作者业务 JS。<a href="./interact.html">交互</a> · <a href="./fetch.html">fetch</a> · <a href="./form.html">表单</a></p>
|
||||
<label for="src">程序</label>
|
||||
<textarea id="src"># main
|
||||
|
||||
@@ -77,6 +77,12 @@
|
||||
<button id="run" disabled>运行</button>
|
||||
</div>
|
||||
<pre id="out">loading wasm…</pre>
|
||||
<script type="module" src="./loader.js"></script>
|
||||
<script
|
||||
type="module"
|
||||
src="./marqdo-bridge.js"
|
||||
data-mq-wasm="./marqdo_wasm.wasm"
|
||||
data-mq-playground="#src,#run,#out"
|
||||
data-mq-ready="#out"
|
||||
></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -62,11 +62,18 @@
|
||||
</head>
|
||||
<body>
|
||||
<h1>Marqdo</h1>
|
||||
<p class="lead">C3:GFM 交互表装配事件;点击由 WASM 会话里的 Marqdo 函数处理并回写 DOM。<a href="./fetch.html">fetch (C4)</a> · <a href="./">打印示例</a></p>
|
||||
<p class="lead">C3/D:GFM 交互表装配事件;官方 <code>mount</code> 自启,业务只在 <code>counter.mq.md</code>。<a href="./fetch.html">fetch</a> · <a href="./form.html">表单</a> · <a href="./">打印</a></p>
|
||||
<div id="count">0</div>
|
||||
<button id="bump" type="button" disabled>加一</button>
|
||||
<button id="reset" class="secondary" type="button" disabled>清零</button>
|
||||
<pre id="log">loading…</pre>
|
||||
<script type="module" src="./interact.js"></script>
|
||||
<script
|
||||
type="module"
|
||||
src="./marqdo-bridge.js"
|
||||
data-mq-wasm="./marqdo_wasm.wasm"
|
||||
data-mq-source-url="./counter.mq.md"
|
||||
data-mq-ready="#log"
|
||||
data-mq-enable="#bump,#reset"
|
||||
></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,53 +0,0 @@
|
||||
import {
|
||||
applyDomPatch,
|
||||
boot,
|
||||
loadWasm,
|
||||
readCString,
|
||||
wireEvents,
|
||||
} from "./marqdo-bridge.js";
|
||||
|
||||
async function main() {
|
||||
const log = document.getElementById("log");
|
||||
const bump = document.getElementById("bump");
|
||||
const reset = document.getElementById("reset");
|
||||
|
||||
let exports;
|
||||
try {
|
||||
exports = await loadWasm("./marqdo_wasm.wasm");
|
||||
} catch (e) {
|
||||
log.classList.add("err");
|
||||
log.textContent = String(e);
|
||||
return;
|
||||
}
|
||||
|
||||
const srcRes = await fetch("./counter.mq.md");
|
||||
if (!srcRes.ok) {
|
||||
log.classList.add("err");
|
||||
log.textContent = `failed to load counter.mq.md (${srcRes.status})`;
|
||||
return;
|
||||
}
|
||||
const source = await srcRes.text();
|
||||
const result = boot(exports, source);
|
||||
if (!result.ok) {
|
||||
log.classList.add("err");
|
||||
log.textContent = result.error || "boot failed";
|
||||
return;
|
||||
}
|
||||
|
||||
const n = wireEvents(exports, result.value, {
|
||||
onError: (err) => {
|
||||
log.classList.add("err");
|
||||
log.textContent = err;
|
||||
},
|
||||
});
|
||||
// Ensure initial display matches Marqdo state.
|
||||
applyDomPatch({ set_text: { "#count": "0" } });
|
||||
|
||||
const ver = readCString(exports.memory, exports.mq_version());
|
||||
log.classList.remove("err");
|
||||
log.textContent = `marqdo-wasm ${ver} · wired ${n} handler(s)\nsource: counter.mq.md`;
|
||||
bump.disabled = false;
|
||||
reset.disabled = false;
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,48 +0,0 @@
|
||||
import {
|
||||
loadWasm,
|
||||
readCString,
|
||||
runSource,
|
||||
} from "./marqdo-bridge.js";
|
||||
|
||||
const DEFAULT_SRC = `# main
|
||||
|
||||
> print text=Hello from browser WASM!
|
||||
`;
|
||||
|
||||
async function main() {
|
||||
const out = document.getElementById("out");
|
||||
const btn = document.getElementById("run");
|
||||
const src = document.getElementById("src");
|
||||
if (!src.value.trim()) src.value = DEFAULT_SRC;
|
||||
|
||||
let exports;
|
||||
try {
|
||||
exports = await loadWasm("./marqdo_wasm.wasm");
|
||||
} catch (e) {
|
||||
out.classList.add("err");
|
||||
out.textContent = String(e);
|
||||
return;
|
||||
}
|
||||
const ver = readCString(exports.memory, exports.mq_version());
|
||||
out.classList.remove("err");
|
||||
out.textContent = `marqdo-wasm ${ver} ready.\n`;
|
||||
btn.disabled = false;
|
||||
|
||||
btn.addEventListener("click", () => {
|
||||
try {
|
||||
const result = runSource(exports, src.value);
|
||||
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) {
|
||||
out.classList.add("err");
|
||||
out.textContent = String(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,11 +1,13 @@
|
||||
/**
|
||||
* Canonical Marqdo browser bridge (route C). Host glue only — not app logic.
|
||||
* Canonical Marqdo browser bridge (route C/D). Host glue only — not app logic.
|
||||
* Copied to site dirs by `marqdo wasm build`.
|
||||
*
|
||||
* 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): set_text, fetch, after
|
||||
* 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)
|
||||
*/
|
||||
|
||||
export function readCString(memory, ptr) {
|
||||
@@ -67,16 +69,196 @@ export async function loadWasm(url = "./marqdo_wasm.wasm") {
|
||||
return instance.exports;
|
||||
}
|
||||
|
||||
/** Apply C3/C4 return effects: set_text, fetch, after */
|
||||
function isPlainObject(v) {
|
||||
return v != null && typeof v === "object" && !Array.isArray(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,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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));
|
||||
} 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 && !el.dataset.mqWasm) continue;
|
||||
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;
|
||||
}
|
||||
|
||||
/** 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",
|
||||
};
|
||||
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 (typeof t.textContent === "string" && !("value" in t)) {
|
||||
args.text = t.textContent;
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/** Apply C3/C4/D3 return effects: DOM patches then fetch/after. */
|
||||
export function applyDomPatch(value) {
|
||||
if (!value || typeof value !== "object") return;
|
||||
if (typeof document === "undefined") return;
|
||||
|
||||
const setText = value.set_text || value.setText;
|
||||
if (setText && typeof setText === "object") {
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -180,12 +362,15 @@ export function wireEvents(exports, bootValue, { onError } = {}) {
|
||||
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 || "";
|
||||
if (!sel || !fn) continue;
|
||||
const nodes = document.querySelectorAll(sel);
|
||||
nodes.forEach((node) => {
|
||||
node.addEventListener(ev, () => {
|
||||
node.addEventListener(ev, (domEv) => {
|
||||
try {
|
||||
const result = call(exports, fn, { event: ev });
|
||||
const args = eventArgsFromDom(domEv, valueFrom);
|
||||
const result = call(exports, fn, args);
|
||||
if (!result.ok) {
|
||||
if (onError) onError(result.error);
|
||||
else console.error(result.error);
|
||||
@@ -202,3 +387,154 @@ export function wireEvents(exports, bootValue, { onError } = {}) {
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
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 boot value is a map with effects alongside wire, apply them.
|
||||
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 };
|
||||
}
|
||||
|
||||
/** Auto-mount from DOM configs (route D). */
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
# web-client-site(路线 D)
|
||||
|
||||
服务端 `ext/web` + 浏览器 WASM 会话;**作者零业务 JS**。
|
||||
|
||||
```bash
|
||||
# 仓库根
|
||||
cargo build -p marqdo --release
|
||||
cargo build --release -p marqdo_plugin_web
|
||||
./target/release/marqdo ext add web
|
||||
|
||||
# 构建 WASM + bridge 到本示例 static/
|
||||
./target/release/marqdo wasm build -o examples/web-client-site/static
|
||||
# 保留 client.mq.md(wasm build 只写入 wasm/bridge)
|
||||
|
||||
cd examples/web-client-site
|
||||
marqdo run index.mq.md
|
||||
# 打开 http://127.0.0.1:18090/
|
||||
```
|
||||
|
||||
`index.mq.md` 用 `web.client_embed source="/static/client.mq.md"` 注入自启脚本;交互在 `static/client.mq.md`。
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
title: web-client-site
|
||||
description: SSR shell + client_embed auto-mount; author zero JS (route D)
|
||||
import web:ext/web/web.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Server page with a counter UI. Client logic lives in `static/client.mq.md`
|
||||
(loaded by official bridge via `client_embed`).
|
||||
|
||||
*`embed` = > web.client_embed bridge="/static/marqdo-bridge.js" wasm="/static/marqdo_wasm.wasm" source="/static/client.mq.md" boot=True*
|
||||
|
||||
*`intro` = "<h1>Marqdo client site</h1><p>SSR + WASM session. No author JS.</p><div id=\"count\">0</div><p><button id=\"bump\" type=\"button\" disabled>Bump</button> <button id=\"reset\" type=\"button\" disabled>Reset</button></p><pre id=\"log\">booting…</pre>" + embed*
|
||||
|
||||
*page = > web.page title="Marqdo client site" intro=intro*
|
||||
*app = > web.app page=page host="127.0.0.1" port=18090*
|
||||
*app = > app.static dir="static" mount="/static"*
|
||||
> `app`.listen
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
title: client counter (route D)
|
||||
description: wired by client_embed auto-mount
|
||||
import json:lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*`count` = 0*
|
||||
|
||||
`wire` =
|
||||
|
||||
| @ | 选择器 | 事件 | 调用 |
|
||||
|---|--------|------|------|
|
||||
| 1 | "#bump" | click | bump |
|
||||
| 2 | "#reset" | click | reset |
|
||||
|
||||
*`ready` = > json.set map=None key="#log" value="client.mq.md ready"*
|
||||
*`enable_bump` = > json.set map=None key="disabled" value=False*
|
||||
*`enable_reset` = > json.set map=None key="disabled" value=False*
|
||||
*`attrs` = > json.set map=None key="#bump" value=enable_bump*
|
||||
*`attrs` = > json.set map=attrs key="#reset" value=enable_reset*
|
||||
*`boot` = > json.set map=None key="wire" value=wire*
|
||||
*`boot` = > json.set map=boot key="set_text" value=ready*
|
||||
**> json.set map=boot key="set_attr" value=attrs**
|
||||
|
||||
## bump
|
||||
*`count` = count + 1*
|
||||
*`label` = > str count*
|
||||
*`patch` = > json.set map=None key="#count" value=label*
|
||||
**> json.set map=None key="set_text" value=patch**
|
||||
|
||||
## reset
|
||||
*`count` = 0*
|
||||
*`patch` = > json.set map=None key="#count" value="0"*
|
||||
**> json.set map=None key="set_text" value=patch**
|
||||
@@ -0,0 +1,540 @@
|
||||
/**
|
||||
* Canonical Marqdo browser bridge (route C/D). Host glue only — not app logic.
|
||||
* Copied to site dirs by `marqdo wasm build`.
|
||||
*
|
||||
* 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)
|
||||
*/
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/** 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,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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));
|
||||
} 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 && !el.dataset.mqWasm) continue;
|
||||
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;
|
||||
}
|
||||
|
||||
/** 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",
|
||||
};
|
||||
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 (typeof t.textContent === "string" && !("value" in t)) {
|
||||
args.text = t.textContent;
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/** Apply C3/C4/D3 return effects: DOM patches then fetch/after. */
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run sync DOM patches then schedule async effects (ADR 0003).
|
||||
*/
|
||||
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 afterSpec = value.after;
|
||||
if (afterSpec && typeof afterSpec === "object" && afterSpec.then) {
|
||||
tasks.push(runAfterEffect(exports, afterSpec, onError));
|
||||
}
|
||||
|
||||
return Promise.all(tasks);
|
||||
}
|
||||
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire events from `# main` return value.
|
||||
* Accepts a list of row maps, 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 || "";
|
||||
if (!sel || !fn) continue;
|
||||
const nodes = document.querySelectorAll(sel);
|
||||
nodes.forEach((node) => {
|
||||
node.addEventListener(ev, (domEv) => {
|
||||
try {
|
||||
const args = eventArgsFromDom(domEv, valueFrom);
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
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 boot value is a map with effects alongside wire, apply them.
|
||||
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 };
|
||||
}
|
||||
|
||||
/** Auto-mount from DOM configs (route D). */
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user