fix(edit): localized failures, and a search that collapses again

**#edit and #export showed a raw English Chrome string as the entire message.**
docs/02 §7 requires a localized sentence plus a separate technical block, and
LegalGate carries a comment describing this exact mistake as a defect that was
already fixed once — writing `detail ?? t(key)` looks like a sensible fallback,
but the raw string is almost always present, so the translation becomes dead
code. Three sites still had it: EditTab's load failure, ExportTab's load
failure, and ExportTab's export toast. A Vietnamese or Japanese user got an
untranslated Chrome message as their whole explanation.

One ErrorCallout now owns that contract, so there is a single place it can be
got wrong, and all three tabs go through the shared describeError.

**Clearing the search box rendered the whole tree in one synchronous pass.**
Search-opened ancestors merge into `expanded` (deliberately — a render-time
union made the disclosure button and ArrowLeft dead keys), but nothing ever
un-merged them. A one-character query expands most of a large profile, and
clearing the box then rendered every row the search had opened at once, with no
virtualization behind it; the 150 ms debounce delayed that growth without
bounding it. src/lib/edit/search-expansion.ts tracks search-owned ids
separately, and toggling a folder transfers it to the user so the collapse
cannot steal it back.

**"Keep the first of each" targeted nodes it cannot delete, then gave up
silently.** The duplicate list had no isEditable filter — unlike the
single-delete path — so duplicates inside a policy-managed subtree were offered
for bulk deletion, and the browser rejects every one of them. The loop then
abandoned the rest on the first rejection, leaving a partial delete measured
against a dialog that had promised an exact number, with no way to tell how many
copies remained. deleteEach never throws and reports how far it got.

EditTab was at 481/500 before this, so the ARIA tree container came out into
TreeList.svelte first — 466 now, and the tree pattern lives somewhere it is not
surrounded by loading, searching, mutation and five dialogs. That extraction
immediately caught a real bug the shorthand had hidden: `{ontoggle}` bound
`window.ontoggle`, not the local `toggle`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 committed 2026-08-03 20:20:05 +07:00
1 parent d8bbd4ca79
commit cfd1e77cb2
12 files changed
+619 -130

No files matched your search

