GizStack
View .mdOpen in ChatGPTOpen in Claude

gizweb/client/kernel

GizWeb's page client, the one copy of it: what a page's attributes mean once it is in a browser (web/kernel.giz lists them). It runs on any host of Page (page.giz): natively in GizBrowser, and as the JavaScript web/kernel.giz serves to every other browser. The host hands it the events of the page after the page's own listeners (on); each part below is one listener of the browser's, in the order a browser runs them.

gizlang
import * as Kernel from "gizweb/client/kernel";

Types

Kernel

gizlang
class Kernel { page: Page; host: Host; version: string; micro: Vec<() => void> = []; epoch: i64 = 0; opening: bool = false; asking: bool = false; again: bool = false; names: Vec<string> = []; busy: Map<i64, () => void> = new Map(); bound: Option<Vec<string>> = undefined; socket: i64 = -1; opened: bool = false; sent: string = ""; generation: i64 = 0; positions: Map<string, Vec<string>> = new Map(); newest: i64 = 0; frames: Map<string, i64> = new Map(); loads: i64 = 0; searching: bool = false; searchNext: i64 = -1; typed: i64 = -1; typedTimer: i64 = -1; restored: Set<string> = new Set(); dragged: Option<Vec<string>> = undefined; events: Vec<Beat> = []; trace: Vec<string> = ["", ""]; path: string; shown: string; errorIds: i64 = 0; constructor(page: Page, host: Host) { this.page = page; this.host = host; this.version = page.get(page.root(), "data-v") ?? ""; this.path = pathOf(host.url()); this.shown = withoutFragment(host.url()); } begin(timing: string): void { this.trace = traceOf(timing); for (const f of this.all("form[data-auto]")) { this.page.submit(f); } this.onlineMark(); this.settled(true); this.flush(); } on(n: i64, type: string, ev: Event): bool { let free = true; if (type === "click") { free = this.clicked(n, ev); } else if (type === "submit") { free = this.submitted(n, ev); } else if (type === "change") { this.changed(n); } else if (type === "input") { this.typing(n); } else if (type === "keydown") { free = this.keyed(n, ev); } else if (type === "close") { this.closed(n); } else if (type === "toggle") { this.toggled(n, ev); } else if (type === "contextmenu") { free = this.menu(n, ev); } else if (type === "dragstart") { this.dragStart(n); } else if (type === "dragend") { this.dragEnd(); } else if (type === "dragover") { free = this.dragOver(n, ev); } else if (type === "dragleave") { this.dragLeave(n, ev); } else if (type === "drop") { free = this.dropped(n, ev); } else if (type === "paste") { free = this.pasted(n, ev); } this.flush(); return free; } popped(): void { if (withoutFragment(this.href()) === this.shown) { return; } this.visit(this.href(), false); this.flush(); } hide(): void { this.flushEvents(); this.saveTyped(); this.flush(); } close(): void { this.flushEvents(); if (this.socket> = 0) { this.host.closeSocket(this.socket); this.socket = -1; } } leaving(): bool { this.saveTyped(); this.flush(); return this.asking || this.busy.size> 0 || this.first("textarea[data-unsaved],form[aria-busy=true]")> = 0; } online(): void { this.onlineMark(); if (this.host.online()) { this.ask([]); } this.flush(); } error(message: string, at: string): void { this.event("error", message, pathOf(this.href()), at === "" ? "{}": `{"at":${quote(at) } }`); } send(name: string, body: string, done: (answer: string) => void): void { const k = this; this.host.act(name, body, (answer: string): void => { if (answer !== "") { done(answer); k.flush(); return; } k.fetch("POST", k.host.resolve(ACTIONS + name, ""), ["content-type", "application/x-www-form-urlencoded"], body, (got: Got): void => { if (got.status === Http.STATUS_CONFLICT && got.stale) { k.renew((): void => {}); done(""); return; } if (got.type.startsWith(GO)) { k.host.open(got.body); done(""); return; } done(got.status === 0 ? "": got.body); }); }); } patched(patches: string): void { const applied = this.apply(jsonOr(patches).list()); this.flush(); } soon(run: () => void): void { this.micro.push(run); } flush(): void { while (this.micro.length> 0) { const runs = this.micro; this.micro = []; for (const run of runs) { run(); } } } later(ms: i64, run: () => void): i64 { const k = this; return this.host.later(ms, (): void => { run(); k.flush(); }); } fetch(method: string, url: string, headers: Vec<string>, body: string, done: (got: Got) => void): void { const k = this; this.host.fetch(method, url, [VERSION, this.version].concat(headers), body, (got: Got): void => { done(got); k.flush(); }); } post(url: string, form: i64, by: i64, picked: Vec<i64>, keepalive: bool, done: (got: Got) => void): void { const k = this; this.host.post(url, [VERSION, this.version], form, by, picked, keepalive, (got: Got): void => { done(got); k.flush(); }); } root(): i64 { return this.page.root(); } first(selector: string): i64 { return this.within(this.root(), selector); } all(selector: string): Vec<i64> { return this.page.query(this.root(), selector, true); } within(root: i64, selector: string): i64 { const found = this.page.query(root, selector, false); return found.length> 0 ? found[0]: -1; } allWithin(root: i64, selector: string): Vec<i64> { return this.page.query(root, selector, true); } byKey(key: string): i64 { return this.first(`[data-k=${cssString(key) }]`); } attr(n: i64, name: string): string { return this.page.get(n, name) ?? ""; } has(n: i64, name: string): bool { return this.page.get(n, name) !== undefined; } formOf(t: i64): i64 { const owner = this.page.get(t, "form"); return owner !== undefined ? this.page.byId(owner!): this.page.closest(t, "form"); } control(f: i64, name: string): i64 { for (const c of this.page.controls(f)) { if (this.attr(c, "name") === name) { return c; } } return -1; } href(): string { return this.host.url(); } own(href: string): string { const to = this.host.resolve(href, ""); return to !== "" && originOf(to) === originOf(this.href()) ? to: ""; } title(root: i64): string { const t = this.within(root, "title"); return t> = 0 ? collapse(this.page.text(t)): ""; } setTitle(text: string): void { let t = this.first("title"); if (t <0) { const head = this.first("head"); if (head <0) { return; } t = this.page.create("title"); this.page.insert(head, t, -1); } if (this.page.text(t) !== text) { this.page.setText(t, text); } } inPage(n: i64): bool { return this.contains(this.root(), n); } contains(root: i64, n: i64): bool { if (root <0) { return false; } for (let x = n; x> = 0; x = this.page.parent(x)) { if (x === root) { return true; } } return false; } lost(): void { const f = this.page.focused(); if (f> = 0 && !this.inPage(f)) { this.page.focus(-1); } } hiddenInPopover(n: i64): bool { const open = this.page.popovers(); for (let x = n; x> = 0; x = this.page.parent(x)) { if (this.page.kind(x) === ELEMENT && this.has(x, "popover") && !open.includes(x)) { return true; } } return false; } clicked(t: i64, ev: Event): bool { const p = this.page; const h = this.host; const k = this; let free = true; const copier = p.closest(t, "[data-copy]"); if (copier> = 0) { const selector = this.attr(copier, "data-copy"); let found: i64 = -1; for (let up = p.parent(copier); up> = 0 && found <0; up = p.parent(up)) { found = this.within(up, selector); } if (found> = 0) { h.copy(found, (): void => { p.set(copier, "data-done", ""); const timer = k.later(1500, (): void => { p.unset(copier, "data-done"); }); }); } } else if (!ev.prevented && ev.button === 0 && (ev.modifiers & (SHIFT | CONTROL | ALT | META)) === 0) { const a = p.closest(t, "a[href]"); const to = a <0 || this.has(a, "target") || this.has(a, "download") || this.has(a, "data-hard") ? "": this.own(this.attr(a, "href")); if (to !== "" && !(pathAndQuery(to) === pathAndQuery(this.href()) && fragmentOf(to).length> 1)) { free = false; const frame = this.attr(a, "data-frame"); if (frame !== "") { this.loadFrame(to, frame, (): void => {}); } else { this.visit(to, true); } } } const cancel = p.closest(t, "[data-cancel]"); const cancelled = cancel> = 0 ? p.closest(cancel, "form"): -1; if (cancelled> = 0 && this.busy.has(cancelled)) { free = false; this.busy.get(cancelled)!(); } const menu = p.closest(t, "[popover][role=menu]"); if (menu> = 0 && p.closest(t, "button[role=menuitem],a[role=menuitem]")> = 0 && p.popovers().includes(menu)) { p.hidePopover(menu); } return free; } changed(t: i64): void { const p = this.page; const h = this.host; const m = p.matches(t, "[role^=menuitem] > input[type=radio]") ? p.closest(t, "[popover][role=menu]"): -1; if (m> = 0) { const chosen = this.first(`[popovertarget=${cssString(this.attr(m, "id")) }] [data-chosen]`); const label = nextElement(p, t); if (chosen> = 0 && label> = 0) { p.setText(chosen, p.text(label)); } p.hidePopover(m); } if (this.has(t, "data-b")) { this.bind(t); } else if (this.has(t, "data-send")) { const f = this.formOf(t); if (f> = 0) { p.requestSubmit(f, -1); } } if (t === this.typed) { h.cancel(this.typedTimer); this.typed = -1; } } typing(t: i64): void { const p = this.page; const h = this.host; const k = this; if (p.matches(t, "textarea[data-b][name^=\"_f.\"]")) { if (this.typed> = 0 && this.typed !== t) { this.saveTyped(); } p.set(t, "data-unsaved", ""); this.typed = t; h.cancel(this.typedTimer); this.typedTimer = this.later(800, (): void => { k.saveTyped(); }); } if (p.matches(t, "input[type=search]")) { const f = this.formOf(t); if (this.has(t, "data-b")) { this.bind(t); } else if (f> = 0 && this.attr(f, "data-frame") !== "" && (p.get(f, "method") ?? "get").toLowerCase() === "get") { this.search(f); } } const named = this.attr(t, "data-filter"); const list = named === "" ? -1: p.byId(named); if (list> = 0 && !this.has(t, "data-b")) { const q = p.value(t).trim().toLowerCase(); for (const x of this.allWithin(list, "[data-filter-item]")) { if (q !== "" && !p.text(x).toLowerCase().includes(q)) { p.set(x, "hidden", ""); } else { p.unset(x, "hidden"); } } } } saveTyped(): void { this.host.cancel(this.typedTimer); const t = this.typed; if (t> = 0) { this.typed = -1; this.bind(t); } } keyed(t: i64, ev: Event): bool { const p = this.page; const h = this.host; const key = ev.key; const mods = ev.modifiers; if (key === "ContextMenu" || (key === "F10" && mods === SHIFT)) { const r = p.box(t); if (r.length === 4 && !this.openContext(t, r[0], r[1] + r[3])) { return false; } } const enter = key === "Enter"; let taken = false; const f = this.formOf(t); const on = p.closest(t, "form[data-on]"); if (enter && p.matches(t, "input:not([type=checkbox],[type=radio],[type=submit],[type=button])") && on> = 0) { const b = this.within(on, "button[name=_a]"); if (b> = 0) { taken = true; p.click(b); } } else if (enter && !ev.composing && p.matches(t, "input[data-b]:not([type=checkbox],[type=radio])") && f> = 0 && this.attr(f, "id") === "_g") { taken = true; p.dispatch(t, "change"); } else if (enter && (mods & SHIFT) === 0 && !ev.composing && p.matches(t, "textarea[data-enter]")) { taken = true; const target = this.attr(t, "data-enter"); const b = target === "" ? -1: p.byId(target); if (p.value(t).trim() !== "") { if (target === "") { if (f> = 0) { p.requestSubmit(f, -1); } } else if (b> = 0 && !this.has(b, "disabled")) { p.click(b); } } } else if ((mods & (CONTROL | META)) !== 0) { const hot = this.first(`[data-hotkey=${cssString(`${(mods & SHIFT) !== 0 ? "shift+": "" }${ key.toLowerCase() }`) }]`); if (hot> = 0) { taken = true; p.click(hot); } } const menu = p.closest(t, "[role=menu]"); if (menu> = 0 && this.attr(t, "role").startsWith("menuitem")) { if ((enter || key === " ") && p.matches(t, "a,button,label")) { taken = true; p.click(t); } else { const items = this.allWithin(menu, "[role^=menuitem]:not([hidden])"); const at = items.indexOf(t); const to = key === "ArrowDown" ? (at + 1) % items.length: key === "ArrowUp" ? (at + items.length - 1) % items.length: key === "Home" ? 0: key === "End" ? items.length - 1: -1; if (to> = 0 && items.length> 0) { taken = true; p.focus(items[to]); } } } if (!ev.prevented && !taken && (mods & (CONTROL | META | ALT)) === 0 && !ev.composing && this.keyFor(t, key)) { taken = true; } const named = this.attr(t, "data-filter"); const list = named === "" ? -1: p.byId(named); const x = list <0 ? -1: this.within(list, "[data-filter-item]:not([hidden])"); if (x> = 0 && (enter || key === "ArrowDown")) { taken = true; const a = p.matches(x, "a,button,label") ? x: this.within(x, "a,button,label"); if (a> = 0) { if (enter) { p.click(a); } else { p.focus(a); } } } return !taken; } keyFor(t: i64, key: string): bool { const p = this.page; const h = this.host; if (key !== "Escape" && p.closest(t, "input,textarea,select,[contenteditable]")> = 0) { return false; } const item = p.closest(t, "[popover]")> = 0 ? -1: p.closest(t, "[data-item]"); const name = key === " " ? "Space": key; if (((name === "ArrowDown" || name === "ArrowUp") && item> = 0) || name === "j" || name === "k") { const items = this.all("[data-item]").filter((n: i64): bool => p.box(n).length> 0); const at = items.indexOf(item); const down = name === "ArrowDown" || name === "j"; const to = down ? at + 1: at <0 ? 0: at - 1; const next = items.length === 0 ? -1: items[to <0 ? 0: to> = items.length ? items.length - 1: to]; const a = next <0 ? -1: this.within(next, "a[href]"); if (a <0) { return false; } p.focus(a); return true; } const named = `[data-key~=${cssString(name) }]`; const mine = item> = 0 ? this.within(item, named): -1; const c = mine> = 0 ? mine: this.first(named); if (c <0) { return false; } const pop = p.closest(c, "[popover]"); if (pop> = 0 && item> = 0 && this.contains(item, pop) && !p.popovers().includes(pop)) { p.showPopover(pop); } else if (p.box(c).length === 0) { return false; } if (p.matches(c, "input,textarea,select")) { p.focus(c); if (p.matches(c, "input,textarea")) { p.selectAll(c); } } else { p.click(c); } return true; } closed(n: i64): void { if (this.has(n, "data-done")) { this.page.unset(n, "data-done"); return; } const back = this.attr(n, "data-back"); const to = back === "" ? "": this.host.resolve(back, ""); if (to !== "" && to !== this.href()) { this.visit(to, true); } } toggled(m: i64, ev: Event): void { const p = this.page; const h = this.host; if (ev.state === "open" && p.matches(m, "[role=menu]")) { const i = this.within(m, "[data-filter],[role^=menuitem]"); if (i> = 0) { p.focus(i); } } if (ev.state === "closed" && this.has(m, "data-at")) { p.unset(m, "data-at"); p.set(m, "style", ""); } } menu(t: i64, ev: Event): bool { if ((ev.modifiers & SHIFT) !== 0) { return true; } return this.openContext(t, ev.x, ev.y); } openContext(t: i64, x: f64, y: f64): bool { const p = this.page; const item = p.closest(t, "[data-item]"); const m = item <0 ? -1: this.within(item, "[popover][role=menu]"); if (m <0) { return true; } p.showPopover(m); const r = p.box(m); const view = p.box(-1); const width = r.length === 4 ? r[2]: 0.0; const height = r.length === 4 ? r[3]: 0.0; const right = view.length === 4 ? view[2]: 0.0; const bottom = view.length === 4 ? view[3]: 0.0; p.set(m, "data-at", ""); p.set(m, "style", `position:fixed;margin:0;inset:auto;left:${clamp(x, right - width - 8.0) }px; top: ${ clamp(y, bottom - height - 8.0) }px`); return false; } zone(t: i64): i64 { return this.page.closest(t, "[data-drop]:not([data-drop='']),form"); } fileInput(t: i64): i64 { const z = this.zone(t); if (z <0) { return -1; } const named = this.attr(z, "data-drop"); const f = named !== "" ? this.page.byId(named): z; if (f <0) { return -1; } for (const c of this.page.controls(f)) { if (this.page.matches(c, "input[type=file]")) { return c; } } return -1; } over(z: i64, on: bool): void { if (z <0 || this.attr(z, "data-drop") === "") { return; } if (on) { this.page.set(z, "data-over", ""); } else { this.page.unset(z, "data-over"); } } dragStart(t: i64): void { const p = this.page; const h = this.host; const d = p.closest(t, "[data-drag]"); if (d <0) { return; } const b = this.within(d, "input[type=checkbox]:checked"); let values: Vec<string> = []; if (b> = 0) { for (const x of this.all(`input[name=${cssString(this.attr(b, "name")) }]: checked`)) { values.push(p.value(x)); } } else { values.push(this.attr(d, "data-drag")); } this.dragged = values; p.drag(values.join("\n")); } dragEnd(): void { this.dragged = undefined; for (const x of this.all("[data-into][data-over]")) { this.page.unset(x, "data-over"); } } into(t: i64): i64 { return this.dragged === undefined ? -1: this.page.closest(t, "[data-into]:not([data-into=''])"); } ownTarget(t: i64): bool { const value = this.attr(t, "data-into"); return (this.dragged ?? []).includes(value.startsWith("/") ? value.slice(1, value.length): value); } dragOver(t: i64, ev: Event): bool { let free = true; if (this.fileInput(t)> = 0 && ev.files> 0) { free = false; this.over(this.zone(t), true); } const target = this.into(t); if (target> = 0 && !this.ownTarget(target)) { free = false; this.page.dropMove(); this.page.set(target, "data-over", ""); } return free; } dragLeave(t: i64, ev: Event): void { const z = this.zone(t); if (z> = 0 && !this.contains(z, ev.related)) { this.over(z, false); } const target = this.into(t); if (target> = 0 && !this.contains(target, ev.related)) { this.page.unset(target, "data-over"); } } dropped(t: i64, ev: Event): bool { const p = this.page; const h = this.host; let free = true; const i = this.fileInput(t); this.over(this.zone(t), false); if (i> = 0 && ev.files> 0) { free = false; p.takeFiles(i); } const target = this.into(t); const f = target <0 ? -1: p.byId(this.attr(target, "data-into-form")); if (f> = 0 && !this.ownTarget(target)) { free = false; p.unset(target, "data-over"); const path = this.control(f, "path"); const to = this.control(f, "to"); if (path> = 0) { p.setValue(path, (this.dragged ?? []).join("\n")); } if (to> = 0) { p.setValue(to, this.attr(target, "data-into")); } p.requestSubmit(f, -1); } return free; } pasted(t: i64, ev: Event): bool { const p = this.page; const h = this.host; let i = this.fileInput(t); if (i <0 && p.closest(t, "form,input,textarea,[contenteditable]") <0) { const z = this.first("[data-drop]:not([data-drop=''])"); if (z> = 0) { i = this.fileInput(z); } } if (i <0 || ev.files === 0) { return true; } p.takeFiles(i); return false; } submitted(f: i64, ev: Event): bool { const p = this.page; const h = this.host; const k = this; const by = ev.submitter; if (this.has(f, "data-passkey") && !this.has(f, "data-answered")) { if (this.attr(f, "aria-busy") !== "true") { p.passkey(f); } return false; } const a = this.attr(f, "data-a"); if (a === "" || (by> = 0 && this.has(by, "formaction"))) { return this.plain(f, by); } if (this.attr(f, "aria-busy") === "true" || !this.confirmed(f)) { return false; } for (const e of this.allWithin(f, "[data-err]")) { p.setText(e, ""); } for (const c of this.allWithin(f, "[data-bad]")) { p.unset(c, "data-bad"); p.unset(c, "aria-invalid"); const mine = this.attr(c, "data-error-id"); const described = words(this.attr(c, "aria-describedby")).filter((id: string): bool => id !== mine); if (described.length> 0) { p.set(c, "aria-describedby", described.join(" ")); } else { p.unset(c, "aria-describedby"); } p.unset(c, "data-error-id"); } p.set(f, "aria-busy", "true"); p.set(f, "data-state", "busy"); const undo = this.optimistic(f); const scope = this.epoch; let dialog = by> = 0 ? p.closest(by, "dialog"): -1; if (dialog <0) { dialog = p.closest(f, "dialog"); } let over = false; const end = (how: i64, r: Json): void => { if (over) { return; } over = true; k.busy.delete(f); let failed = true; if (how === ANSWERED && r.field("ok").boolean() && dialog> = 0) { p.set(dialog, "data-done", ""); p.close(dialog); } const live = scope === k.epoch && k.inPage(f); if (live && how === CANCELLED) { p.set(f, "data-state", "cancelled"); } else if (live && how === LOST) { k.problem(f, NONE, h.online() ? "Cannot connect. Please try again.": "You are offline. Send again when connected."); } else if (live && how === ANSWERED) { if (!r.field("ok").boolean()) { const errors = r.field("errors").list(); for (const m of errors.length> 0 ? errors: [r]) { k.problem(f, m, m.field("message").text()); } } else { failed = false; k.reset(f); if (r.get("o") !== undefined) { const applied = k.apply(r.field("o").list()); } const go = k.control(f, "_go"); const to = go <0 || p.value(go) === "" ? "": h.resolve(fillGo(p.value(go), r.field("value")), ""); if (to !== "") { k.visit(to, true); } } } p.set(f, "aria-busy", "false"); if (k.attr(f, "data-state") === "busy") { p.set(f, "data-state", failed ? "error": "ok"); } if (failed && live) { undo(); } if (how === STALE && live && !k.has(f, "data-again")) { k.renew((): void => { if (!k.inPage(f) || !k.has(f, "data-a")) { return; } p.set(f, "data-again", "1"); p.requestSubmit(f, by> = 0 && k.contains(f, by) ? by: -1); }); } else { p.unset(f, "data-again"); } k.waited(); }; this.busy.set(f, (): void => { end(CANCELLED, NONE); }); h.act(a, form(texts(p.formData(f, by))), (answer: string): void => { if (over) { return; } if (answer !== "") { end(ANSWERED, jsonOr(answer)); k.flush(); return; } k.post(h.resolve(ACTIONS + a, ""), f, by, [], false, (got: Got): void => { if (got.status === Http.STATUS_CONFLICT && got.stale) { end(STALE, NONE); return; } const r = got.status === 0 ? NONE: jsonOr(got.body); end(r.kind === "object" ? ANSWERED: LOST, r); }); }); return false; } confirmed(f: i64): bool { const q = this.attr(f, "data-confirm"); return q === "" || this.has(f, "data-again") || this.host.confirm(q); } problem(f: i64, m: Json, text: string): void { const p = this.page; const h = this.host; const name = m.field("field").kind === "string" ? m.field("field").text(): ""; let e = this.within(f, `[data-for=${cssString(name) }]`); if (e <0) { e = this.within(f, "[data-for=\"\"]"); } if (e> = 0) { p.setText(e, text); } const c = name === "" ? -1: this.within(f, `[name=${cssString(name) }]: not([type = hidden])`); if (c <0) { return; } p.set(c, "aria-invalid", "true"); p.set(c, "data-bad", ""); if (e> = 0) { if (this.attr(e, "id") === "") { this.errorIds + = 1; p.set(e, "id", `err${this.errorIds }`); } const id = this.attr(e, "id"); p.set(c, "data-error-id", id); let described = words(this.attr(c, "aria-describedby")).filter((x: string): bool => x !== id); described.push(id); p.set(c, "aria-describedby", described.join(" ")); } const focused = p.focused(); if (focused <0 || !this.contains(f, focused) || !this.has(focused, "data-bad")) { const bad = this.within(f, "[data-bad]"); if (bad> = 0) { p.focus(bad); } } } optimistic(f: i64): () => void { const p = this.page; const h = this.host; let undo: Vec<() => void> = []; for (const word of words(this.attr(f, "data-optimistic"))) { const eq = word.indexOf("="); if (eq <= 0 || eq === word.length - 1) { continue; } const left = word.slice(0, eq); const name = word.slice(eq + 1, word.length); const at = left.indexOf("@"); const key = at <0 ? left: left.slice(0, at); const attribute = at <0 ? "": left.slice(at + 1, left.length); const e = this.byKey(key); const c = this.control(f, name); if (e <0 || c <0) { continue; } const v = p.matches(c, "[type=checkbox]") ? (p.checked(c) ? "1": ""): p.value(c); if (attribute !== "") { const old = p.get(e, attribute); p.set(e, attribute, v); undo.push((): void => { if (old === undefined) { p.unset(e, attribute); } else { p.set(e, attribute, old!); } }); } else { const old = p.text(e); p.setText(e, v); undo.push((): void => { p.setText(e, old); }); } } return (): void => { for (const u of undo) { u(); } }; } reset(f: i64): void { const p = this.page; const h = this.host; let kept: Vec<i64> = []; let values: Vec<string> = []; let checks: Vec<bool> = []; for (const c of p.controls(f)) { if (this.has(c, "data-keep") || (this.has(c, "data-b") && this.names.includes(this.attr(c, "name")))) { kept.push(c); values.push(p.value(c)); checks.push(p.checked(c)); } } p.reset(f); for (let i = 0; i <kept.length; i + = 1) { if (p.matches(kept[i], "[type=checkbox],[type=radio]")) { p.setChecked(kept[i], checks[i]); } else { p.setValue(kept[i], values[i]); } } } plain(f: i64, by: i64): bool { const p = this.page; const h = this.host; const k = this; const method = this.attr(f, "method").toLowerCase(); if (method === "dialog" || (by> = 0 && this.attr(by, "formmethod").toLowerCase() === "dialog")) { return true; } if (method === "post" && !this.has(f, "target") && !h.online()) { this.unsent(); return false; } if (this.has(f, "target") || this.has(f, "data-hard") || (by> = 0 && (this.has(by, "data-hard") || this.has(by, "formtarget") || this.has(by, "formmethod") || this.has(by, "formenctype")))) { return true; } const action = by> = 0 && this.attr(by, "formaction") !== "" ? this.attr(by, "formaction"): this.attr(f, "action"); const target = this.own(action === "" ? this.href(): action); if (target === "") { return true; } const enctype = this.attr(f, "enctype").toLowerCase(); if (enctype.includes("multipart") && this.attr(f, "data-progress") !== "" && method === "post") { this.upload(f, by); return false; } if (enctype.includes("multipart") || enctype === "text/plain") { return true; } if (this.attr(f, "aria-busy") === "true" || !this.confirmed(f)) { return false; } const pairs = texts(p.formData(f, by)); if (method !== "post") { const u = withQuery(target, form(pairs)); const frame = this.attr(f, "data-frame"); if (frame !== "") { this.loadFrame(u, frame, (): void => {}); } else { this.visit(u, true); } return false; } this.epoch + = 1; const n = this.epoch; p.set(f, "aria-busy", "true"); this.fetch("POST", target, ["content-type", "application/x-www-form-urlencoded"], form(pairs), (got: Got): void => { if (got.status === Http.STATUS_CONFLICT && got.stale) { if (n === k.epoch) { k.renew((): void => {}); } } else if (got.type.startsWith(GO)) { h.open(got.body); } else if (got.status === 0) { if (h.online()) { h.reload(); } else { k.unsent(); } } else if (n === k.epoch) { if (got.status> = 200 && got.status <300) { k.reset(f); let dialog = by> = 0 ? p.closest(by, "dialog"): -1; if (dialog <0) { dialog = p.closest(f, "dialog"); } if (dialog> = 0) { p.set(dialog, "data-done", ""); p.close(dialog); } } const frame = k.attr(f, "data-frame"); if (frame !== "") { k.frame(got.body, frame, got.url); } else { k.arrive(got.body, got.url, got.url !== k.href(), n, got.timing, true, 1); } } p.set(f, "aria-busy", "false"); k.waited(); }); return false; } upload(f: i64, by: i64): void { const p = this.page; const h = this.host; const k = this; if (this.attr(f, "aria-busy") === "true") { return; } this.epoch + = 1; const scope = this.epoch; const shown = p.byId(this.attr(f, "data-progress")); const bar = shown <0 ? -1: this.within(shown, "progress"); p.set(f, "aria-busy", "true"); const action = by> = 0 && this.attr(by, "formaction") !== "" ? this.attr(by, "formaction"): this.attr(f, "action"); h.upload(h.resolve(action === "" ? this.href(): action, ""), f, by, (sent: f64, total: f64): void => { if (shown <0 || total <= 0.0) { return; } p.unset(shown, "hidden"); p.set(shown, "data-pct", `${i64(sent * 100.0 / total) }%`); if (bar> = 0) { p.set(bar, "max", `${i64(total) }`); p.set(bar, "value", `${i64(sent) }`); } }, (got: Got): void => { p.set(f, "aria-busy", "false"); if (scope === k.epoch && k.inPage(f)) { if (shown> = 0) { p.set(shown, "hidden", ""); } if (got.status> = 200 && got.status <300 && got.url !== "") { k.reset(f); k.arrive(got.body, got.url, got.url !== k.href(), -1, got.timing, true, 1); } else { p.set(f, "data-state", "error"); const e = k.within(f, "[data-err]"); if (e> = 0) { p.setText(e, got.status !== 0 ? "The upload was refused. Your inputs were kept.": "The upload could not connect. Your inputs were kept."); } } k.waited(); } k.flush(); }); } search(f: i64): void { if (this.searching) { this.searchNext = f; return; } this.searching = true; const k = this; const action = this.attr(f, "action"); const target = this.host.resolve(action === "" ? this.href(): action, ""); this.loadFrame(withQuery(target, form(texts(this.page.formData(f, -1)))), this.attr(f, "data-frame"), (): void => { k.searching = false; const next = k.searchNext; k.searchNext = -1; if (next> = 0) { k.search(next); } }); } visit(href: string, link: bool): void { const p = this.page; const h = this.host; const k = this; this.epoch + = 1; const n = this.epoch; this.generation + = 1; this.sent = ""; let cancels: Vec<() => void> = []; for (const [f, cancel] of this.busy) { cancels.push(cancel); } for (const cancel of cancels) { cancel(); } this.bound = undefined; this.names = []; this.again = false; this.opening = true; p.set(this.root(), "aria-busy", "true"); this.fetch("GET", href, [], "", (got: Got): void => { if (n !== k.epoch) { return; } if (got.status <200 || got.status> = 300 || !got.type.includes("html")) { k.opening = false; p.unset(k.root(), "aria-busy"); h.open(href); return; } k.arrive(got.body, got.url !== "" ? got.url: href, link, n, got.timing, true, 0); }); } renew(then: () => void): void { const k = this; const href = this.href(); this.fetch("GET", href, ["cache-control", "no-store"], "", (got: Got): void => { if (got.status <200 || got.status> = 300) { k.host.reload(); return; } k.arrive(got.body, href, false, -1, "", false, 0); then(); }); } arrive(text: string, url: string, link: bool, at: i64, timing: string, counted: bool, pushed: i64): void { if (at <0) { this.epoch + = 1; } const n = at <0 ? this.epoch: at; if (n !== this.epoch) { return; } const p = this.page; const h = this.host; const k = this; const root = this.root(); const s = p.parse(text); if (scripts(p, s) !== scripts(p, root) || (p.get(s, "data-wasm") ?? "") !== this.attr(root, "data-wasm")) { h.open(url); return; } this.sheets(s); const head = this.first("head"); const newHead = this.within(s, "head"); if (head> = 0) { for (const e of this.allWithin(head, "[data-page]")) { p.detach(e); } if (newHead> = 0) { for (const e of this.allWithin(newHead, "[data-page]")) { p.insert(head, p.adopt(e), -1); } } } for (const a of ["lang", "dir"]) { const v = p.get(s, a); if (v !== p.get(root, a)) { if (v === undefined) { p.unset(root, a); } else { p.set(root, a, v!); } } } const version = p.get(s, "data-v") ?? ""; if (version !== this.version) { this.version = version; p.set(root, "data-v", version); } const title = this.title(s); this.shown = withoutFragment(url); if (counted) { this.trace = traceOf(timing); const to = pathOf(url); this.event("page", title, to, `{"from":${quote(this.path) } }`); this.path = to; } const show = (): void => { if (n !== k.epoch) { return; } k.setTitle(title); if (link) { for (const o of p.popovers()) { p.hidePopover(o); } } const body = k.first("body"); const newBody = k.within(s, "body"); if (body> = 0 && newBody> = 0) { k.morph(body, newBody); k.lost(); } const g = p.get(s, "data-generation"); if (g !== undefined) { p.set(root, "data-generation", g!); } const shown = parseInt(k.attr(root, "data-generation")); if (shown !== undefined && k.newest> shown!) { k.soon((): void => { k.ask([]); }); } const address = stateAddress(p, h, s, url); if (link || (pushed> 0 && address !== k.href())) { const top = link || pathOf(address) !== pathOf(k.href()); h.move(address, pushed === 2); k.shown = withoutFragment(address); if (top) { h.top(); } } k.opening = false; p.unset(root, "aria-busy"); k.settled(link); k.waited(); k.flush(); }; if (link) { h.transition(show); } else { show(); } } sheets(s: i64): void { const selector = "link[rel=stylesheet]"; let shown: Vec<string> = []; for (const l of this.all(selector)) { shown.push(this.attr(l, "href")); } let wanted: Vec<string> = []; for (const l of this.allWithin(s, selector)) { wanted.push(this.attr(l, "href")); } if (shown.join("\n") !== wanted.join("\n")) { this.host.sheets(wanted); } } settled(link: bool): void { const p = this.page; const h = this.host; this.connect(); if (link) { for (const f of this.all("[autofocus]")) { if (!this.hiddenInPopover(f)) { p.focus(f); break; } } } for (const dialog of this.all("dialog[data-shown]:not([open])")) { p.showModal(dialog); } this.restore(); if (link && this.first("[data-connect]")> = 0) { this.ask([]); } } restore(): void { const p = this.page; const h = this.host; const g = p.byId("_g"); if (g <0) { return; } let again = false; for (const i of p.controls(g)) { if (!p.matches(i, "input[data-local]")) { continue; } const name = this.attr(i, "name"); const key = `g:${pathOf(this.href()) }: ${ name }`; const v = h.stored(key); if (!this.restored.has(key)) { this.restored.add(key); if (v !== undefined && v! !== p.value(i)) { p.setValue(i, v!); for (const c of this.all("[data-b]")) { if (this.formOf(c) !== g || this.attr(c, "name") !== name) { continue; } if (p.matches(c, "[type=checkbox]")) { p.setChecked(c, v! === "true"); } else { p.setValue(c, v!); } } again = true; continue; } } h.store(key, p.value(i)); } for (const i of p.controls(g)) { if (p.matches(i, "input[data-cookie]")) { const name = this.attr(i, "name"); h.cookie(`g.${name.slice(3, name.length) }`, p.value(i)); } } if (again) { this.ask([]); } } ask(names: Vec<string>): void { for (const name of names) { if (!this.names.includes(name)) { this.names.push(name); } } this.again = true; const p = this.page; const h = this.host; const k = this; const g = p.byId("_g"); if (this.asking || this.opening || this.busy.size> 0 || (g> = 0 && this.attr(g, "aria-busy") === "true")) { return; } const u = this.href(); this.epoch + = 1; const n = this.epoch; const changed = this.names; let picked: Vec<i64> = []; let fields: Vec<string> = []; let files = false; const pairs = g> = 0 ? p.formData(g, -1): []; for (let i = 0; i + 1 <pairs.length; i + = 2) { const key = pairs[i]; const named = key.startsWith("_o.") ? `_f.${key.slice(3, key.length) }`: key; if (key.startsWith("_s.") || key === "_revision" || changed.includes(named)) { picked.push(i / 2); fields.push(key); fields.push(pairs[i + 1]); if (pairs[i + 1].length> 1 && pairs[i + 1].startsWith(FILE)) { files = true; } } } if (files) { let once: Vec<i64> = []; for (let j = 0; j <picked.length; j + = 1) { let later = false; for (let m = j + 1; m <picked.length; m + = 1) { if (fields[m * 2] === fields[j * 2]) { later = true; } } if (fields[j * 2 + 1].startsWith(FILE) || !later) { once.push(picked[j]); } } picked = once; } const typed = changed.length> 0 && changed.every((name: string): bool => k.first(`[data-b][name=${cssString(name) }]: is([type = search], [type = text])`)> = 0); this.names = []; this.again = false; this.asking = true; const done = (got: Got): void => { k.asking = false; if (got.status === Http.STATUS_CONFLICT && got.stale) { k.renew((): void => {}); } else if (got.type.includes("html") && ((got.status> = 200 && got.status <300) || (g> = 0 && got.status !== 0)) && u === k.href()) { k.arrive(got.body, u, false, n, "", false, typed ? 2: 1); if (got.status> = 200 && got.status <300) { for (const c of k.all("textarea[data-unsaved]")) { let last = ""; let had = false; for (let i = 0; i + 1 <fields.length; i + = 2) { if (fields[i] === k.attr(c, "name")) { last = fields[i + 1]; had = true; } } if (had && p.value(c) === last) { p.unset(c, "data-unsaved"); } } } } k.waited(); }; if (g> = 0) { this.post(u, g, -1, picked, h.hidden() && !files, done); if (files) { for (const c of this.all("input[type=file][form=\"_g\"]")) { p.setValue(c, ""); } } } else { this.fetch("GET", u, ["cache-control", "no-store"], "", done); } } waited(): void { if (this.again) { this.ask([]); } } bind(t: i64): void { const name = this.attr(t, "name"); if (this.bound === undefined) { this.bound = []; const k = this; this.soon((): void => { const names = k.bound ?? []; k.bound = undefined; k.ask(names); }); } let names = this.bound!; names.push(name); this.bound = names; } onlineMark(): void { if (this.host.online()) { this.page.unset(this.root(), "data-offline"); } else { this.page.set(this.root(), "data-offline", ""); } } unsent(): void { const k = this; this.page.set(this.root(), "data-offline", "unsent"); const timer = this.later(4000, (): void => { k.onlineMark(); }); } loadFrame(url: string, key: string, done: () => void): void { const scope = this.epoch; const k = this; this.loads + = 1; const mine = this.loads; this.frames.set(key, mine); this.fetch("GET", url, [], "", (got: Got): void => { if (scope === k.epoch && k.frames.get(key) === mine) { if (got.status> = 200 && got.status <300 && got.type.includes("html")) { k.frame(got.body, key, url); } else { k.host.open(url); } } done(); }); } frame(text: string, key: string, url: string): void { const p = this.page; const h = this.host; const s = p.parse(text); const n = this.within(s, `[data-k=${cssString(key) }]`); const e = this.byKey(key); if (n <0 || e <0) { h.open(url); return; } this.morph(e, n); this.lost(); } apply(o: Vec<Json>): bool { const p = this.page; const h = this.host; let applied = true; for (const patch of o) { const parts = patch.list(); if (parts.length <2) { continue; } const t = parts[0].text(); const key = parts[1].text(); const v = parts.length> 2 ? parts[2]: NONE; const c = parts.length> 3 ? parts[3]: NONE; if (t === "page") { this.ask([]); applied = false; continue; } if (t === "title") { this.setTitle(p.text(this.fragment(v.text()))); continue; } if (t === "rng" || t === "rows") { const r = this.range(key); if (r.length === 0) { this.ask([]); applied = false; continue; } if (t === "rows") { if (!this.rows(key, r, v.list(), c.list())) { applied = false; this.ask([]); } } else { let x: Vec<i64> = []; for (let at = p.next(r[0]); at> = 0 && at !== r[1]; at = p.next(at)) { x.push(at); } this.morphChildren(p.parent(r[0]), x, children(p, this.fragment(v.text())), r[1]); } continue; } const e = this.byKey(key); if (t === "text") { if (e> = 0) { p.setText(e, v.text()); } } else if (t === "attr") { if (e> = 0) { if (c.kind === "null") { p.unset(e, v.text()); } else { p.set(e, v.text(), c.text()); } } } else if (t === "del") { if (e> = 0) { p.detach(e); } } else if (t === "all" || t === "end") { if (e> = 0) { if (t === "all") { while (p.first(e)> = 0) { p.detach(p.first(e)); } } for (const x of children(p, this.fragment(v.text()))) { p.insert(e, p.adopt(x), -1); } } } else { const made = firstElement(p, this.fragment(v.text())); if (made <0) { continue; } if (t === "top") { if (e> = 0) { p.detach(e); } const into = this.byKey(c.text()); if (into> = 0) { p.insert(into, p.adopt(made), p.first(into)); } } else if (e> = 0) { if (identity(p, e) === identity(p, made)) { this.morph(e, made); } else { p.insert(p.parent(e), p.adopt(made), e); p.detach(e); } } else { const into = this.byKey(c.text()); if (into> = 0) { p.insert(into, p.adopt(made), -1); } } } } this.lost(); return applied; } fragment(markup: string): i64 { return this.within(this.page.parse(markup), "body"); } range(id: string): Vec<i64> { const p = this.page; const h = this.host; const body = this.first("body"); if (body <0) { return []; } const open = `g:${id }`; const end = `/g:${id }`; let start: i64 = -1; for (let n = following(p, body, body); n> = 0; n = following(p, n, body)) { if (p.kind(n) !== COMMENT) { continue; } if (start <0) { if (p.data(n) === open) { start = n; } } else if (p.data(n) === end) { return [start, n]; } } return []; } rows(id: string, r: Vec<i64>, list: Vec<Json>, gone: Vec<Json>): bool { const p = this.page; const h = this.host; const open = r[0]; const end = r[1]; const parent = p.parent(open); let m: Map<string, i64> = new Map(); for (let n = p.next(open); n> = 0 && n !== end; n = p.next(n)) { if (p.kind(n) === ELEMENT) { const key = this.attr(n, "data-k"); m.set(key.slice(id.length + 1, key.length), n); } } for (const key of gone) { const n = m.get(key.text()); if (n !== undefined) { p.detach(n!); } m.delete(key.text()); } for (const row of list) { const parts = row.list(); if (parts.length <3) { continue; } const key = parts[0].text(); const after = parts[2].kind === "string" ? parts[2].text(): ""; const made = firstElement(p, this.fragment(parts[1].text())); const w = after !== "" ? m.get(after) ?? -1: open; if (made <0 || w <0) { return false; } const was = m.get(key); const before = p.next(w); if (was === undefined) { const n = p.adopt(made); p.insert(parent, n, before); m.set(key, n); } else { if (was! !== before) { p.insert(parent, was!, before); } if (identity(p, was!) === identity(p, made)) { this.morph(was!, made); } else { const n = p.adopt(made); p.insert(parent, n, was!); p.detach(was!); m.set(key, n); } } } return true; } morph(a: i64, b: i64): void { const p = this.page; const h = this.host; if (p.kind(a) === ELEMENT) { if (this.has(a, "data-own")) { return; } const tag = p.tag(a); const ownOpen = tag === "details" || tag === "dialog"; const touched = p.changed(a); const kept = (name: string): bool => (ownOpen && name === "open") || ((name === "value" || name === "checked") && touched); for (const name of p.names(a)) { if (!kept(name) && name !== "data-unsaved" && p.get(b, name) === undefined) { p.unset(a, name); } } for (const name of p.names(b)) { const v = p.get(b, name)!; if (!kept(name) && p.get(a, name) !== v) { p.set(a, name, v); } } if (tag === "textarea") { if (!touched && p.text(a) !== p.text(b)) { p.setText(a, p.text(b)); } return; } const shadow = p.shadow(b, -1); if (shadow> = 0) { this.morph(p.shadow(a, shadow), shadow); } if (tag.includes("-") && p.first(b) <0) { return; } } let x: Vec<i64> = []; for (let c = p.first(a); c> = 0; c = p.next(c)) { x.push(c); } this.morphChildren(a, x, children(p, b), -1); } morphChildren(parent: i64, x: Vec<i64>, y: Vec<i64>, end: i64): void { const p = this.page; const index = twins(p, x); let taken: Vec<i64> = index.lists.map(l => 0); let kept = new Set<i64>(); let cursor = x.length> 0 ? x[0]: end; for (const q of y) { const slot = index.slots.get(identity(p, q)) ?? -1; const twin = slot> = 0 && taken[slot] <index.lists[slot].length ? index.lists[slot][taken[slot]]: -1; if (twin> = 0) { taken[slot] + = 1; kept.add(twin); if (twin !== cursor) { p.insert(parent, twin, cursor); } if (p.kind(twin) === ELEMENT) { this.morph(twin, q); } else if (p.data(twin) !== p.data(q)) { p.setData(twin, p.data(q)); } cursor = p.next(twin); } else { p.insert(parent, p.adopt(q), cursor); } } for (const n of x) { if (!kept.has(n)) { p.detach(n); } } } subscriptions(): string { const p = this.page; const h = this.host; let items: Vec<string> = []; for (const e of this.all("[data-sub]:not([data-sub=''])")) { const topic = this.attr(e, "data-sub"); const pos = p.get(e, "data-pos"); const at = pos === undefined ? "null": quote(pos!); const held = this.positions.get(topic); if (held === undefined || held![1] !== at) { this.positions.set(topic, [at, at]); } const src = this.attr(e, "data-src"); items.push(`[${quote(topic) }, ${ this.positions.get(topic)![0] }, ${ quote(src !== "" ? src: pathAndQuery(this.href())) }]`); } const host = hostOf(this.href()); if (this.attr(this.root(), "data-generation") !== "" && (host === "localhost" || host === "127.0.0.1" || host === "[::1]")) { if (!this.positions.has(DEV)) { this.positions.set(DEV, ["\"\"", "\"\""]); } items.push(`[${quote(DEV) }, ${ this.positions.get(DEV)![0] }, ${ quote(pathOf(this.href())) }]`); } const g = p.byId("_g"); let state: Vec<string> = []; const pairs = g> = 0 ? texts(p.formData(g, -1)): []; for (let i = 0; i + 1 <pairs.length; i + = 2) { if (pairs[i].startsWith("_s.")) { state.push(pairs[i]); state.push(pairs[i + 1]); } } return `{"v":${quote(this.version) }, "s": [${ items.join(",") }], "st": ${ quote(form(state)) }`; } connect(): void { const set = this.subscriptions(); if (this.socket> = 0) { if (this.opened && set !== this.sent) { this.sent = set; this.generation + = 1; this.host.send(this.socket, `${set }, "g": ${ this.generation } }`); } return; } if (set.includes("\"s\":[]")) { return; } const origin = originOf(this.href()); const address = `${origin.startsWith("https:") ? `wss${origin.slice(5, origin.length) }`: origin.startsWith("http:") ? `ws${origin.slice(4, origin.length) }`: origin }${ SUBSCRIPTIONS }`; const k = this; this.opened = false; let mine: i64 = -1; mine = this.host.socket(address, (kind: i64, text: string): void => { if (mine === k.socket) { k.heard(kind, text); k.flush(); } }); this.socket = mine; } heard(kind: i64, text: string): void { const k = this; if (kind === OPENED) { this.opened = true; this.sent = this.subscriptions(); this.generation + = 1; this.host.send(this.socket, `${this.sent }, "g": ${ this.generation } }`); return; } if (kind === CLOSED) { this.socket = -1; this.sent = ""; this.opened = false; const timer = this.later(1000, (): void => { k.connect(); }); return; } if (kind !== MESSAGE) { return; } const j = jsonOr(text); if (j.field("g").integerOr(-1) !== this.generation) { return; } if (j.get("r") !== undefined && j.field("r").kind !== "null") { if (j.field("r").integerOr(0) === Http.STATUS_CONFLICT) { this.renew((): void => {}); } return; } const topic = j.field("t").text(); const held = this.positions.get(topic); if (held === undefined) { return; } const o = j.field("o").list(); if (topic === DEV) { this.dev(o.length> 0 ? o[0]: NONE); this.positions.set(topic, [stringify(j.field("p")), held![1]]); return; } const e = this.first(`[data-sub=${cssString(topic) }]`); const page = o.some((x: Json): bool => x.list().length> 0 && x.list()[0].text() === "page"); if (e> = 0 && this.attr(e, "data-src") !== "" && this.attr(e, "data-k") !== "" && page) { this.refresh(e); const applied = this.apply(o.filter((x: Json): bool => x.list().length === 0 || x.list()[0].text() !== "page")); } else if (this.apply(o)) { this.positions.set(topic, [stringify(j.field("p")), held![1]]); } } refresh(e: i64): void { const k = this; const scope = this.epoch; const generation = this.generation; const key = this.attr(e, "data-k"); const src = this.attr(e, "data-src"); this.fetch("GET", this.host.resolve(src, ""), [], "", (got: Got): void => { if (got.status> = 200 && got.status <300 && scope === k.epoch && generation === k.generation && k.inPage(e)) { k.frame(got.body, key, src); } }); } dev(o: Json): void { const p = this.page; const h = this.host; const parts = o.list(); const g = parts.length> 1 ? parts[1].integerOr(0): 0; const message = parts.length> 2 && parts[2].kind === "string" ? parts[2].text(): ""; let overlay = p.byId("giz-overlay"); if (message === "") { if (overlay> = 0) { p.detach(overlay); } this.newest = g; const shown = parseInt(this.attr(this.root(), "data-generation")); if (shown !== undefined && g> shown!) { this.ask([]); } return; } if (overlay <0) { overlay = p.create("pre"); p.set(overlay, "id", "giz-overlay"); p.set(overlay, "role", "alert"); p.set(overlay, "style", "position:fixed;inset:0;z-index:2147483647;margin:0;padding:24px;overflow:auto;background:#1d1d1fee;color:#ffb4ab;font:14px/1.5 ui-monospace,monospace;white-space:pre-wrap"); const body = this.first("body"); if (body> = 0) { p.insert(body, overlay, -1); } } p.setText(overlay, message); } event(kind: string, name: string, path: string, at: string): void { if (this.trace[0] === "") { return; } const n = name.length> 300 ? name.slice(0, 300): name; this.events.push({ k: kind, n, p: path, t: this.trace[0], s: this.trace[1], w: this.host.now(), a: at }); if (this.events.length> = 20) { this.flushEvents(); } } flushEvents(): void { if (this.events.length === 0) { return; } const now = this.host.now(); let items: Vec<string> = []; for (const e of this.events) { items.push(`{"k":${quote(e.k) }, "n": ${ quote(e.n) }, "p": ${ quote(e.p) }, "t": ${ quote(e.t) }, "s": ${ quote(e.s) }, "w": ${ i64(now - e.w + 0.5) }, "a": ${ e.a } }`); } this.events = []; this.host.beacon(this.host.resolve(EVENTS, ""), `[${items.join(",") }]`); } }

