plexus-ui-engine 0.1.0

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
// FRAME-12: the host's JS face — `host.js`, beside `engine.js` in every
// bundle. `engine.js` imports it (wasm-bindgen's raw_module "./host.js"), and
// a module may import it from its own version's folder (`../host.js`).
//
// It holds no state. Everything a component needs arrives through `mount`'s
// context — `mount(target, { props, bus })` — and every function here reads
// only what it is handed, so a module that imports the `host.js` of another
// version is still on the page's one bus: the bus is the one it was given.
//
//   bus.call(method, params)         → Promise of the answer, FRAME-37:
//                                       the call's data events carrying `ok`,
//                                       `events` (itself) and `message` — what
//                                       rhx's call(…, "fold") folds; `ok`
//                                       false on an in-band error or refused,
//                                       the service's refusal, or the socket
//                                       dropping ("disconnected"), never sent
//                                       again; rejected only before the
//                                       socket, when the component's `uses`
//                                       does not name it
//   bus.live(spec)                   → { subscribe(fn) → unsubscribe, get(),
//                                       update(patch) } of { rows, status },
//                                       shared by spec; `fn` is called before
//                                       `subscribe` returns. FRAME-20:
//                                       `fn(value, change)` — the change
//                                       `{ upsert, remove }`, or `{ replace:
//                                       rows }` when whole. FRAME-19: the spec
//                                       may carry `when` (false: nothing asked)
//                                       and `debounce_ms`; `update({ params?,
//                                       changes_params?, when? })` moves them,
//                                       the host's registry keeping the time
//   bus.markdown(text)               → the engine's sanitized render as HTML,
//                                       what rhx's {@html markdown(text)} draws
//   bus.emit(topic, data, opts?)     page-wide, bare string topics; `plexus.…`
//                                       is the host's; never heard by the emitter.
//                                       FRAME-53: `{ sticky: true }` keeps it as
//                                       the topic's last event (a later emit on
//                                       the topic, sticky or not, replaces it)
//   bus.on(topic, fn, opts?)         → unsubscribe. FRAME-53: `{ last: true }`
//                                       calls `fn` at once with the topic's kept
//                                       event, if any (`plexus.booted` is kept)
//   bus.last(topic)                  → the topic's kept event, or undefined
//   bus.navigate(route)
//   bus.keys({ "ctrl+k": fn, "j": { to: fn, label, in_inputs, only, in_controls } })
//                                    → unsubscribe. FRAME-36: the module's
//                                       shortcuts, handled by the host on the
//                                       window (capture phase): a match is
//                                       never the page's or the browser's;
//                                       `fn({ key, chord, target })`. They go
//                                       with the module's destroy too
//   bus.slots.set(layout, slot, component, version?) → Promise; held to `uses`
//   bus.props                        the props now

// FRAME-16: the page's boot, in parallel — what an entrypoint calls:
//
//   const { start } = await import(`/app/${version}/host.js`); start(version);
//
// The socket is made, and the version's manifest.json and components.json
// asked, before engine.js is imported and the wasm instantiated; all three
// are handed to the wasm (`boot_started`), which adopts the socket. Nothing
// is kept here: everything goes to the wasm.
//
// UI-19: each of the version's files is asked at its content URL
// (`/app/f/<sha256>.<ext>`, `fileUrl`) when the page was served with it.
export async function start(version) {
  const socket = new WebSocket(socketUrl());
  const text = (file) => fetch(fileUrl(`/app/${version}/${file}`)).then((r) => (r.ok ? r.text() : null), () => null);
  const manifest = text("manifest.json");
  const components = text("components.json");
  const engine = await import(new URL("./engine.js", import.meta.url).href);
  await engine.default({ module_or_path: fileUrl(`/app/${version}/engine.wasm`) });
  engine.boot_started(version, socket, manifest, components);
}

// UI-19: the page's files by their content — the import map the service
// stamps first in the entrypoint (`<script type="importmap"
// id="plexus-ui-files">`): each `/app/<version>/<path>` of the version the
// page was served for, to `/app/f/<sha256>.<ext>`. The browser resolves
// every module import through it; `fileUrl` is the same for a fetch (the
// manifest, components.json, the wasm, a component's tree, handlers and
// sheet). A URL it does not name (another version's, a page served without
// it) is asked as it is.
let files = null;
function filesMap() {
  if (files) return files;
  try {
    files = JSON.parse(document.getElementById("plexus-ui-files")?.textContent || "{}").imports || {};
  } catch {
    files = {};
  }
  return files;
}
export function fileUrl(url) {
  return filesMap()[url] ?? url;
}

// UI-19: the service worker (`/app/sw.js`, the service's) keeps every
// `/app/f/…` answer across versions — cache-first, they never change — and
// is told the content URLs this version names, so it drops the ones no
// recent version names. Registered once the page is drawn; nothing waits
// on it, and a page served without a files map registers nothing.
export function keepFiles(version) {
  const urls = [...new Set(Object.values(filesMap()).filter((u) => u.startsWith("/app/f/")))];
  if (!urls.length || !("serviceWorker" in navigator) || !globalThis.isSecureContext) return;
  navigator.serviceWorker
    .register("/app/sw.js", { scope: "/" })
    .then(() => navigator.serviceWorker.ready)
    .then((r) => r.active?.postMessage({ type: "plexus-ui:files", version, urls }))
    .catch(() => {});
}

