fix(review): focus after a delete, the webkit WebRTC alias, one new folder, a sturdier harness

A second adversarial review, of the review-fix commits themselves, found
six problems. All are fixed here.

- Focus after a delete: a delete from the duplicate panel, or from the trash
  button of a row that did not have focus, left keyboard focus on <body>.
  The dialog cannot hand focus back to a button that went with what it
  deleted. `confirmDelete` now says where the delete was asked for: the
  tree gets focus back, and the panel moves it to the next copy's button,
  else to its close button. Checking for <body> was not enough: after a
  dialog closes, focus sits on its button until the browser's next
  rendering update, so a control in a closed dialog, or a detached one,
  now counts as lost too. Confirmed in the harness for all three paths.
- Import step 04: confirming the safety backup removed both of its buttons
  and dropped focus. A phase change now hands focus back to the heading.
- WebRTC: both gates matched `\bRTCPeerConnection\b`, which no word
  boundary lets match `webkitRTCPeerConnection`, an alias Chrome still
  ships. Prefixed aliases now count. The evasion comment in guard.mjs no
  longer claims to cover every way of hiding a member name.
- New folder: Chrome fires onCreated before create() resolves, so the live
  event could insert the folder first and newFolder then inserted a second
  row with the same id. It now inserts only when the folder is not already
  there, with a test that loses the race on purpose.
- Screenshot harness: `wxt build` empties .output first, and re-listing it
  threw inside the request handler, which ended the process. It now answers
  404 or 503 and recovers once the build is back.
- The duplicate summary uses one wrapper key instead of two fragments glued
  together in markup (docs/07 §2); Japanese gets its own separator again.
- Docs: the popup's tabId and `tabs.getCurrent` (docs/02 §6, 08 §2), the
  new-folder race (03 §3), focus after deletes and import phases (06 §5).
  SonarCloud's scan job now also receives the generated .wxt/, so
  tsconfig.json's `extends` and the `@/` alias resolve (12 §2.5).
- Tests for edit/tree-keys.ts, which had none, and for the focus helpers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 committed 2026-10-29 04:03:56 +07:00
1 parent 7f306d1271
commit 70f535eeba
27 files changed
+424 -91

No files matched your search