The page client of one page: it runs the page's attributes over a host of Page and talks to the server through Host.

  • page: M115.Page
  • host: M115.Host
  • version: string — The code version the page was rendered by (html data-v), sent with each request.
  • micro: Vec<() => void>
  • epoch: i64 — A page load or an action that owns the screen (epoch moves with each); the asks of bound controls wait for it.
  • opening: bool
  • asking: bool — The bound-state ask in flight, one more waiting, and the changed controls the next one names.
  • again: bool
  • names: Vec<string>
  • busy: _gizlang_sdk_collections.Map<i64, () => void> — The forms whose action is in flight, by node, each with what cancels it (data-cancel, a new page).
  • bound: _gizlang_sdk_core.Option<Vec<string>> — The bound controls changed in this turn, sent as one ask.
  • socket: i64 — The live channel: its socket (-1 none), whether it is open, the set it last sent, its generation, each topic's position [held, rendered] as JSON text, and the newest generation a live host announced.
  • opened: bool
  • sent: string
  • generation: i64
  • positions: _gizlang_sdk_collections.Map<string, Vec<string>>
  • newest: i64
  • frames: _gizlang_sdk_collections.Map<string, i64> — Each frame's newest load, and a search frame's ask in flight and the form that waits.
  • loads: i64
  • searching: bool
  • searchNext: i64
  • typed: i64 — A text area typed into and not yet saved, and its timer.
  • typedTimer: i64
  • restored: _gizlang_sdk_collections.Set<string> — The keys of kept state already put back on this visit.
  • dragged: _gizlang_sdk_core.Option<Vec<string>> — The values an item drag carries (data-drag), or none.
  • events: Vec<M114.Beat> — The page's events for EVENTS, its trace (traceparent's ids), the path it left and the error slots made.
  • trace: Vec<string>
  • path: string
  • shown: string — The address of the page shown, without its fragment: a step of the history within it (a fragment) loads nothing.
  • errorIds: i64