// The page's socket, as the wasm names it: over https the origin's /ws,
// else the stamped port (plexus-ws-port, else menger-ws-port) on the
// page's host.
function socketUrl() {
  if (location.protocol === "https:") return `wss://${location.host}/ws`;
  const meta = (name) => document.querySelector(`meta[name="${name}"]`)?.getAttribute("content") ?? "";
  const digits = (p) => /^[0-9]+$/.test(p);
  const port = [meta("plexus-ws-port"), meta("menger-ws-port")].find(digits) ?? "4455";
  return `ws://${location.hostname}:${port}`;
}

// FRAME-50: `fn` in a task of its own, posted behind the tasks the page has
// queued — the boot's mount yields between its sections through it, so an
// answer that arrived meanwhile is handled before the next section mounts. A
// MessageChannel's message: setTimeout clamps a chain of them to 4 ms, and
// scheduler.yield()'s continuation runs before the queued tasks — the answers
// the yield is for.
const turns = [];
let channel = null;
export function yieldTask(fn) {
  if (!channel) {
    channel = new MessageChannel();
    channel.port1.onmessage = () => turns.shift()?.();
  }
  turns.push(fn);
  channel.port2.postMessage(null);
}

// Imports a module (the wasm cannot `import()`).
export function importModule(url) {
  return import(url);
}

// The bus object a module is handed, over the wasm's handle of its member.
export function busOf(handle) {
  return Object.freeze({
    call: (method, params) => handle.call(method, params ?? {}),
    live: (spec) => store(handle.live(spec), spec?.key),
    emit: (topic, data, opts) => handle.emit(topic, data ?? null, opts),
    on: (topic, fn, opts) => handle.on(topic, fn, opts),
    last: (topic) => handle.last(topic),
    navigate: (route) => handle.navigate(route),
    keys: (map) => handle.keys(map),
    markdown: (text) => handle.markdown(String(text ?? "")),
    slots: Object.freeze({ set: (layout, slot, component, version) => handle.slots_set(layout, slot, component, version ?? undefined) }),
    get props() {
      return handle.props();
    },
  });
}

// FRAME-20: a `live` collection as a store, over the wasm's handle. The
// handle hands each subscriber the move — `{ status, message?, replace: rows }`
// (the first call, a resync, a switch: whole) or `{ status, message?,
// upsert: [rows], remove: [keys] }` (the fold's change by key) — and the
// store keeps the rows and applies it: an upserted row replaces the one of
// its key in place, or comes last; a removed key goes. Each move is a new
// value and a new array of the rows kept, the same objects but the ones the
// change named, so a keyed each touches only those. `fn(value, change)`:
// the value as ever, `{ rows, status }` (and `message`), and the change —
// `{ replace: rows }` or `{ upsert, remove }`.
function store(handle, key) {
  const keyOf = (row) => {
    const k = row?.[key];
    return typeof k === "string" ? k : JSON.stringify(k ?? null);
  };
  return {
    get: () => handle.get(),
    update: (patch) => handle.update(patch),
    subscribe(fn) {
      let rows = [];
      let at = new Map();
      return handle.subscribe((move) => {
        let change;
        if (move.replace) {
          rows = move.replace;
          at = new Map(rows.map((r, i) => [keyOf(r), i]));
          change = { replace: rows };
        } else {
          rows = rows.slice();
          if (move.remove.length) {
            const gone = new Set(move.remove);
            rows = rows.filter((r) => !gone.has(keyOf(r)));
            at = new Map(rows.map((r, i) => [keyOf(r), i]));
          }
          for (const r of move.upsert) {
            const k = keyOf(r);
            const i = at.get(k);
            if (i === undefined) {
              at.set(k, rows.length);
              rows.push(r);
            } else {
              rows[i] = r;
            }
          }
          change = { upsert: move.upsert, remove: move.remove };
        }
        const value = { rows, status: move.status };
        if (move.message !== undefined) value.message = move.message;
        fn(value, change);
      });
    },
  };
}

// FRAME-30: a component's sheet, adopted by the page — a constructed
// CSSStyleSheet in document.adoptedStyleSheets, keyed by the component and
// its sheet's sha256; synchronous, so the element is never drawn bare (no
// <link> to wait on). Each engine on the page adopts a key once and drops it
// when its last instance goes; the page counts them, so two engines (the
// studio drawing a tenant's components beside its own) never drop each
// other's.
const sheets = new Map();
export function adoptSheet(key, css) {
  const held = sheets.get(key);
  if (held) {
    held.n += 1;
    return;
  }
  const sheet = new CSSStyleSheet();
  sheet.replaceSync(css);
  sheets.set(key, { sheet, n: 1 });
  document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
}
export function dropSheet(key) {
  const held = sheets.get(key);
  if (!held || --held.n > 0) return;
  sheets.delete(key);
  document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== held.sheet);
}

// What the host calls: a module's `mount`, `update` and `destroy`.
export function mountModule(module, target, props, handle) {
  if (typeof module?.mount !== "function") throw new Error("the module exports no mount(target, { props, bus })");
  return module.mount(target, { props, bus: busOf(handle) }) ?? {};
}

export function updateModule(mounted, props) {
  mounted?.update?.(props);
}

export function destroyModule(mounted) {
  mounted?.destroy?.();
}

// Helpers for a module's own code (a hand-written esm/1 module's):
// each reads the bus it is handed, never one of its own.
export function live(bus, spec) {
  return bus.live(spec);
}

export function on(bus, topic, fn, opts) {
  return bus.on(topic, fn, opts);
}

// FRAME-53: the topic's kept event, or undefined.
export function last(bus, topic) {
  return bus.last(topic);
}