Files
pipelines/web/src/modal.js
T
alan 4072698731 web: keep chat stable while streaming and refresh Settings
Preserve scroll intent for touch scrolling, coalesce live frames into one paint,
keep stable dialogs mounted across re-renders, and add a Settings refresh that
pings the server for a fresh build/time card.
2026-10-20 03:35:45 +01:00

692 lines
22 KiB
JavaScript

// The shared modal controller: one focus trap, one background-inert rule and
// one Escape/close path for every role="dialog" surface in the web client.
//
// It is deliberately DOM-only and dependency-free. Views keep owning their
// markup, copy and state transitions: a view stage()s the dialog it built (or
// open()s an imperative viewer) and gives the controller the callback that
// closes it. The controller never mutates view state itself.
//
// The dialog layer lives outside .app-root (see app.js): inert inherits, so a
// panel inside the inert root could not become interactive. Every active panel
// is re-parented into #modalLayer, the app root gets native `inert` (or the
// aria-hidden + tabindex fallback), and only the top panel owns Tab/Escape.
/** The selectors a focusable candidate can match, in DOM order at discovery. */
export const FOCUSABLE_SELECTOR = [
"a[href]",
"area[href]",
"button",
"input",
"select",
"textarea",
"iframe",
"object",
"embed",
"summary",
"audio[controls]",
"video[controls]",
"[contenteditable]",
"[tabindex]",
].join(",");
const NATIVE_FOCUSABLE = new Set([
"button",
"input",
"select",
"textarea",
"iframe",
"object",
"embed",
"summary",
]);
function attr(node, name) {
return typeof node.getAttribute === "function" ? node.getAttribute(name) : null;
}
function hasAttr(node, name) {
return typeof node.hasAttribute === "function" ? node.hasAttribute(name) : attr(node, name) != null;
}
function tagName(node) {
return String(node.tagName ?? "").toLowerCase();
}
function computedStyle(node) {
try {
return node.ownerDocument?.defaultView?.getComputedStyle?.(node) ?? null;
} catch {
return null;
}
}
function hiddenBySelf(node) {
if (node.hidden) return true;
if (attr(node, "aria-hidden") === "true") return true;
if (hasAttr(node, "inert")) return true;
const style = computedStyle(node);
return Boolean(style && (style.display === "none" || style.visibility === "hidden"));
}
function hiddenByAncestor(node, root) {
let current = node;
while (current) {
if (hiddenBySelf(current)) return true;
if (current === root) break;
current = current.parentElement ?? null;
}
return false;
}
/** Whether one node is a reachable control (not disabled, hidden or removed). */
export function isFocusable(node, { root = null } = {}) {
if (!node || (node.nodeType != null && node.nodeType !== 1)) return false;
if (node.disabled === true || hasAttr(node, "disabled")) return false;
if (hiddenByAncestor(node, root)) return false;
const tabindex = attr(node, "tabindex");
if (tabindex != null && Number(tabindex) < 0) return false;
if (node.isContentEditable === true) return true;
const tag = tagName(node);
if (tag === "input" && String(attr(node, "type") ?? "").toLowerCase() === "hidden") return false;
if (tag === "a" || tag === "area") return hasAttr(node, "href");
if (NATIVE_FOCUSABLE.has(tag)) return true;
if (tag === "audio" || tag === "video") return hasAttr(node, "controls");
if (tag === "" && typeof node.focus === "function") return true;
// A div/span with a non-negative tabindex is focusable even though it is not
// a native control (the change/timeline rows use exactly this form).
return tabindex != null && Number(tabindex) >= 0;
}
/** Every reachable control inside [panel], in DOM order. */
export function focusableElements(panel) {
if (!panel || typeof panel.querySelectorAll !== "function") return [];
return [...panel.querySelectorAll(FOCUSABLE_SELECTOR)].filter((node) =>
isFocusable(node, { root: panel }),
);
}
/** The wrapped index for one Tab/Shift+Tab step; -1 when there is no control. */
export function wrapFocusIndex(index, direction, count) {
if (count <= 0) return -1;
if (!Number.isInteger(index) || index < 0) return direction < 0 ? count - 1 : 0;
return ((index + direction) % count + count) % count;
}
/** The initial focus target is the first control, else the panel itself (-1). */
export function initialFocusIndex(count) {
return count > 0 ? 0 : -1;
}
function supportsNativeInert() {
try {
return typeof HTMLElement !== "undefined" && "inert" in HTMLElement.prototype;
} catch {
return false;
}
}
function isConnected(node) {
return Boolean(node) && node.isConnected !== false;
}
function contains(root, node) {
if (!root || !node) return false;
return root === node || root.contains?.(node) === true;
}
function inInertSubtree(node, document_) {
let current = node;
while (current) {
if (hasAttr(current, "inert")) return true;
current = current.parentElement ?? null;
}
return false;
}
function focusElement(element) {
if (!element || typeof element.focus !== "function") return false;
try {
element.focus({ preventScroll: true });
} catch {
try {
element.focus();
} catch {
return false;
}
}
return true;
}
/**
* Create one controller for the page. Options are injectable for the unit tests:
* a document, a layer, the background element/skip links, and whether native
* inert exists. Production passes none of them and uses the real document.
*/
export function createModalController(options = {}) {
const document_ = options.document ?? globalThis.document;
const window_ = options.window ?? globalThis.window;
const getLayer =
typeof options.layer === "function"
? options.layer
: () => options.layer ?? document_?.getElementById?.("modalLayer") ?? document_?.body;
const getBackground =
typeof options.background === "function"
? options.background
: () => document_?.querySelector?.(".app-root") ?? null;
const getSkipLinks =
typeof options.skipLinks === "function"
? options.skipLinks
: () =>
options.skipLinks ??
(document_?.querySelectorAll ? [...document_.querySelectorAll(".skip-link")] : []);
const nativeInert =
typeof options.supportsInert === "function" ? options.supportsInert : () => supportsNativeInert();
const defaultFallbackSelectors = options.fallbackSelectors ?? [
"#detailTitle",
"#listTitle",
".detail-pane h1",
".list-pane .pane-title",
"#pane-main",
];
/** @type {Array<object>} active entries, bottom first */
const stack = [];
/** @type {Map<string, object>} dialogs staged during the current render */
const pending = new Map();
let backgroundState = null;
let keydownBound = false;
let focusinBound = false;
let fallbackMode = false;
// One history entry per open modal, so the browser Back button closes it the
// same way Escape and the backdrop do. A modal that closes through the UI
// pops its own entry instead of leaving a dead one behind.
let historyPushed = false;
let historyClosing = false;
function pushModalHistory(id) {
if (historyPushed || !window_?.history) return;
try {
window_.history.pushState(
{ ...(window_.history.state ?? {}), pipelinesModal: id },
"",
);
historyPushed = true;
} catch {
// A history-refusing environment simply keeps the UI close paths.
}
}
function popModalHistory() {
if (!historyPushed || historyClosing) return;
historyPushed = false;
try {
// Only pop our own entry. If the app navigated while the dialog was open,
// its route entry is on top now; calling back() here would undo that
// navigation (the dialog's own entry is buried under it).
if (window_.history?.state?.pipelinesModal == null) return;
window_.history.back();
} catch {
// Nothing to pop.
}
}
if (window_?.addEventListener) {
window_.addEventListener("popstate", () => {
if (!historyPushed) return;
historyPushed = false;
const entry = top();
if (!entry) return;
historyClosing = true;
closeEntry(entry, { restore: true });
historyClosing = false;
});
}
function layer() {
return getLayer() ?? document_?.body ?? null;
}
function top() {
return stack.length ? stack[stack.length - 1] : null;
}
function find(id) {
return stack.find((entry) => entry.id === id) ?? null;
}
function normalizeTrigger(candidate, panel) {
if (!candidate || candidate === document_?.body) return null;
if (candidate.nodeType != null && candidate.nodeType !== 1) return null;
if (contains(panel, candidate)) return null;
return candidate;
}
/**
* Capture the opener now, before the view's state render replaces the trigger.
* A stage for an already-open id deliberately keeps the original trigger.
*/
function stage(id, panel, entryOptions = {}) {
if (!panel) return;
const existing = find(id);
pending.set(id, {
panel,
options: entryOptions,
trigger: existing
? existing.trigger
: normalizeTrigger(entryOptions.trigger ?? document_?.activeElement, panel),
});
}
function ensureEntryBackground(entry) {
const root = getBackground();
const skip = getSkipLinks();
const targets = [root, ...skip].filter(Boolean);
if (!targets.length) return;
if (!backgroundState) {
fallbackMode = !nativeInert();
backgroundState = {
mode: fallbackMode ? "fallback" : "inert",
targets: targets.map((element) => ({
element,
inert: attr(element, "inert"),
ariaHidden: attr(element, "aria-hidden"),
})),
tabindexes: fallbackMode ? new Map() : null,
};
}
if (backgroundState.mode === "inert") {
for (const state of backgroundState.targets) {
state.element.setAttribute("inert", "");
if (state.element !== root) state.element.setAttribute("aria-hidden", "true");
}
return;
}
for (const state of backgroundState.targets) {
state.element.setAttribute("aria-hidden", "true");
}
const focusables = [];
for (const state of backgroundState.targets) {
const element = state.element;
if (element.matches?.(FOCUSABLE_SELECTOR) || isFocusable(element)) focusables.push(element);
if (element.querySelectorAll) focusables.push(...element.querySelectorAll(FOCUSABLE_SELECTOR));
}
for (const element of focusables) {
if (!isConnected(element)) continue;
if (!backgroundState.tabindexes.has(element)) {
backgroundState.tabindexes.set(element, attr(element, "tabindex"));
}
element.setAttribute("tabindex", "-1");
}
if (entry && !focusinBound) {
document_.addEventListener("focusin", onFocusIn, true);
focusinBound = true;
}
}
function restoreBackground() {
const state = backgroundState;
backgroundState = null;
fallbackMode = false;
if (!state) return;
for (const target of state.targets) {
if (target.inert == null) target.element.removeAttribute?.("inert");
else target.element.setAttribute("inert", target.inert);
if (target.ariaHidden == null) target.element.removeAttribute?.("aria-hidden");
else target.element.setAttribute("aria-hidden", target.ariaHidden);
}
if (state.tabindexes) {
for (const [element, value] of state.tabindexes) {
if (!isConnected(element)) continue;
if (value == null) element.removeAttribute("tabindex");
else element.setAttribute("tabindex", value);
}
}
}
function setLowerInert(entry, inert) {
if (!entry) return;
if (inert) {
if (entry.inertedByStack) return;
entry.inertedByStack = true;
entry.inertPrior = attr(entry.panel, "inert");
entry.panel.setAttribute("inert", "");
return;
}
if (!entry.inertedByStack) return;
entry.inertedByStack = false;
if (entry.inertPrior == null) entry.panel.removeAttribute?.("inert");
else entry.panel.setAttribute("inert", entry.inertPrior);
entry.inertPrior = null;
}
function focusPanel(panel) {
if (!panel) return;
if (!hasAttr(panel, "tabindex")) panel.setAttribute("tabindex", "-1");
focusElement(panel);
}
function focusInside(panel, index = -1) {
const focusables = focusableElements(panel);
if (!focusables.length) {
focusPanel(panel);
return;
}
const target = focusables[initialFocusIndex(focusables.length)];
focusElement(target);
}
function rememberFocus(panel) {
const active = document_?.activeElement ?? null;
if (!active) return { wasPanel: false, index: -1 };
if (active === panel) return { wasPanel: true, index: -1 };
const index = focusableElements(panel).indexOf(active);
return { wasPanel: false, index };
}
function updateEntry(entry, staged) {
entry.options = { ...entry.options, ...staged.options };
if (entry.trigger == null && staged.trigger) entry.trigger = staged.trigger;
if (entry.panel === staged.panel) return false;
// A stable dialog keeps its mounted panel across streaming re-renders. A
// rebuild would restart the modal-in animation (the rename dialog visibly
// blinked/reappeared on every chat frame) and discard whatever the operator
// had typed into it.
if (
entry.panel?.getAttribute?.("data-modal-stable") === "true" &&
staged.panel?.getAttribute?.("data-modal-stable") === "true"
) {
return false;
}
const remembered = rememberFocus(entry.panel);
const oldPanel = entry.panel;
if (typeof oldPanel.replaceWith === "function" && oldPanel.parentElement) {
oldPanel.replaceWith(staged.panel);
} else {
oldPanel.remove?.();
layer()?.append(staged.panel);
}
entry.panel = staged.panel;
if (entry.inertedByStack) staged.panel.setAttribute("inert", "");
if (remembered.wasPanel) {
focusPanel(staged.panel);
} else if (remembered.index >= 0) {
const focusables = focusableElements(staged.panel);
if (!focusables.length) focusPanel(staged.panel);
else focusElement(focusables[Math.min(remembered.index, focusables.length - 1)]);
}
return true;
}
function openEntry(id, staged, renderManaged) {
const previous = top();
if (previous) setLowerInert(previous, true);
const entry = {
id,
panel: staged.panel,
options: staged.options,
trigger: staged.trigger ?? null,
renderManaged,
inertedByStack: false,
inertPrior: null,
};
stack.push(entry);
const host = layer();
if (host && staged.panel.parentElement !== host) host.append(staged.panel);
return entry;
}
function resolveReturnTarget(entry) {
const options = entry.options ?? {};
if (typeof options.restore === "function") {
const explicit = options.restore();
if (explicit) return explicit;
}
if (entry.trigger && isConnected(entry.trigger) && !inInertSubtree(entry.trigger)) {
return entry.trigger;
}
const selectors = [];
if (options.triggerSelector) selectors.push(options.triggerSelector);
if (Array.isArray(options.fallbackSelectors)) selectors.push(...options.fallbackSelectors);
selectors.push(...defaultFallbackSelectors);
for (const selector of selectors) {
if (!selector) continue;
let target = null;
try {
target = document_?.querySelector?.(selector) ?? null;
} catch {
target = null;
}
if (target && isConnected(target) && !inInertSubtree(target)) return target;
}
const pane = document_?.getElementById?.("pane-main") ?? null;
if (pane) return pane;
return document_?.body ?? null;
}
function restoreFocus(entry) {
if (entry.options?.restoreFocus === false) return;
const target = resolveReturnTarget(entry);
if (!target) return;
if (target === document_?.body) {
const pane = document_?.getElementById?.("pane-main");
if (pane) {
if (!hasAttr(pane, "tabindex")) pane.setAttribute("tabindex", "-1");
focusElement(pane);
}
return;
}
if (!hasAttr(target, "tabindex") && !NATIVE_FOCUSABLE.has(tagName(target)) && tagName(target) !== "a") {
target.setAttribute("tabindex", "-1");
}
focusElement(target);
// The rebuilt background may still be mid-layout at this synchronous point
// (Chrome can refuse focus while the freshly inserted pane has no boxes yet).
// One next-frame retry re-resolves the trigger, so a re-render between the
// close and the frame cannot leave focus on <body>.
if (document_.activeElement !== target) {
const frame = document_.defaultView?.requestAnimationFrame ?? globalThis.requestAnimationFrame;
if (typeof frame === "function") {
frame(() => {
if (document_.activeElement !== document_?.body) return;
const current = resolveReturnTarget(entry);
if (current && current !== document_?.body) focusElement(current);
});
}
}
}
function releaseIfEmpty() {
if (stack.length) return;
restoreBackground();
if (keydownBound) {
document_.removeEventListener("keydown", onKeyDown, false);
keydownBound = false;
}
if (focusinBound) {
document_.removeEventListener("focusin", onFocusIn, true);
focusinBound = false;
}
}
function closeEntry(entry, { restore = true } = {}) {
const index = stack.indexOf(entry);
if (index === -1) return false;
const wasTop = index === stack.length - 1;
stack.splice(index, 1);
if (entry.panel?.parentElement) entry.panel.remove();
if (wasTop) {
const next = top();
if (next) setLowerInert(next, false);
}
if (stack.length) {
ensureEntryBackground(top());
} else {
releaseIfEmpty();
}
if (restore && wasTop) restoreFocus(entry);
if (!stack.length) popModalHistory();
return true;
}
function ensureListeners() {
if (!stack.length) return;
if (!keydownBound) {
document_.addEventListener("keydown", onKeyDown, false);
keydownBound = true;
}
if (fallbackMode && !focusinBound) {
document_.addEventListener("focusin", onFocusIn, true);
focusinBound = true;
}
}
function onKeyDown(event) {
const entry = top();
if (!entry) return;
if (event.key === "Escape") {
if (event.defaultPrevented) return;
event.preventDefault();
event.stopPropagation();
entry.options?.onClose?.();
return;
}
if (event.key !== "Tab") return;
const focusables = focusableElements(entry.panel);
if (!focusables.length) {
event.preventDefault();
focusPanel(entry.panel);
return;
}
const active = document_?.activeElement ?? null;
const current = focusables.indexOf(active);
if (current === -1) {
event.preventDefault();
focusElement(focusables[event.shiftKey ? focusables.length - 1 : 0]);
return;
}
if (event.shiftKey && current === 0) {
event.preventDefault();
focusElement(focusables[focusables.length - 1]);
return;
}
if (!event.shiftKey && current === focusables.length - 1) {
event.preventDefault();
focusElement(focusables[0]);
}
}
function onFocusIn(event) {
const entry = top();
if (!entry) return;
if (contains(entry.panel, event.target)) return;
focusInside(entry.panel);
}
function applyStackState() {
if (!stack.length) {
releaseIfEmpty();
return;
}
ensureEntryBackground(top());
ensureListeners();
}
/**
* Open (or update) one dialog immediately. Imperative viewers call this
* directly; render-managed dialogs stage() during a render and reconcile().
*/
function open(id, panel, entryOptions = {}) {
if (!panel) return null;
const existing = find(id);
if (existing) {
updateEntry(existing, { panel, options: entryOptions, trigger: existing.trigger });
applyStackState();
return existing.panel;
}
const entry = openEntry(
id,
{
panel,
options: entryOptions,
trigger: normalizeTrigger(entryOptions.trigger ?? document_?.activeElement, panel),
},
entryOptions.renderManaged !== false,
);
applyStackState();
// Only overlays that act as their own view carry a history entry (the
// viewers). A transient sheet must not, or closing it while the app
// navigates would undo that navigation with history.back().
if (entryOptions.history !== false) pushModalHistory(id);
if (entryOptions.focus !== false) focusInside(entry.panel);
return entry.panel;
}
/**
* Reconcile the dialogs a view built this render. Same-id elements replace
* their panel and keep focus; render-managed ids that disappeared close and
* return focus; staged ids in order become the stack.
*/
function reconcile() {
if (!pending.size) {
// Nothing staged is a real state when no render-managed dialog is open;
// persistent (imperative) entries are untouched.
if (stack.some((entry) => entry.renderManaged)) {
const missing = stack.filter((entry) => entry.renderManaged).reverse();
for (const entry of missing) closeEntry(entry, { restore: stack[stack.length - 1] === entry });
}
applyStackState();
return;
}
const staged = new Map(pending);
pending.clear();
const missing = stack.filter((entry) => entry.renderManaged && !staged.has(entry.id)).reverse();
for (const entry of missing) {
closeEntry(entry, { restore: stack[stack.length - 1] === entry });
}
let opened = null;
for (const [id, item] of staged) {
const existing = find(id);
if (existing) {
updateEntry(existing, item);
} else {
opened = openEntry(id, item, true);
}
}
applyStackState();
if (opened && top() === opened) focusInside(opened.panel);
}
/** Close one dialog by id (used by the imperative viewers and the sheet). */
function close(id, { restoreFocus: restore = true } = {}) {
const entry = find(id);
if (!entry) return false;
return closeEntry(entry, { restore });
}
function closeAll() {
while (stack.length) {
const entry = stack[stack.length - 1];
closeEntry(entry, { restore: false });
}
}
return {
stage,
open,
reconcile,
close,
closeAll,
top,
isOpen: (id) => Boolean(find(id)),
stackIds: () => stack.map((entry) => entry.id),
pendingCount: () => pending.size,
// Exposed for focused tests: the listener state must return to zero after
// the last dialog closes.
listenerState: () => ({ keydown: keydownBound, focusin: focusinBound }),
};
}