Functions

constructor

gizlang
constructor(page: Page, host: Host)

A kernel for the page PAGE, shown by HOST.

Effects: fail, write, alloc.

Methods

Kernel.begin

gizlang
begin(timing: string): void

The page is in, with the trace of the answer that made it (its Server-Timing): forms that send themselves go, the device's state shows, and the page settles for the first time.

Effects: fail, read, write, console, io, alloc.

Kernel.on

gizlang
on(n: i64, type: string, ev: Event): bool

Event TYPE of EV at N, after the page's listeners: false when the kernel took its default (preventDefault).

Effects: fail, read, write, console, io, alloc.

Kernel.popped

gizlang
popped(): void

A step of the history (popstate): the address shown comes in place.

Effects: fail, read, write, console, io, alloc.

Kernel.hide

gizlang
hide(): void

The page is hidden: its events go, and a typed text is saved now.

Effects: fail, read, write, console, io, alloc.

Kernel.close

gizlang
close(): void

The page goes (pagehide): its events go, its socket closes.

Effects: fail, read, write, alloc.

Kernel.leaving

gizlang
leaving(): bool

The person leaves (beforeunload): a typed text is saved; true when something is still unsaved and the browser should ask.

Effects: fail, read, write, console, io, alloc.

Kernel.online

gizlang
online(): void

