From b43338e80557c9f15bce16cd01fbcb65b9acf841 Mon Sep 17 00:00:00 2001 From: Jack O'Sullivan Date: Sun, 29 Nov 2026 13:28:35 +0000 Subject: [PATCH] web: Keep pages current with Server-Sent Events Pages polled `/api/version` every three seconds, then fetched the pending list and replaced it, or reloaded a request's page. Now each page follows one stream from `/events`, whose `morph` events carry a region of the page: the pending list, or the request, as a whole element with its `id`, rendered by the page's own templates. The page script morphs it into the page with idiomorph, vendored, so open details, the focus and typing stay. The stream starts with the current region, so a page catches up when the browser reconnects, and it ends when the approver signs out. `/api/version` and `/pending` are gone. Co-Authored-By: Claude Opus 5.5 --- docs/architecture.md | 2 +- docs/design.md | 12 +- src/queue.rs | 5 - src/web/assets/app.js | 69 +- src/web/assets/idiomorph.js | 1466 +++++++++++++++++++++++++++++++++ src/web/events.rs | 186 +++++ src/web/mod.rs | 50 +- src/web/page.rs | 75 +- templates/base.html | 1 + templates/index.html | 2 - templates/pending.html | 2 + templates/request.html | 17 +- templates/request_region.html | 16 + 13 files changed, 1800 insertions(+), 103 deletions(-) create mode 100644 src/web/assets/idiomorph.js create mode 100644 src/web/events.rs create mode 100644 templates/request_region.html diff --git a/docs/architecture.md b/docs/architecture.md index d73ca92..00d3bb6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -142,7 +142,7 @@ What each request runs, and whose code, decides whether it needs an approval fir | `src/bin/slop-broker.rs` | Daemon (`serve`); `slop-approve` when run under that name | | `src/bin/slop.rs` | Agent client; `slop guide` prints `slop-tools.md` | | `tests/broker.rs` | Handler tests over an in-memory duplex stream with a fake `ssh` | -| `src/web/` | The approvals web app: routes (`mod.rs`), OIDC sign-in and passkey confirmation (`auth.rs`), Web Push (`push.rs`), the audit log by request (`history.rs`), the pages (`page.rs`) and static assets | +| `src/web/` | The approvals web app: routes (`mod.rs`), each page's Server-Sent Events (`events.rs`), OIDC sign-in and passkey confirmation (`auth.rs`), Web Push (`push.rs`), the audit log by request (`history.rs`), the pages (`page.rs`) and static assets, among them the page script (`assets/app.js`) and idiomorph, vendored (`assets/idiomorph.js`) | | `templates/`, `askama.toml` | The web app's HTML, as [askama](https://askama.rs) templates compiled into the broker; `askama.toml` passes everything they show through `ops::printable` before escaping it | | `nix/` | The package, NixOS modules (`modules/nixos`), home-manager module (`modules/home-manager`), the VM test (`vm-test.nix`, `checks..vm`), clippy and rustfmt checks (`lints.nix`) and the demo's VMs and repository template (`demo/`, `packages..demo` and `demo-box`) | | `devenv.nix` | The development environment, its scripts and the demo's host side (`devenv up`); `nix develop` gives a plainer shell from `flake.nix` without them | diff --git a/docs/design.md b/docs/design.md index 0839336..037102d 100644 --- a/docs/design.md +++ b/docs/design.md @@ -233,7 +233,17 @@ on a desktop shows what `slop-approve` can only print. - Each request's page shows its full timeline, including the detail approvers saw, so a notification for a request that's since been answered still leads somewhere useful. - **Front end.** Server-rendered HTML that works without JavaScript. - - A small script refreshes the list and manages notifications, and a service worker shows them. + - A small script keeps the page current and manages notifications, and a service worker shows + them. + - **Live updates.** Each open page follows one stream of Server-Sent Events (`/events`). + - Each event carries a region of the page as HTML: a whole element with its `id`, such as the + pending list or a request, rendered by the same templates as the page. Agent-supplied text + is only ever escaped by them, never in the browser. + - The script morphs each region into the page with + [idiomorph](https://github.com/bigskysoftware/idiomorph) (vendored), so open details, the + focus and what's being typed stay. + - A region comes when the stream starts, so a page that lost its connection catches up when + the browser reconnects, and then when it changes. Signing out ends the stream. - Everything shown passes through the same filter as `slop-approve` for control and bidirectional characters. - A strict content security policy allows only the app's own scripts. diff --git a/src/queue.rs b/src/queue.rs index d55106b..6f44065 100644 --- a/src/queue.rs +++ b/src/queue.rs @@ -279,11 +279,6 @@ impl Queue { leases.sort(); leases } - - /// The current version of the pending set, which [`Queue::subscribe`] reports changes of. - pub fn version(&self) -> u64 { - self.state.lock().unwrap().sequence - } } fn info(id: &str, entry: &Entry, now: Instant) -> PendingInfo { diff --git a/src/web/assets/app.js b/src/web/assets/app.js index 2cf9290..b5f50de 100644 --- a/src/web/assets/app.js +++ b/src/web/assets/app.js @@ -18,36 +18,48 @@ function formatLeft(seconds) { return `${seconds}s`; } -setInterval(() => { +function showCountdowns() { for (const element of document.querySelectorAll(".expires[data-until]")) { const seconds = Math.max(0, Math.round((Number(element.dataset.until) - Date.now()) / 1000)); element.textContent = seconds > 0 ? `expires in ${formatLeft(seconds)}` : "expired"; } -}, 1000); +} -// Polls for changes to the pending set while the page is visible. -async function refresh() { - const pending = document.getElementById("pending"); +setInterval(showCountdowns, 1000); + +// Follows the broker's events for this page. Each `morph` event is a region of the page, a whole +// element with its `id`, which is morphed into the one here (with idiomorph) rather than replacing +// it, so open details, the focus and what's being typed stay. +function listen() { const request = document.getElementById("request"); - const container = pending || request; - if (!container || document.hidden) return; + if ((!document.getElementById("pending") && !request) || !("EventSource" in window)) return; - const response = await fetch("/api/version", { credentials: "same-origin" }); - if (response.status === 401) return location.reload(); - if (!response.ok) return; - const { version } = await response.json(); - if (String(version) === container.dataset.version) return; + const path = request ? `/events?request=${encodeURIComponent(request.dataset.id)}` : "/events"; + const source = new EventSource(path); + source.addEventListener("morph", (event) => { + const template = document.createElement("template"); + template.innerHTML = event.data; + for (const region of template.content.children) { + const current = document.getElementById(region.id); + if (!current) continue; + Idiomorph.morph(current, region, { ignoreActiveValue: true, callbacks: { beforeAttributeUpdated: keepOpen } }); + ready(document.getElementById(region.id)); + } + }); + // Signed out: reloading leads to signing in again. + source.addEventListener("signed-out", () => { + source.close(); + location.reload(); + }); + // The browser reconnects by itself, unless the broker refused; then start again later. + source.addEventListener("error", () => { + if (source.readyState === EventSource.CLOSED) setTimeout(() => location.reload(), 30000); + }); +} - if (request) return location.reload(); - - // Swap in the new list, keeping open details open. - const open = new Set([...pending.querySelectorAll("article details[open]")].map((d) => d.closest("article").id)); - const fragment = await fetch("/pending", { credentials: "same-origin" }); - if (!fragment.ok) return; - pending.innerHTML = await fragment.text(); - pending.dataset.version = String(version); - for (const id of open) document.getElementById(id)?.querySelector("details")?.setAttribute("open", ""); - startCountdowns(pending); +// Whether a details element stays open or closed is the approver's. +function keepOpen(attribute, element) { + return !(attribute === "open" && element.tagName === "DETAILS"); } function base64urlToBytes(text) { @@ -128,8 +140,13 @@ function localTimes(root) { } } -localTimes(document); -startCountdowns(document); -setInterval(() => refresh().catch(() => {}), 3000); -document.addEventListener("visibilitychange", () => refresh().catch(() => {})); +// What rendered times need, for the page or a region of it +function ready(root) { + localTimes(root); + startCountdowns(root); + showCountdowns(); +} + +ready(document); +listen(); setUpPush().catch(() => {}); diff --git a/src/web/assets/idiomorph.js b/src/web/assets/idiomorph.js new file mode 100644 index 0000000..497fc8e --- /dev/null +++ b/src/web/assets/idiomorph.js @@ -0,0 +1,1466 @@ +// idiomorph 0.8.0 (https://github.com/bigskysoftware/idiomorph), Zero-Clause BSD licence: +// `dist/idiomorph.js` from the npm package idiomorph-0.8.0.tgz, unchanged, whose integrity is +// sha512-R47JBL+6jHDQvcnbppIUtXXcxi5h6+wuCEEZXnRhUltsgzPFKzThL5PuHppP9ypJuy+7WawcY1TsSBD/iQbMhw==. +// The web app's page script morphs regions of the page with it. +/** + * @typedef {object} ConfigHead + * + * @property {'merge' | 'append' | 'morph' | 'none'} [style] + * @property {boolean} [block] + * @property {function(Element): boolean} [shouldPreserve] + * @property {function(Element): boolean} [shouldReAppend] + * @property {function(Element): boolean} [shouldRemove] + * @property {function(Element, {added: Node[], kept: Element[], removed: Element[]}): void} [afterHeadMorphed] + */ + +/** + * @typedef {object} ConfigCallbacks + * + * @property {function(Node): boolean} [beforeNodeAdded] + * @property {function(Node): void} [afterNodeAdded] + * @property {function(Element, Node): boolean} [beforeNodeMorphed] + * @property {function(Element, Node): void} [afterNodeMorphed] + * @property {function(Element): boolean} [beforeNodeRemoved] + * @property {function(Element): void} [afterNodeRemoved] + * @property {function(string, Element, "update" | "remove"): boolean} [beforeAttributeUpdated] + */ + +/** + * @typedef {object} Config + * + * @property {'outerHTML' | 'innerHTML'} [morphStyle] + * @property {boolean} [ignoreActive] + * @property {boolean} [ignoreActiveValue] + * @property {boolean} [restoreFocus] + * @property {ConfigCallbacks} [callbacks] + * @property {ConfigHead} [head] + */ + +/** + * @callback NoOp + * + * @returns {void} + */ + +/** + * @typedef {object} ConfigHeadInternal + * + * @property {'merge' | 'append' | 'morph' | 'none'} style + * @property {boolean} [block] + * @property {(function(Element): boolean) | NoOp} shouldPreserve + * @property {(function(Element): boolean) | NoOp} shouldReAppend + * @property {(function(Element): boolean) | NoOp} shouldRemove + * @property {(function(Element, {added: Node[], kept: Element[], removed: Element[]}): void) | NoOp} afterHeadMorphed + */ + +/** + * @typedef {object} ConfigCallbacksInternal + * + * @property {(function(Node): boolean) | NoOp} beforeNodeAdded + * @property {(function(Node): void) | NoOp} afterNodeAdded + * @property {(function(Node, Node): boolean) | NoOp} beforeNodeMorphed + * @property {(function(Node, Node): void) | NoOp} afterNodeMorphed + * @property {(function(Node): boolean) | NoOp} beforeNodeRemoved + * @property {(function(Node): void) | NoOp} afterNodeRemoved + * @property {(function(string, Element, "update" | "remove"): boolean) | NoOp} beforeAttributeUpdated + */ + +/** + * @typedef {object} ConfigInternal + * + * @property {'outerHTML' | 'innerHTML'} morphStyle + * @property {boolean} [ignoreActive] + * @property {boolean} [ignoreActiveValue] + * @property {boolean} [restoreFocus] + * @property {ConfigCallbacksInternal} callbacks + * @property {ConfigHeadInternal} head + */ + +/** + * @typedef {Object} IdElement + * @property {Element} elt + * @property {string} id + */ + +/** + * @typedef {Object} IdSets + * @property {Set} persistentIds + * @property {Map>} idMap + */ + +/** + * @callback Morph + * + * @param {Node} oldNode + * @param {Node | HTMLCollection | Node[] | string | null} newContent + * @param {Config} [config] + * @returns {Promise | Node[]} + */ + +// base IIFE to define idiomorph +/** + * + * @type {{defaults: ConfigInternal, morph: Morph}} + */ +var Idiomorph = (function () { + "use strict"; + + /** + * @typedef {object} MorphContext + * + * @property {Element} target + * @property {Element} newContent + * @property {Document} doc + * @property {ConfigInternal} config + * @property {ConfigInternal['morphStyle']} morphStyle + * @property {ConfigInternal['ignoreActive']} ignoreActive + * @property {ConfigInternal['ignoreActiveValue']} ignoreActiveValue + * @property {ConfigInternal['restoreFocus']} restoreFocus + * @property {Map>} idMap + * @property {Set} persistentIds + * @property {ConfigInternal['callbacks']} callbacks + * @property {ConfigInternal['head']} head + * @property {HTMLDivElement} pantry + * @property {Element[]} activeElementAndParents + */ + + //============================================================================= + // AND NOW IT BEGINS... + //============================================================================= + + const noOp = () => {}; + /** + * Default configuration values, updatable by users now + * @type {ConfigInternal} + */ + const defaults = { + morphStyle: "outerHTML", + callbacks: { + beforeNodeAdded: noOp, + afterNodeAdded: noOp, + beforeNodeMorphed: noOp, + afterNodeMorphed: noOp, + beforeNodeRemoved: noOp, + afterNodeRemoved: noOp, + beforeAttributeUpdated: noOp, + }, + head: { + style: "merge", + shouldPreserve: (elt) => elt.getAttribute("im-preserve") === "true", + shouldReAppend: (elt) => elt.getAttribute("im-re-append") === "true", + shouldRemove: noOp, + afterHeadMorphed: noOp, + }, + restoreFocus: true, + }; + + /** + * Core idiomorph function for morphing one DOM tree to another + * + * @param {Node} oldNode + * @param {Node | HTMLCollection | Node[] | string | null} newContent + * @param {Config} [config] + * @returns {Promise | Node[]} + */ + function morph(oldNode, newContent, config = {}) { + const oldElt = normalizeElement(oldNode); + const newNode = normalizeParent(newContent); + const ctx = createMorphContext(oldElt, newNode, config); + + return withHeadBlocking( + ctx, + oldElt, + newNode, + /** @param {MorphContext} ctx */ (ctx) => { + const morphedNodes = saveAndRestoreFocus(ctx, () => { + if (ctx.morphStyle === "innerHTML") { + morphChildren(ctx, oldElt, newNode); + return Array.from(oldElt.childNodes); + } else { + return morphOuterHTML(ctx, oldElt, newNode); + } + }); + ctx.pantry.remove(); + return morphedNodes; + }, + ); + } + + /** + * Morph just the outerHTML of the oldNode to the newContent + * We have to be careful because the oldNode could have siblings which need to be untouched + * @param {MorphContext} ctx + * @param {Element} oldNode + * @param {Element} newNode + * @returns {Node[]} + */ + function morphOuterHTML(ctx, oldNode, newNode) { + const oldParent = normalizeParent(oldNode); + morphChildren( + ctx, + oldParent, + newNode, + // these two optional params are the secret sauce + oldNode, // start point for iteration + oldNode.nextSibling, // end point for iteration + ); + // this is safe even with siblings, because normalizeParent returns a SlicedParentNode if needed. + return Array.from(oldParent.childNodes); + } + + /** + * @param {MorphContext} ctx + * @param {Function} fn + * @returns {Node[]} + */ + function saveAndRestoreFocus(ctx, fn) { + if (!ctx.config.restoreFocus) return fn(); + let activeElement = + /** @type {HTMLInputElement|HTMLTextAreaElement|null} */ ( + ctx.doc.activeElement + ); + + // don't bother if the active element is not an input or textarea + if ( + !(is.inputElement(activeElement) || is.textAreaElement(activeElement)) + ) { + return fn(); + } + + const { id: activeElementId, selectionStart, selectionEnd } = activeElement; + + const results = fn(); + + if ( + activeElementId && + activeElementId !== ctx.doc.activeElement?.getAttribute("id") + ) { + activeElement = ctx.target.querySelector( + `[id="${CSS.escape(activeElementId)}"]`, + ); + activeElement?.focus(); + } + if (activeElement && !activeElement.selectionEnd && selectionEnd) { + try { + activeElement.setSelectionRange(selectionStart, selectionEnd); + } catch { + // the element may not support setSelectionRange: it's no longer an + // input/textarea after the morph, or it's an input type (number, + // email, date, ...) that doesn't support text selection + } + } + + return results; + } + + const morphChildren = (function () { + /** + * This is the core algorithm for matching up children. The idea is to use id sets to try to match up + * nodes as faithfully as possible. We greedily match, which allows us to keep the algorithm fast, but + * by using id sets, we are able to better match up with content deeper in the DOM. + * + * Basic algorithm: + * - for each node in the new content: + * - search self and siblings for an id set match, falling back to a soft match + * - if match found + * - remove any nodes up to the match: + * - pantry persistent nodes + * - delete the rest + * - morph the match + * - elsif no match found, and node is persistent + * - find its match by querying the old root (future) and pantry (past) + * - move it and its children here + * - morph it + * - else + * - create a new node from scratch as a last result + * + * @param {MorphContext} ctx the merge context + * @param {Element} oldParent the old content that we are merging the new content into + * @param {Element} newParent the parent element of the new content + * @param {Node|null} [insertionPoint] the point in the DOM we start morphing at (defaults to first child) + * @param {Node|null} [endPoint] the point in the DOM we stop morphing at (defaults to after last child) + */ + function morphChildren( + ctx, + oldParent, + newParent, + insertionPoint = null, + endPoint = null, + ) { + // normalize + if (is.templateElement(oldParent) && is.templateElement(newParent)) { + // @ts-ignore we can pretend the DocumentFragment is an Element + oldParent = oldParent.content; + // @ts-ignore ditto + newParent = newParent.content; + } + insertionPoint ||= oldParent.firstChild; + + // run through all the new content + for (const newChild of newParent.childNodes) { + // once we reach the end of the old parent content skip to the end and insert the rest + if (insertionPoint && insertionPoint != endPoint) { + const bestMatch = findBestMatch( + ctx, + newChild, + insertionPoint, + endPoint, + ); + if (bestMatch) { + // if the node to morph is not at the insertion point then remove/move up to it + if (bestMatch !== insertionPoint) { + removeNodesBetween(ctx, insertionPoint, bestMatch); + } + morphNode(bestMatch, newChild, ctx); + insertionPoint = bestMatch.nextSibling; + continue; + } + } + + // if the matching node is elsewhere in the original content + if (is.element(newChild)) { + // we can pretend the id is non-null because the next `.has` line will reject it if not + const newChildId = /** @type {String} */ ( + newChild.getAttribute("id") + ); + if (ctx.persistentIds.has(newChildId)) { + // move it and all its children here and morph + const movedChild = moveBeforeById( + oldParent, + newChildId, + insertionPoint, + ctx, + ); + morphNode(movedChild, newChild, ctx); + insertionPoint = movedChild.nextSibling; + continue; + } + } + + // last resort: insert the new node from scratch + const insertedNode = createNode( + oldParent, + newChild, + insertionPoint, + ctx, + ); + // could be null if beforeNodeAdded prevented insertion + if (insertedNode) { + insertionPoint = insertedNode.nextSibling; + } + } + + // remove any remaining old nodes that didn't match up with new content + while (insertionPoint && insertionPoint != endPoint) { + const tempNode = insertionPoint; + insertionPoint = insertionPoint.nextSibling; + removeNode(ctx, tempNode); + } + } + + /** + * This performs the action of inserting a new node while handling situations where the node contains + * elements with persistent ids and possible state info we can still preserve by moving in and then morphing + * + * @param {Element} oldParent + * @param {Node} newChild + * @param {Node|null} insertionPoint + * @param {MorphContext} ctx + * @returns {Node|null} + */ + function createNode(oldParent, newChild, insertionPoint, ctx) { + if (ctx.callbacks.beforeNodeAdded(newChild) === false) return null; + if (ctx.idMap.has(newChild)) { + // node has children with ids with possible state so create a dummy elt of same type and apply full morph algorithm + // createElementNS doesn't case-normalize, so localName rather than tagName + const newEmptyChild = ctx.doc.createElementNS( + /** @type {Element} */ (newChild).namespaceURI, + /** @type {Element} */ (newChild).localName, + ); + oldParent.insertBefore(newEmptyChild, insertionPoint); + morphNode(newEmptyChild, newChild, ctx); + ctx.callbacks.afterNodeAdded(newEmptyChild); + return newEmptyChild; + } else { + // optimisation: no id state to preserve so we can just insert a clone of the newChild and its descendants + const newClonedChild = ctx.doc.importNode(newChild, true); // importNode to not mutate newParent + oldParent.insertBefore(newClonedChild, insertionPoint); + ctx.callbacks.afterNodeAdded(newClonedChild); + return newClonedChild; + } + } + + //============================================================================= + // Matching Functions + //============================================================================= + const findBestMatch = (function () { + /** + * Scans forward from the startPoint to the endPoint looking for a match + * for the node. It looks for an id set match first, then a soft match. + * We abort softmatching if we find two future soft matches, to reduce churn. + * @param {Node} node + * @param {MorphContext} ctx + * @param {Node | null} startPoint + * @param {Node | null} endPoint + * @returns {Node | null} + */ + function findBestMatch(ctx, node, startPoint, endPoint) { + let softMatch = null; + let nextSibling = node.nextSibling; + let siblingSoftMatchCount = 0; + + let cursor = startPoint; + while (cursor && cursor != endPoint) { + // soft matching is a prerequisite for id set matching + if (isSoftMatch(cursor, node)) { + if (isIdSetMatch(ctx, cursor, node)) { + return cursor; // found an id set match, we're done! + } + + // we haven't yet saved a soft match fallback + if (softMatch === null) { + // the current soft match will hard match something else in the future, leave it + if (!ctx.idMap.has(cursor)) { + // save this as the fallback if we get through the loop without finding a hard match + softMatch = cursor; + } + } + } + if ( + softMatch === null && + nextSibling && + isSoftMatch(cursor, nextSibling) + ) { + // The next new node has a soft match with this node, so + // increment the count of future soft matches + siblingSoftMatchCount++; + nextSibling = nextSibling.nextSibling; + + // If there are two future soft matches, block soft matching for this node to allow + // future siblings to soft match. This is to reduce churn in the DOM when an element + // is prepended. + if (siblingSoftMatchCount >= 2) { + softMatch = undefined; + } + } + + // if the current node contains active element, stop looking for better future matches, + // because if one is found, this node will be moved to the pantry, reparenting it and thus losing focus + // @ts-ignore pretend cursor is Element rather than Node, we're just testing for array inclusion + if (ctx.activeElementAndParents.includes(cursor)) break; + + cursor = cursor.nextSibling; + } + + return softMatch || null; + } + + /** + * + * @param {MorphContext} ctx + * @param {Node} oldNode + * @param {Node} newNode + * @returns {boolean} + */ + function isIdSetMatch(ctx, oldNode, newNode) { + let oldSet = ctx.idMap.get(oldNode); + let newSet = ctx.idMap.get(newNode); + + if (!newSet || !oldSet) return false; + + for (const id of oldSet) { + // a potential match is an id in the new and old nodes that + // has not already been merged into the DOM + // But the newNode content we call this on has not been + // merged yet and we don't allow duplicate IDs so it is simple + if (newSet.has(id)) { + return true; + } + } + return false; + } + + /** + * + * @param {Node} oldNode + * @param {Node} newNode + * @returns {boolean} + */ + function isSoftMatch(oldNode, newNode) { + // ok to cast: if one is not element, `id` and `tagName` will be undefined and we'll just compare that. + const oldElt = /** @type {Element} */ (oldNode); + const newElt = /** @type {Element} */ (newNode); + + return ( + oldElt.nodeType === newElt.nodeType && + oldElt.tagName === newElt.tagName && + // If oldElt has an `id` with possible state and it doesn't match newElt.id then avoid morphing. + // We'll still match an anonymous node with an IDed newElt, though, because if it got this far, + // its not persistent, and new nodes can't have any hidden state. + // We can't use .id because of form input shadowing, and we can't count on .getAttribute's presence because it could be a document-fragment + (!oldElt.getAttribute?.("id") || + oldElt.getAttribute?.("id") === newElt.getAttribute?.("id")) + ); + } + + return findBestMatch; + })(); + + //============================================================================= + // DOM Manipulation Functions + //============================================================================= + + /** + * Gets rid of an unwanted DOM node; strategy depends on nature of its reuse: + * - Persistent nodes will be moved to the pantry for later reuse + * - Other nodes will have their hooks called, and then are removed + * @param {MorphContext} ctx + * @param {Node} node + */ + function removeNode(ctx, node) { + // don't accidentally morph the pantry out of existence when morphing the full document + if (node === ctx.pantry) return; + // are we going to id set match this later? + if (ctx.idMap.has(node)) { + // skip callbacks and move to pantry + moveBefore(ctx.pantry, node, null); + } else { + // remove for realsies + if (ctx.callbacks.beforeNodeRemoved(node) === false) return; + node.parentNode?.removeChild(node); + ctx.callbacks.afterNodeRemoved(node); + } + } + + /** + * Remove nodes between the start and end nodes + * @param {MorphContext} ctx + * @param {Node} startInclusive + * @param {Node} endExclusive + * @returns {Node|null} + */ + function removeNodesBetween(ctx, startInclusive, endExclusive) { + /** @type {Node | null} */ + let cursor = startInclusive; + // remove nodes until the endExclusive node + while (cursor && cursor !== endExclusive) { + let tempNode = /** @type {Node} */ (cursor); + cursor = cursor.nextSibling; + removeNode(ctx, tempNode); + } + return cursor; + } + + /** + * Search for an element by id within the document and pantry, and move it using moveBefore. + * + * @param {Element} parentNode - The parent node to which the element will be moved. + * @param {string} id - The ID of the element to be moved. + * @param {Node | null} after - The reference node to insert the element before. + * If `null`, the element is appended as the last child. + * @param {MorphContext} ctx + * @returns {Element} The found element + */ + function moveBeforeById(parentNode, id, after, ctx) { + const selector = `[id="${CSS.escape(id)}"]`; + const target = + /** @type {Element} - will always be found */ + ( + // ctx.target.id unsafe because of form input shadowing + // ctx.target could be a document fragment which doesn't have `getAttribute` + (ctx.target.getAttribute?.("id") === id && ctx.target) || + ctx.target.querySelector(selector) || + ctx.pantry.querySelector(selector) + ); + removeElementFromAncestorsIdMaps(target, ctx); + moveBefore(parentNode, target, after); + return target; + } + + /** + * Removes an element from its ancestors' id maps. This is needed when an element is moved from the + * "future" via `moveBeforeId`. Otherwise, its erstwhile ancestors could be mistakenly moved to the + * pantry rather than being deleted, preventing their removal hooks from being called. + * + * @param {Element} element - element to remove from its ancestors' id maps + * @param {MorphContext} ctx + */ + function removeElementFromAncestorsIdMaps(element, ctx) { + // we know id is non-null String, because this function is only called on elements with ids + const id = /** @type {String} */ (element.getAttribute("id")); + /** @ts-ignore - safe to loop in this way **/ + while ((element = element.parentNode)) { + let idSet = ctx.idMap.get(element); + if (idSet) { + idSet.delete(id); + if (!idSet.size) { + ctx.idMap.delete(element); + } + } + } + } + + /** + * Moves an element before another element within the same parent. + * Uses the `moveBefore` API if available (and working), otherwise falls back to `insertBefore`. + * This is essentialy a forward-compat wrapper. + * + * @param {Element} parentNode - The parent node containing the after element. + * @param {Node} element - The element to be moved. + * @param {Node | null} after - The reference node to insert `element` before. + * If `null`, `element` is appended as the last child. + */ + function moveBefore(parentNode, element, after) { + // @ts-ignore - use proposed moveBefore feature + if (parentNode.moveBefore) { + try { + // @ts-ignore - use proposed moveBefore feature + parentNode.moveBefore(element, after); + } catch (e) { + // moveBefore throws unless both nodes share a root, e.g. when morphing a detached subtree + parentNode.insertBefore(element, after); + } + } else { + parentNode.insertBefore(element, after); + } + } + + return morphChildren; + })(); + + //============================================================================= + // Single Node Morphing Code + //============================================================================= + const morphNode = (function () { + /** + * @param {Node} oldNode root node to merge content into + * @param {Node} newContent new content to merge + * @param {MorphContext} ctx the merge context + * @returns {Node | null} the element that ended up in the DOM + */ + function morphNode(oldNode, newContent, ctx) { + if (ctx.ignoreActive && oldNode === ctx.doc.activeElement) { + // don't morph focused element + return null; + } + + if (ctx.callbacks.beforeNodeMorphed(oldNode, newContent) === false) { + return oldNode; + } + + if (is.headElement(oldNode) && ctx.head.style === "none") { + // ignore the head element + } else if (is.headElement(oldNode) && ctx.head.style !== "morph") { + // ok to cast: if newContent wasn't also a , it would've got caught in the `!isSoftMatch` branch above + handleHeadElement( + oldNode, + /** @type {HTMLHeadElement} */ (newContent), + ctx, + ); + } else { + morphAttributes(oldNode, newContent, ctx); + if (!ignoreValueOfActiveElement(oldNode, ctx)) { + // @ts-ignore newContent can be a node here because .firstChild will be null + morphChildren(ctx, oldNode, newContent); + } + } + ctx.callbacks.afterNodeMorphed(oldNode, newContent); + return oldNode; + } + + /** + * syncs the oldNode to the newNode, copying over all attributes and + * inner element state from the newNode to the oldNode + * + * @param {Node} oldNode the node to copy attributes & state to + * @param {Node} newNode the node to copy attributes & state from + * @param {MorphContext} ctx the merge context + */ + function morphAttributes(oldNode, newNode, ctx) { + let type = newNode.nodeType; + + // if is an element type, sync the attributes from the + // new node into the new node + if (type === 1 /* element type */) { + const oldElt = /** @type {Element} */ (oldNode); + const newElt = /** @type {Element} */ (newNode); + + const oldAttributes = oldElt.attributes; + const newAttributes = newElt.attributes; + for (const newAttribute of newAttributes) { + if (oldElt.getAttribute(newAttribute.name) === newAttribute.value) { + continue; + } + if (ignoreAttribute(newAttribute.name, oldElt, "update", ctx)) { + continue; + } + // setAttribute drops namespaces and rejects names like `@click` + oldElt.setAttributeNode( + /** @type {Attr} */ (newAttribute.cloneNode()), + ); + } + // iterate backwards to avoid skipping over items when a delete occurs + for (let i = oldAttributes.length - 1; 0 <= i; i--) { + const oldAttribute = oldAttributes[i]; + + // toAttributes is a live NamedNodeMap, so iteration+mutation is unsafe + // e.g. custom element attribute callbacks can remove other attributes + if (!oldAttribute) continue; + + if (!newElt.hasAttribute(oldAttribute.name)) { + if (ignoreAttribute(oldAttribute.name, oldElt, "remove", ctx)) { + continue; + } + oldElt.removeAttribute(oldAttribute.name); + } + } + + if (!ignoreValueOfActiveElement(oldElt, ctx)) { + syncInputValue(oldElt, newElt, ctx); + } + } + + // sync text nodes + if (type === 8 /* comment */ || type === 3 /* text */) { + if (oldNode.nodeValue !== newNode.nodeValue) { + oldNode.nodeValue = newNode.nodeValue; + } + } + } + + /** + * NB: many bothans died to bring us information: + * + * https://github.com/patrick-steele-idem/morphdom/blob/master/src/specialElHandlers.js + * https://github.com/choojs/nanomorph/blob/master/lib/morph.jsL113 + * + * @param {Element} oldElement the element to sync the input value to + * @param {Element} newElement the element to sync the input value from + * @param {MorphContext} ctx the merge context + */ + function syncInputValue(oldElement, newElement, ctx) { + if ( + is.inputElement(oldElement) && + is.inputElement(newElement) && + newElement.type !== "file" + ) { + let newValue = newElement.value; + let oldValue = oldElement.value; + + // sync boolean attributes + syncBooleanAttribute(oldElement, newElement, "checked", ctx); + syncBooleanAttribute(oldElement, newElement, "disabled", ctx); + + if (!newElement.hasAttribute("value")) { + if (!ignoreAttribute("value", oldElement, "remove", ctx)) { + oldElement.value = ""; + oldElement.removeAttribute("value"); + } + } else if (oldValue !== newValue) { + if (!ignoreAttribute("value", oldElement, "update", ctx)) { + oldElement.setAttribute("value", newValue); + oldElement.value = newValue; + } + } + // TODO: QUESTION(1cg): this used to only check `newElement` unlike the other branches -- why? + // did I break something? + } else if (is.optionElement(oldElement) && is.optionElement(newElement)) { + syncBooleanAttribute(oldElement, newElement, "selected", ctx); + } else if ( + is.textAreaElement(oldElement) && + is.textAreaElement(newElement) + ) { + let newValue = newElement.value; + let oldValue = oldElement.value; + if (ignoreAttribute("value", oldElement, "update", ctx)) { + return; + } + if (newValue !== oldValue) { + oldElement.value = newValue; + } + if ( + oldElement.firstChild && + oldElement.firstChild.nodeValue !== newValue + ) { + oldElement.firstChild.nodeValue = newValue; + } + } + } + + /** + * @param {Element} oldElement element to write the value to + * @param {Element} newElement element to read the value from + * @param {string} attributeName the attribute name + * @param {MorphContext} ctx the merge context + */ + function syncBooleanAttribute(oldElement, newElement, attributeName, ctx) { + // @ts-ignore this function is only used on boolean attrs that are reflected as dom properties + const newLiveValue = newElement[attributeName], + // @ts-ignore ditto + oldLiveValue = oldElement[attributeName]; + if (newLiveValue !== oldLiveValue) { + const ignoreUpdate = ignoreAttribute( + attributeName, + oldElement, + "update", + ctx, + ); + if (!ignoreUpdate) { + // update attribute's associated DOM property + // @ts-ignore this function is only used on boolean attrs that are reflected as dom properties + oldElement[attributeName] = newElement[attributeName]; + } + if (newLiveValue) { + if (!ignoreUpdate) { + // https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML + // this is the correct way to set a boolean attribute to "true" + oldElement.setAttribute(attributeName, ""); + } + } else { + if (!ignoreAttribute(attributeName, oldElement, "remove", ctx)) { + oldElement.removeAttribute(attributeName); + } + } + } + } + + /** + * @param {string} attr the attribute to be mutated + * @param {Element} element the element that is going to be updated + * @param {"update" | "remove"} updateType + * @param {MorphContext} ctx the merge context + * @returns {boolean} true if the attribute should be ignored, false otherwise + */ + function ignoreAttribute(attr, element, updateType, ctx) { + if ( + attr === "value" && + ctx.ignoreActiveValue && + element === ctx.doc.activeElement + ) { + return true; + } + return ( + ctx.callbacks.beforeAttributeUpdated(attr, element, updateType) === + false + ); + } + + /** + * @param {Node} possibleActiveElement + * @param {MorphContext} ctx + * @returns {boolean} + */ + function ignoreValueOfActiveElement(possibleActiveElement, ctx) { + return ( + !!ctx.ignoreActiveValue && + possibleActiveElement === ctx.doc.activeElement && + possibleActiveElement !== ctx.doc.body + ); + } + + return morphNode; + })(); + + //============================================================================= + // Head Management Functions + //============================================================================= + /** + * @param {MorphContext} ctx + * @param {Element} oldNode + * @param {Element} newNode + * @param {function} callback + * @returns {Node[] | Promise} + */ + function withHeadBlocking(ctx, oldNode, newNode, callback) { + if (ctx.head.block && ctx.head.style !== "none") { + const oldHead = oldNode.querySelector("head"); + const newHead = newNode.querySelector("head"); + if (oldHead && newHead) { + const promises = handleHeadElement(oldHead, newHead, ctx); + // when head promises resolve, proceed ignoring the head tag + return Promise.all(promises).then(() => { + const newCtx = Object.assign(ctx, { + head: { + block: false, + style: "none", + }, + }); + return callback(newCtx); + }); + } + } + // just proceed if we not head blocking + return callback(ctx); + } + + /** + * The HEAD tag can be handled specially, either w/ a 'merge' or 'append' style + * + * @param {Element} oldHead + * @param {Element} newHead + * @param {MorphContext} ctx + * @returns {Promise[]} + */ + function handleHeadElement(oldHead, newHead, ctx) { + let added = []; + let removed = []; + let preserved = []; + let nodesToAppend = []; + + // put all new head elements into a Map, by their outerHTML + let srcToNewHeadNodes = new Map(); + for (const newHeadChild of newHead.children) { + srcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild); + } + + // for each elt in the current head + for (const currentHeadElt of oldHead.children) { + // If the current head element is in the map + let inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML); + let isReAppended = ctx.head.shouldReAppend(currentHeadElt); + let isPreserved = ctx.head.shouldPreserve(currentHeadElt); + if (inNewContent || isPreserved) { + if (isReAppended) { + // remove the current version and let the new version replace it and re-execute + removed.push(currentHeadElt); + } else { + // this element already exists and should not be re-appended, so remove it from + // the new content map, preserving it in the DOM + srcToNewHeadNodes.delete(currentHeadElt.outerHTML); + preserved.push(currentHeadElt); + } + } else { + if (ctx.head.style === "append") { + // we are appending and this existing element is not new content + // so if and only if it is marked for re-append do we do anything + if (isReAppended) { + removed.push(currentHeadElt); + nodesToAppend.push(currentHeadElt); + } + } else { + // if this is a merge, we remove this content since it is not in the new head + if (ctx.head.shouldRemove(currentHeadElt) !== false) { + removed.push(currentHeadElt); + } + } + } + } + + // Push the remaining new head elements in the Map into the + // nodes to append to the head tag + nodesToAppend.push(...srcToNewHeadNodes.values()); + + let promises = []; + for (const newNode of nodesToAppend) { + // TODO: This could theoretically be null, based on type + let newElt = /** @type {ChildNode} */ ( + ctx.doc.createRange().createContextualFragment(newNode.outerHTML) + .firstChild + ); + if (ctx.callbacks.beforeNodeAdded(newElt) !== false) { + if ( + ("href" in newElt && newElt.href) || + ("src" in newElt && newElt.src) + ) { + /** @type {(result?: any) => void} */ let resolve; + let promise = new Promise(function (_resolve) { + resolve = _resolve; + }); + newElt.addEventListener("load", function () { + resolve(); + }); + promises.push(promise); + } + oldHead.appendChild(newElt); + ctx.callbacks.afterNodeAdded(newElt); + added.push(newElt); + } + } + + // remove all removed elements, after we have appended the new elements to avoid + // additional network requests for things like style sheets + for (const removedElement of removed) { + if (ctx.callbacks.beforeNodeRemoved(removedElement) !== false) { + oldHead.removeChild(removedElement); + ctx.callbacks.afterNodeRemoved(removedElement); + } + } + + ctx.head.afterHeadMorphed(oldHead, { + added: added, + kept: preserved, + removed: removed, + }); + return promises; + } + + //============================================================================= + // Create Morph Context Functions + //============================================================================= + const createMorphContext = (function () { + /** + * + * @param {Element} oldNode + * @param {Element} newContent + * @param {Config} config + * @returns {MorphContext} + */ + function createMorphContext(oldNode, newContent, config) { + const { persistentIds, idMap } = createIdMaps(oldNode, newContent); + + const mergedConfig = mergeDefaults(config); + const morphStyle = mergedConfig.morphStyle || "outerHTML"; + if (!["innerHTML", "outerHTML"].includes(morphStyle)) { + throw `Do not understand how to morph style ${morphStyle}`; + } + // Text and Comment have no ParentNode methods, so they cannot take innerHTML + if (morphStyle === "innerHTML" && !oldNode.append) { + throw `Cannot morph the innerHTML of a ${oldNode.nodeName} node, as it cannot have children`; + } + + const headStyle = mergedConfig.head.style || "merge"; + if (!["merge", "append", "morph", "none"].includes(headStyle)) { + throw `Do not understand how to morph head style ${headStyle}`; + } + + const doc = oldNode.ownerDocument; + + return { + target: oldNode, + newContent: newContent, + doc: doc, + config: mergedConfig, + morphStyle: morphStyle, + ignoreActive: mergedConfig.ignoreActive, + ignoreActiveValue: mergedConfig.ignoreActiveValue, + restoreFocus: mergedConfig.restoreFocus, + idMap: idMap, + persistentIds: persistentIds, + pantry: createPantry(doc), + activeElementAndParents: createActiveElementAndParents(oldNode, doc), + callbacks: mergedConfig.callbacks, + head: mergedConfig.head, + }; + } + + /** + * Deep merges the config object and the Idiomorph.defaults object to + * produce a final configuration object + * @param {Config} config + * @returns {ConfigInternal} + */ + function mergeDefaults(config) { + let finalConfig = Object.assign({}, defaults); + + // copy top level stuff into final config + Object.assign(finalConfig, config); + + // copy callbacks into final config (do this to deep merge the callbacks) + finalConfig.callbacks = Object.assign( + {}, + defaults.callbacks, + config.callbacks, + ); + + // copy head config into final config (do this to deep merge the head) + finalConfig.head = Object.assign({}, defaults.head, config.head); + + return finalConfig; + } + + /** + * @param {Document} doc + * @returns {HTMLDivElement} + */ + function createPantry(doc) { + const pantry = doc.createElement("div"); + pantry.hidden = true; + doc.documentElement.append(pantry); + return pantry; + } + + /** + * @param {Element} oldNode + * @param {Document} doc + * @returns {Element[]} + */ + function createActiveElementAndParents(oldNode, doc) { + /** @type {Element[]} */ + let activeElementAndParents = []; + let elt = doc.activeElement; + if (elt?.tagName !== "BODY" && oldNode.contains(elt)) { + while (elt) { + activeElementAndParents.push(elt); + if (elt === oldNode) break; + elt = elt.parentElement; + } + } + return activeElementAndParents; + } + + /** + * Returns all elements with a non-empty ID contained within the root node and its + * descendants, each paired with its id so that it only has to be read once. + * + * @param {Node} root + * @returns {IdElement[]} + */ + function findIdElements(root) { + /** @type {IdElement[]} */ + let elements = []; + // root could be a text or comment node which has no `querySelectorAll`, + // or a document fragment which has no `getAttribute` + const rootElt = /** @type {Partial} */ (root); + for (const elt of rootElt.querySelectorAll?.("[id]") ?? []) { + // elt.id is unsafe because of form input shadowing, and `id=""` is not persistable + const id = elt.getAttribute("id"); + if (id) elements.push({ elt, id }); + } + const rootId = rootElt.getAttribute?.("id"); + if (rootId) + elements.push({ elt: /** @type {Element} */ (root), id: rootId }); + return elements; + } + + /** + * A bottom-up algorithm that populates a map of Element -> IdSet. + * The idSet for a given element is the set of all IDs contained within its subtree. + * As an optimzation, we filter these IDs through the given list of persistent IDs, + * because we don't need to bother considering IDed elements that won't be in the new content. + * + * @param {Map>} idMap + * @param {Set} persistentIds + * @param {Element} root + * @param {IdElement[]} elements + */ + function populateIdMapWithTree(idMap, persistentIds, root, elements) { + for (const { elt, id } of elements) { + if (persistentIds.has(id)) { + /** @type {Element|null} */ + let current = elt; + // walk up the parent hierarchy of that element, adding the id + // of element to the parent's id set + while (current) { + let idSet = idMap.get(current); + // if the id set doesn't exist, create it and insert it in the map + if (idSet == null) { + idSet = new Set(); + idMap.set(current, idSet); + } + idSet.add(id); + + if (current === root) break; + current = current.parentElement; + } + } + } + } + + /** + * This function computes a map of nodes to all ids contained within that node (inclusive of the + * node). This map can be used to ask if two nodes have intersecting sets of ids, which allows + * for a looser definition of "matching" than tradition id matching, and allows child nodes + * to contribute to a parent nodes matching. + * + * @param {Element} oldContent the old content that will be morphed + * @param {Element} newContent the new content to morph to + * @returns {IdSets} + */ + function createIdMaps(oldContent, newContent) { + const oldIdElements = findIdElements(oldContent); + const newIdElements = findIdElements(newContent); + + const persistentIds = createPersistentIds(oldIdElements, newIdElements); + + /** @type {Map>} */ + let idMap = new Map(); + populateIdMapWithTree(idMap, persistentIds, oldContent, oldIdElements); + + /** @ts-ignore - if newContent is a duck-typed parent, pass its single child node as the root to halt upwards iteration */ + const newRoot = newContent.__idiomorphRoot || newContent; + populateIdMapWithTree(idMap, persistentIds, newRoot, newIdElements); + + return { persistentIds, idMap }; + } + + /** + * This function computes the set of ids that persist between the two contents excluding duplicates + * + * @param {IdElement[]} oldIdElements + * @param {IdElement[]} newIdElements + * @returns {Set} + */ + function createPersistentIds(oldIdElements, newIdElements) { + let duplicateIds = new Set(); + + /** @type {Map} */ + let oldIdTagNameMap = new Map(); + for (const { elt, id } of oldIdElements) { + if (oldIdTagNameMap.has(id)) { + duplicateIds.add(id); + } else { + oldIdTagNameMap.set(id, elt.tagName); + } + } + + let persistentIds = new Set(); + for (const { elt, id } of newIdElements) { + if (persistentIds.has(id)) { + duplicateIds.add(id); + } else if (oldIdTagNameMap.get(id) === elt.tagName) { + persistentIds.add(id); + } + // skip if tag types mismatch because its not possible to morph one tag into another + } + + for (const id of duplicateIds) { + persistentIds.delete(id); + } + if (duplicateIds.size) { + console.warn( + "[Warning] duplicate ids found during morph, state loss within these elements is possible:", + Array.from(duplicateIds), + ); + } + return persistentIds; + } + + return createMorphContext; + })(); + + //============================================================================= + // HTML Normalization Functions + //============================================================================= + const { normalizeElement, normalizeParent } = (function () { + /** @type {WeakSet} */ + const generatedByIdiomorph = new WeakSet(); + + /** + * + * @param {Node} content + * @returns {Element} + */ + function normalizeElement(content) { + if (is.document(content)) { + return content.documentElement; + } else { + // a Text or Comment node is not an Element, but morphOuterHTML only ever reads Node members off it + return /** @type {Element} */ (content); + } + } + + /** + * + * @param {null | string | Node | HTMLCollection | Node[]} newContent + * @returns {Element} + */ + function normalizeParent(newContent) { + if (newContent == null) { + return document.createElement("div"); // dummy parent element + } else if (typeof newContent === "string") { + return normalizeParent(parseContent(newContent)); + } else if ( + generatedByIdiomorph.has(/** @type {Element} */ (newContent)) + ) { + // the template tag created by idiomorph parsing can serve as a dummy parent + return /** @type {Element} */ (newContent); + } else if (is.node(newContent)) { + if (newContent.parentNode) { + // we can't use the parent directly because newContent may have siblings + // that we don't want in the morph, and reparenting might be expensive (TODO is it?), + // so instead we create a fake parent node that only sees a slice of its children. + /** @type {Element} */ + return /** @type {any} */ (new SlicedParentNode(newContent)); + } else { + // a single node is added as a child to a dummy parent + const dummyParent = document.createElement("div"); + dummyParent.append(newContent); + return dummyParent; + } + } else { + // all nodes in the array or HTMLElement collection are consolidated under + // a single dummy parent element + const dummyParent = document.createElement("div"); + for (const elt of [...newContent]) { + dummyParent.append(elt); + } + return dummyParent; + } + } + + /** + * A fake duck-typed parent element to wrap a single node, without actually reparenting it. + * This is useful because the node may have siblings that we don't want in the morph, and it may also be moved + * or replaced with one or more elements during the morph. This class effectively allows us a window into + * a slice of a node's children. + * "If it walks like a duck, and quacks like a duck, then it must be a duck!" -- James Whitcomb Riley (1849–1916) + */ + class SlicedParentNode { + /** @param {Node} node */ + constructor(node) { + this.originalNode = node; + this.realParentNode = /** @type {Element} */ (node.parentNode); + this.previousSibling = node.previousSibling; + this.nextSibling = node.nextSibling; + } + + /** @returns {Node[]} */ + get childNodes() { + // return slice of realParent's current childNodes, based on previousSibling and nextSibling + const nodes = []; + let cursor = this.previousSibling + ? this.previousSibling.nextSibling + : this.realParentNode.firstChild; + while (cursor && cursor != this.nextSibling) { + nodes.push(cursor); + cursor = cursor.nextSibling; + } + return nodes; + } + + /** + * @param {string} selector + * @returns {Element[]} + */ + querySelectorAll(selector) { + return this.childNodes.reduce((results, node) => { + if (is.element(node)) { + if (node.matches(selector)) results.push(node); + const nodeList = node.querySelectorAll(selector); + for (let i = 0; i < nodeList.length; i++) { + results.push(nodeList[i]); + } + } + return results; + }, /** @type {Element[]} */ ([])); + } + + /** + * @param {Node} node + * @param {Node} referenceNode + * @returns {Node} + */ + insertBefore(node, referenceNode) { + return this.realParentNode.insertBefore(node, referenceNode); + } + + /** + * @param {Node} node + * @param {Node} referenceNode + * @returns {Node} + */ + moveBefore(node, referenceNode) { + // @ts-ignore - use new moveBefore feature + return this.realParentNode.moveBefore(node, referenceNode); + } + + /** + * for later use with populateIdMapWithTree to halt upwards iteration + * @returns {Node} + */ + get __idiomorphRoot() { + return this.originalNode; + } + } + + /** + * + * @param {string} newContent + * @returns {Node | null | DocumentFragment} + */ + function parseContent(newContent) { + let parser = new DOMParser(); + + // remove svgs to avoid false-positive matches on head, etc. + let contentWithSvgsRemoved = newContent.replace( + /]*>|>)([\s\S]*?)<\/svg>/gim, + "", + ); + + // if the newContent contains a html, head or body tag, we can simply parse it w/o wrapping + if ( + contentWithSvgsRemoved.match(/<\/html>/) || + contentWithSvgsRemoved.match(/<\/head>/) || + contentWithSvgsRemoved.match(/<\/body>/) + ) { + let content = parser.parseFromString(newContent, "text/html"); + // a doctype can neither be morphed nor inserted, and would displace the parent container below + content.doctype?.remove(); + // if it is a full HTML document, return the document itself as the parent container + if (contentWithSvgsRemoved.match(/<\/html>/)) { + generatedByIdiomorph.add(content); + return content; + } else { + // otherwise return the html element as the parent container + let htmlElement = content.firstChild; + if (htmlElement) { + generatedByIdiomorph.add(htmlElement); + } + return htmlElement; + } + } else { + // if it is partial HTML, wrap it in a template tag to provide a parent element and also to help + // deal with touchy tags like tr, tbody, etc. + let responseDoc = parser.parseFromString( + "", + "text/html", + ); + let content = /** @type {HTMLTemplateElement} */ ( + responseDoc.body.querySelector("template") + ).content; + generatedByIdiomorph.add(content); + return content; + } + } + + return { normalizeElement, normalizeParent }; + })(); + + //============================================================================= + // Realm-safe node type checks + //============================================================================= + const is = (function () { + /** @param {Node | null | undefined} value @returns {value is Element} */ + const element = (value) => + value instanceof Element || value?.nodeType === Node.ELEMENT_NODE; + + /** + * @param {Node | null | undefined} value + * @param {string} localName + * @returns {value is Element} + */ + const htmlElement = (value, localName) => + element(value) && + value.localName === localName && + value.namespaceURI === "http://www.w3.org/1999/xhtml"; + + return { + element, + /** @param {unknown} value @returns {value is Node} */ + node: (value) => + value instanceof Node || + typeof (/** @type {any} */ (value)?.nodeType) === "number", + /** @param {Node | null | undefined} value @returns {value is Document} */ + document: (value) => + value instanceof Document || value?.nodeType === Node.DOCUMENT_NODE, + /** @param {Node | null | undefined} value @returns {value is HTMLTemplateElement} */ + templateElement: (value) => htmlElement(value, "template"), + /** @param {Node | null | undefined} value @returns {value is HTMLHeadElement} */ + headElement: (value) => htmlElement(value, "head"), + /** @param {Node | null | undefined} value @returns {value is HTMLInputElement} */ + inputElement: (value) => htmlElement(value, "input"), + /** @param {Node | null | undefined} value @returns {value is HTMLOptionElement} */ + optionElement: (value) => htmlElement(value, "option"), + /** @param {Node | null | undefined} value @returns {value is HTMLTextAreaElement} */ + textAreaElement: (value) => htmlElement(value, "textarea"), + }; + })(); + + //============================================================================= + // This is what ends up becoming the Idiomorph global object + //============================================================================= + return { + morph, + defaults, + }; +})(); diff --git a/src/web/events.rs b/src/web/events.rs new file mode 100644 index 0000000..5bad3ce --- /dev/null +++ b/src/web/events.rs @@ -0,0 +1,186 @@ +//! Keeps open pages current with one stream of Server-Sent Events each. +//! +//! - Each `morph` event carries a region of the page: a whole element with its `id`, which the +//! page script morphs into the one it has, so open details and the focus stay. The main page's +//! region is the pending list (`#pending`), and a request's page's is the request (`#request`). +//! - A region comes when the stream starts, so a page catches up after reconnecting, and then +//! whenever it changes. +//! - `signed-out` ends the stream, when the approver signs out or the session expires. +use std::convert::Infallible; +use std::future::Future; +use std::pin::Pin; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use axum::response::sse::{Event, KeepAlive, Sse}; +use axum::response::{IntoResponse, Response}; +use tokio::sync::watch; +use tower_sessions::Session; + +use super::{User, page}; +use crate::server::Broker; + +/// How often a page gets updates at most. +const INTERVAL: Duration = Duration::from_secs(1); + +/// The signed-in approver's CSRF token, or `None` once they've signed out. +type SignedIn = Box Pin> + Send>> + Send>; + +pub fn stream(broker: Arc, session: Session, request: Option) -> Response { + let signed_in: SignedIn = Box::new(move || { + let session = session.clone(); + Box::pin(async move { session.get::(super::USER).await.ok().flatten().map(|user| user.csrf) }) + }); + let updates = Updates::new(broker, signed_in, request); + + let events = futures_util::stream::unfold(updates, |mut updates| async move { + let (name, data) = updates.next().await?; + Some((Ok::<_, Infallible>(Event::default().event(name).data(data)), updates)) + }); + + let mut response = Sse::new(events).keep_alive(KeepAlive::default()).into_response(); + // Proxies such as nginx would otherwise hold events back. + response.headers_mut().insert("x-accel-buffering", axum::http::HeaderValue::from_static("no")); + response +} + +struct Updates { + broker: Arc, + signed_in: SignedIn, + /// The request whose page it is, or none for the main page. + request: Option, + queue: watch::Receiver, + /// The region last sent. + sent: Option, + last: Option, + ended: bool, +} + +impl Updates { + fn new(broker: Arc, signed_in: SignedIn, request: Option) -> Updates { + let queue = broker.queue.subscribe(); + Updates { broker, signed_in, request, queue, sent: None, last: None, ended: false } + } + + /// The next event, as a name and data, once something changes; `None` ends the stream. + async fn next(&mut self) -> Option<(&'static str, String)> { + if self.ended { + return None; + } + + loop { + // The region at first, then when it changes, at most once an interval + if let Some(last) = self.last { + self.queue.changed().await.ok()?; + tokio::time::sleep(INTERVAL.saturating_sub(last.elapsed())).await; + } + self.last = Some(Instant::now()); + self.queue.borrow_and_update(); + + // Signing out, or the session expiring, ends it. + let Some(csrf) = (self.signed_in)().await else { + self.ended = true; + return Some(("signed-out", "signed out".into())); + }; + + let region = self.region(&csrf); + if self.sent.as_ref() != Some(®ion) { + self.sent = Some(region.clone()); + return Some(("morph", region)); + } + } + } + + fn region(&self, csrf: &str) -> String { + match &self.request { + None => page::pending(csrf, &self.broker.queue.list(), &self.broker.queue.all_leases()), + Some(id) => { + let (entry, past) = super::request_parts(&self.broker, id); + let view = page::RequestView { id, entry: entry.as_ref(), past: past.as_ref() }; + page::request_region(csrf, &view) + } + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicBool, Ordering}; + + use super::*; + use crate::detail::Detail; + use crate::queue::NewRequest; + + fn broker() -> Arc { + let config = serde_json::from_value(serde_json::json!({ + "requesters": {}, + "policies": {}, + "approve_socket": "/unused", + "approver_group": "root", + })) + .unwrap(); + Arc::new(Broker::new(config).unwrap()) + } + + fn submit(broker: &Broker, id: &str) -> tokio::sync::oneshot::Receiver { + let request = NewRequest { + requester: "agent".into(), + op: "ssh".into(), + lease_key: "k".into(), + summary: "ssh river".into(), + detail: Detail::new(), + label: None, + sensitive: false, + passkey: false, + leases: vec![300], + }; + broker.queue.submit(id, request, 4).unwrap() + } + + #[tokio::test] + async fn the_main_page_gets_its_list_as_it_changes() { + let broker = broker(); + let signed_out = Arc::new(AtomicBool::new(false)); + let check = signed_out.clone(); + let signed_in: SignedIn = Box::new(move || { + let out = check.load(Ordering::SeqCst); + Box::pin(async move { (!out).then(|| "token".to_owned()) }) + }); + let mut updates = Updates::new(broker.clone(), signed_in, None); + + // The list to start with, as a whole element + let (name, data) = updates.next().await.unwrap(); + assert_eq!(name, "morph"); + assert!(data.starts_with(r#"
"#) && data.contains("Nothing is waiting"), "{data}"); + + // A new request, then its leaving + let _reply = submit(&broker, "abc"); + let (_, data) = updates.next().await.unwrap(); + assert!(data.contains("ssh river"), "{data}"); + broker.queue.cancel("abc"); + let (_, data) = updates.next().await.unwrap(); + assert!(data.contains("Nothing is waiting"), "{data}"); + + signed_out.store(true, Ordering::SeqCst); + let _reply = submit(&broker, "def"); + assert_eq!(updates.next().await.unwrap().0, "signed-out"); + assert!(updates.next().await.is_none()); + } + + #[tokio::test] + async fn a_request_page_gets_its_request() { + let broker = broker(); + let signed_in: SignedIn = Box::new(|| Box::pin(async { Some("token".to_owned()) })); + let mut updates = Updates::new(broker.clone(), signed_in, Some("abc".into())); + + let (_, data) = updates.next().await.unwrap(); + assert!(data.starts_with(r#"
"#), "{data}"); + assert!(data.contains("The audit log has nothing"), "{data}"); + + // Other requests change nothing here, so nothing comes until this one does + let _other = submit(&broker, "xyz"); + let _reply = submit(&broker, "abc"); + let (_, data) = updates.next().await.unwrap(); + assert!(data.contains("

