Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion frontend/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { submitSetupCode, setupCodeKey, useOllama, hideOnboarding, onSetupCurato
import { activityTabKey, cancelTask, loadScheduled, loadTaskHistory, reloadPage, runScheduledJob, setHistoryFilter, showActivityTab, showNoopRuns, toggleHideNoop } from './activity.js';
import { checkMappingCoverage, closeKbDrilldown, kbDismissFinding, kbFixMatch, kbIgnore, kbRetry, kbUnignore, loadCacheInventory, loadEnrichStatus, loadKbAttention, loadKbItems, loadMappingStats, loadProfiles, runMaintenance, showKbTab, startBackfill, startSprint, stopBackfill, stopSprint } from './kb.js';
import { checkOrphans, loadLibraryConfig, saveLibraries, searchOnEnter } from './libraries.js';
import { _errMsg, activeDialog, closeMenus, syncTabRoles, closeModal, toggleMenu, keyActivate, hideOnError, onPageLoad, posterLoaded, toast, trapFocus } from './ui.js';
import { _errMsg, activeDialog, closeMenus, syncTabRoles, tabRowKey, closeModal, toggleMenu, keyActivate, hideOnError, onPageLoad, posterLoaded, toast, trapFocus } from './ui.js';
import { condensePrinciples, downscaleDone, liftProtection, loadDownscale, loadJudgeProtections, loadPrinciples, loadRedundancy, loadUpgrades, setPrinciple, shutdownServer, curationSection, checkUncensored } from './curation.js';
import { answerFollowup, askTonight, correctChatAnchor, explainFollowup, hideMoment, hideTonight, momentPlaylist, titleKeep, titleWatchlist, tonightNext, tonightWatchlist, deleteFromDiscussion, discussLastPlayed, exitDiscussion, fillPrompt, handleKey, hideFollowup, jumpLatest, newChat, onApplyOrphanRepair, onDiscussDeletion, onDiscussRec, saveComment, sendMessage, useStarter } from './chat.js';
import { discussPrinciple, loadUnreadMessages, respondToMessage, skipMessage, toggleMsgPanel } from './notifications.js';
Expand Down Expand Up @@ -103,6 +103,7 @@ window.addEventListener('storage', ev => {
});
document.addEventListener('keydown', ev => {
if (ev.key === 'Tab') { trapFocus(ev, activeDialog()); return; }
tabRowKey(ev);
if (ev.key !== 'Escape') return;
const menu = document.querySelector('.menu.open');
if (menu) { // innermost layer first; focus back on its button
Expand Down
2 changes: 2 additions & 0 deletions frontend/js/swipe.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,10 @@ export function swipeCategory(cat) {
function _renderTabs() {
const el = _el('swipe-tabs');
if (!el) return;
const had = el.contains(document.activeElement); // the redraw would drop a keyboard user's focus
el.innerHTML = _cats().map(([c, label]) =>
`<button class="cat-tab${c === _cat ? ' active' : ''}" role="tab" aria-selected="${c === _cat}" ${act('swipeCategory', c)}>${esc(label)}</button>`).join('');
if (had) el.querySelector('.cat-tab.active')?.focus();
}

function _renderReactions() {
Expand Down
21 changes: 21 additions & 0 deletions frontend/js/ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -471,9 +471,30 @@ export function syncTabRoles(root = document) {
tab.setAttribute('role', 'tab');
tab.setAttribute('aria-selected', String(tab.classList.contains('active')));
}
// One Tab stop per row, on the chosen tab; the arrows move along it.
const tabs = [...list.querySelectorAll(':scope > [role="tab"]')];
const stop = tabs.find(x => x.classList.contains('active')) || tabs.find(x => !x.hidden);
for (const tab of tabs) tab.tabIndex = tab === stop ? 0 : -1;
}
}

// Arrow keys, Home and End move focus along a tab row (WAI-ARIA tabs,
// manual activation: Enter or Space picks the tab, as the button already
// does). Activity's own row has its handler and is left to it.
export function tabRowKey(ev) {
const keys = ['ArrowRight', 'ArrowLeft', 'Home', 'End'];
if (!keys.includes(ev.key) || ev.altKey || ev.ctrlKey || ev.metaKey) return;
const list = ev.target.closest?.('.cat-tabs, .arr-tabs');
if (!list || list.classList.contains('act-tabs') || ev.target.parentElement !== list) return;
const tabs = [...list.querySelectorAll(':scope > [role="tab"]')].filter(x => !x.hidden);
const i = tabs.indexOf(ev.target);
if (i < 0) return;
const j = ev.key === 'Home' ? 0 : ev.key === 'End' ? tabs.length - 1
: (i + (ev.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length;
ev.preventDefault();
tabs[j].focus();
}

// skeletonHtml(label, {kind, n}) — the shape of what is loading, shimmering
// like a poster that has not arrived: 'cards' (recommendations, deletions),
// 'rows' (lists), 'tiles' (Wrap-Up). The label stays for screen readers and
Expand Down
52 changes: 52 additions & 0 deletions tests/test_a11y_nav.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,58 @@ def test_setup_nav_focuses_step_heading():
'.setup-heading[tabindex="-1"]:focus' in styles())


def test_tab_rows_roving_and_arrows():
ui = _read("ui.js")
sync, key = _fn(ui, "syncTabRoles"), _fn(ui, "tabRowKey")
check("syncTabRoles and tabRowKey exist", bool(sync) and bool(key))
out = _node(r"""
const mkTab = (n, active = false, hidden = false) => ({name: n, hidden, tabIndex: 0, attrs: {}, classList: {contains: c => c === 'active' && active},
setAttribute(k, v) { this.attrs[k] = v; }, focus() { document.activeElement = this; }});
const tabs = [mkTab('a'), mkTab('b', true), mkTab('c'), mkTab('gone', false, true)];
const list = {classList: {contains: () => false}, querySelectorAll: () => tabs};
tabs.forEach(t => { t.parentElement = list; t.closest = () => list; });
globalThis.document = {activeElement: null, querySelectorAll: () => [list]};
list.setAttribute = () => {};
%s
%s
syncTabRoles();
const out = {stops: tabs.map(t => t.tabIndex)};
const press = (at, k, extra = {}) => { document.activeElement = at; let p = false;
tabRowKey({key: k, target: at, preventDefault() { p = true; }, ...extra}); return [document.activeElement.name, p]; };
out.right = press(tabs[1], 'ArrowRight');
out.wrap = press(tabs[2], 'ArrowRight');
out.left = press(tabs[0], 'ArrowLeft');
out.end = press(tabs[0], 'End');
out.home = press(tabs[2], 'Home');
out.other = press(tabs[0], 'a');
out.ctrl = press(tabs[0], 'ArrowRight', {ctrlKey: true});
console.log(JSON.stringify(out));
""" % (sync, key)) if sync and key else None
if out is not None:
check("one Tab stop per row: the active tab", out.get("stops") == [-1, 0, -1, -1])
check("ArrowRight moves to the next tab, wrapping past the last (hidden tabs skipped)",
out.get("right") == ["c", True] and out.get("wrap") == ["a", True])
check("ArrowLeft wraps to the last visible tab; Home and End jump", out.get("left") == ["c", True]
and out.get("end") == ["c", True] and out.get("home") == ["a", True])
check("other keys and modified arrows are left alone",
out.get("other") == ["a", False] and out.get("ctrl") == ["a", False])
sw = _fn(_read("swipe.js"), "_renderTabs")
out = _node(r"""
const act = () => '', esc = x => x, _cats = () => [['a', 'A'], ['b', 'B']]; let _cat = 'b';
let focused = null; const active = {focus() { focused = 'active'; }};
let inside = true;
const el = {contains: () => inside, set innerHTML(v) {}, querySelector: () => active};
globalThis.document = {activeElement: {}, getElementById: () => el};
const _el = id => document.getElementById(id);
%s
_renderTabs(); const kept = focused; focused = null; inside = false; _renderTabs();
console.log(JSON.stringify({kept, left: focused}));
""" % sw) if sw else None
if out is not None:
check("Swipe's tab redraw refocuses the active tab, only if focus was on the row",
out.get("kept") == "active" and out.get("left") is None)


if __name__ == "__main__":
for name, fn in list(globals().items()):
if name.startswith("test_") and callable(fn):
Expand Down
Loading