The device went online or offline: the page says so, and is fetched again once it is back.

Effects: fail, read, write, console, io, alloc.

Kernel.error

gizlang
error(message: string, at: string): void

A script error of the page (window error or unhandledrejection) as an event, AT its file:line:column ("" none).

Effects: fail, read, write, alloc.

Kernel.send

gizlang
send(name: string, body: string, done: (answer: string) => void): void

A custom element's action (kernel/elements.js X): NAME with the urlencoded BODY, through the client module first. DONE gets the answer as JSON text, or "" when it was stale (the page renews) or did not connect.

Effects: fail, read, alloc.

Kernel.patched

gizlang
patched(patches: string): void

Patches a custom element's action answered (kernel/elements.js P), as JSON text.

Effects: fail, read, write, console, io, alloc.

Kernel.soon

gizlang
soon(run: () => void): void

RUN once the current turn's work is done (queueMicrotask).

Effects: fail, write, alloc.

Kernel.flush

gizlang
flush(): void

Runs the work queued for after this turn (soon), and the work that queues, until none is left.

Effects: fail, read, write, console, io, alloc.

Kernel.later

gizlang
later(ms: i64, run: () => void): i64

Runs RUN after MS milliseconds as a turn of its own (then flush); the timer, which Host.cancel stops.