ssh river

"), "{data}"); + } +} diff --git a/src/web/mod.rs b/src/web/mod.rs index ec30c84..b3353b5 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -2,6 +2,7 @@ //! for approvers signed in through an OpenID Connect provider, plus Web Push notifications. It //! sits behind a reverse proxy, which is the only thing that should reach its listener. mod auth; +mod events; mod history; mod page; mod push; @@ -81,10 +82,9 @@ pub async fn run(broker: Arc, config: WebConfig, secret: String) -> Resu let app = Router::new() .route("/", get(index)) - .route("/pending", get(pending_fragment)) .route("/requests/{id}", get(request_page).post(answer)) .route("/log", get(log_page)) - .route("/api/version", get(version)) + .route("/events", get(page_events)) .route("/api/csrf", get(csrf)) .route("/push/key", get(push_key)) .route("/push/subscribe", post(subscribe)) @@ -94,6 +94,7 @@ pub async fn run(broker: Arc, config: WebConfig, secret: String) -> Resu .route("/auth/logout", post(logout)) .route("/signed-out", get(signed_out)) .route("/app.js", get(|| async { page::asset("text/javascript", include_str!("assets/app.js")) })) + .route("/idiomorph.js", get(|| async { page::asset("text/javascript", include_str!("assets/idiomorph.js")) })) .route("/sw.js", get(|| async { page::asset("text/javascript", include_str!("assets/sw.js")) })) .route("/style.css", get(|| async { page::asset("text/css", include_str!("assets/style.css")) })) .route("/icon.svg", get(|| async { page::asset("image/svg+xml", include_str!("assets/icon.svg")) })) @@ -204,14 +205,7 @@ async fn index(State(web): State>, session: Session) -> Result>, session: Session) -> Result { - let user = api_user(&session).await?; - let entries = web.broker.queue.list(); - let leases = web.broker.queue.all_leases(); - Ok(page::pending(&user.csrf, &entries, &leases).into_response()) + Ok(page::index(&user.name, &user.csrf, &entries, &leases).into_response()) } async fn request_page( @@ -223,14 +217,35 @@ async fn request_page( Ok(user) => user, Err(redirect) => return Ok(redirect), }; - // The log may be missing or unreadable; the request itself still shows. - let past = web.broker.audit.tail(LOG_RECORDS).ok().and_then(|records| { + let (entry, past) = request_parts(&web.broker, &id); + let view = page::RequestView { id: &id, entry: entry.as_ref(), past: past.as_ref() }; + Ok(page::request(&user.name, &user.csrf, &view).into_response()) +} + +/// A request while it waits, and what the audit log has of it. The log may be missing or +/// unreadable; the request itself still shows. +fn request_parts(broker: &Broker, id: &str) -> (Option, Option) { + let entry = broker.queue.list().into_iter().find(|e| e.id == id); + let past = broker.audit.tail(LOG_RECORDS).ok().and_then(|records| { let (histories, _) = history::gather(records); histories.into_iter().find(|h| h.id == id) }); - let current = pending(&web, &id); - Ok(page::request(&user.name, &user.csrf, &id, current.as_ref(), past.as_ref(), web.broker.queue.version()) - .into_response()) + (entry, past) +} + +#[derive(Deserialize)] +struct EventsQuery { + request: Option, +} + +/// The page's stream of updates (see [`events`]): the main page's, or a request's. +async fn page_events( + State(web): State>, + session: Session, + Query(query): Query, +) -> Result { + api_user(&session).await?; + Ok(events::stream(web.broker.clone(), session, query.request)) } #[derive(Deserialize)] @@ -310,11 +325,6 @@ async fn log_page( Ok(page::log(&user.name, &user.csrf, &view).into_response()) } -async fn version(State(web): State>, session: Session) -> Result { - api_user(&session).await?; - Ok(axum::Json(serde_json::json!({ "version": web.broker.queue.version() })).into_response()) -} - async fn csrf(session: Session) -> Result { let user = api_user(&session).await?; Ok(axum::Json(serde_json::json!({ "csrf": user.csrf })).into_response()) diff --git a/src/web/page.rs b/src/web/page.rs index f33d9de..69a0bdd 100644 --- a/src/web/page.rs +++ b/src/web/page.rs @@ -82,7 +82,7 @@ pub fn message(title: &str, text: &str) -> Html { render(Message { title, text }) } -/// The pending requests and leases, which the page script swaps in when they change. +/// The pending requests and leases: the main page's region that the page script keeps current. #[derive(Template)] #[template(path = "pending.html")] struct Pending<'a> { @@ -91,8 +91,8 @@ struct Pending<'a> { leases: &'a [(String, String, u64)], } -pub fn pending(csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> Html { - render(Pending { csrf, entries, leases }) +pub fn pending(csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> String { + render(Pending { csrf, entries, leases }).0 } #[derive(Template)] @@ -102,17 +102,27 @@ struct Index<'a> { csrf: &'a str, entries: &'a [PendingInfo], leases: &'a [(String, String, u64)], - version: u64, } -pub fn index( - name: &str, - csrf: &str, - entries: &[PendingInfo], - leases: &[(String, String, u64)], - version: u64, -) -> Html { - render(Index { name, csrf, entries, leases, version }) +pub fn index(name: &str, csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> Html { + render(Index { name, csrf, entries, leases }) +} + +/// What a request's page shows: the request while it waits, and what the audit log has of it. +pub struct RequestView<'a> { + pub id: &'a str, + pub entry: Option<&'a PendingInfo>, + pub past: Option<&'a History>, +} + +impl RequestView<'_> { + fn heading(&self) -> String { + match (self.entry, self.past) { + (Some(entry), _) => entry.summary.clone(), + (None, Some(past)) if !past.summary.is_empty() => past.summary.clone(), + _ => format!("Request {}", short(self.id)), + } + } } #[derive(Template)] @@ -120,26 +130,23 @@ pub fn index( struct Request<'a> { name: &'a str, csrf: &'a str, - heading: String, - entry: Option<&'a PendingInfo>, - past: Option<&'a History>, - version: u64, + view: &'a RequestView<'a>, } -pub fn request( - name: &str, - csrf: &str, - id: &str, - entry: Option<&PendingInfo>, - past: Option<&History>, - version: u64, -) -> Html { - let heading = match (entry, past) { - (Some(entry), _) => entry.summary.clone(), - (None, Some(past)) if !past.summary.is_empty() => past.summary.clone(), - _ => format!("Request {}", short(id)), - }; - render(Request { name, csrf, heading, entry, past, version }) +pub fn request(name: &str, csrf: &str, view: &RequestView) -> Html { + render(Request { name, csrf, view }) +} + +/// A request's page without the rest: the region that the page script keeps current. +#[derive(Template)] +#[template(path = "request_region.html")] +struct RequestRegion<'a> { + csrf: &'a str, + view: &'a RequestView<'a>, +} + +pub fn request_region(csrf: &str, view: &RequestView) -> String { + render(RequestRegion { csrf, view }).0 } /// What the log page is filtered by. @@ -256,7 +263,8 @@ mod tests { offers: vec![Decision::Once, Decision::Lease(300), Decision::Deny], expires_in: 125, }; - let html = pending("token", &[entry], &[]).0; + let html = pending("token", &[entry], &[]); + assert!(html.starts_with("
") && html.trim_end().ends_with("
"), "{html}"); assert!(html.contains(r#"value="5m""#)); assert!(html.contains("For 5m")); assert!(html.contains("ssh river <x>")); @@ -296,7 +304,10 @@ mod tests { ]; let (histories, _) = super::history::gather(records); - let html = request("broker", "token", "abc", None, Some(&histories[0]), 0).0; + let view = RequestView { id: "abc", entry: None, past: Some(&histories[0]) }; + let html = request("broker", "token", &view).0; + assert!(html.contains(r#"
"#), "{html}"); + assert!(html.contains(request_region("token", &view).trim()), "{html}"); assert!(html.contains("
Command
uptime
"), "{html}"); assert!(html.contains("+a"), "{html}"); assert!(html.contains("Details (Text)") && html.contains("
Old: text
"), "{html}"); diff --git a/templates/base.html b/templates/base.html index d6bc518..81f3e35 100644 --- a/templates/base.html +++ b/templates/base.html @@ -7,6 +7,7 @@ + diff --git a/templates/index.html b/templates/index.html index ffd01ee..2758630 100644 --- a/templates/index.html +++ b/templates/index.html @@ -5,7 +5,5 @@ -
{% include "pending.html" %} -
{% endblock %} diff --git a/templates/pending.html b/templates/pending.html index 0e0f42c..7a80873 100644 --- a/templates/pending.html +++ b/templates/pending.html @@ -1,4 +1,5 @@ {%- import "macros.html" as m -%} +
{% if entries.is_empty() %}