+7 -2
View File
@@ -53,10 +53,15 @@ jobs:
# lcov for Sonar; the docs/11 §1 thresholds still gate core here too.
- run: npm run coverage
# The lcov report, and the generated .wxt/ that tsconfig.json extends (it
# defines the `@/` alias), so the scan can resolve our own modules.
- uses: actions/upload-artifact@v7
with:
name: lcov
path: coverage/lcov.info
path: |
coverage/lcov.info
.wxt/
include-hidden-files: true
retention-days: 1
if-no-files-found: error
@@ -77,7 +82,7 @@ jobs:
- uses: actions/download-artifact@v8
with:
name: lcov
path: coverage
path: .
# No npm here: the runner's own Node reads one field of a JSON file.
- name: Read the package version
+2 -1
View File
@@ -125,7 +125,8 @@ itself. **Needs Chrome 136 or later.**
screen-reader users now land on each step of an import, and hear how it
ended.
- Dialogs name their close button "Dismiss", and screen readers read the
confirmation's details with its title.
confirmation's details with its title. After a delete, keyboard focus goes
back to the tree or the duplicate panel instead of the top of the page.
- At narrow widths the edit toolbar wraps instead of pushing the page sideways,
and titles keep their room before the domain beside them.
- Wording: an untitled item is named by its address in dialogs, plurals read
+7 -4
View File
@@ -273,11 +273,14 @@ submission (`08 §8`).
2. Found → `browser.tabs.update(tabId, { active: true })` +
`browser.windows.update(windowId, { focused: true })` (no `tabs`
permission needed for these calls).
Before focusing, it posts `{ kind: 'navigate', route }` on the
Before focusing, it posts `{ kind: 'navigate', route, tabId }` on the
`bookmarkmagic-manager` `BroadcastChannel` (same-origin, in-browser, no
permission). The Manager validates the route and switches to it — unless an
import is writing, when it refuses with the same "busy" toast the tab bar
uses (`03 §5`). 1.0.x only focused the tab, so "Export…" in the popup landed
permission). Each Manager compares `tabId` with its own, from
`tabs.getCurrent()` (no permission), so only the tab being focused acts;
with two Managers open, 1.1.0's first cut switched both. The Manager
validates the message and the route and switches to it — unless an import is
writing, when it refuses with the same "busy" toast the tab bar uses
(`03 §5`). 1.0.x only focused the tab, so "Export…" in the popup landed
wherever the Manager had been left.
3. Not found → `browser.tabs.create({ url: browser.runtime.getURL('/manager.html') + hash })`.
+1 -1
View File
@@ -192,7 +192,7 @@ tree key was ignored.
| Rename | F2 or the row button → inline input, focused with its text selected; Enter or blur commits, Esc cancels (a blur after Esc does not commit), and after Enter or Esc focus returns to the tree → trimmed; blank or unchanged → nothing; else `bookmarks.update(id, { title })` |
| Move | drag & drop onto a row — before, after or into (`planDrop`, `05 §10`) → `bookmarks.move(id, { parentId, index })`, or `{ parentId }` alone into a folder; "Move to…" (row button, menu key / Shift+F10) → modal folder list with a filter → `bookmarks.move(id, { parentId })`, appended |
| Delete | Del or the row button → confirm dialog (folder shows descendant count) → `removeTree` / `remove`; when the deleted row had focus, focus moves to the next row, else the previous. A copy deleted from the duplicate panel leaves the tree's focus where it was |
| New folder | toolbar button → `bookmarks.create({ parentId, title })` in the focused folder, beside a focused bookmark, else in the first writable root → inserted at once (the live event then finds it present), a search that would hide it cleared, and every folder above it opened as the user's own — so clearing the search cannot close them again → inline rename |
| New folder | toolbar button → `bookmarks.create({ parentId, title })` in the focused folder, beside a focused bookmark, else in the first writable root → inserted at once unless its live event got there first (Chrome fires `onCreated` before `create` resolves, so either may win), a search that would hide it cleared, and every folder above it opened as the user's own — so clearing the search cannot close them again → inline rename |
| Sort A→Z | toolbar (the focused folder, or the focused bookmark's folder) or a folder row's button → `planSort` (`05 §10`) → confirm stating how many items move → one awaited `bookmarks.move(id, { parentId, index })` per planned move, yielding every 25, under the write lock (§5). Refused part-way → "moved d of t" and a re-read: there is no undo |
| Open bookmark | Enter, double-click, or the row's Open button → `tabs.create({ url })` for `http:`/`https:` only (`09` T3); anything else is refused with a toast |
| Copy link | the row button, or Ctrl/⌘+C on the focused row → `navigator.clipboard.writeText` (`09` T8) |
+10 -5
View File
@@ -442,11 +442,16 @@ held failures at the head of the one queue instead, and every later toast —
link. Ctrl/⌘+F focuses search from anywhere in the tab. Keys typed into the
rename input belong to it.
- **Focus never dangles.** A focused row that leaves the screen hands focus to
its nearest visible folder (`03 §3`); a step that replaces another (the
import's preview, progress and result) moves focus to its own heading
(`components/focus-heading.ts`) — only when focus was lost or already inside
that tab, never stolen from elsewhere — and the import's outcome is spoken by
one always-present live region (`ImportAnnouncer`).
its nearest visible folder (`03 §3`). After a delete, focus goes back where
the delete was asked for — the tree, or in the duplicate panel the next
copy's delete button, else the panel's close button — because the dialog
cannot return it to a button that went with what it deleted. A step that
replaces another (the import's preview, progress and result) moves focus to
its own heading (`components/focus-heading.ts`) — only when focus was lost or
already inside that tab, never stolen from elsewhere; inside step 04, a phase
change that removes the focused control (confirming the backup) hands focus
to the step's heading again. The import's outcome is spoken by one
always-present live region (`ImportAnnouncer`).
- **Dialogs** (`Modal`): the × is named "Dismiss" — it was named after the
dialog, so a screen reader announced the cancel button as "Delete this
item?" — and a confirmation's body is its `aria-describedby`, so the counts
+5 -3
View File
@@ -43,8 +43,9 @@ Chrome 136 floor (§7):
| Copy diagnostics (`browser/diagnostics.ts`, `09 §7`) | Module memory + `navigator.clipboard.writeText` | Kept in the page's memory, never in `storage`; copied only on the user's click, like Copy link |
Finding the open Manager still uses `runtime.getContexts()`, `tabs.update` and
`windows.update`, none of which needs `tabs`, because nothing reads a tab's URL
or title (`02 §6`). Nothing here touches what §5 certifies: the extension
`windows.update`, and a Manager learns its own tab id from `tabs.getCurrent()` —
none of which needs `tabs`, because nothing reads a tab's URL or title
(`02 §6`). Nothing here touches what §5 certifies: the extension
transmits none of it, and the diagnostics log leaves the device only if the
user pastes it somewhere.
@@ -78,7 +79,8 @@ closes everything left unlisted (web app manifests, prefetches). Every directive
the pages use is listed explicitly, so `default-src` changes nothing for them.
`style-src` keeps `'unsafe-inline'` because Svelte sets `style` attributes.
**WebRTC is not governed by any CSP directive Chrome enforces**, so it is held
by the other two layers: both scan for `RTCPeerConnection`. User-initiated
by the other two layers: both scan for `RTCPeerConnection`, prefixed aliases
(`webkitRTCPeerConnection`, which Chrome still ships) included. User-initiated
navigation — an About link, or "Open" on a bookmark via `tabs.create` — is not
governed by a page CSP and is not a request the extension makes (`09 §1`).
+6 -2
View File
@@ -190,11 +190,15 @@ Added 2026-10-28, replacing SonarCloud's Automatic Analysis so the project gets
job's secrets are loaded into its runner for the whole job, and any step can
read them from the runner process whatever its own `env:` says (the shape of
the March 2025 tj-actions compromise). `coverage` does the common install and
`npm run coverage` with **no secret**, and uploads `coverage/lcov.info` as a
one-day artifact; `scan` installs nothing — full-history checkout
`npm run coverage` with **no secret**, and uploads `coverage/lcov.info` and
the generated `.wxt/` (which `tsconfig.json` extends, and which defines the
`@/` alias) as a one-day artifact; `scan` installs nothing — full-history checkout
(`fetch-depth: 0`, for new-code detection), the artifact, then the scan with
`-Dsonar.projectVersion=<package.json version>`, so "new code" means "since
the last release".
- The price of that isolation: the scan job has no `node_modules`, so Sonar's
type-aware rules resolve our own modules (through `.wxt/`) but not the
dependencies' types.
- The scan action is **pinned to a commit** (`v8.3.0`): it is the step that
holds `SONAR_TOKEN`. Dependabot and fork PRs get no repository secrets, so the
scan is skipped with a notice instead of failing.
+1 -1
View File
@@ -103,7 +103,7 @@ const REQUIRED_FILES = [
* enforces governs it.
*/
const NETWORK_IN_BUNDLE =
/\b(?:fetch|XMLHttpRequest|WebSocket|WebTransport|EventSource|sendBeacon|RTCPeerConnection|importScripts)\b/;
/\b(?:fetch|XMLHttpRequest|WebSocket|WebTransport|EventSource|sendBeacon|(?:webkit|moz)?RTCPeerConnection|importScripts)\b/;
/** `src`/`href` values in a built page. Vite writes them double-quoted. */
const PAGE_REFS = /\b(?:src|href)="([^"]*)"/g;
+7 -3
View File
@@ -72,7 +72,9 @@ const RULES = [
['network', 'WebTransport', /\bWebTransport\b/g],
['network', 'EventSource', /\bEventSource\b/g],
['network', 'sendBeacon', /\bsendBeacon\b/g],
['network', 'RTCPeerConnection', /\bRTCPeerConnection\b/g],
// Prefixed aliases too: no word boundary separates `webkit` from `RTC`, and
// Chrome still ships `webkitRTCPeerConnection` as the same constructor.
['network', 'RTCPeerConnection', /\b(?:webkit|moz)?RTCPeerConnection\b/g],
['network', 'importScripts', /\bimportScripts\b/g],
// `globalThis['fe' + 'tch']` — computed access on a global is how every
// identifier rule above is evaded, so it is banned as a shape, optional
@@ -124,8 +126,10 @@ const RULES = [
['raw HTML', 'createContextualFragment', /\bcreateContextualFragment\b/g],
['raw HTML', 'srcdoc', /\bsrcdoc\b/gi],
['raw HTML', 'document.write', /\bdocument\s*\.\s*write(?:ln)?\b/g],
// Evasion. Every rule above matches a NAME; these are the ways of using a
// member without writing its name. `Reflect.get(globalThis, 'fe' + 'tch')`
// Evasion. Every rule above matches a NAME; these catch the common ways of
// using a member without writing it. Not all of them — `el[['inner',
// 'HTML'].join('')]` still gets past any pattern — which is why the CSP and
// the built-bundle scan stand behind this gate. `Reflect.get(globalThis, 'fe' + 'tch')`
// and `Reflect.set(el, 'outer' + 'HTML', h)` reach anything, and nothing
// here needs Reflect at all.
['evasion', 'Reflect', /\bReflect\b/g],
+24 -4
View File
@@ -137,6 +137,21 @@ function buildIndex() {
function serve() {
const csp = productionCsp();
let files = buildIndex();
/**
* A rebuild while the harness runs renames the hashed chunks, so a miss
* re-lists once. `wxt build` empties the directory first; listing it then
* throws, and an uncaught throw in the handler ended the whole process.
* @param {string} urlPath @returns {string | undefined}
*/
const lookup = (urlPath) => {
if (files.has(urlPath)) return files.get(urlPath);
try {
files = buildIndex();
} catch {
return undefined;
}
return files.get(urlPath);
};
const server = createServer((req, res) => {
const url = new URL(req.url ?? '/', `http://${HOST}:${PORT}`);
if (url.pathname === '/__shim.js') {
@@ -151,15 +166,20 @@ function serve() {
res.writeHead(400).end('bad request');
return;
}
// A rebuild while the harness runs renames the hashed chunks: re-list once.
if (!files.has(decoded)) files = buildIndex();
const path = files.get(decoded);
const path = lookup(decoded);
if (path === undefined) {
res.writeHead(404).end('not found');
return;
}
const type = TYPES[extname(path)] ?? 'application/octet-stream';
let body = readFileSync(path);
let body;
try {
body = readFileSync(path);
} catch {
// Listed, then deleted: a build is rewriting .output under us.
res.writeHead(503).end('build in progress');
return;
}
if (type.startsWith('text/html')) {
const tags = `<meta http-equiv="Content-Security-Policy" content="${csp}"><script src="/__shim.js"></script>`;
body = Buffer.from(body.toString('utf8').replace('<head>', `<head>${tags}`));
+33 -7
View File
@@ -1,12 +1,14 @@
<script lang="ts">
import type { DuplicateGroup } from '../core/dedupe';
import { folderPaths } from '../edit/edit-node';
import { displayTitle, folderPaths } from '../edit/edit-node';
import type { EditNode } from '../edit/patch-tree';
import { t, tPlural } from '../i18n/index.svelte';
import Button from './Button.svelte';
import Icon from './icons/Icon.svelte';
interface Props {
/** The panel's root, for the tab to move focus into after a delete. */
element?: HTMLElement | undefined;
groups: readonly DuplicateGroup<EditNode>[];
roots: readonly EditNode[];
busy: boolean;
@@ -15,21 +17,41 @@
onkeepFirst: () => void;
}
let { groups, roots, busy, onclose, ondelete, onkeepFirst }: Props = $props();
let {
element = $bindable(),
groups,
roots,
busy,
onclose,
ondelete,
onkeepFirst,
}: Props = $props();
const extra = $derived(groups.reduce((n, group) => n + group.nodes.length - 1, 0));
// Two copies of one link differ only by where they live, so say where (uM22).
const paths = $derived(folderPaths(roots));
</script>
<aside aria-label={t('edit.duplicates')}>
<aside bind:this={element} aria-label={t('edit.duplicates')}>
<header>
<span class="eyebrow">{t('edit.duplicates')}</span>
<Button variant="ghost" size="sm" icon="close" label={t('common.dismiss')} onclick={onclose} />
<Button
variant="ghost"
size="sm"
icon="close"
label={t('common.dismiss')}
data-panel-close
onclick={onclose}
/>
</header>
<!-- One sentence with two counts: a wrapper key, never two fragments
glued with a separator in markup (docs/07 §2). -->
<p class="summary" aria-live="polite">
{tPlural('edit.duplicateLinks', groups.length)} · {tPlural('edit.extraCopies', extra)}
{t('edit.duplicateSummary', {
links: tPlural('edit.duplicateLinks', groups.length),
copies: tPlural('edit.extraCopies', extra),
})}
</p>
{#if groups.length === 0}
@@ -47,7 +69,7 @@
{#each group.nodes as node, i (node.id)}
<li>
<span class="where">
<span class="title">{node.title === '' ? t('edit.untitled') : node.title}</span>
<span class="title">{displayTitle(node, t('edit.untitled'))}</span>
<span class="path mono">
<Icon name="folder" size={12} />{paths.get(node.id) ?? ''}
</span>
@@ -60,8 +82,12 @@
variant="ghost"
icon="trash"
iconMotion="tilt"
label={t('edit.deleteCopy', { title: node.title, path: paths.get(node.id) ?? '' })}
label={t('edit.deleteCopy', {
title: displayTitle(node, t('edit.untitled')),
path: paths.get(node.id) ?? '',
})}
disabled={busy}
data-copy-delete
onclick={() => ondelete(node)}
/>
{/if}
+21 -18
View File
@@ -4,7 +4,7 @@
* and commands live in `stores/edit-session.svelte.ts`, live events in
* `edit/live-sync.ts`.
*/
import { onMount, untrack } from 'svelte';
import { onMount, tick, untrack } from 'svelte';
import { subscribe } from '../browser/bookmarks';
import { copyToClipboard } from '../browser/clipboard';
import { openBookmarkUrl } from '../browser/open-url';
@@ -20,12 +20,14 @@
import DuplicatePanel from './DuplicatePanel.svelte';
import EditToolbar from './EditToolbar.svelte';
import ErrorCallout from './ErrorCallout.svelte';
import { focusIfLost } from './focus-heading';
import MoveToDialog from './MoveToDialog.svelte';
import TreeList from './TreeList.svelte';
const session = new EditSession(undefined, getLocale);
let searchInput = $state<HTMLInputElement | undefined>();
let treeEl = $state<HTMLElement | undefined>();
let panelEl = $state<HTMLElement | undefined>();
onMount(() => {
void session.load();
@@ -113,20 +115,7 @@
}
function onKeydown(event: KeyboardEvent): void {
onTreeKey(event, session, {
open: (node) => void open(node),
copy: (node) => void copy(node),
scroll: scrollFocusedIntoView,
});
}
/** Keep the focused row on screen — the tree is a fixed-height scroller. */
function scrollFocusedIntoView(): void {
const id = session.focusedId;
if (treeEl === undefined || id === undefined) return;
queueMicrotask(() => {
treeEl?.querySelector(`[data-node-id="${CSS.escape(id)}"]`)?.scrollIntoView({ block: 'nearest' });
});
onTreeKey(event, session, { open: (node) => void open(node), copy: (node) => void copy(node) });
}
/** ⌘/Ctrl-F focuses the search box, whatever the case of the F (docs/06 §3.3). */
@@ -137,9 +126,22 @@
searchInput?.select();
}
/** Focus follows a delete to the next row, not into the void (uM4). */
/**
* Focus goes back where the delete was asked for (uM4). The dialog cannot
* hand it back to the button that opened it — that button went with what it
* deleted — so a panel delete lands on the next copy's button, else on the
* panel's close button.
*/
async function confirmDelete(): Promise<void> {
if (await session.confirmDelete()) treeEl?.focus();
const origin = await session.confirmDelete();
await tick();
if (origin === 'tree') treeEl?.focus();
else if (origin === 'panel') {
focusIfLost(
panelEl?.querySelector<HTMLElement>('[data-copy-delete]') ??
panelEl?.querySelector<HTMLElement>('[data-panel-close]'),
);
}
}
</script>
@@ -180,11 +182,12 @@
{#if session.showDuplicates}
<DuplicatePanel
bind:element={panelEl}
groups={session.duplicateGroups}
roots={session.roots}
busy={session.busy}
onclose={() => (session.showDuplicates = false)}
ondelete={(node) => session.requestDelete(node, false)}
ondelete={(node) => session.requestDelete(node, 'panel')}
onkeepFirst={() => (session.pendingKeepFirst = true)}
/>
{/if}
+23 -11
View File
@@ -12,37 +12,49 @@
} from '../stores/import-session.svelte';
import Button from './Button.svelte';
import Callout from './Callout.svelte';
import { focusWhenShown } from './focus-heading';
import { focusLost, focusWhenShown } from './focus-heading';
import ProgressBar from './ProgressBar.svelte';
type Writing = Extract<ImportState, { kind: 'backing-up' | 'attesting' | 'clearing' | 'writing' }>;
interface Props {
state: Writing;
phase: Writing;
}
let { state }: Props = $props();
let { phase }: Props = $props();
let heading = $state<HTMLElement | undefined>();
// The step stays mounted from the backup to the last write, so its heading
// takes focus once on its own. A phase change can then remove the control
// that had focus — confirming the backup removes both of its buttons — and
// focus fell to `<body>`: hand it to the heading again.
$effect(() => {
void phase.kind;
if (heading !== undefined && focusLost()) heading.focus();
});
</script>
<section class="panel">
<h2 class="eyebrow" tabindex="-1" {@attach focusWhenShown}>04 · {t('import.stepWriting')}</h2>
{#if state.kind === 'backing-up'}
<h2 class="eyebrow" tabindex="-1" bind:this={heading} {@attach focusWhenShown}>
04 · {t('import.stepWriting')}
</h2>
{#if phase.kind === 'backing-up'}
<Callout tone="warn">{t('import.backingUp')}</Callout>
{:else if state.kind === 'attesting'}
{:else if phase.kind === 'attesting'}
<!-- The anchor download reports nothing, so this confirmation is the only
thing standing between the user and an unbacked-up deletion. -->
<Callout tone="danger">{t('import.attest', { name: state.backupFilename })}</Callout>
<Callout tone="danger">{t('import.attest', { name: phase.backupFilename })}</Callout>
<div class="actions">
<Button variant="danger" onclick={() => answerAttestation(true)}>{t('import.attestConfirm')}</Button>
<Button onclick={() => answerAttestation(false)}>{t('common.cancel')}</Button>
</div>
{:else if state.kind === 'clearing'}
{:else if phase.kind === 'clearing'}
<Callout tone="danger">{t('import.clearing')}</Callout>
{:else}
<ProgressBar done={state.progress.done} total={state.progress.total} label={t('common.import')} />
<ProgressBar done={phase.progress.done} total={phase.progress.total} label={t('common.import')} />
<p class="muted mono">
{t('import.progress', { done: num(state.progress.done), total: num(state.progress.total) })}
{#if state.progress.currentPath !== ''}<span class="path">{state.progress.currentPath}</span>{/if}
{t('import.progress', { done: num(phase.progress.done), total: num(phase.progress.total) })}
{#if phase.progress.currentPath !== ''}<span class="path">{phase.progress.currentPath}</span>{/if}
</p>
<Callout tone="warn">{t('import.keepTabOpen')}</Callout>
<div class="actions"><Button icon="close" onclick={cancelWrite}>{t('common.cancel')}</Button></div>
+1 -1
View File
@@ -204,7 +204,7 @@
{:else if session.kind === 'done' || session.kind === 'cancelled' || session.kind === 'error'}
<ImportReport state={session} />
{:else}
<ImportProgress state={session} />
<ImportProgress phase={session} />
{/if}
</div>
+1 -1
View File
@@ -52,7 +52,7 @@
<button tabindex="-1" disabled={session.busy} title={t('edit.moveTo')} aria-label={t('edit.moveTo')} onclick={act(() => session.startMove(node))}>
<Icon name="move" size={14} motion="bob" />
</button>
<button tabindex="-1" disabled={session.busy} class="delete" title={t('edit.delete')} aria-label={t('edit.delete')} onclick={act(() => session.requestDelete(node, true))}>
<button tabindex="-1" disabled={session.busy} class="delete" title={t('edit.delete')} aria-label={t('edit.delete')} onclick={act(() => session.requestDelete(node, 'tree'))}>
<Icon name="trash" size={14} motion="tilt" />
</button>
{/if}
+11
View File
@@ -61,6 +61,17 @@
untrack(() => session.repairFocus());
});
// Keep the focused row on screen — the tree is a fixed-height scroller.
// Tracks the focus alone: following every tree change would yank the view
// back to the focus each time a live event landed while the user scrolled.
$effect(() => {
const id = session.focusedId;
if (id === undefined || element === undefined) return;
untrack(() =>
element?.querySelector(`[data-node-id="${CSS.escape(id)}"]`)?.scrollIntoView({ block: 'nearest' }),
);
});
function grow(next: (current: RowWindow, total: number) => RowWindow): void {
win = next(follow(win, focusIndex, rows.length), rows.length);
}
+22 -2
View File
@@ -12,6 +12,26 @@
export function focusWhenShown(heading: HTMLElement): void {
const active = document.activeElement;
const scope = heading.closest('[data-focus-scope]');
const lost = active === null || active === document.body;
if (lost || scope?.contains(active) === true) heading.focus();
if (focusLost() || scope?.contains(active) === true) heading.focus();
}
/**
* Focus fell to `<body>`, or is about to: the control that had it was removed,
* or sits in a dialog that just closed. The browser moves such a focus to
* `<body>` only at its next rendering update, after any code that runs now —
* so checking for `<body>` alone left focus to fall there anyway.
*/
export function focusLost(): boolean {
const active = document.activeElement;
if (active === null || active === document.body) return true;
return !active.isConnected || active.closest('dialog:not([open])') !== null;
}
/**
* Put focus on `target` if it has fallen to `<body>` — for when the control
* that had it was removed by the very action it started (a dialog cannot hand
* focus back to a button that went with what it deleted).
*/
export function focusIfLost(target: HTMLElement | null | undefined): void {
if (target !== null && target !== undefined && focusLost()) target.focus();
}
+2 -4
View File
@@ -17,8 +17,6 @@ import { resolveKey } from './tree-keyboard';
export interface TreeKeyEffects {
open: (node: EditNode) => void;
copy: (node: EditNode) => void;
/** The focus moved: bring its row into view. */
scroll: () => void;
}
export function onTreeKey(
@@ -46,8 +44,8 @@ export function onTreeKey(
switch (action.kind) {
case 'focus':
// TreeList scrolls the row into view once it is mounted.
session.focusedId = action.id;
effects.scroll();
break;
case 'expand':
case 'collapse':
@@ -57,7 +55,7 @@ export function onTreeKey(
if (node !== undefined) session.startRename(node);
break;
case 'delete':
if (node !== undefined) session.requestDelete(node, true);
if (node !== undefined) session.requestDelete(node, 'tree');
break;
case 'move':
if (node !== undefined) session.startMove(node);
+1
View File
@@ -108,6 +108,7 @@ const dict = {
other: 'Delete "{title}" and the {n} items inside it? This cannot be undone.',
},
duplicates: 'Duplicates',
duplicateSummary: '{links} · {copies}',
duplicateLinks: { one: '{n} duplicated link', other: '{n} duplicated links' },
extraCopies: { one: '{n} extra copy', other: '{n} extra copies' },
noDuplicates: 'No duplicate links found.',
+1
View File
@@ -99,6 +99,7 @@ export default {
other: '「{title}」と、その中の {n} 件を削除しますか?元に戻せません。',
},
duplicates: '重複',
duplicateSummary: '{links}・{copies}',
duplicateLinks: { one: '重複リンク {n} 件', other: '重複リンク {n} 件' },
extraCopies: { one: '余分なコピー {n} 件', other: '余分なコピー {n} 件' },
noDuplicates: '重複するリンクは見つかりませんでした。',
+1
View File
@@ -97,6 +97,7 @@ export default {
other: 'Xóa "{title}" và {n} mục bên trong? Không thể hoàn tác.',
},
duplicates: 'Mục trùng',
duplicateSummary: '{links} · {copies}',
duplicateLinks: { one: '{n} liên kết bị trùng', other: '{n} liên kết bị trùng' },
extraCopies: { one: '{n} bản dư', other: '{n} bản dư' },
noDuplicates: 'Không tìm thấy liên kết trùng.',
+25 -16
View File
@@ -55,6 +55,9 @@ export interface BulkProgress {
/** A failed command, shown above the tree rather than replacing it. */
export type ActionError = DescribedError & { partial?: BulkProgress };
/** Where a delete was asked for: the tree (Del, a row's button) or the duplicate panel. */
export type DeleteOrigin = 'tree' | 'panel';
const BROWSER_API: EditApi = {
getRootChildren,
getChildren,
@@ -74,8 +77,8 @@ export class EditCommands extends EditView {
actionError = $state<ActionError | undefined>();
/** A bulk command is running; every other write waits for it. */
busy = $state(false);
/** Whether the pending delete was asked for from the tree (key or row button). */
private deleteFromTree = false;
/** Where the pending delete was asked for. */
private deleteOrigin: DeleteOrigin = 'tree';
protected readonly api: EditApi;
protected readonly locale: () => string;
@@ -152,24 +155,26 @@ export class EditCommands extends EditView {
});
};
requestDelete = (node: EditNode, fromTree: boolean): void => {
requestDelete = (node: EditNode, origin: DeleteOrigin): void => {
if (this.busy || !this.isEditable(node)) return;
this.pendingDelete = node;
this.deleteFromTree = fromTree;
this.deleteOrigin = origin;
};
/**
* Delete what `requestDelete` asked about. Focus moves to the next row only
* when the deleted row had it, and the result — whether keyboard focus
* belongs back in the tree — is true only when the delete started there:
* from the duplicate panel it pulled focus out of the panel and moved the
* tree's selection (v1.1.0 review).
* Delete what `requestDelete` asked about. The tree's focus moves to the
* next row only when the deleted row had it — a copy deleted from the
* duplicate panel used to move the tree's selection (v1.1.0 review).
*
* @returns where the delete was asked for, once it went through, so the
* caller can put keyboard focus back there: the button that opened the
* dialog went with what it deleted, and focus fell to `<body>`.
*/
confirmDelete = async (): Promise<boolean> => {
confirmDelete = async (): Promise<DeleteOrigin | undefined> => {
const node = this.pendingDelete;
const fromTree = this.deleteFromTree;
const origin = this.deleteOrigin;
this.pendingDelete = undefined;
if (node === undefined || this.busy || !this.isEditable(node)) return false;
if (node === undefined || this.busy || !this.isEditable(node)) return undefined;
const hadFocus = node.id === this.focusedId;
const next = hadFocus ? this.neighbourOf(node.id) : undefined;
const ok = await this.guard(async () => {
@@ -178,7 +183,7 @@ export class EditCommands extends EditView {
else await this.api.remove(node.id);
});
if (ok && hadFocus) this.focusedId = next;
return ok && hadFocus && fromTree;
return ok ? origin : undefined;
};
newFolder = async (title: string): Promise<void> => {
@@ -187,9 +192,13 @@ export class EditCommands extends EditView {
if (parentId === undefined) return;
await this.guard(async () => {
const created = toEditNode(await this.api.create({ parentId, title }));
// In the tree now, not a frame later from the live event (which then
// finds it present and does nothing): the rename box needs its row.
this.roots = insertNode(this.roots, parentId, undefined, created);
// In the tree now, not a frame later from the live event: the rename
// box needs its row. Chrome fires `onCreated` BEFORE `create` resolves,
// so the event may have won the race — inserting again put two rows
// with one id in the keyed list.
if (findNode(this.roots, created.id) === undefined) {
this.roots = insertNode(this.roots, parentId, undefined, created);
}
// A search would hide it, and clearing that search closes the folders
// it opened — so every folder above it is opened as the user's own.
if (this.filtering) this.clearSearch();
@@ -0,0 +1,59 @@
import { afterEach, describe, expect, it } from 'vitest';
import { focusIfLost, focusLost, focusWhenShown } from '@/lib/components/focus-heading';
/** Focus repair for multi-step screens and deletes — docs/06 §5. */
afterEach(() => {
document.body.replaceChildren();
});
function button(parent: HTMLElement = document.body): HTMLButtonElement {
return parent.appendChild(document.createElement('button'));
}
describe('focusLost', () => {
it('is true on <body>, false on a live control', () => {
expect(focusLost()).toBe(true);
button().focus();
expect(focusLost()).toBe(false);
});
it('counts a control inside a closed dialog as lost — the browser moves it later', () => {
const dialog = document.body.appendChild(document.createElement('dialog'));
dialog.setAttribute('open', '');
const confirm = button(dialog);
confirm.focus();
expect(focusLost()).toBe(false);
dialog.removeAttribute('open');
expect(focusLost()).toBe(true);
});
});
describe('focusIfLost', () => {
it('moves a lost focus to the target, and leaves a live one alone', () => {
const target = button();
focusIfLost(target);
expect(document.activeElement).toBe(target);
const other = button();
other.focus();
focusIfLost(target);
expect(document.activeElement).toBe(other);
focusIfLost(undefined);
expect(document.activeElement).toBe(other);
});
});
describe('focusWhenShown', () => {
it('takes focus inside its scope or when lost, never from elsewhere', () => {
const scope = document.body.appendChild(document.createElement('div'));
scope.setAttribute('data-focus-scope', '');
const heading = scope.appendChild(document.createElement('h2'));
heading.tabIndex = -1;
const outside = button();
outside.focus();
focusWhenShown(heading);
expect(document.activeElement).toBe(outside);
button(scope).focus();
focusWhenShown(heading);
expect(document.activeElement).toBe(heading);
});
});
+118
View File
@@ -0,0 +1,118 @@
import { beforeEach, describe, expect, it, type Mock, vi } from 'vitest';
import type { EditNode } from '@/lib/edit/patch-tree';
import { onTreeKey } from '@/lib/edit/tree-keys';
import { EditSession } from '@/lib/stores/edit-session.svelte';
import { FakeBookmarks } from '../../helpers/fake-bookmarks';
/**
* The #edit tree's keyboard contract applied to a real session — docs/06 §5.
* Keys are dispatched on an element whose listener is the handler, exactly as
* TreeList wires it, so the target/currentTarget rule is exercised too.
*/
let fake: FakeBookmarks;
let session: EditSession;
let tree: HTMLUListElement;
let effects: { open: Mock<(id: string) => void>; copy: Mock<(id: string) => void> };
let ids: { dev: string; gh: string; docs: string };
beforeEach(async () => {
fake = new FakeBookmarks();
ids = {
docs: fake.seed('1', { title: 'Docs', url: 'https://docs.example/' }),
dev: fake.seed('1', { title: 'Dev' }),
gh: '',
};
ids.gh = fake.seed(ids.dev, { title: 'GitHub', url: 'https://github.com/' });
session = new EditSession(
{
getRootChildren: async () => (await fake.getTree())[0]?.children ?? [],
getChildren: async (id: string) => fake.children(id),
create: fake.create,
update: fake.update,
move: fake.move,
remove: fake.remove,
removeTree: fake.removeTree,
},
() => 'en',
);
await session.load();
effects = { open: vi.fn<(id: string) => void>(), copy: vi.fn<(id: string) => void>() };
tree = document.createElement('ul');
tree.addEventListener('keydown', (event) =>
onTreeKey(event, session, {
open: (node: EditNode) => effects.open(node.id),
copy: (node: EditNode) => effects.copy(node.id),
}),
);
});
function press(key: string, init: KeyboardEventInit = {}, target: Element = tree): KeyboardEvent {
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true, ...init });
target.dispatchEvent(event);
return event;
}
describe('onTreeKey', () => {
it('moves the focus and claims the key', () => {
session.focusedId = '1';
const event = press('ArrowDown');
expect(session.focusedId).toBe(ids.docs);
expect(event.defaultPrevented).toBe(true);
});
it('opens and closes folders, and opens bookmarks', () => {
session.focusedId = ids.dev;
press('ArrowRight');
expect(session.expanded.has(ids.dev)).toBe(true);
press('Enter');
expect(session.expanded.has(ids.dev)).toBe(false);
session.focusedId = ids.docs;
press('Enter');
expect(effects.open).toHaveBeenCalledWith(ids.docs);
});
it('starts a rename, a delete from the tree, and "Move to…" — by menu key or Shift+F10', () => {
session.focusedId = ids.docs;
press('F2');
expect(session.renamingId).toBe(ids.docs);
session.renamingId = undefined;
press('Delete');
expect(session.pendingDelete?.id).toBe(ids.docs);
session.pendingDelete = undefined;
press('ContextMenu');
expect(session.movingNode?.id).toBe(ids.docs);
session.movingNode = undefined;
press('F10', { shiftKey: true });
// toMatchObject, not `?.id`: TS keeps the `undefined` narrowing across the call.
expect(session.movingNode).toMatchObject({ id: ids.docs });
});
it('copies the focused bookmark with Ctrl or ⌘ + C, whatever the case', () => {
session.focusedId = ids.docs;
press('c', { ctrlKey: true });
press('C', { metaKey: true });
expect(effects.copy).toHaveBeenCalledTimes(2);
});
it('leaves alone: keys while renaming, keys aimed at a row control, other modifiers', () => {
session.focusedId = ids.docs;
session.renamingId = ids.docs;
expect(press('ArrowDown').defaultPrevented).toBe(false);
session.renamingId = undefined;
const button = tree.appendChild(document.createElement('button'));
expect(press('ArrowDown', {}, button).defaultPrevented).toBe(false);
expect(press('ArrowDown', { altKey: true }).defaultPrevented).toBe(false);
expect(session.focusedId).toBe(ids.docs);
});
it('starts no write while a bulk command runs', () => {
session.focusedId = ids.docs;
session.busy = true;
press('F2');
press('Delete');
press('ContextMenu');
expect(session.renamingId).toBeUndefined();
expect(session.pendingDelete).toBeUndefined();
expect(session.movingNode).toBeUndefined();
});
});
@@ -137,6 +137,7 @@ describe('check-manifest.mjs', () => {
['XMLHttpRequest', 'chunks/x.js', 'new XMLHttpRequest'],
['sendBeacon', 'assets/deep/y.js', 'navigator.sendBeacon(u)'],
['RTCPeerConnection', 'chunks/x.js', 'new RTCPeerConnection({iceServers:[]})'],
['webkitRTCPeerConnection', 'chunks/x.js', 'new webkitRTCPeerConnection({iceServers:[]})'],
['importScripts', 'chunks/x.js', 'importScripts("x.js")'],
])('fails on %s anywhere in the shipped JavaScript', (api, file, code) => {
const { status, output } = check(build(MANIFEST, { [file]: code }));
+6
View File
@@ -50,6 +50,12 @@ const BANNED: readonly (readonly [string, string, string, string])[] = [
['EventSource', 'a.ts', 'new EventSource(u);', 'EventSource'],
['sendBeacon', 'a.ts', 'navigator.sendBeacon(u, d);', 'sendBeacon'],
['RTCPeerConnection', 'a.ts', 'new RTCPeerConnection({ iceServers: [] });', 'RTCPeerConnection'],
[
'the webkit-prefixed RTCPeerConnection',
'a.ts',
'new webkitRTCPeerConnection({ iceServers: [] });',
'RTCPeerConnection',
],
['importScripts', 'a.ts', "importScripts('x.js');", 'importScripts'],
['computed globalThis access', 'a.ts', "globalThis['fe' + 'tch'](u);", 'computed global access'],
[
+28 -5
View File
@@ -137,8 +137,8 @@ describe('EditSession — rename, delete, new folder', () => {
session.focusedId = a;
const node = session.roots[0]?.children?.[0];
if (node === undefined) throw new Error('no row');
session.requestDelete(node, true);
expect(await session.confirmDelete()).toBe(true);
session.requestDelete(node, 'tree');
expect(await session.confirmDelete()).toBe('tree');
expect(session.focusedId).toBe(b);
expect(fake.childTitles('1')).toEqual(['b']);
});
@@ -149,8 +149,8 @@ describe('EditSession — rename, delete, new folder', () => {
session.focusedId = a;
const copy = session.roots[0]?.children?.find((n) => n.id === b);
if (copy === undefined) throw new Error('no row');
session.requestDelete(copy, false);
expect(await session.confirmDelete()).toBe(false);
session.requestDelete(copy, 'panel');
expect(await session.confirmDelete()).toBe('panel');
expect(session.focusedId).toBe(a);
expect(fake.childTitles('1')).toEqual(['a']);
});
@@ -165,6 +165,29 @@ describe('EditSession — rename, delete, new folder', () => {
expect(session.rows.some((row) => row.node.id === session.renamingId)).toBe(true);
});
it('does not insert a new folder twice when the live event wins the race (v1.1.0 review)', async () => {
// Chrome fires onCreated before create() resolves: let the event land first.
const create = fake.create;
fake.create = async (details) => {
const node = await create(details);
session.applyLiveEvents([
{
kind: 'created',
parentId: details.parentId,
index: undefined,
node: { id: node.id, title: node.title, children: [] },
},
]);
return node;
};
session = new EditSession(api(fake), () => 'en');
await session.load();
await session.newFolder('New folder');
const id = session.renamingId;
expect(id).toBeDefined();
expect(session.rows.filter((row) => row.node.id === id)).toHaveLength(1);
});
it('keeps a new folder visible when the search that opened its parent clears (v1.1.0 review)', async () => {
const dev = fake.seed('1', { title: 'Dev' });
const ref = fake.seed(dev, { title: 'Reference' });
@@ -267,7 +290,7 @@ describe('EditSession — one bulk command at a time (v1.1.0 review)', () => {
const row = session.roots[0]?.children?.find((n) => n.id === x);
if (row === undefined) throw new Error('no row');
session.startRename(row);
session.requestDelete(row, true);
session.requestDelete(row, 'tree');
await session.newFolder('New');
expect(session.renamingId).toBeUndefined();
expect(session.pendingDelete).toBeUndefined();