Effects: fail, read, alloc.

Kernel.fetch

gizlang
fetch(method: string, url: string, headers: Vec<string>, body: string, done: (got: Got) => void): void

A request of the kernel: its version goes with it, and its answer is a turn.

Effects: fail, read, alloc.

Kernel.post

gizlang
post(url: string, form: i64, by: i64, picked: Vec<i64>, keepalive: bool, done: (got: Got) => void): void

Posts the form FORM to URL, as the control BY submits it, with the files PICKED; DONE gets the answer as a turn.

Effects: fail, read, alloc.

Kernel.root

gizlang
root(): i64

The page's root element (html).

Effects: fail, read.

Kernel.first

gizlang
first(selector: string): i64

The first element of the page that SELECTOR matches, or -1.

Effects: fail, read.

Kernel.all

gizlang
all(selector: string): Vec<i64>

Every element of the page that SELECTOR matches, in document order.

Effects: fail, read.

Kernel.within

gizlang
within(root: i64, selector: string): i64

The first element at or below ROOT that SELECTOR matches, or -1.

Effects: fail, read.

Kernel.allWithin

gizlang
allWithin(root: i64, selector: string): Vec<i64>

Every element at or below ROOT that SELECTOR matches, in document order.

Effects: fail, read.

Kernel.byKey

