web: shared modal focus controller (M1/M2) — work in progress

This commit is contained in:
2026-10-19 20:46:15 +01:00
parent a7991077d2
commit b1e9400d6e
11 changed files with 1562 additions and 121 deletions
+27 -54
View File
@@ -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;
+631
View File
@@ -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 }),
};
}
+12 -4
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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");
+6 -2
View File
@@ -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;
}