Nothing is waiting for an answer.

{% endif %} @@ -13,3 +14,4 @@ {% endfor %} {% endif %} +
diff --git a/templates/request.html b/templates/request.html index d0cc0f5..937b4cb 100644 --- a/templates/request.html +++ b/templates/request.html @@ -1,20 +1,5 @@ {% extends "base.html" %} -{% import "macros.html" as m %} {% block title %}Approval request{% endblock %} {% block main %} -

{{ heading }}

-
-{% if let Some(entry) = entry %} -{% call m::card(entry, csrf, true) %}{% endcall %} -{% endif %} -{% if let Some(past) = past %} -{% if entry.is_none() %} -

{{ past.requester }} · {{ past.op }} · {% call m::outcome(past.outcome) %}{% endcall %}

-{% endif %} -

History

-{% call m::timeline(past.records.as_slice()) %}{% endcall %} -{% else if entry.is_none() %} -

The audit log has nothing about this request.

-{% endif %} -
+{% include "request_region.html" %} {% endblock %} diff --git a/templates/request_region.html b/templates/request_region.html new file mode 100644 index 0000000..5c07b48 --- /dev/null +++ b/templates/request_region.html @@ -0,0 +1,16 @@ +{%- import "macros.html" as m -%} +
+

{{ view.heading() }}

+{% if let Some(entry) = view.entry %} +{% call m::card(entry, csrf, true) %}{% endcall %} +{% endif %} +{% if let Some(past) = view.past %} +{% if view.entry.is_none() %} +

{{ past.requester }} · {{ past.op }} · {% call m::outcome(past.outcome) %}{% endcall %}

+{% endif %} +

History

+{% call m::timeline(past.records.as_slice()) %}{% endcall %} +{% else if view.entry.is_none() %} +

The audit log has nothing about this request.

+{% endif %} +