gizlang
byKey(key: string): i64

The element keyed KEY (data-k) of the page, or -1.

Effects: fail, read, alloc.

Kernel.attr

gizlang
attr(n: i64, name: string): string

The attribute NAME of N, or "" when it has none.

Effects: fail, read.

Kernel.has

gizlang
has(n: i64, name: string): bool

Whether N has the attribute NAME.

Effects: fail, read.

Kernel.formOf

gizlang
formOf(t: i64): i64

The form a control belongs to: its form attribute's, else the form it is in; -1 none.

Effects: fail, read.

Kernel.control

gizlang
control(f: i64, name: string): i64

FORM's control NAME, or -1.

Effects: fail, read.

Kernel.href

gizlang
href(): string

The page's address.

Effects: fail, read.

Kernel.own

gizlang
own(href: string): string

HREF as an absolute address of this page's origin, or "" when it is another origin's or none.

Effects: fail, read, alloc.

Kernel.title

gizlang
title(root: i64): string

document.title of the document at ROOT, and the page's title set (a title element made when the head has none).

Effects: fail, read, alloc.

Kernel.setTitle

gizlang
setTitle(text: string): void

Sets the page's title to TEXT, adding a title element to the head when there is none.

Effects: fail, read, write.

Kernel.inPage

gizlang
inPage(n: i64): bool

