web: shared modal focus controller (M1/M2) — work in progress
This commit is contained in:
+1
-1
File diff suppressed because one or more lines are too long
+27
-54
@@ -42,6 +42,7 @@ import {
|
||||
} from "./search.js";
|
||||
import { DecisionDraft, pendingDecision } from "./actions.js";
|
||||
import { h } from "./dom.js";
|
||||
import { createModalController } from "./modal.js";
|
||||
import { describeError, isExecuting } from "./format.js";
|
||||
import {
|
||||
createAttentionView,
|
||||
@@ -510,9 +511,24 @@ const dock = h(
|
||||
// The attention sheet lives in its own layer so it can overlay any view without
|
||||
// being torn down by a content re-render; renderAttentionSheet rebuilds it.
|
||||
const attentionLayer = h("div", { id: "attentionLayer" });
|
||||
// Dialogs are re-parented here, outside the inert app root. `inert` inherits and
|
||||
// cannot be overridden by a descendant, so a panel left inside .app-root could
|
||||
// never be interactive while the background is inert.
|
||||
const modalLayer = h("div", { id: "modalLayer" });
|
||||
const skipLink = h("a", { class: "skip-link", href: "#pane-main", text: "Skip to detail" });
|
||||
document.body.append(skipLink);
|
||||
document.body.append(h("div", { class: "app-root" }, appRail, workspace, dock, attentionLayer));
|
||||
document.body.append(h("div", { class: "app-root" }, appRail, workspace, dock));
|
||||
document.body.append(attentionLayer);
|
||||
document.body.append(modalLayer);
|
||||
|
||||
// One controller owns Escape, the Tab trap, the background's inert state and
|
||||
// focus return for every role="dialog" surface.
|
||||
const modal = createModalController({
|
||||
document,
|
||||
layer: () => modalLayer,
|
||||
background: () => document.querySelector(".app-root"),
|
||||
skipLinks: () => [...document.querySelectorAll(".skip-link")],
|
||||
});
|
||||
|
||||
/** Whether the URL field currently holds a usable endpoint for Reconnect. */
|
||||
function endpointConfigured() {
|
||||
@@ -931,6 +947,7 @@ function renderContent() {
|
||||
nodes.push(h("div", { class: "settings-pane", id: "detail-panel" }, renderSettingsView()));
|
||||
captureChatPosition();
|
||||
content.replaceChildren(...nodes);
|
||||
modal.reconcile();
|
||||
stopChatClock();
|
||||
stopListClock();
|
||||
stopDetailClock();
|
||||
@@ -1021,11 +1038,13 @@ function renderContent() {
|
||||
content.replaceChildren(...nodes);
|
||||
if (state.view === "chat") {
|
||||
afterChatRender();
|
||||
modal.reconcile();
|
||||
stopListClock();
|
||||
stopDetailClock();
|
||||
refreshChatClock();
|
||||
return;
|
||||
}
|
||||
modal.reconcile();
|
||||
stopChatClock();
|
||||
if (state.view === "runs") {
|
||||
refreshListClock();
|
||||
@@ -2035,6 +2054,7 @@ const runtime = {
|
||||
repo,
|
||||
runAlerts,
|
||||
attentionLayer,
|
||||
modal,
|
||||
searchHost,
|
||||
render,
|
||||
renderContent,
|
||||
@@ -2070,12 +2090,11 @@ const {
|
||||
renderAttentionBell,
|
||||
refreshAttentionBell,
|
||||
renderAttentionSheet,
|
||||
closeAttentionSheet,
|
||||
onRunAlertFrame,
|
||||
} = views.attention;
|
||||
const { renderSettingsView, refreshServerUrlError } = views.settings;
|
||||
const { renderPipelineList, renderPipelineDetail } = views.pipelines;
|
||||
const { renderTemplateGallery, renderTemplateDetail, loadTemplates, selectTemplate, resetTemplateCreateState, resetTemplateSelection, closeTemplateCreateDialog } =
|
||||
const { renderTemplateGallery, renderTemplateDetail, loadTemplates, selectTemplate, resetTemplateCreateState, resetTemplateSelection } =
|
||||
views.templates;
|
||||
const renderRunList = () => views.runs.renderRunList(listNow);
|
||||
const renderRunDetail = () => views.runDetail.renderRunDetail(detailNow);
|
||||
@@ -2098,8 +2117,6 @@ const {
|
||||
onChatEvent,
|
||||
onChatPermission,
|
||||
onChatFrame,
|
||||
dismissChatClose,
|
||||
dismissChatRename,
|
||||
} = views.chat;
|
||||
const {
|
||||
openSearch,
|
||||
@@ -2108,8 +2125,7 @@ const {
|
||||
onSearchInput,
|
||||
sendSearchNow,
|
||||
} = views.search;
|
||||
const { openDecisionSheet, closeDecisionSheet, dismissConfirm, dismissActionError } = views.dialogs;
|
||||
const { closeStagePane } = views.runDetail;
|
||||
const { openDecisionSheet } = views.dialogs;
|
||||
|
||||
// Kept as named exports for the UI smoke's page-rendered markdown/tool samples.
|
||||
export const renderToolCallRow = views.chat.renderToolCallRow;
|
||||
@@ -2200,55 +2216,12 @@ client.addEventListener("frame", (event) => {
|
||||
onChatFrame(message);
|
||||
});
|
||||
|
||||
// The stage pane, the decision sheet, the confirm/Action-failed dialogs, the
|
||||
// omni-search field and the attention sheet are modal: Escape closes the topmost
|
||||
// one (the artifact viewer or the diff viewer, when either is above, owns Escape
|
||||
// first via its own listener). The attention sheet, when open, is the topmost
|
||||
// overlay and owns Escape first. Registered once; every branch is a no-op when
|
||||
// nothing is open.
|
||||
// The shared modal controller owns Escape for every role="dialog" (attention
|
||||
// sheet, stage pane, viewers, decision/confirm/Action-failed, chat Rename/Close,
|
||||
// template create). Only the non-modal surfaces below are handled here: the Chat
|
||||
// actions menu and the Search disclosure, which are not dialogs.
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key !== "Escape") return;
|
||||
if (state.attentionSheetOpen) {
|
||||
event.preventDefault();
|
||||
closeAttentionSheet();
|
||||
return;
|
||||
}
|
||||
if (document.querySelector(".artifact-viewer") || document.querySelector(".change-viewer")) return;
|
||||
if (state.templateCreateOpen) {
|
||||
event.preventDefault();
|
||||
closeTemplateCreateDialog();
|
||||
return;
|
||||
}
|
||||
if (state.actionError) {
|
||||
event.preventDefault();
|
||||
dismissActionError();
|
||||
return;
|
||||
}
|
||||
if (state.chatRename) {
|
||||
event.preventDefault();
|
||||
dismissChatRename();
|
||||
return;
|
||||
}
|
||||
if (state.chatClose) {
|
||||
event.preventDefault();
|
||||
dismissChatClose();
|
||||
return;
|
||||
}
|
||||
if (state.confirmKind) {
|
||||
event.preventDefault();
|
||||
dismissConfirm();
|
||||
return;
|
||||
}
|
||||
if (state.decisionOpen) {
|
||||
event.preventDefault();
|
||||
closeDecisionSheet();
|
||||
return;
|
||||
}
|
||||
if (state.runStagePane) {
|
||||
event.preventDefault();
|
||||
closeStagePane();
|
||||
return;
|
||||
}
|
||||
if (state.chatMenu) {
|
||||
event.preventDefault();
|
||||
state.chatMenu = null;
|
||||
|
||||
@@ -0,0 +1,631 @@
|
||||
// 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 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;
|
||||
|
||||
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;
|
||||
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);
|
||||
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();
|
||||
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 }),
|
||||
};
|
||||
}
|
||||
@@ -37,7 +37,7 @@ export function loadNotifyAsked() {
|
||||
}
|
||||
|
||||
export function createAttentionView(rt) {
|
||||
const { state, attentionLayer, runAlerts } = rt;
|
||||
const { state, attentionLayer, runAlerts, modal } = rt;
|
||||
const render = (...args) => rt.render(...args);
|
||||
const selectRun = (...args) => rt.selectRun(...args);
|
||||
|
||||
@@ -126,6 +126,7 @@ function refreshAttentionBell() {
|
||||
function renderAttentionSheet() {
|
||||
if (!state.attentionSheetOpen) {
|
||||
attentionLayer.replaceChildren();
|
||||
modal.close("attention-sheet");
|
||||
return;
|
||||
}
|
||||
const entries = attentionEntries(state.runs, state.attentionDismissed);
|
||||
@@ -175,6 +176,14 @@ function renderAttentionSheet() {
|
||||
const sheet = h("div", { class: "attention-sheet-panel", tabindex: "-1" }, head, body);
|
||||
overlay.append(sheet);
|
||||
attentionLayer.replaceChildren(overlay);
|
||||
modal.open("attention-sheet", overlay, {
|
||||
// The sheet is rebuilt by renderAttentionSheet, not by renderContent's
|
||||
// staged set, so it is managed imperatively rather than reconciled away.
|
||||
renderManaged: false,
|
||||
onClose: () => closeAttentionSheet(),
|
||||
triggerSelector: "#attentionBell",
|
||||
fallbackSelectors: ["#listTitle", "#pane-main"],
|
||||
});
|
||||
}
|
||||
|
||||
/** One attention row: status icon, the two text lines, and a trailing Dismiss. */
|
||||
@@ -227,16 +236,15 @@ function openAttentionSheet() {
|
||||
attentionEntries(state.runs, state.attentionDismissed),
|
||||
);
|
||||
render();
|
||||
document.querySelector(".attention-sheet-close")?.focus();
|
||||
}
|
||||
|
||||
/** Close the sheet, dropping the snapshot; focus returns to the bell. */
|
||||
/** Close the sheet, dropping the snapshot; the controller returns focus to the bell. */
|
||||
function closeAttentionSheet({ restoreFocus = true } = {}) {
|
||||
if (!state.attentionSheetOpen) return;
|
||||
state.attentionSheetOpen = false;
|
||||
state.attentionSnapshot = null;
|
||||
if (!restoreFocus) modal.close("attention-sheet", { restoreFocus: false });
|
||||
render();
|
||||
if (restoreFocus) document.querySelector("#attentionBell")?.focus();
|
||||
}
|
||||
|
||||
/** Dismiss one or more entries for good, persisting the identity set. */
|
||||
|
||||
+11
-3
@@ -254,7 +254,7 @@ export function readChatSeenStore() {
|
||||
}
|
||||
|
||||
export function createChatView(rt) {
|
||||
const { state, repo } = rt;
|
||||
const { state, repo, modal } = rt;
|
||||
let chatClock = null;
|
||||
let chatNow = Date.now();
|
||||
const renderContent = (...args) => rt.renderContent(...args);
|
||||
@@ -915,8 +915,6 @@ function openChatRename(session) {
|
||||
state.chatMenu = null;
|
||||
state.chatRename = session;
|
||||
renderContent();
|
||||
// Same re-render note as the menu: put the cursor in the Name field.
|
||||
document.getElementById("chatRenameInput")?.focus();
|
||||
}
|
||||
|
||||
function dismissChatRename() {
|
||||
@@ -2003,6 +2001,11 @@ function renderChatRenameDialog(session) {
|
||||
actions.append(save);
|
||||
panel.append(actions);
|
||||
overlay.append(panel);
|
||||
modal.stage("chat-rename", overlay, {
|
||||
onClose: () => dismissChatRename(),
|
||||
triggerSelector: `#chatRows .chat-row[data-session="${CSS.escape(String(session.id))}"] .chat-menu-button`,
|
||||
fallbackSelectors: ["#detailTitle", "#listTitle", "#pane-main"],
|
||||
});
|
||||
return overlay;
|
||||
}
|
||||
|
||||
@@ -3041,6 +3044,11 @@ function renderChatCloseDialog(session) {
|
||||
);
|
||||
panel.append(actions);
|
||||
overlay.append(panel);
|
||||
modal.stage("chat-close", overlay, {
|
||||
onClose: () => dismissChatClose(),
|
||||
triggerSelector: `#chatRows .chat-row[data-session="${CSS.escape(String(session.id))}"] .chat-menu-button`,
|
||||
fallbackSelectors: ["#detailTitle", "#listTitle", "#pane-main"],
|
||||
});
|
||||
return overlay;
|
||||
}
|
||||
|
||||
|
||||
+37
-34
@@ -51,27 +51,18 @@ import {
|
||||
} from "../actions.js";
|
||||
|
||||
export function createDialogsView(rt) {
|
||||
const { state, repo } = rt;
|
||||
const { state, repo, modal } = rt;
|
||||
const renderContent = (...args) => rt.renderContent(...args);
|
||||
const selectRun = (...args) => rt.selectRun(...args);
|
||||
|
||||
let changeViewerOverlay = null;
|
||||
let changeViewerKeydown = null;
|
||||
let changeViewerIndex = null;
|
||||
|
||||
/** Close the diff viewer, returning focus to the row that opened it. */
|
||||
/** Close the diff viewer; the controller returns focus to the viewed row. */
|
||||
function closeChangeViewer() {
|
||||
if (changeViewerKeydown) {
|
||||
document.removeEventListener("keydown", changeViewerKeydown);
|
||||
changeViewerKeydown = null;
|
||||
}
|
||||
const index = changeViewerIndex;
|
||||
changeViewerOverlay?.remove();
|
||||
changeViewerOverlay = null;
|
||||
modal.close("change-viewer");
|
||||
changeViewerIndex = null;
|
||||
if (index != null) {
|
||||
document.querySelector(`.change-row[data-change-index="${index}"]`)?.focus();
|
||||
}
|
||||
changeViewerOverlay = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -85,7 +76,7 @@ function closeChangeViewer() {
|
||||
* give a patch for (binary, truncated, or a capture that recorded none) shows the
|
||||
* honest reason in place of a diff rather than a fabricated one.
|
||||
*/
|
||||
function openChangeViewer(files, startIndex) {
|
||||
function openChangeViewer(files, startIndex, trigger = null) {
|
||||
closeChangeViewer();
|
||||
if (!files?.length) return;
|
||||
let index = Math.min(Math.max(Number(startIndex) || 0, 0), files.length - 1);
|
||||
@@ -209,12 +200,16 @@ function openChangeViewer(files, startIndex) {
|
||||
};
|
||||
|
||||
renderViewer();
|
||||
document.body.append(overlay);
|
||||
changeViewerOverlay = overlay;
|
||||
changeViewerKeydown = (event) => {
|
||||
if (event.key === "Escape") closeChangeViewer();
|
||||
};
|
||||
document.addEventListener("keydown", changeViewerKeydown);
|
||||
modal.open("change-viewer", overlay, {
|
||||
onClose: () => closeChangeViewer(),
|
||||
trigger,
|
||||
restore: () =>
|
||||
changeViewerIndex == null
|
||||
? null
|
||||
: document.querySelector(`.change-row[data-change-index="${changeViewerIndex}"]`),
|
||||
fallbackSelectors: ["#detailTitle", "#pane-main"],
|
||||
});
|
||||
}
|
||||
|
||||
/** The rendered reading: the stat line, an optional truncation note, each hunk. */
|
||||
@@ -267,7 +262,6 @@ function openDecisionSheet(decision) {
|
||||
state.decisionDraft = new DecisionDraft();
|
||||
state.decisionError = "";
|
||||
renderContent();
|
||||
document.querySelector(".decision-sheet .decision-option")?.focus();
|
||||
}
|
||||
|
||||
/** Dismiss the decision sheet (never while a decision is in flight). */
|
||||
@@ -280,7 +274,6 @@ function closeDecisionSheet() {
|
||||
state.decisionDraft = new DecisionDraft();
|
||||
if (!wasOpen) return;
|
||||
renderContent();
|
||||
document.querySelector(".decision-card .decision-open")?.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -367,6 +360,11 @@ function renderDecisionSheet(decision) {
|
||||
);
|
||||
sheet.append(actions);
|
||||
overlay.append(sheet);
|
||||
modal.stage("decision-sheet", overlay, {
|
||||
onClose: () => closeDecisionSheet(),
|
||||
triggerSelector: ".decision-card .decision-open",
|
||||
fallbackSelectors: ["#detailTitle", "#pane-main"],
|
||||
});
|
||||
return overlay;
|
||||
}
|
||||
|
||||
@@ -477,6 +475,12 @@ function renderConfirmDialog(d) {
|
||||
);
|
||||
panel.append(actions);
|
||||
overlay.append(panel);
|
||||
modal.stage("confirm", overlay, {
|
||||
onClose: () => dismissConfirm(),
|
||||
triggerSelector:
|
||||
kind.kind === "cancel" ? ".run-actions .cancel-run" : ".run-actions .retry-run",
|
||||
fallbackSelectors: ["#detailTitle", "#pane-main"],
|
||||
});
|
||||
return overlay;
|
||||
}
|
||||
|
||||
@@ -521,6 +525,10 @@ function renderActionFailedDialog() {
|
||||
h("button", { class: "action-failed-ok", type: "button", text: ACTION_FAILED_OK, onclick: dismissActionError }),
|
||||
);
|
||||
overlay.append(panel);
|
||||
modal.stage("action-error", overlay, {
|
||||
onClose: () => dismissActionError(),
|
||||
fallbackSelectors: ["#detailTitle", "#listTitle", "#pane-main"],
|
||||
});
|
||||
return overlay;
|
||||
}
|
||||
|
||||
@@ -530,15 +538,10 @@ function dismissActionError() {
|
||||
}
|
||||
|
||||
let viewerOverlay = null;
|
||||
let viewerKeydown = null;
|
||||
|
||||
/** Close the full-screen viewer and remove its Escape listener. */
|
||||
/** Close the full-screen viewer; the controller returns focus to its trigger. */
|
||||
function closeArtifactViewer() {
|
||||
if (viewerKeydown) {
|
||||
document.removeEventListener("keydown", viewerKeydown);
|
||||
viewerKeydown = null;
|
||||
}
|
||||
viewerOverlay?.remove();
|
||||
modal.close("artifact-viewer");
|
||||
viewerOverlay = null;
|
||||
}
|
||||
|
||||
@@ -548,7 +551,7 @@ function closeArtifactViewer() {
|
||||
* a single artifact; Escape and a backdrop click close it. Nothing autoplays: a
|
||||
* non-image artifact shows a still poster placeholder instead.
|
||||
*/
|
||||
function openArtifactViewer(viewable, startIndex) {
|
||||
function openArtifactViewer(viewable, startIndex, trigger = null) {
|
||||
closeArtifactViewer();
|
||||
if (!viewable?.length) return;
|
||||
let index = pagedIndex(startIndex, 0, viewable.length);
|
||||
@@ -660,12 +663,12 @@ function openArtifactViewer(viewable, startIndex) {
|
||||
};
|
||||
|
||||
renderViewer();
|
||||
document.body.append(overlay);
|
||||
viewerOverlay = overlay;
|
||||
viewerKeydown = (event) => {
|
||||
if (event.key === "Escape") closeArtifactViewer();
|
||||
};
|
||||
document.addEventListener("keydown", viewerKeydown);
|
||||
modal.open("artifact-viewer", overlay, {
|
||||
onClose: () => closeArtifactViewer(),
|
||||
trigger,
|
||||
fallbackSelectors: ["#detailTitle", "#pane-main"],
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
+27
-23
@@ -91,7 +91,7 @@ const ARTIFACT_SERVER_HINT =
|
||||
"Set the server URL in Settings to open or copy artifact links.";
|
||||
|
||||
export function createRunDetailView(rt) {
|
||||
const { state, repo } = rt;
|
||||
const { state, repo, modal } = rt;
|
||||
const renderContent = (...args) => rt.renderContent(...args);
|
||||
const selectRun = (...args) => rt.selectRun(...args);
|
||||
const pushRoute = (...args) => rt.pushRoute(...args);
|
||||
@@ -347,7 +347,6 @@ function renderChangesBody(changes) {
|
||||
* the diff viewer on this file, whose position there confirms which row it is.
|
||||
*/
|
||||
function renderChangeRow(entry, index, files) {
|
||||
const open = () => openChangeViewer(files, index);
|
||||
const row = h("div", {
|
||||
class: "change-row",
|
||||
role: "button",
|
||||
@@ -355,6 +354,7 @@ function renderChangeRow(entry, index, files) {
|
||||
"data-change-index": String(index),
|
||||
"aria-label": `Open ${entry.path}`,
|
||||
});
|
||||
const open = () => openChangeViewer(files, index, row);
|
||||
row.addEventListener("click", open);
|
||||
row.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
@@ -492,6 +492,23 @@ function renderStagePane(d) {
|
||||
}
|
||||
for (const spec of specs) body.append(renderStageSection(spec, step));
|
||||
overlay.append(h("div", { class: "stage-pane-sheet" }, bar, body));
|
||||
modal.stage("stage-pane", overlay, {
|
||||
onClose: () => closeStagePane(),
|
||||
fallbackSelectors: ["#detailTitle", "#pane-main"],
|
||||
// A pane opened from the Timeline returns to its row; one opened from the
|
||||
// Graph returns to the stage node (there is no timeline row then).
|
||||
restore: () => {
|
||||
const row = [...document.querySelectorAll(".timeline-row")].find(
|
||||
(node) =>
|
||||
node.dataset.stageKey === stageKey && node.dataset.visitIndex === String(visitIndex),
|
||||
);
|
||||
return (
|
||||
row ??
|
||||
[...document.querySelectorAll(".graph-node")].find((node) => node.dataset.key === stageKey) ??
|
||||
null
|
||||
);
|
||||
},
|
||||
});
|
||||
return overlay;
|
||||
}
|
||||
|
||||
@@ -570,7 +587,7 @@ function renderVerdictLink(text, artifact, step) {
|
||||
const link = h("a", { class: "verdict-link", href: resolved, target: "_blank", rel: "noreferrer", text });
|
||||
link.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
openArtifactFromVerdict(artifact, step, resolved);
|
||||
openArtifactFromVerdict(artifact, step, resolved, link);
|
||||
});
|
||||
return link;
|
||||
}
|
||||
@@ -583,12 +600,12 @@ function renderVerdictRef(artifact, step) {
|
||||
type: "button",
|
||||
text: artifact.name || "(unnamed artifact)",
|
||||
});
|
||||
chip.addEventListener("click", () => openArtifactFromVerdict(artifact, step, resolved));
|
||||
chip.addEventListener("click", () => openArtifactFromVerdict(artifact, step, resolved, chip));
|
||||
return chip;
|
||||
}
|
||||
|
||||
/** Open a referenced artifact: media in the viewer, everything else externally. */
|
||||
function openArtifactFromVerdict(artifact, step, resolved) {
|
||||
function openArtifactFromVerdict(artifact, step, resolved, trigger = null) {
|
||||
if (!resolved) return;
|
||||
const group = { stageKey: step.stage, visit: displayVisit(step, 0), artifacts: presentedArtifacts(step) };
|
||||
const viewable = pagedArtifacts([group]);
|
||||
@@ -596,11 +613,11 @@ function openArtifactFromVerdict(artifact, step, resolved) {
|
||||
const at = viewerIndexOf.get(artifact.url);
|
||||
const kind = artifactKind(artifact.content_type, artifact.name);
|
||||
const media = kind === ArtifactKind.Image || kind === ArtifactKind.Video;
|
||||
if (media && at != null) openArtifactViewer(viewable, at);
|
||||
if (media && at != null) openArtifactViewer(viewable, at, trigger);
|
||||
else window.open(resolved, "_blank", "noopener,noreferrer");
|
||||
}
|
||||
|
||||
/** Open the stage pane for one visit of a stage and move focus into it. */
|
||||
/** Open the stage pane for one visit of a stage; the controller moves focus in. */
|
||||
function openStagePane(stageKey, visitIndex, { updateRoute = true } = {}) {
|
||||
state.runStagePane = { stageKey, visitIndex };
|
||||
state.runStageSections = new Set();
|
||||
@@ -613,30 +630,17 @@ function openStagePane(stageKey, visitIndex, { updateRoute = true } = {}) {
|
||||
});
|
||||
}
|
||||
renderContent();
|
||||
document.querySelector(".stage-pane-back")?.focus();
|
||||
}
|
||||
|
||||
/** Close the stage pane, returning focus to the timeline row that opened it. */
|
||||
/** Close the stage pane; the controller returns focus to the row or graph node. */
|
||||
function closeStagePane({ updateRoute = true } = {}) {
|
||||
const closing = state.runStagePane;
|
||||
if (!closing) return;
|
||||
if (!state.runStagePane) return;
|
||||
state.runStagePane = null;
|
||||
state.runStageSections = new Set();
|
||||
if (updateRoute && state.selectedRunId) {
|
||||
pushRoute({ kind: "run", id: state.selectedRunId });
|
||||
}
|
||||
renderContent();
|
||||
const row = [...document.querySelectorAll(".timeline-row")].find(
|
||||
(node) => node.dataset.stageKey === closing.stageKey && node.dataset.visitIndex === String(closing.visitIndex),
|
||||
);
|
||||
// A pane opened from the Timeline returns to its row; one opened from the Graph
|
||||
// returns to the stage node that opened it (there is no timeline row then).
|
||||
const focusTarget =
|
||||
row ??
|
||||
[...document.querySelectorAll(".graph-node")].find(
|
||||
(candidate) => candidate.dataset.key === closing.stageKey,
|
||||
);
|
||||
focusTarget?.focus();
|
||||
}
|
||||
|
||||
// --- Run-level operator actions (R11–R14) ----------------------------------
|
||||
@@ -856,7 +860,7 @@ function renderArtifactTile(artifact, viewable, viewerIndexOf) {
|
||||
});
|
||||
const openViewer = () => {
|
||||
const at = viewerIndexOf.get(artifact.url);
|
||||
if (at != null) openArtifactViewer(viewable, at);
|
||||
if (at != null) openArtifactViewer(viewable, at, tile);
|
||||
};
|
||||
const openTab = () => {
|
||||
if (resolved) window.open(resolved, "_blank", "noopener,noreferrer");
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
} from "../templates.js";
|
||||
|
||||
export function createTemplatesView(rt) {
|
||||
const { state, repo } = rt;
|
||||
const { state, repo, modal } = rt;
|
||||
const renderContent = (...args) => rt.renderContent(...args);
|
||||
const focusDetailHeading = (...args) => rt.focusDetailHeading(...args);
|
||||
const pushRoute = (...args) => rt.pushRoute(...args);
|
||||
@@ -133,7 +133,6 @@ function openTemplateCreateDialog() {
|
||||
state.templateCreateError = "";
|
||||
state.templateCreateCreated = null;
|
||||
renderContent();
|
||||
document.querySelector(".template-create-name")?.focus();
|
||||
}
|
||||
|
||||
/** Dismiss the create dialog (never while a validate+submit is in flight). */
|
||||
@@ -229,6 +228,11 @@ function renderTemplateCreateDialog(entry) {
|
||||
);
|
||||
panel.append(actions);
|
||||
overlay.append(panel);
|
||||
modal.stage("template-create", overlay, {
|
||||
onClose: () => closeTemplateCreateDialog(),
|
||||
triggerSelector: ".template-create-open",
|
||||
fallbackSelectors: ["#detailTitle", "#pane-main"],
|
||||
});
|
||||
return overlay;
|
||||
}
|
||||
|
||||
|
||||
@@ -285,6 +285,31 @@ export async function launchChrome({ width = 1440, height = 900, chromePath } =
|
||||
{ timeout, what: `text ${JSON.stringify(text)}` },
|
||||
);
|
||||
},
|
||||
/**
|
||||
* Dispatch one real key event pair (Input.dispatchKeyEvent), so the page
|
||||
* sees the same trusted Tab/Escape/Enter a keyboard operator produces.
|
||||
*/
|
||||
async pressKey(key, { shift = false } = {}) {
|
||||
const keys = {
|
||||
Tab: { code: "Tab", windowsVirtualKeyCode: 9 },
|
||||
Escape: { code: "Escape", windowsVirtualKeyCode: 27 },
|
||||
Enter: { code: "Enter", windowsVirtualKeyCode: 13, text: "\r", unmodifiedText: "\r" },
|
||||
" ": { code: "Space", windowsVirtualKeyCode: 32, text: " ", unmodifiedText: " " },
|
||||
ArrowDown: { code: "ArrowDown", windowsVirtualKeyCode: 40 },
|
||||
ArrowUp: { code: "ArrowUp", windowsVirtualKeyCode: 38 },
|
||||
};
|
||||
const info = keys[key] ?? { code: key, windowsVirtualKeyCode: 0 };
|
||||
const base = {
|
||||
key,
|
||||
code: info.code,
|
||||
windowsVirtualKeyCode: info.windowsVirtualKeyCode,
|
||||
nativeVirtualKeyCode: info.windowsVirtualKeyCode,
|
||||
modifiers: shift ? 8 : 0,
|
||||
...(info.text ? { text: info.text, unmodifiedText: info.unmodifiedText } : {}),
|
||||
};
|
||||
await session("Input.dispatchKeyEvent", { type: "keyDown", ...base });
|
||||
await session("Input.dispatchKeyEvent", { type: "keyUp", ...base });
|
||||
},
|
||||
async text() {
|
||||
return api.evaluate("document.body.innerText");
|
||||
},
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
// Focused modal-focus probe: serves web/ on a free port against the live
|
||||
// Pipelines server, then drives the real page in headless Chrome with trusted
|
||||
// key events. It proves the shared controller's contract on the attention
|
||||
// sheet, the retry confirm and the changes viewer, plus one replaced/stacked
|
||||
// overlay (the artifact viewer over a stage pane).
|
||||
//
|
||||
// cd web && node test/modal-probe.mjs --out ../captures
|
||||
//
|
||||
// It is read-only: no run is retried/cancelled/decided, no chat or template is
|
||||
// created or changed. The one PNG is an open state focused from the keyboard.
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import net from "node:net";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { eventually, launchChrome } from "./browser.mjs";
|
||||
|
||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const pipelines = flag(process.argv, "--pipelines", process.env.PIPELINES_TARGET ?? "127.0.0.1:8080");
|
||||
const out = resolve(flag(process.argv, "--out", process.env.WEB_MODAL_OUT ?? resolve(ROOT, "../captures")));
|
||||
const port = flag(process.argv, "--port", process.env.WEB_MODAL_PORT);
|
||||
const settle = (ms = 120) => new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
|
||||
|
||||
function flag(argv, name, fallback) {
|
||||
const index = argv.indexOf(name);
|
||||
return index !== -1 && argv[index + 1] ? argv[index + 1] : fallback;
|
||||
}
|
||||
|
||||
function freePort() {
|
||||
return new Promise((resolvePort) => {
|
||||
const server = net.createServer();
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const { port: bound } = server.address();
|
||||
server.close(() => resolvePort(bound));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const FOCUSABLE = [
|
||||
"a[href]",
|
||||
"button:not([disabled])",
|
||||
"input:not([disabled])",
|
||||
"select:not([disabled])",
|
||||
"textarea:not([disabled])",
|
||||
"[tabindex]:not([tabindex='-1'])",
|
||||
].join(",");
|
||||
|
||||
const focusableList = (selector) => `(() => {
|
||||
const panel = document.querySelector(${JSON.stringify(selector)});
|
||||
if (!panel) return [];
|
||||
return [...panel.querySelectorAll(${JSON.stringify(FOCUSABLE)})].filter((node) =>
|
||||
!node.hidden &&
|
||||
node.getAttribute("aria-hidden") !== "true" &&
|
||||
!node.closest("[inert]") &&
|
||||
getComputedStyle(node).display !== "none" &&
|
||||
getComputedStyle(node).visibility !== "hidden"
|
||||
);
|
||||
})()`;
|
||||
|
||||
const activeId = () =>
|
||||
page.evaluate(`(() => {
|
||||
const active = document.activeElement;
|
||||
if (!active) return "";
|
||||
return active.id || active.getAttribute("data-change-index") || active.className || active.tagName;
|
||||
})()`);
|
||||
|
||||
const inertState = () =>
|
||||
page.evaluate(`(() => ({
|
||||
appRoot: document.querySelector(".app-root")?.hasAttribute("inert") ?? false,
|
||||
skipHidden: document.querySelector(".skip-link")?.getAttribute("aria-hidden") ?? null,
|
||||
skipTabindex: document.querySelector(".skip-link")?.getAttribute("tabindex") ?? null,
|
||||
skipInert: document.querySelector(".skip-link")?.hasAttribute("inert") ?? false,
|
||||
}))()`);
|
||||
|
||||
const insideDialog = (selector) =>
|
||||
page.evaluate(`(() => {
|
||||
const panel = document.querySelector(${JSON.stringify(selector)});
|
||||
return Boolean(panel && panel.contains(document.activeElement));
|
||||
})()`);
|
||||
|
||||
async function wrapCheck(selector, label) {
|
||||
const count = await page.evaluate(`${focusableList(selector)}.length`);
|
||||
if (!count) throw new Error(`${label}: no focusable control in the dialog`);
|
||||
await page.evaluate(`(() => {
|
||||
const list = ${focusableList(selector)};
|
||||
list[list.length - 1].focus();
|
||||
})()`);
|
||||
await page.pressKey("Tab");
|
||||
const afterTab = await page.evaluate(`(() => {
|
||||
const list = ${focusableList(selector)};
|
||||
return list.indexOf(document.activeElement);
|
||||
})()`);
|
||||
if (afterTab !== 0) throw new Error(`${label}: Tab from the last control landed on index ${afterTab}`);
|
||||
await page.pressKey("Tab", { shift: true });
|
||||
const afterShift = await page.evaluate(`(() => {
|
||||
const list = ${focusableList(selector)};
|
||||
return list.indexOf(document.activeElement);
|
||||
})()`);
|
||||
const last = count - 1;
|
||||
if (afterShift !== last) {
|
||||
throw new Error(`${label}: Shift+Tab from the first control landed on index ${afterShift}, expected ${last}`);
|
||||
}
|
||||
console.log(` ${label}: ${count} controls; Tab last->first and Shift+Tab first->last`);
|
||||
}
|
||||
|
||||
async function assertInert(label) {
|
||||
const state = await inertState();
|
||||
if (!state.appRoot) throw new Error(`${label}: .app-root is not inert while the dialog is open`);
|
||||
return state;
|
||||
}
|
||||
|
||||
async function assertRestored(label, prior) {
|
||||
const state = await inertState();
|
||||
if (state.appRoot) throw new Error(`${label}: .app-root stayed inert after close`);
|
||||
if (state.skipHidden !== prior.skipHidden || state.skipTabindex !== prior.skipTabindex) {
|
||||
throw new Error(`${label}: skip-link state was not restored exactly: ${JSON.stringify({ before: prior, after: state })}`);
|
||||
}
|
||||
console.log(` ${label}: app root and skip link restored exactly`);
|
||||
}
|
||||
|
||||
async function openRun(id) {
|
||||
const detail = `.run-detail .run-identity`;
|
||||
await eventually(() => page.evaluate(`document.querySelector(${JSON.stringify(detail)})?.textContent?.includes("run ${id} ") ?? false`), {
|
||||
timeout: 25000,
|
||||
what: `run ${id} detail`,
|
||||
});
|
||||
}
|
||||
|
||||
let serve = null;
|
||||
let browser = null;
|
||||
let page = null;
|
||||
|
||||
try {
|
||||
await mkdir(out, { recursive: true });
|
||||
const webPort = port ? Number(port) : await freePort();
|
||||
console.log(`• serving web/ on 127.0.0.1:${webPort} (proxy /connect -> ${pipelines})`);
|
||||
serve = spawn(process.execPath, ["serve.mjs", "--port", String(webPort), "--pipelines", pipelines], {
|
||||
cwd: ROOT,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let serveLog = "";
|
||||
serve.stdout.on("data", (chunk) => (serveLog += chunk.toString()));
|
||||
serve.stderr.on("data", (chunk) => (serveLog += chunk.toString()));
|
||||
await eventually(
|
||||
async () => {
|
||||
if (serve.exitCode != null) throw new Error(`serve.mjs exited: ${serveLog.trim().slice(-400)}`);
|
||||
const response = await fetch(`http://127.0.0.1:${webPort}/`).catch(() => null);
|
||||
return response?.ok;
|
||||
},
|
||||
{ what: "the page to be served" },
|
||||
);
|
||||
|
||||
console.log("• launching headless Chrome");
|
||||
browser = await launchChrome({ width: 1440, height: 900 });
|
||||
page = await browser.openPage();
|
||||
await page.addInitScript(`(() => {
|
||||
localStorage.setItem("pipelines.web.serverUrl.v2", "ws://127.0.0.1:${webPort}/connect");
|
||||
localStorage.removeItem("pipelines.web.attention.v1");
|
||||
localStorage.removeItem("pipelines.web.workspace.v1");
|
||||
})()`);
|
||||
const pageUrl = `http://127.0.0.1:${webPort}/`;
|
||||
await page.goto(pageUrl);
|
||||
await page.waitForSelector('#shellStatus[data-state="connected"]', { timeout: 30000 });
|
||||
const runsClicked = await page.evaluate(`(() => {
|
||||
const all = [...document.querySelectorAll('[data-destination="runs"]')];
|
||||
const control = all.find((node) => node.offsetParent !== null) ?? all[0];
|
||||
if (!control) return false;
|
||||
control.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!runsClicked) throw new Error("no Runs destination control");
|
||||
await page.waitForSelector(".list.runs .run-row", { timeout: 30000 });
|
||||
|
||||
const prior = await inertState();
|
||||
console.log(`• attention sheet (prior app inert=${prior.appRoot}, skip aria-hidden=${prior.skipHidden})`);
|
||||
await page.waitForSelector("#attentionBell", { timeout: 15000 });
|
||||
const bellCount = await page.evaluate(
|
||||
`Number(document.querySelector("#attentionBell .attention-badge")?.dataset.count ?? 0)`,
|
||||
);
|
||||
if (!(bellCount > 0)) throw new Error("the live server has no attention entries to open");
|
||||
await page.evaluate(`document.querySelector("#attentionBell").focus()`);
|
||||
await page.pressKey("Enter");
|
||||
await page.waitForSelector(".attention-sheet", { timeout: 10000 });
|
||||
await settle();
|
||||
await assertInert("attention open");
|
||||
if (!(await insideDialog(".attention-sheet"))) {
|
||||
throw new Error("attention sheet: focus is outside the panel after open");
|
||||
}
|
||||
if (await page.evaluate(`!!document.querySelector(".attention-sheet [inert]")`)) {
|
||||
throw new Error("attention sheet: its own controls are inert");
|
||||
}
|
||||
const capture = `${out}/86-modal-focus-attention.png`;
|
||||
await page.screenshot(capture);
|
||||
console.log(` capture ${capture}`);
|
||||
await wrapCheck(".attention-sheet", "attention sheet");
|
||||
await page.pressKey("Escape");
|
||||
await eventually(() => page.evaluate(`!document.querySelector(".attention-sheet")`), {
|
||||
timeout: 5000,
|
||||
what: "the attention sheet to close",
|
||||
});
|
||||
const afterAttention = await activeId();
|
||||
if (afterAttention !== "attentionBell") {
|
||||
throw new Error(`attention sheet: Escape returned focus to ${afterAttention || "body"}, not #attentionBell`);
|
||||
}
|
||||
await assertRestored("attention close", prior);
|
||||
|
||||
console.log("• retry confirm (run 440)");
|
||||
await page.goto(`${pageUrl}runs/440`);
|
||||
await page.waitForSelector(".run-detail .run-actions .retry-run", { timeout: 25000 });
|
||||
await openRun(440);
|
||||
await page.evaluate(`document.querySelector(".run-detail .run-actions .retry-run").focus()`);
|
||||
await page.pressKey("Enter");
|
||||
await page.waitForSelector(".confirm-dialog.confirm-retry", { timeout: 10000 });
|
||||
await settle();
|
||||
await assertInert("retry confirm open");
|
||||
if (!(await insideDialog(".confirm-dialog.confirm-retry"))) {
|
||||
throw new Error("retry confirm: focus is outside the panel after open");
|
||||
}
|
||||
await wrapCheck(".confirm-dialog.confirm-retry", "retry confirm");
|
||||
await page.pressKey("Escape");
|
||||
await eventually(() => page.evaluate(`!document.querySelector(".confirm-dialog.confirm-retry")`), {
|
||||
timeout: 5000,
|
||||
what: "the retry confirm to close",
|
||||
});
|
||||
await settle();
|
||||
const afterConfirm = await activeId();
|
||||
if (!String(afterConfirm).includes("retry-run")) {
|
||||
throw new Error(`retry confirm: Escape returned focus to ${afterConfirm || "body"}, not .retry-run`);
|
||||
}
|
||||
await assertRestored("retry confirm close", prior);
|
||||
|
||||
console.log("• changes viewer (run 438)");
|
||||
await page.goto(`${pageUrl}runs/438`);
|
||||
await page.waitForSelector("#detailTitle", { timeout: 25000 });
|
||||
await openRun(438);
|
||||
const expanded = await page.evaluate(`(() => {
|
||||
const toggle = [...document.querySelectorAll(".run-detail .collapsible .section-toggle")]
|
||||
.find((node) => /\\d+ files? changed/.test(node.querySelector(".section-title")?.textContent ?? ""));
|
||||
if (!toggle) return false;
|
||||
toggle.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!expanded) throw new Error("changes viewer: no Changes section on run 438");
|
||||
await page.waitForSelector(".run-detail .changes-list .change-row", { timeout: 15000 });
|
||||
await page.evaluate(`(() => {
|
||||
const row = document.querySelector(".run-detail .changes-list .change-row");
|
||||
row.scrollIntoView({ block: "center" });
|
||||
row.focus();
|
||||
})()`);
|
||||
await page.pressKey("Enter");
|
||||
await page.waitForSelector(".change-viewer", { timeout: 10000 });
|
||||
await settle();
|
||||
await assertInert("changes viewer open");
|
||||
if (!(await insideDialog(".change-viewer"))) {
|
||||
throw new Error("changes viewer: focus is outside the panel after open");
|
||||
}
|
||||
await wrapCheck(".change-viewer", "changes viewer");
|
||||
await page.pressKey("Escape");
|
||||
await eventually(() => page.evaluate(`!document.querySelector(".change-viewer")`), {
|
||||
timeout: 5000,
|
||||
what: "the changes viewer to close",
|
||||
});
|
||||
const afterChanges = await activeId();
|
||||
if (afterChanges !== "0") {
|
||||
throw new Error(`changes viewer: Escape returned focus to ${afterChanges || "body"}, not change row 0`);
|
||||
}
|
||||
await assertRestored("changes viewer close", prior);
|
||||
|
||||
console.log("• stacking: artifact viewer over the stage pane (run 440)");
|
||||
await page.goto(`${pageUrl}runs/440`);
|
||||
await page.waitForSelector("#detailTitle", { timeout: 25000 });
|
||||
await openRun(440);
|
||||
const timelineClicked = await page.evaluate(`(() => {
|
||||
const tab = [...document.querySelectorAll(".rail-tab, .strip-tab")]
|
||||
.find((node) => node.offsetParent !== null && node.textContent.trim() === "Timeline");
|
||||
if (!tab) return false;
|
||||
tab.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!timelineClicked) throw new Error("stacking: no Timeline tab");
|
||||
await page.waitForSelector(".run-detail .timeline-row", { timeout: 15000 });
|
||||
await page.evaluate(`document.querySelector(".run-detail .timeline-row").focus()`);
|
||||
await page.pressKey("Enter");
|
||||
await page.waitForSelector(".stage-pane", { timeout: 10000 });
|
||||
const openedArtifacts = await page.evaluate(`(() => {
|
||||
const toggle = [...document.querySelectorAll(".stage-pane .section-toggle")]
|
||||
.find((node) => node.querySelector(".section-title")?.textContent?.trim().startsWith("Artifacts"));
|
||||
if (!toggle) return false;
|
||||
toggle.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!openedArtifacts) throw new Error("stacking: no Artifacts section in the stage pane");
|
||||
await page.waitForSelector(".stage-pane .artifact-grid button.artifact-tile", { timeout: 10000 });
|
||||
await page.evaluate(`(() => {
|
||||
const tiles = [...document.querySelectorAll(".stage-pane .artifact-grid button.artifact-tile")];
|
||||
const tile = tiles.find((node) => node.querySelector("img")) ?? tiles[0];
|
||||
tile.scrollIntoView({ block: "center" });
|
||||
tile.focus();
|
||||
})()`);
|
||||
await page.pressKey("Enter");
|
||||
await page.waitForSelector(".artifact-viewer", { timeout: 10000 });
|
||||
await settle();
|
||||
const stack = await page.evaluate(`(() => ({
|
||||
lower: document.querySelector(".stage-pane")?.hasAttribute("inert") ?? false,
|
||||
upper: document.querySelector(".artifact-viewer")?.hasAttribute("inert") ?? false,
|
||||
activeInsideUpper: document.querySelector(".artifact-viewer")?.contains(document.activeElement) ?? false,
|
||||
appRoot: document.querySelector(".app-root")?.hasAttribute("inert") ?? false,
|
||||
}))()`);
|
||||
if (!stack.lower) throw new Error("stacking: the lower stage pane is still tabbable while the viewer is open");
|
||||
if (stack.upper) throw new Error("stacking: the top artifact viewer is inert");
|
||||
if (!stack.activeInsideUpper) throw new Error("stacking: focus is not inside the top artifact viewer");
|
||||
if (!stack.appRoot) throw new Error("stacking: the app root is not inert under both dialogs");
|
||||
await page.pressKey("Escape");
|
||||
await eventually(() => page.evaluate(`!document.querySelector(".artifact-viewer")`), {
|
||||
timeout: 5000,
|
||||
what: "the artifact viewer to close",
|
||||
});
|
||||
const lowerRestored = await page.evaluate(`(() => ({
|
||||
lowerInert: document.querySelector(".stage-pane")?.hasAttribute("inert") ?? false,
|
||||
activeInsideLower: document.querySelector(".stage-pane")?.contains(document.activeElement) ?? false,
|
||||
appRoot: document.querySelector(".app-root")?.hasAttribute("inert") ?? false,
|
||||
}))()`);
|
||||
if (lowerRestored.lowerInert) throw new Error("stacking: the stage pane stayed inert after the viewer closed");
|
||||
if (!lowerRestored.activeInsideLower) throw new Error("stacking: focus did not return into the stage pane");
|
||||
if (!lowerRestored.appRoot) throw new Error("stacking: the app root lost inert while the stage pane remained open");
|
||||
await page.pressKey("Escape");
|
||||
await eventually(() => page.evaluate(`!document.querySelector(".stage-pane")`), {
|
||||
timeout: 5000,
|
||||
what: "the stage pane to close",
|
||||
});
|
||||
const afterStack = await page.evaluate(`(() => ({
|
||||
activeRow: document.activeElement?.getAttribute("data-stage-key") ?? "",
|
||||
appRoot: document.querySelector(".app-root")?.hasAttribute("inert") ?? false,
|
||||
}))()`);
|
||||
if (!afterStack.activeRow) throw new Error("stacking: focus was not returned to the timeline row");
|
||||
if (afterStack.appRoot) throw new Error("stacking: the app root stayed inert after the last close");
|
||||
console.log(` artifact viewer -> stage pane -> timeline row (${afterStack.activeRow}); app root restored`);
|
||||
|
||||
console.log("\nMODAL PROBE PASS");
|
||||
} finally {
|
||||
await page?.close().catch(() => {});
|
||||
await browser?.close().catch(() => {});
|
||||
if (serve) {
|
||||
serve.kill("SIGTERM");
|
||||
await eventually(async () => serve.exitCode != null || serve.signalCode != null, {
|
||||
timeout: 5000,
|
||||
what: "serve.mjs exit",
|
||||
}).catch(() => {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
// Focused unit tests for the shared modal controller. A tiny DOM stub gives the
|
||||
// controller the same surface it uses in the browser (attributes, children,
|
||||
// focus and document listeners) without a test dependency or a live server.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
createModalController,
|
||||
focusableElements,
|
||||
initialFocusIndex,
|
||||
isFocusable,
|
||||
wrapFocusIndex,
|
||||
} from "../src/modal.js";
|
||||
|
||||
class FakeElement {
|
||||
constructor(tag = "div", document_ = null) {
|
||||
this.tagName = tag.toUpperCase();
|
||||
this.ownerDocument = document_;
|
||||
this.nodeType = 1;
|
||||
this.attributes = new Map();
|
||||
this.children = [];
|
||||
this.parentElement = null;
|
||||
this.isConnected = false;
|
||||
this.hidden = false;
|
||||
this.disabled = false;
|
||||
this.textContent = "";
|
||||
}
|
||||
|
||||
getAttribute(name) {
|
||||
return this.attributes.has(name) ? this.attributes.get(name) : null;
|
||||
}
|
||||
|
||||
setAttribute(name, value) {
|
||||
this.attributes.set(name, String(value));
|
||||
}
|
||||
|
||||
hasAttribute(name) {
|
||||
return this.attributes.has(name);
|
||||
}
|
||||
|
||||
removeAttribute(name) {
|
||||
this.attributes.delete(name);
|
||||
}
|
||||
|
||||
append(...nodes) {
|
||||
for (const node of nodes) {
|
||||
if (node.parentElement) node.remove();
|
||||
node.parentElement = this;
|
||||
node.isConnected = true;
|
||||
this.children.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
replaceChildren(...nodes) {
|
||||
for (const child of this.children) {
|
||||
child.parentElement = null;
|
||||
child.isConnected = false;
|
||||
}
|
||||
this.children = [];
|
||||
this.append(...nodes);
|
||||
}
|
||||
|
||||
replaceWith(next) {
|
||||
const parent = this.parentElement;
|
||||
if (!parent) return;
|
||||
const index = parent.children.indexOf(this);
|
||||
if (index === -1) return;
|
||||
parent.children[index] = next;
|
||||
next.parentElement = parent;
|
||||
next.isConnected = true;
|
||||
this.parentElement = null;
|
||||
this.isConnected = false;
|
||||
}
|
||||
|
||||
remove() {
|
||||
const parent = this.parentElement;
|
||||
if (!parent) return;
|
||||
const index = parent.children.indexOf(this);
|
||||
if (index !== -1) parent.children.splice(index, 1);
|
||||
this.parentElement = null;
|
||||
this.isConnected = false;
|
||||
}
|
||||
|
||||
contains(node) {
|
||||
if (node === this) return true;
|
||||
return this.children.some((child) => child.contains(node));
|
||||
}
|
||||
|
||||
querySelectorAll() {
|
||||
const found = [];
|
||||
const walk = (element) => {
|
||||
for (const child of element.children) {
|
||||
found.push(child);
|
||||
walk(child);
|
||||
}
|
||||
};
|
||||
walk(this);
|
||||
return found;
|
||||
}
|
||||
|
||||
querySelector(selector) {
|
||||
return this.querySelectorAll(selector)[0] ?? null;
|
||||
}
|
||||
|
||||
matches(selector) {
|
||||
if (selector === "a[href]") return this.tagName === "A" && this.hasAttribute("href");
|
||||
if (selector === "button") return this.tagName === "BUTTON";
|
||||
if (selector === "[tabindex]") return this.hasAttribute("tabindex");
|
||||
return false;
|
||||
}
|
||||
|
||||
focus() {
|
||||
this.ownerDocument.activeElement = this;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeDocument {
|
||||
constructor() {
|
||||
this.body = new FakeElement("body", this);
|
||||
this.body.isConnected = true;
|
||||
this.activeElement = this.body;
|
||||
this.byId = new Map();
|
||||
this.bySelector = new Map();
|
||||
this.listeners = new Map();
|
||||
this.defaultView = { getComputedStyle: () => ({ display: "block", visibility: "visible" }) };
|
||||
}
|
||||
|
||||
createElement(tag) {
|
||||
return new FakeElement(tag, this);
|
||||
}
|
||||
|
||||
register(selector, element) {
|
||||
if (selector.startsWith("#")) this.byId.set(selector.slice(1), element);
|
||||
this.bySelector.set(selector, element);
|
||||
return element;
|
||||
}
|
||||
|
||||
getElementById(id) {
|
||||
return this.byId.get(id) ?? null;
|
||||
}
|
||||
|
||||
querySelector(selector) {
|
||||
return this.bySelector.get(selector) ?? null;
|
||||
}
|
||||
|
||||
querySelectorAll(selector) {
|
||||
const element = this.bySelector.get(selector);
|
||||
return element ? [element] : [];
|
||||
}
|
||||
|
||||
addEventListener(type, listener, capture = false) {
|
||||
const key = `${type}:${capture ? "capture" : "bubble"}`;
|
||||
const list = this.listeners.get(key) ?? [];
|
||||
list.push(listener);
|
||||
this.listeners.set(key, list);
|
||||
}
|
||||
|
||||
removeEventListener(type, listener, capture = false) {
|
||||
const key = `${type}:${capture ? "capture" : "bubble"}`;
|
||||
const list = this.listeners.get(key) ?? [];
|
||||
this.listeners.set(
|
||||
key,
|
||||
list.filter((candidate) => candidate !== listener),
|
||||
);
|
||||
}
|
||||
|
||||
listenerCount(type, capture = false) {
|
||||
return (this.listeners.get(`${type}:${capture ? "capture" : "bubble"}`) ?? []).length;
|
||||
}
|
||||
|
||||
dispatch(type, event, capture = false) {
|
||||
for (const listener of [...(this.listeners.get(`${type}:${capture ? "capture" : "bubble"}`) ?? [])]) {
|
||||
listener(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function harness({ fallback = false } = {}) {
|
||||
const document_ = new FakeDocument();
|
||||
const root = document_.register(".app-root", new FakeElement("div", document_));
|
||||
document_.body.append(root);
|
||||
const skip = document_.register(".skip-link", new FakeElement("a", document_));
|
||||
skip.setAttribute("href", "#main");
|
||||
document_.body.append(skip);
|
||||
const layer = new FakeElement("div", document_);
|
||||
document_.body.append(layer);
|
||||
const title = document_.register("#detailTitle", new FakeElement("h1", document_));
|
||||
title.setAttribute("tabindex", "-1");
|
||||
root.append(title);
|
||||
const pane = document_.register("#pane-main", new FakeElement("div", document_));
|
||||
pane.setAttribute("tabindex", "-1");
|
||||
root.append(pane);
|
||||
|
||||
const controller = createModalController({
|
||||
document: document_,
|
||||
layer,
|
||||
background: root,
|
||||
skipLinks: [skip],
|
||||
supportsInert: () => !fallback,
|
||||
fallbackSelectors: ["#detailTitle", "#pane-main"],
|
||||
});
|
||||
return { document_, root, skip, layer, title, controller };
|
||||
}
|
||||
|
||||
function button(document_, text, props = {}) {
|
||||
const node = new FakeElement("button", document_);
|
||||
node.textContent = text;
|
||||
node.tagName = "BUTTON";
|
||||
for (const [key, value] of Object.entries(props)) {
|
||||
if (key === "disabled") node.disabled = value;
|
||||
else if (key === "hidden") node.hidden = value;
|
||||
else node.setAttribute(key, value);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
function panelWith(document_, ...controls) {
|
||||
const panel = new FakeElement("div", document_);
|
||||
panel.setAttribute("role", "dialog");
|
||||
panel.append(...controls);
|
||||
return panel;
|
||||
}
|
||||
|
||||
test("focusable discovery keeps DOM order and excludes every unreachable form", () => {
|
||||
const document_ = new FakeDocument();
|
||||
const panel = new FakeElement("div", document_);
|
||||
const first = button(document_, "first");
|
||||
const disabled = button(document_, "disabled", { disabled: true });
|
||||
const hidden = button(document_, "hidden", { hidden: true });
|
||||
const ariaHidden = button(document_, "aria hidden", { "aria-hidden": "true" });
|
||||
const inert = button(document_, "inert", { inert: "" });
|
||||
const negative = button(document_, "negative", { tabindex: "-1" });
|
||||
const nested = new FakeElement("div", document_);
|
||||
nested.setAttribute("aria-hidden", "true");
|
||||
nested.append(button(document_, "nested"));
|
||||
const last = button(document_, "last");
|
||||
panel.append(first, disabled, hidden, ariaHidden, inert, negative, nested, last);
|
||||
|
||||
assert.deepEqual(
|
||||
focusableElements(panel).map((node) => node.textContent),
|
||||
["first", "last"],
|
||||
);
|
||||
assert.equal(isFocusable(first, { root: panel }), true);
|
||||
assert.equal(isFocusable(disabled, { root: panel }), false);
|
||||
assert.equal(isFocusable(negative, { root: panel }), false);
|
||||
});
|
||||
|
||||
test("Tab and Shift+Tab arithmetic wraps in both directions", () => {
|
||||
assert.equal(wrapFocusIndex(2, 1, 3), 0);
|
||||
assert.equal(wrapFocusIndex(0, -1, 3), 2);
|
||||
assert.equal(wrapFocusIndex(1, 1, 3), 2);
|
||||
assert.equal(wrapFocusIndex(1, -1, 3), 0);
|
||||
assert.equal(wrapFocusIndex(-1, 1, 3), 0);
|
||||
assert.equal(wrapFocusIndex(-1, -1, 3), 2);
|
||||
assert.equal(wrapFocusIndex(0, 1, 0), -1);
|
||||
assert.equal(initialFocusIndex(0), -1);
|
||||
assert.equal(initialFocusIndex(2), 0);
|
||||
});
|
||||
|
||||
test("a panel with no focusable control focuses the panel itself", () => {
|
||||
const { document_, layer, controller } = harness();
|
||||
const panel = panelWith(document_, button(document_, "disabled", { disabled: true }));
|
||||
controller.open("empty", panel);
|
||||
assert.equal(document_.activeElement, panel);
|
||||
assert.equal(panel.getAttribute("tabindex"), "-1");
|
||||
assert.equal(layer.children.includes(panel), true);
|
||||
controller.close("empty");
|
||||
assert.equal(document_.activeElement, document_.getElementById("detailTitle"));
|
||||
});
|
||||
|
||||
test("opening the same id twice keeps one trigger and one set of listeners", () => {
|
||||
const { document_, title, controller } = harness();
|
||||
const trigger = button(document_, "open");
|
||||
title.append(trigger);
|
||||
trigger.focus();
|
||||
const first = panelWith(document_, button(document_, "a"));
|
||||
controller.open("same", first, { onClose: () => {} });
|
||||
assert.equal(document_.listenerCount("keydown"), 1);
|
||||
const second = panelWith(document_, button(document_, "b"));
|
||||
const other = button(document_, "other");
|
||||
title.append(other);
|
||||
other.focus();
|
||||
controller.open("same", second, { onClose: () => {} });
|
||||
assert.equal(document_.listenerCount("keydown"), 1);
|
||||
assert.equal(controller.stackIds().length, 1);
|
||||
controller.close("same");
|
||||
assert.equal(document_.activeElement, trigger, "the original opener is still the return target");
|
||||
assert.equal(controller.listenerState().keydown, false);
|
||||
});
|
||||
|
||||
test("a same-id re-render replaces the panel and keeps the focused control", () => {
|
||||
const { document_, title, controller } = harness();
|
||||
const trigger = button(document_, "trigger");
|
||||
title.append(trigger);
|
||||
trigger.focus();
|
||||
const firstPanel = panelWith(document_, button(document_, "one"), button(document_, "two"));
|
||||
controller.open("same", firstPanel, { onClose: () => {} });
|
||||
const second = firstPanel.children[1];
|
||||
second.focus();
|
||||
const replacement = panelWith(document_, button(document_, "one again"), button(document_, "two again"));
|
||||
controller.open("same", replacement, { onClose: () => {} });
|
||||
assert.equal(controller.stackIds().length, 1);
|
||||
assert.equal(document_.activeElement.textContent, "two again");
|
||||
controller.close("same");
|
||||
assert.equal(document_.activeElement, trigger);
|
||||
});
|
||||
|
||||
test("a second overlay inerts the first and closing it restores the first", () => {
|
||||
const { document_, root, skip, title, controller } = harness();
|
||||
const firstTrigger = button(document_, "first trigger");
|
||||
title.append(firstTrigger);
|
||||
firstTrigger.focus();
|
||||
const first = panelWith(document_, button(document_, "first control"));
|
||||
controller.open("first", first);
|
||||
|
||||
assert.equal(root.getAttribute("inert"), "");
|
||||
assert.equal(skip.getAttribute("aria-hidden"), "true");
|
||||
|
||||
const secondTrigger = button(document_, "second trigger");
|
||||
title.append(secondTrigger);
|
||||
secondTrigger.focus();
|
||||
const second = panelWith(document_, button(document_, "second control"));
|
||||
controller.open("second", second);
|
||||
assert.equal(first.getAttribute("inert"), "");
|
||||
assert.equal(second.hasAttribute("inert"), false);
|
||||
assert.deepEqual(controller.stackIds(), ["first", "second"]);
|
||||
|
||||
controller.close("second");
|
||||
assert.equal(first.hasAttribute("inert"), false, "the lower panel is interactive again");
|
||||
assert.equal(root.getAttribute("inert"), "");
|
||||
assert.equal(controller.isOpen("first"), true);
|
||||
|
||||
controller.close("first");
|
||||
assert.equal(root.hasAttribute("inert"), false);
|
||||
assert.equal(skip.hasAttribute("aria-hidden"), false);
|
||||
assert.equal(controller.listenerState().keydown, false);
|
||||
});
|
||||
|
||||
test("native inert and aria-hidden/tabindex restore the exact prior values", () => {
|
||||
const { document_, root, skip, controller } = harness();
|
||||
root.setAttribute("inert", "kept");
|
||||
skip.setAttribute("aria-hidden", "false");
|
||||
const trigger = button(document_, "trigger");
|
||||
root.append(trigger);
|
||||
trigger.focus();
|
||||
controller.open("exact", panelWith(document_, button(document_, "ok")));
|
||||
controller.close("exact");
|
||||
assert.equal(root.getAttribute("inert"), "kept");
|
||||
assert.equal(skip.getAttribute("aria-hidden"), "false");
|
||||
});
|
||||
|
||||
test("the no-inert fallback hides the background, removes its tab stops and restores them", () => {
|
||||
const { document_, root, skip, controller } = harness({ fallback: true });
|
||||
const first = button(document_, "one", { tabindex: "3" });
|
||||
const second = button(document_, "two");
|
||||
const trigger = button(document_, "trigger");
|
||||
root.append(first, second, trigger);
|
||||
trigger.focus();
|
||||
|
||||
controller.open("fallback", panelWith(document_, button(document_, "inside")));
|
||||
assert.equal(root.getAttribute("aria-hidden"), "true");
|
||||
assert.equal(skip.getAttribute("aria-hidden"), "true");
|
||||
assert.equal(first.getAttribute("tabindex"), "-1");
|
||||
assert.equal(second.getAttribute("tabindex"), "-1");
|
||||
assert.equal(document_.listenerCount("keydown"), 1);
|
||||
assert.equal(document_.listenerCount("focusin", true), 1);
|
||||
|
||||
controller.close("fallback");
|
||||
assert.equal(root.hasAttribute("aria-hidden"), false);
|
||||
assert.equal(skip.hasAttribute("aria-hidden"), false);
|
||||
assert.equal(first.getAttribute("tabindex"), "3");
|
||||
assert.equal(second.hasAttribute("tabindex"), false);
|
||||
assert.equal(document_.listenerCount("keydown"), 0);
|
||||
assert.equal(document_.listenerCount("focusin", true), 0);
|
||||
});
|
||||
|
||||
test("Tab from the last control wraps to the first; Shift+Tab wraps back", () => {
|
||||
const { document_, title, controller } = harness();
|
||||
const trigger = button(document_, "trigger");
|
||||
title.append(trigger);
|
||||
trigger.focus();
|
||||
const first = button(document_, "first");
|
||||
const last = button(document_, "last");
|
||||
controller.open("trap", panelWith(document_, first, last));
|
||||
|
||||
last.focus();
|
||||
const tab = {
|
||||
key: "Tab",
|
||||
shiftKey: false,
|
||||
defaultPrevented: false,
|
||||
preventDefault() {
|
||||
this.defaultPrevented = true;
|
||||
},
|
||||
stopPropagation() {},
|
||||
};
|
||||
document_.dispatch("keydown", tab);
|
||||
assert.equal(document_.activeElement, first);
|
||||
|
||||
const shiftTab = {
|
||||
key: "Tab",
|
||||
shiftKey: true,
|
||||
defaultPrevented: false,
|
||||
preventDefault() {
|
||||
this.defaultPrevented = true;
|
||||
},
|
||||
stopPropagation() {},
|
||||
};
|
||||
document_.dispatch("keydown", shiftTab);
|
||||
assert.equal(document_.activeElement, last);
|
||||
});
|
||||
|
||||
test("Escape closes through the supplied callback and returns focus", () => {
|
||||
const { document_, title, controller } = harness();
|
||||
const trigger = button(document_, "trigger");
|
||||
title.append(trigger);
|
||||
trigger.focus();
|
||||
let closed = 0;
|
||||
controller.open("escape", panelWith(document_, button(document_, "ok")), {
|
||||
onClose: () => {
|
||||
closed += 1;
|
||||
controller.close("escape");
|
||||
},
|
||||
});
|
||||
const escape = {
|
||||
key: "Escape",
|
||||
defaultPrevented: false,
|
||||
preventDefault() {},
|
||||
stopPropagation() {},
|
||||
};
|
||||
document_.dispatch("keydown", escape);
|
||||
assert.equal(closed, 1);
|
||||
assert.equal(controller.isOpen("escape"), false);
|
||||
assert.equal(document_.activeElement, trigger);
|
||||
});
|
||||
Reference in New Issue
Block a user