+96 -111
View File
@@ -10,7 +10,7 @@
update,
} from '../browser/bookmarks';
import { copyToClipboard } from '../browser/clipboard';
import { BmBrowserError } from '../browser/errors';
import { type DescribedError, describeError } from '../browser/describe-error';
import { openBookmarkUrl } from '../browser/open-url';
import { findDuplicateGroups } from '../core/dedupe';
import { searchTree } from '../core/search';
@@ -30,31 +30,41 @@
moveNode,
removeNode,
} from '../edit/patch-tree';
import { deleteEach } from '../edit/bulk-delete';
import { canMoveInto, moveTargets } from '../edit/move-target';
import {
collapseSearchExpansion,
forgetSearchExpansion,
mergeSearchExpansion,
} from '../edit/search-expansion';
import { resolveKey, visibleRows } from '../edit/tree-keyboard';
import { num, t } from '../i18n/index.svelte';
import { pushToast } from '../stores/toast.svelte';
import Callout from './Callout.svelte';
import ErrorCallout from './ErrorCallout.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
import DuplicatePanel from './DuplicatePanel.svelte';
import EditToolbar from './EditToolbar.svelte';
import MoveToDialog from './MoveToDialog.svelte';
import TreeRow from './TreeRow.svelte';
import TreeList from './TreeList.svelte';
let roots = $state<EditNode[]>([]);
let expanded = $state<Set<string>>(new Set());
let expanded = $state<ReadonlySet<string>>(new Set());
let focusedId = $state<string | undefined>();
let renamingId = $state<string | undefined>();
let query = $state('');
let debounced = $state('');
let showDuplicates = $state(false);
let loadError = $state<string | undefined>();
let loadError = $state<DescribedError | undefined>();
let pendingDelete = $state<EditNode | undefined>();
let pendingKeepFirst = $state(false);
let draggingId = $state<string | undefined>();
let movingNode = $state<EditNode | undefined>();
/** Per-operation failure, shown ABOVE the tree rather than replacing it. */
let actionError = $state<{ message: string; detail: string | undefined } | undefined>();
let actionError = $state<
(DescribedError & { partial?: { done: number; total: number } }) | undefined
>();
/** Folders the search opened, so clearing the search can close them again. */
let searchOpened = $state<ReadonlySet<string>>(new Set());
let searchInput = $state<HTMLInputElement | undefined>();
let treeEl = $state<HTMLElement | undefined>();
@@ -96,7 +106,9 @@
roots = (await getRootChildren()).map(toEditNode);
expanded = new Set(roots.map((root) => root.id));
} catch (err) {
loadError = err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN');
// Was `err.detail` alone: a raw English Chrome string as the entire
// screen, in every language (docs/02 §7).
loadError = describeError(err);
}
}
@@ -114,16 +126,43 @@
// Search-opened ancestors are merged INTO `expanded` rather than unioned at
// render time. Reading from a union that toggle() cannot write to made the
// disclosure button and ArrowLeft dead keys on every search-expanded folder.
//
// The merge is remembered so it can be undone: a one-character query expands
// most of a large tree, and clearing the box used to render every one of
// those rows at once, in a single synchronous pass, with no virtualization.
$effect(() => {
if (search.expand.size === 0) return;
const missing = [...search.expand].filter((id) => !expanded.has(id));
if (missing.length > 0) expanded = new Set([...expanded, ...missing]);
if (!filtering) {
if (searchOpened.size === 0) return;
expanded = collapseSearchExpansion(expanded, searchOpened);
searchOpened = new Set();
return;
}
const merged = mergeSearchExpansion(expanded, search.expand, searchOpened);
if (merged.expanded === expanded) return;
expanded = merged.expanded;
searchOpened = merged.opened;
});
const rows = $derived(visibleRows(roots, expanded, filtering ? search.visible : undefined));
const partialNote = $derived(
actionError?.partial === undefined
? undefined
: t('edit.keepFirstPartial', {
done: num(actionError.partial.done),
total: num(actionError.partial.total),
}),
);
// `isEditable` matters as much as the url check: without it, duplicates
// inside a policy-managed subtree were offered for bulk deletion, and the
// browser rejects every one of them. The single-delete path has always
// filtered; docs/15 makes it normative that unmodifiable nodes offer no
// destructive affordance at all.
const duplicateGroups = $derived(
findDuplicateGroups(flattenTree(roots).filter((node) => node.url !== undefined)),
findDuplicateGroups(
flattenTree(roots).filter((node) => node.url !== undefined && isEditable(node)),
),
);
/**
@@ -136,10 +175,7 @@
try {
await run();
} catch (err) {
actionError =
err instanceof BmBrowserError
? { message: t('errors.BROWSER'), detail: err.detail }
: { message: t('errors.UNKNOWN'), detail: err instanceof Error ? err.message : undefined };
actionError = describeError(err);
await load();
}
}
@@ -149,6 +185,9 @@
if (next.has(id)) next.delete(id);
else next.add(id);
expanded = next;
// Touching a folder makes it the user's, so clearing the search must not
// close it again.
searchOpened = forgetSearchExpansion(searchOpened, id);
}
function onKeydown(event: KeyboardEvent): void {
@@ -251,12 +290,21 @@
// Snapshot the ids first: duplicateGroups is $derived from `roots`, so
// reading it inside the loop would recompute mid-iteration.
const doomed = extraCopyIds(duplicateGroups);
await guardEdit(async () => {
for (const id of doomed) {
roots = removeNode(roots, id);
await remove(id);
}
actionError = undefined;
const outcome = await deleteEach(doomed, remove, (id) => {
roots = removeNode(roots, id);
});
if (outcome.error === undefined) return;
// The dialog promised an exact number. Saying only "the browser refused"
// after deleting some of them leaves the user unable to tell how many
// copies are left, on an action that cannot be undone.
actionError = {
...describeError(outcome.error),
partial: { done: outcome.deleted, total: outcome.total },
};
await load();
}
/** Shared by the drag path and the keyboard "Move to…" path. */
@@ -300,7 +348,7 @@
</script>
{#if loadError !== undefined}
<Callout tone="danger">{loadError}</Callout>
<ErrorCallout messageKey={loadError.messageKey} detail={loadError.detail} />
{:else}
<EditToolbar
bind:input={searchInput}
@@ -313,65 +361,37 @@
/>
{#if actionError !== undefined}
<div class="action-error">
<Callout tone="danger">{actionError.message}</Callout>
{#if actionError.detail !== undefined}
<pre>{actionError.detail}</pre>
{/if}
</div>
<ErrorCallout
messageKey={actionError.messageKey}
detail={actionError.detail}
note={partialNote}
/>
{/if}
<div class="split" class:with-panel={showDuplicates}>
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
<ul
bind:this={treeEl}
class="tree"
role="tree"
aria-label={t('common.edit')}
tabindex="0"
aria-activedescendant={focusedId === undefined ? undefined : `node-${focusedId}`}
<TreeList
bind:element={treeEl}
{rows}
{focusedId}
{renamingId}
{filtering}
{draggingId}
matched={search.matched}
editable={isEditable}
canDropInto={(id) => draggingId !== undefined && canMoveInto(roots, draggingId, id)}
onkeydown={onKeydown}
>
{#each rows as row (row.node.id)}
<li
id="node-{row.node.id}"
data-node-id={row.node.id}
role="treeitem"
aria-level={row.depth}
aria-expanded={row.expandable ? row.expanded : undefined}
aria-selected={focusedId === row.node.id}
>
<TreeRow
node={row.node}
depth={row.depth}
expandable={row.expandable}
expanded={row.expanded}
focused={focusedId === row.node.id}
matched={search.matched.has(row.node.id)}
renaming={renamingId === row.node.id}
ontoggle={() => toggle(row.node.id)}
onfocus={() => (focusedId = row.node.id)}
onstartRename={() => (renamingId = row.node.id)}
onrename={(title) => void commitRename(row.node.id, title)}
oncancelRename={() => (renamingId = undefined)}
ondelete={() => (pendingDelete = row.node)}
onopen={() => void openUrl(row.node.url ?? '')}
oncopyUrl={() => void copyUrl(row.node.url ?? '')}
onmoveTo={() => (movingNode = row.node)}
ondragstart={() => (draggingId = row.node.id)}
ondropinto={() => onDrop(row.node.id)}
dropTarget={draggingId !== undefined &&
canMoveInto(roots, draggingId, row.node.id)}
draggable={isEditable(row.node)}
editable={isEditable(row.node)}
/>
</li>
{/each}
{#if rows.length === 0}
<li class="empty">{filtering ? t('edit.noMatches') : t('edit.empty')}</li>
{/if}
</ul>
ontoggle={toggle}
onfocusRow={(id) => (focusedId = id)}
onstartRename={(id) => (renamingId = id)}
onrename={(id, title) => void commitRename(id, title)}
oncancelRename={() => (renamingId = undefined)}
ondelete={(node) => (pendingDelete = node)}
onopen={(node) => void openUrl(node.url ?? "")}
oncopyUrl={(node) => void copyUrl(node.url ?? "")}
onmoveTo={(node) => (movingNode = node)}
ondragstart={(id) => (draggingId = id)}
ondropinto={(id) => onDrop(id)}
/>
{#if showDuplicates}
<DuplicatePanel
@@ -441,41 +461,6 @@
}
}
.tree {
list-style: none;
margin: 0;
padding: 0;
font-size: var(--fs-1);
max-height: 560px;
overflow: auto;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
}
.tree:focus-visible {
outline: 2px solid var(--accent);
}
.action-error {
margin-bottom: var(--sp-3);
}
.action-error pre {
margin: var(--sp-2) 0 0;
font-size: var(--fs-0);
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
overflow: auto;
user-select: all;
}
.empty {
color: var(--fg-muted);
padding: var(--sp-4);
text-align: center;
}
</style>
+66
View File
@@ -0,0 +1,66 @@
<script lang="ts">
/**
* A failure, shown the way docs/02 §7 requires: a localized sentence, and the
* raw browser string in a separate, copyable block.
*
* One component owns this because there is one specific way to get it wrong
* and it has been got wrong three times. Writing `detail ?? t(key)` looks
* like a sensible fallback, but the raw string is almost always present — so
* the translation becomes dead code and a Vietnamese or Japanese user sees an
* untranslated Chrome message as the entire explanation. LegalGate carries a
* comment recording that exact defect; #edit and #export still had it.
*
* The detail is `user-select: all` so a reporter can grab it in one click for
* an issue — it is the only part worth pasting.
*/
import { t } from '../i18n/index.svelte';
import Callout from './Callout.svelte';
interface Props {
/** Dotted i18n path. Never a resolved string. */
messageKey: string;
/** Raw, untranslated technical text. Omitted when there is none. */
detail?: string | undefined;
/**
* An already-localized sentence adding what the failure left behind — how
* many of a promised batch actually completed, for instance. Resolved by
* the caller because it interpolates counts they hold.
*/
note?: string | undefined;
}
let { messageKey, detail, note }: Props = $props();
</script>
<div class="error">
<Callout tone="danger">{t(messageKey)}</Callout>
{#if note !== undefined}
<p class="note">{note}</p>
{/if}
{#if detail !== undefined}
<pre>{detail}</pre>
{/if}
</div>
<style>
.error {
margin-bottom: var(--sp-3);
}
.note {
margin: var(--sp-2) 0 0;
color: var(--fg-muted);
font-size: var(--fs-1);
}
pre {
margin: var(--sp-2) 0 0;
font-size: var(--fs-0);
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
overflow: auto;
user-select: all;
}
</style>
+11 -6
View File
@@ -1,7 +1,7 @@
<script lang="ts">
import { onMount } from 'svelte';
import { getRootChildren, type LiveNode } from '../browser/bookmarks';
import { BmBrowserError } from '../browser/errors';
import { type DescribedError, describeError } from '../browser/describe-error';
import type { ExportFormat } from '../browser/storage';
import type { CsvDelimiter } from '../core/serialize/csv';
import type { MarkdownStyle } from '../core/serialize/markdown';
@@ -16,13 +16,14 @@
import { pushToast } from '../stores/toast.svelte';
import Button from './Button.svelte';
import Callout from './Callout.svelte';
import ErrorCallout from './ErrorCallout.svelte';
import FolderPickTree from './FolderPickTree.svelte';
import FormatSelect from './FormatSelect.svelte';
let roots = $state<LiveNode[]>([]);
let selection = $state<ReadonlySet<string> | undefined>(undefined);
let format = $state<ExportFormat>('netscape-html');
let loadError = $state<string | undefined>();
let loadError = $state<DescribedError | undefined>();
let csvDelimiter = $state<CsvDelimiter>(',');
let markdownStyle = $state<MarkdownStyle>('nested');
@@ -39,7 +40,9 @@
csvDelimiter = settings.csvDelimiter;
markdownStyle = settings.markdownStyle;
} catch (err) {
loadError = err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN');
// Was `err.detail` alone — a raw English Chrome string as the entire
// screen, in all three languages (docs/02 §7).
loadError = describeError(err);
}
}
@@ -63,15 +66,17 @@
pushToast(t('export.saved', { name: result.filename }), 'success');
} catch (err) {
// Tone matters: this used to share a variable with the success message
// and rendered failures in success-green.
pushToast(err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN'), 'danger');
// and rendered failures in success-green. The message is the localized
// sentence — a toast has no room for a detail block, which is the same
// reasoning the header's save-failure toast records.
pushToast(t(describeError(err).messageKey), 'danger');
}
})();
}
</script>
{#if loadError !== undefined}
<Callout tone="danger">{loadError}</Callout>
<ErrorCallout messageKey={loadError.messageKey} detail={loadError.detail} />
{:else}
<div class="split">
<section aria-label={t('export.scope')}>
+2 -13
View File
@@ -22,6 +22,7 @@
import Button from './Button.svelte';
import Callout from './Callout.svelte';
import DropZone from './DropZone.svelte';
import ErrorCallout from './ErrorCallout.svelte';
import ImportOptions from './ImportOptions.svelte';
import ProgressBar from './ProgressBar.svelte';
import StatsCard from './StatsCard.svelte';
@@ -201,10 +202,7 @@
onclick={resetImport}>{t('import.another')}</Button
>
{:else if session.kind === 'error'}
<Callout tone="danger">{t(session.messageKey)}</Callout>
{#if session.detail !== undefined}
<pre class="detail">{session.detail}</pre>
{/if}
<ErrorCallout messageKey={session.messageKey} detail={session.detail} />
{#if session.created !== undefined && session.created > 0}
<p class="muted">{t('import.partialCreated', { created: num(session.created) })}</p>
{/if}
@@ -264,13 +262,4 @@
margin-top: var(--sp-3);
}
.detail {
font-size: var(--fs-0);
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
overflow: auto;
user-select: all;
}
</style>
+142
View File
@@ -0,0 +1,142 @@
<script lang="ts">
/**
* The `role="tree"` container and its rows — docs/06 §3.3.
*
* Split out of `EditTab` so the ARIA structure lives in one place rather than
* inside a component that also owns loading, searching, mutation and five
* dialogs. The WAI-ARIA tree pattern is exacting — roving focus expressed
* through `aria-activedescendant`, `aria-level` starting at 1, `aria-expanded`
* present only on expandable rows — and it is easier to keep right when it is
* not surrounded by unrelated state.
*
* The keydown handler lives on this `<ul>`, not on a wrapper: a keydown
* handler on a non-focusable container never fires, and svelte-check flags it.
*/
import type { EditNode } from '../edit/patch-tree';
import type { VisibleRow } from '../edit/tree-keyboard';
import { t } from '../i18n/index.svelte';
import TreeRow from './TreeRow.svelte';
interface Props {
rows: readonly VisibleRow[];
focusedId: string | undefined;
renamingId: string | undefined;
/** Ids matching the current search, highlighted rather than filtered. */
matched: ReadonlySet<string>;
/** True while a search is narrowing the tree — picks the empty message. */
filtering: boolean;
draggingId: string | undefined;
editable: (node: EditNode) => boolean;
canDropInto: (id: string) => boolean;
element?: HTMLElement | undefined;
onkeydown: (event: KeyboardEvent) => void;
ontoggle: (id: string) => void;
onfocusRow: (id: string) => void;
onstartRename: (id: string) => void;
onrename: (id: string, title: string) => void;
oncancelRename: () => void;
ondelete: (node: EditNode) => void;
onopen: (node: EditNode) => void;
oncopyUrl: (node: EditNode) => void;
onmoveTo: (node: EditNode) => void;
ondragstart: (id: string) => void;
ondropinto: (id: string) => void;
}
let {
rows,
focusedId,
renamingId,
matched,
filtering,
draggingId,
editable,
canDropInto,
element = $bindable(),
onkeydown,
ontoggle,
onfocusRow,
onstartRename,
onrename,
oncancelRename,
ondelete,
onopen,
oncopyUrl,
onmoveTo,
ondragstart,
ondropinto,
}: Props = $props();
</script>
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
<ul
bind:this={element}
class="tree"
role="tree"
aria-label={t('common.edit')}
tabindex="0"
aria-activedescendant={focusedId === undefined ? undefined : `node-${focusedId}`}
{onkeydown}
>
{#each rows as row (row.node.id)}
<li
id="node-{row.node.id}"
data-node-id={row.node.id}
role="treeitem"
aria-level={row.depth}
aria-expanded={row.expandable ? row.expanded : undefined}
aria-selected={focusedId === row.node.id}
>
<TreeRow
node={row.node}
depth={row.depth}
expandable={row.expandable}
expanded={row.expanded}
focused={focusedId === row.node.id}
matched={matched.has(row.node.id)}
renaming={renamingId === row.node.id}
ontoggle={() => ontoggle(row.node.id)}
onfocus={() => onfocusRow(row.node.id)}
onstartRename={() => onstartRename(row.node.id)}
onrename={(title) => onrename(row.node.id, title)}
{oncancelRename}
ondelete={() => ondelete(row.node)}
onopen={() => onopen(row.node)}
oncopyUrl={() => oncopyUrl(row.node)}
onmoveTo={() => onmoveTo(row.node)}
ondragstart={() => ondragstart(row.node.id)}
ondropinto={() => ondropinto(row.node.id)}
dropTarget={draggingId !== undefined && canDropInto(row.node.id)}
draggable={editable(row.node)}
editable={editable(row.node)}
/>
</li>
{/each}
{#if rows.length === 0}
<li class="empty">{filtering ? t('edit.noMatches') : t('edit.empty')}</li>
{/if}
</ul>
<style>
.tree {
list-style: none;
margin: 0;
padding: var(--sp-2);
font-size: var(--fs-1);
max-height: 560px;
overflow: auto;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
}
.tree:focus-visible {
outline: 2px solid var(--accent);
}
.empty {
color: var(--fg-muted);
padding: var(--sp-4);
text-align: center;
}
</style>
+47
View File
@@ -0,0 +1,47 @@
/**
* Delete many nodes, one awaited call at a time, and report what happened —
* docs/03 §3.
*
* Purpose: give the "keep the first of each" bulk delete an outcome the caller
* cannot forget to handle.
* Inputs: the ids to remove, an injected remove, and a per-success callback for
* the optimistic local update.
* Guarantees: **never throws.** It stops at the first rejection and returns how
* far it got.
*
* Not throwing is the point. This is the project's recurring defect shape —
* mutate local state optimistically, await a `chrome.*` call that can reject,
* never handle the rejection — and it lived here in its purest form: the loop
* removed each node locally, awaited the browser, and on the first rejection
* abandoned the rest, leaving the user with a partial delete measured against a
* confirmation dialog that had promised an exact number.
*/
export interface BulkDeleteOutcome {
/** How many the browser actually accepted. */
deleted: number;
/** How many were asked for. */
total: number;
/** The rejection that stopped it, if one did. */
error?: unknown;
}
export async function deleteEach(
ids: readonly string[],
remove: (id: string) => Promise<void>,
onDeleted: (id: string) => void,
): Promise<BulkDeleteOutcome> {
let deleted = 0;
for (const id of ids) {
try {
await remove(id);
} catch (error) {
return { deleted, total: ids.length, error };
}
// Only after the browser has confirmed it. Updating first would leave the
// tree disagreeing with the browser for every id after a failure.
onDeleted(id);
deleted++;
}
return { deleted, total: ids.length };
}
+75
View File
@@ -0,0 +1,75 @@
/**
* Track which folders a *search* opened, separately from the ones the user
* opened — docs/03 §3.
*
* Purpose: let the tree collapse back when the search box is cleared, without
* closing anything the user opened by hand.
* Inputs: the current expanded set, the ids a search wants open, and the ids
* this module opened last time.
* Guarantees: pure, and never returns a new Set when nothing changed, so the
* `$effect` driving it does not thrash.
*
* Why the search merges into `expanded` at all: a render-time union of the two
* sets made the disclosure button and ArrowLeft dead on every search-expanded
* folder, because `toggle()` had nothing it could write to. The merge is
* deliberate; what was missing was the un-merge, so one character typed into
* the search box permanently expanded most of a large tree — and clearing the
* box then rendered every one of those rows at once, with no virtualization.
*/
export interface MergeResult {
expanded: ReadonlySet<string>;
/** Ids this module opened, to be closed again when the search clears. */
opened: ReadonlySet<string>;
}
/**
* Open everything the search needs, remembering what was not already open.
*
* @param expanded ids currently expanded
* @param wanted ids the search needs expanded
* @param opened ids a previous merge opened and has not yet collapsed
*/
export function mergeSearchExpansion(
expanded: ReadonlySet<string>,
wanted: ReadonlySet<string>,
opened: ReadonlySet<string>,
): MergeResult {
const missing = [...wanted].filter((id) => !expanded.has(id));
// Identity is preserved when there is nothing to do — the caller stores these
// in `$state`, and reassigning an equal Set would re-run every dependent.
if (missing.length === 0) return { expanded, opened };
return {
expanded: new Set([...expanded, ...missing]),
opened: new Set([...opened, ...missing]),
};
}
/**
* Close only what the search opened.
*
* A folder the user expanded themselves stays open even if the search also
* needed it — `forget` removes it from the search-owned set the moment they
* touch it, so ownership is decided at the point of interaction rather than
* guessed at collapse time.
*/
export function collapseSearchExpansion(
expanded: ReadonlySet<string>,
opened: ReadonlySet<string>,
): ReadonlySet<string> {
if (opened.size === 0) return expanded;
const next = new Set(expanded);
for (const id of opened) next.delete(id);
return next;
}
/** The user toggled this folder, so the search no longer owns it. */
export function forgetSearchExpansion(
opened: ReadonlySet<string>,
id: string,
): ReadonlySet<string> {
if (!opened.has(id)) return opened;
const next = new Set(opened);
next.delete(id);
return next;
}
+4
View File
@@ -142,6 +142,10 @@ const dict = {
keepFirstTitle: 'Delete duplicate copies?',
keepFirstBody:
'Keep the first copy of each link and delete the other {n}? This cannot be undone.',
// The dialog promises an exact number, so a partial delete has to reconcile
// against it — the action cannot be undone.
keepFirstPartial:
'Deleted {done} of {total} copies before this failed. Nothing else was removed.',
},
settings: {
autosave: 'Changes are saved as you make them.',
+2
View File
@@ -130,6 +130,8 @@ export default {
keeps: '保持',
keepFirstTitle: '重複したコピーを削除しますか?',
keepFirstBody: '各リンクの最初のコピーを残し、他の {n} 件を削除しますか?元に戻せません。',
keepFirstPartial:
'エラーが発生する前に {total} 件中 {done} 件を削除しました。それ以外は削除されていません。',
},
settings: {
autosave: '変更は自動的に保存されます。',
+2
View File
@@ -129,6 +129,8 @@ export default {
keeps: 'giữ lại',
keepFirstTitle: 'Xóa các bản trùng?',
keepFirstBody: 'Giữ bản đầu tiên của mỗi liên kết và xóa {n} bản còn lại? Không thể hoàn tác.',
keepFirstPartial:
'Đã xóa {done} trong số {total} bản trước khi lỗi xảy ra. Không có gì khác bị xóa.',
},
settings: {
autosave: 'Thay đổi được lưu ngay khi bạn chỉnh.',
+81
View File
@@ -0,0 +1,81 @@
import { describe, expect, it, vi } from 'vitest';
import { deleteEach } from '@/lib/edit/bulk-delete';
/**
* Bulk delete — docs/03 §3.
*
* `deleteEach` exists to make the project's recurring defect shape impossible
* here: mutate local state optimistically, await a `chrome.*` call that can
* reject, never handle the rejection. It never throws, so the caller cannot
* forget the failure case, and it reports how far it got — the confirmation
* dialog promised an exact number and the action cannot be undone.
*/
describe('deleteEach', () => {
it('deletes every id and reports a clean run', async () => {
const removed: string[] = [];
const outcome = await deleteEach(
['a', 'b', 'c'],
async () => {},
(id) => removed.push(id),
);
expect(outcome).toEqual({ deleted: 3, total: 3 });
expect(removed).toEqual(['a', 'b', 'c']);
});
it('stops at the first rejection and says how many landed', async () => {
const remove = vi.fn(async (id: string) => {
if (id === 'c') throw new Error('nope');
});
const outcome = await deleteEach(['a', 'b', 'c', 'd'], remove, () => {});
expect(outcome.deleted).toBe(2);
expect(outcome.total).toBe(4);
expect(outcome.error).toBeInstanceOf(Error);
// 'd' is never attempted — one refusal usually means the rest will refuse
// too, and hammering the API would just lengthen a frozen tab.
expect(remove).toHaveBeenCalledTimes(3);
});
it('never throws, whatever the remove does', async () => {
await expect(
deleteEach(
['a'],
() => Promise.reject(new Error('boom')),
() => {},
),
).resolves.toMatchObject({ deleted: 0 });
await expect(
deleteEach(
['a'],
() => Promise.reject('a string'),
() => {},
),
).resolves.toMatchObject({ deleted: 0, error: 'a string' });
});
it('confirms locally only after the browser accepted', async () => {
// The other order is the defect: updating first leaves the tree claiming a
// node is gone that the browser still has, for every id after a failure.
const confirmed: string[] = [];
await deleteEach(
['a', 'b'],
async (id) => {
if (id === 'a') throw new Error('refused');
},
(id) => confirmed.push(id),
);
expect(confirmed).toEqual([]);
});
it('handles an empty list', async () => {
expect(
await deleteEach(
[],
async () => {},
() => {},
),
).toEqual({ deleted: 0, total: 0 });
});
});
+91
View File
@@ -0,0 +1,91 @@
import { describe, expect, it } from 'vitest';
import {
collapseSearchExpansion,
forgetSearchExpansion,
mergeSearchExpansion,
} from '@/lib/edit/search-expansion';
/**
* Search-driven expansion — docs/03 §3.
*
* The bug this closes: a one-character query expands most of a large tree, and
* clearing the box then rendered every one of those rows at once in a single
* synchronous pass, with no virtualization behind it. The 150 ms debounce
* delayed that; it never bounded it.
*/
const set = (...ids: string[]): ReadonlySet<string> => new Set(ids);
describe('mergeSearchExpansion', () => {
it('opens what the search needs and remembers only what it opened', () => {
const result = mergeSearchExpansion(set('a'), set('a', 'b', 'c'), set());
expect([...result.expanded].sort()).toEqual(['a', 'b', 'c']);
// 'a' was already open, so the search does not own it and must not close it.
expect([...result.opened].sort()).toEqual(['b', 'c']);
});
it('accumulates across successive queries', () => {
const first = mergeSearchExpansion(set(), set('a'), set());
const second = mergeSearchExpansion(first.expanded, set('b'), first.opened);
expect([...second.opened].sort()).toEqual(['a', 'b']);
});
it('returns the SAME set objects when nothing is missing', () => {
// Identity, not equality: the caller stores these in `$state`, so returning
// an equal-but-new Set would re-run every dependent on every keystroke.
const expanded = set('a', 'b');
const opened = set('b');
const result = mergeSearchExpansion(expanded, set('a'), opened);
expect(result.expanded).toBe(expanded);
expect(result.opened).toBe(opened);
});
it('is a no-op for an empty search', () => {
const expanded = set('a');
expect(mergeSearchExpansion(expanded, set(), set()).expanded).toBe(expanded);
});
});
describe('collapseSearchExpansion', () => {
it('closes only what the search opened', () => {
const result = collapseSearchExpansion(set('a', 'b', 'c'), set('b', 'c'));
expect([...result]).toEqual(['a']);
});
it('leaves a folder the user opened themselves alone', () => {
// The whole point: a user who expanded a folder while searching keeps it.
const merged = mergeSearchExpansion(set(), set('a', 'b'), set());
const owned = forgetSearchExpansion(merged.opened, 'a');
expect([...collapseSearchExpansion(merged.expanded, owned)]).toEqual(['a']);
});
it('returns the same set when the search opened nothing', () => {
const expanded = set('a');
expect(collapseSearchExpansion(expanded, set())).toBe(expanded);
});
it('tolerates an id that is no longer expanded', () => {
expect([...collapseSearchExpansion(set('a'), set('gone'))]).toEqual(['a']);
});
});
describe('forgetSearchExpansion', () => {
it('drops the id, transferring ownership to the user', () => {
expect([...forgetSearchExpansion(set('a', 'b'), 'a')]).toEqual(['b']);
});
it('returns the same set for an id it never owned', () => {
const opened = set('a');
expect(forgetSearchExpansion(opened, 'zzz')).toBe(opened);
});
});
describe('the whole cycle', () => {
it('search, then clear, returns exactly to the starting state', () => {
const start = set('root');
const merged = mergeSearchExpansion(start, set('root', 'x', 'y', 'z'), set());
expect(merged.expanded.size).toBe(4);
const cleared = collapseSearchExpansion(merged.expanded, merged.opened);
expect([...cleared]).toEqual(['root']);
});
});