Whether N is in the page (the root or below it).

Effects: fail, read.

Kernel.contains

gizlang
contains(root: i64, n: i64): bool

Whether N is ROOT or below it.

Effects: fail, read.

Kernel.lost

gizlang
lost(): void

The focus on a node a morph took out leaves it, as a browser's does.

Effects: fail, read.

Kernel.hiddenInPopover

gizlang
hiddenInPopover(n: i64): bool

Whether N is inside a popover that is closed ([popover]:not(:popover-open) among its ancestors).

Effects: fail, read.

Kernel.clicked

gizlang
clicked(t: i64, ev: Event): bool

The click listener: data-copy, links, menus and the other click attributes of T. Whether the browser may still take its default.

Effects: fail, read, write, console, io, alloc.

Kernel.changed

gizlang
changed(t: i64): void

The change listener: a choice in a menu closes it, and a bound control asks the server for its state.

Effects: fail, read, write, alloc.

Kernel.typing

gizlang
typing(t: i64): void

The input listener: a text area bound to a stored field writes after a pause in typing.

Effects: fail, read, write, alloc.

Kernel.saveTyped

gizlang
saveTyped(): void

Writes the text area typed in now (typing), at once.

Effects: fail, read, write, alloc.

Kernel.keyed

gizlang
keyed(t: i64, ev: Event): bool

The keydown listener: shortcuts, Enter in a form, and moving in menus and lists. Whether the browser may still take its default.

Effects: fail, read, alloc.

Kernel.keyFor

gizlang
keyFor(t: i64, key: string): bool

data-key and data-item: a key named by data-key ("Space" for the space bar), pressed outside a field, focuses that field or presses that control; within an item (data-item) the item's own control answers first, even inside its closed menu, which opens. The arrow keys (and j, k) move between the items' first links. True when it took it.

Effects: fail, read, alloc.

Kernel.closed

gizlang
closed(n: i64): void

Closing a dialog that the address opened (Escape, its close link) goes back to the address without it.

Effects: fail, read, write, console, io, alloc.

Kernel.toggled

gizlang
toggled(m: i64, ev: Event): void

The toggle listener of a popover M: an opened menu takes the focus on its filter or first item.

Effects: fail, read.

Kernel.menu

gizlang
menu(t: i64, ev: Event): bool

A right click on an item opens the item's menu where the pointer is, inside the window (with Shift, the browser's own menu).

Effects: fail, read, alloc.

Kernel.openContext

gizlang
openContext(t: i64, x: f64, y: f64): bool

Opens the containing item's menu at a pointer or keyboard anchor. False when it took the event.

Effects: fail, read, alloc.

Kernel.zone

gizlang
zone(t: i64): i64

A file dropped or pasted on a form that has a file input fills the input; an element with data-drop="FORM" is a drop zone for FORM, marked data-over while files are over it.

Effects: fail, read.

Kernel.fileInput

gizlang
fileInput(t: i64): i64

The file input that a drop on T fills (its data-drop zone or form), or -1.

Effects: fail, read.

Kernel.over

gizlang
over(z: i64, on: bool): void

Marks the drop zone Z (data-over) while files are over it, and unmarks it.

Effects: fail, read, write.

Kernel.dragStart

gizlang
dragStart(t: i64): void

An item with data-drag="VALUE" drags onto an element with data-into="VALUE": the form its data-into-form names gets the dragged values (every chosen item's when the dragged one is chosen) in path, the target's in to, and is sent.

Effects: fail, read, write, alloc.

Kernel.dragEnd

gizlang
dragEnd(): void

The dragend listener: no item is dragged, and no target stays marked.

Effects: fail, read, write.

Kernel.into

gizlang
into(t: i64): i64

The data-into target at or above T while an item is dragged, or -1.

Effects: fail, read.

Kernel.ownTarget

gizlang
ownTarget(t: i64): bool

Whether the target T is one of the dragged items itself, which takes no drop.

Effects: fail, read, alloc.

Kernel.dragOver

gizlang
dragOver(t: i64, ev: Event): bool

The dragover listener: marks a drop zone or target under the pointer. Whether the browser may still take its default.

Effects: fail, read, write, alloc.

Kernel.dragLeave

gizlang
dragLeave(t: i64, ev: Event): void

The dragleave listener: unmarks a zone or target the pointer left.

Effects: fail, read, write.

Kernel.dropped

gizlang
dropped(t: i64, ev: Event): bool

The drop listener: dropped files fill the zone's file input, and a dragged item posts to its target's form. Whether the browser may still take its default.

Effects: fail, read, write, alloc.

Kernel.pasted

gizlang
pasted(t: i64, ev: Event): bool

Files pasted outside any form go to the page's drop zone, if it has one.

Effects: fail, read.

Kernel.submitted

gizlang
submitted(f: i64, ev: Event): bool

A form's submit event: an action form (data-a) posts to its action in place; a plain one opens its answer in place (plain). False when it took the default.

Effects: fail, read, write, console, io, alloc.

Kernel.confirmed

gizlang
confirmed(f: i64): bool

Whether FORM may send: one with data-confirm asks first (not again for a stale form sent again).

Effects: fail, read.

Kernel.problem

gizlang
problem(f: i64, m: Json, text: string): void

A rejection M of FORM's action, its message TEXT: the slot of its field (data-for) shows it, and the control it is about says so to assistive technology; the first such control takes the focus.

Effects: fail, read, write, alloc.

Kernel.optimistic

gizlang
optimistic(f: i64): () => void

data-optimistic="KEY=FIELD KEY@ATTRIBUTE=FIELD": the element keyed KEY shows the value of FORM's FIELD at once; the function given puts the old values back.

Effects: fail, read, write, alloc.

Kernel.reset

gizlang
reset(f: i64): void

A form whose action is done starts over, but keeps its data-keep controls and each bound control changed while the action was in flight.

Effects: fail, read, alloc.

Kernel.plain

gizlang
plain(f: i64, by: i64): bool

A form without an action (data-a): a GET opens its page in place (or its frame), a POST posts and opens its answer in place. A dialog form, a target, data-hard, a file or plain text, a submitter of its own method, and another origin stay the browser's. False when it took the default.

Effects: fail, read, write, console, io, alloc.

Kernel.upload

gizlang
upload(f: i64, by: i64): void

A file form with data-progress="ID" sends in place and shows how much went in element ID (its progress element, and its data-pct); the answer is the next page. One this page cannot read (another host answered) shows why.

Effects: fail, read, write, alloc.

gizlang
search(f: i64): void

A search field of a GET form with data-frame asks for its frame: one ask in flight, the newest text next.

Effects: fail, read, write, alloc.

Kernel.visit

gizlang
visit(href: string, link: bool): void

Opens the page at HREF in place (LINK: a link's, which starts at its top in a view transition): its HTML is fetched and morphed into the shown one. While it loads the document is busy (aria-busy on html).

Effects: fail, read, write, console, io, alloc.

Kernel.renew

gizlang
renew(then: () => void): void

The page of the new version, morphed in (a stale answer): its address fetched again; a failure loads in full. THEN runs once it is in.

Effects: fail, read, alloc.

Kernel.arrive

gizlang
arrive(text: string, url: string, link: bool, at: i64, timing: string, counted: bool, pushed: i64): void

The page TEXT from URL in place of the shown one, unless a newer load began (AT, the epoch it began at; -1: a new one now): its head's sheets and page tags, its language, its version, then its body morphed in. LINK starts it at its top. COUNTED records a page event with the trace of TIMING (its Server-Timing). PUSHED (0 none, 1 a step, 2 a replaced step) says how a new address of its state enters the history: the page answers a change of the person's.

Effects: fail, read, write, console, io, alloc.

Kernel.sheets

gizlang
sheets(s: i64): void

The style sheets of the page S beside the shown ones: when they differ, the host loads the new set.

Effects: fail, read, alloc.

Kernel.settled

gizlang
settled(link: bool): void

After a page is in (LINK: opened, not re-rendered): the channel follows its subscriptions, its autofocus (not one in a closed popover) and the dialog its address names open, its kept state comes back.

Effects: fail, read, write, alloc.

Kernel.restore

gizlang
restore(): void

State that stays in the browser (input[data-local] and input[data-cookie] of form#_g): a visit puts back what the person left, every state the page shows is kept for the next, and a cookie carries a choice the server renders.

Effects: fail, read, write, alloc.

Kernel.ask

gizlang
ask(names: Vec<string>): void

A page that keeps state (form#_g) asks again with its state fields and the changed bound controls NAMES (each with its old value, _o.NAME, which the server checks); the rows it shows are not sent back. Files of a bound file input go as a multipart form. One ask is in flight; those that come meanwhile are one more when it lands.

Effects: fail, read, write, alloc.

Kernel.waited

gizlang
waited(): void

The asks that waited go once the screen settles.

Effects: fail, read, write, alloc.

Kernel.bind

gizlang
bind(t: i64): void

The bound controls that change in one turn go in one ask (a paste in a grid changes many).

Effects: fail, read, write, alloc.

Kernel.onlineMark

gizlang
onlineMark(): void

The html says whether the device is online; data-offline="unsent" says for a moment that a form was not sent.

Effects: fail, read, write.

Kernel.unsent

gizlang
unsent(): void

Marks the page as having changes the server did not get (data-offline=unsent) until it is online again.

Effects: fail, read, write, alloc.

Kernel.loadFrame

gizlang
loadFrame(url: string, key: string, done: () => void): void

Loads the frame KEY (the element data-k=KEY) from URL: only its element of the answer goes in, while its page is current and no newer load of it began; an answer that is not HTML loads URL in full. DONE runs after.

Effects: fail, read, write, alloc.

Kernel.frame

gizlang
frame(text: string, key: string, url: string): void

The element KEY of the page TEXT morphed into the shown one; a page without it loads URL in full.

Effects: fail, read, alloc.

Kernel.apply

gizlang
apply(o: Vec<Json>): bool

Applies the server's patches O (web/html.giz): whether all applied; a "page" one, or a range that is gone, asks for the page instead.

Effects: fail, read, write, console, io, alloc.

Kernel.fragment

gizlang
fragment(markup: string): i64

MARKUP parsed: the body of its document, whose children are its nodes.

Effects: fail, read.

Kernel.range

gizlang
range(id: string): Vec<i64>

The comments that open and close the range ID (<!--g:ID-->, <!--/g:ID-->), or none.

Effects: fail, read, alloc.

Kernel.rows

gizlang
rows(id: string, r: Vec<i64>, list: Vec<Json>, gone: Vec<Json>): bool

The rows of the list ID between the comments R: each element data-k="ID:KEY". Each of LIST ([key, html, after]) goes after the row AFTER (the first when ""), and the keys GONE leave. False when a row could not be placed.

Effects: fail, read, alloc.

Kernel.morph

gizlang
morph(a: i64, b: i64): void

A (of the page) becomes B (of a parsed document): only the attributes and text that differ change, so the focus, a selection, what a person is typing and scroll positions stay. A data-own element is the client's; a disclosure's and a dialog's open stays; a control the host would let a new value overwrite keeps it; a text area's default value follows; an open shadow root is morphed; a custom element the server wrote empty keeps its children.

Effects: fail, read, alloc.

Kernel.morphChildren

gizlang
morphChildren(parent: i64, x: Vec<i64>, y: Vec<i64>, end: i64): void

The nodes X of PARENT, up to END (-1: the last), become the nodes Y of a parsed document: a node with its twin (identity) stays and is morphed, the rest of Y comes in, the rest of X goes.

Effects: fail, read, alloc.

Kernel.subscriptions

gizlang
subscriptions(): string

The page's subscriptions as the channel sends them, without the closing brace: each element's topic (data-sub) from its position (data-pos), for its address (data-src, else the page's), with the page's state (_s.*).

Effects: fail, read, write, alloc.

Kernel.connect

gizlang
connect(): void

The channel follows the page: a changed set goes on the open socket; a page with subscriptions opens one.

Effects: fail, read, write, alloc.

Kernel.heard

gizlang
heard(kind: i64, text: string): void

An event of the channel: opened, a message, or closed, which comes back after a second from the positions reached, so nothing is missed.

Effects: fail, read, write, console, io, alloc.

Kernel.refresh

gizlang
refresh(e: i64): void

A "page" patch of a subscribed element with data-src renders that element again (a frame), not the page; an answer that came after another page or another set is dropped.

Effects: fail, read, alloc.

Kernel.dev

gizlang
dev(o: Json): void

A live host's word on the channel ([_, generation, message]): a new generation is fetched (a busy page compares it when its answer lands); an error shows over the page until an edit fixes it.

Effects: fail, read, write, alloc.

Kernel.event

gizlang
event(kind: string, name: string, path: string, at: string): void

Queues a page event (App.Event) of KIND and NAME at PATH, with its detail AT; 20 queued events go at once. Only a host that records events gives the page its trace (Serving.record), so a page without one sends none.

Effects: fail, read, write, alloc.

Kernel.flushEvents

gizlang
flushEvents(): void

The events go in one beacon, each with how long ago it happened (w, in ms).

Effects: fail, read, write, alloc.