feat(export,edit): the #export and #edit tabs (Phase 3)

Adds the export pipeline (tri-state folder picker, four format cards,
per-format options, download) and the edit tree (CRUD, search, duplicate
panel, drag & drop with keyboard "Move to…" parity, live event sync, WAI-ARIA
keyboard navigation). 338 tests, npm run verify green, manifest unchanged.

The Phase 3 exit criterion is covered by a test: an exported HTML file
re-imports losslessly, toolbar marker and all.

Pure logic lives in core/edit modules so the whole keyboard and selection
contract is testable without mounting components: core/select.ts (tri-state,
including the ancestor-splitting untick), core/search.ts, edit/patch-tree.ts
(immutable event patching), edit/tree-keyboard.ts, edit/move-target.ts.

An adversarial review found 14 defects, all fixed here. The pattern in the
serious ones was the same: mutate locally, then await a browser call that can
reject, and never look at the result.

- Every mutation now runs through a guard that reports the failure and
  resyncs from the browser. Previously a rejected delete removed an entire
  subtree from the UI while it still existed in the profile, with no error and
  no way back but a reload — and a rejected move left a node displayed under a
  folder it was not in.
- Permanent roots and policy-managed nodes were fully editable. Rename, delete
  and Move-to are now gated on both, in the mouse and keyboard paths, so calls
  the browser will always reject are never attempted. "Move to…" previously
  validated only the destination, so moving a root nested the two roots.
- New folder resolved the focused node's PARENT, so selecting a root yielded
  the synthetic root "0" and every create failed silently; selecting a folder
  created a sibling. It now targets the focused folder itself and expands it,
  so the inline rename input actually mounts.
- The tree kept DOM focus on the container and never published
  aria-activedescendant, so arrow-key navigation announced nothing.
- The container keydown handler ignored event.target and modifier state, so it
  stole keys aimed at row buttons and swallowed Ctrl/Cmd-F — which was not
  implemented at all.
- Search expansion was unioned in at render time but toggle() wrote only to
  `expanded`, making the disclosure button and ArrowLeft dead on every
  search-expanded folder. Search expansion is now merged into `expanded`.
- The tri-state checkbox never showed indeterminate: a parameterless Svelte
  action runs once at creation, so a partially selected folder looked
  identical to an unselected one.
- The export button re-serialized the whole tree on every render just to show
  a count, and its filename disagreed with the saved one.
- Markdown layout and CSV delimiter were unreachable from the Export tab.
- Search tested title and url separately; the spec defines one haystack.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 committed 2026-07-26 06:13:53 +07:00
1 parent f54af08980
commit e12e8009d7
29 files changed
+3174 -2

No files matched your search

+2
View File
@@ -36,3 +36,5 @@ npm-debug.log*
# Generated fixtures that are too big to commit (tests/fixtures/generate-huge.ts
# writes here on demand — docs/11 §2)
tests/fixtures/generated/
.claude/
+6
View File
@@ -1,5 +1,7 @@
<script lang="ts">
import { onMount } from 'svelte';
import EditTab from '@/lib/components/EditTab.svelte';
import ExportTab from '@/lib/components/ExportTab.svelte';
import ImportTab from '@/lib/components/ImportTab.svelte';
import TabBar from '@/lib/components/TabBar.svelte';
import { t } from '@/lib/i18n/index.svelte';
@@ -36,6 +38,10 @@
<main>
{#if getRoute() === 'import'}
<ImportTab />
{:else if getRoute() === 'export'}
<ExportTab />
{:else if getRoute() === 'edit'}
<EditTab />
{:else}
<!-- Phases 3-4 fill these in; the routes exist now so the shell is real. -->
<p class="placeholder">{t('common.comingSoon', { tab: t(`common.${getRoute()}`) })}</p>
+71 -1
View File
@@ -133,10 +133,80 @@ export async function create(details: {
return created as LiveNode;
}
async function removeTree(id: string): Promise<void> {
export async function update(id: string, changes: { title?: string; url?: string }): Promise<void> {
await guard('bookmarks.update', () => browser.bookmarks.update(id, changes));
}
export async function move(
id: string,
destination: { parentId?: string; index?: number },
): Promise<void> {
await guard('bookmarks.move', () => browser.bookmarks.move(id, destination));
}
/** Remove a single bookmark. Folders need `removeTree`. */
export async function remove(id: string): Promise<void> {
await guard('bookmarks.remove', () => browser.bookmarks.remove(id));
}
export async function removeTree(id: string): Promise<void> {
await guard('bookmarks.removeTree', () => browser.bookmarks.removeTree(id));
}
/** Events the #edit tree subscribes to — docs/03 §3 "Live sync". */
export interface BookmarkEvents {
onCreated: (id: string, node: LiveNode) => void;
onRemoved: (id: string) => void;
onChanged: (id: string, changes: { title?: string; url?: string }) => void;
onMoved: (id: string, info: { parentId: string; index: number }) => void;
}
type Listenable<T extends unknown[]> = {
addListener: (fn: (...args: T) => void) => void;
removeListener: (fn: (...args: T) => void) => void;
};
/**
* Subscribe to bookmark changes; returns an unsubscribe function.
*
* Listeners attach on tab enter and detach on leave (docs/03 §3) — an #edit
* tab left subscribed while an import runs would otherwise take one event per
* created node.
*/
export function subscribe(handlers: BookmarkEvents): () => void {
const api = browser.bookmarks as unknown as {
onCreated: Listenable<[string, LiveNode]>;
onRemoved: Listenable<[string, unknown]>;
onChanged: Listenable<[string, { title?: string; url?: string }]>;
onMoved: Listenable<[string, { parentId: string; index: number }]>;
};
const onCreated = (id: string, node: LiveNode): void => {
handlers.onCreated(id, node);
};
const onRemoved = (id: string): void => {
handlers.onRemoved(id);
};
const onChanged = (id: string, changes: { title?: string; url?: string }): void => {
handlers.onChanged(id, changes);
};
const onMoved = (id: string, info: { parentId: string; index: number }): void => {
handlers.onMoved(id, info);
};
api.onCreated.addListener(onCreated);
api.onRemoved.addListener(onRemoved);
api.onChanged.addListener(onChanged);
api.onMoved.addListener(onMoved);
return () => {
api.onCreated.removeListener(onCreated);
api.onRemoved.removeListener(onRemoved);
api.onChanged.removeListener(onChanged);
api.onMoved.removeListener(onMoved);
};
}
/**
* Delete the CHILDREN of the given roots, never the roots themselves (the API
* forbids that anyway). Managed nodes are skipped — docs/05 §6.
+5 -1
View File
@@ -9,10 +9,11 @@
*/
import { browser } from 'wxt/browser';
import type { CsvDelimiter } from '../core/serialize/csv';
import type { MarkdownStyle } from '../core/serialize/markdown';
import type { Locale } from '../i18n/resolve-locale';
export type ThemePreference = 'system' | 'light' | 'dark';
type ExportFormat = 'netscape-html' | 'bm-json' | 'csv' | 'markdown';
export type ExportFormat = 'netscape-html' | 'bm-json' | 'csv' | 'markdown';
export type ImportMode = 'new-folder' | 'merge' | 'replace';
export interface Settings {
@@ -21,6 +22,7 @@ export interface Settings {
defaultExportFormat: ExportFormat;
defaultMergeMode: ImportMode;
csvDelimiter: CsvDelimiter;
markdownStyle: MarkdownStyle;
}
export interface LegalAcceptance {
@@ -35,6 +37,7 @@ export const DEFAULT_SETTINGS: Settings = {
defaultExportFormat: 'netscape-html',
defaultMergeMode: 'new-folder',
csvDelimiter: ',',
markdownStyle: 'nested',
};
const SETTINGS_KEY = 'settings';
@@ -61,6 +64,7 @@ function coerceSettings(raw: unknown): Settings {
]),
defaultMergeMode: pick('defaultMergeMode', ['new-folder', 'merge', 'replace']),
csvDelimiter: pick('csvDelimiter', [',', ';']),
markdownStyle: pick('markdownStyle', ['nested', 'flat']),
};
}
+82
View File
@@ -0,0 +1,82 @@
<script lang="ts">
interface Props {
open: boolean;
title: string;
body: string;
confirmLabel: string;
cancelLabel: string;
danger?: boolean;
onconfirm: () => void;
oncancel: () => void;
}
let { open, title, body, confirmLabel, cancelLabel, danger = false, onconfirm, oncancel }: Props =
$props();
let dialog: HTMLDialogElement | undefined = $state();
// showModal() gives the focus trap and Esc handling for free — no library,
// and it is the native behaviour docs/06 §5 asks for.
$effect(() => {
if (dialog === undefined) return;
if (open && !dialog.open) dialog.showModal();
if (!open && dialog.open) dialog.close();
});
</script>
<dialog bind:this={dialog} oncancel={oncancel} onclose={oncancel} aria-label={title}>
<h2>{title}</h2>
<p>{body}</p>
<div class="actions">
<button class="cancel" onclick={oncancel}>{cancelLabel}</button>
<button class:danger onclick={onconfirm}>{confirmLabel}</button>
</div>
</dialog>
<style>
dialog {
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--bg);
color: var(--fg);
padding: var(--sp-4);
max-width: 44ch;
}
dialog::backdrop {
background: rgb(0 0 0 / 0.45);
}
h2 {
margin: 0 0 var(--sp-2);
font-size: var(--fs-3);
}
p {
margin: 0 0 var(--sp-4);
color: var(--fg-muted);
font-size: var(--fs-1);
}
.actions {
display: flex;
justify-content: flex-end;
gap: var(--sp-2);
}
button {
font: inherit;
padding: var(--sp-2) var(--sp-4);
border-radius: var(--radius-sm);
border: 1px solid var(--border);
background: var(--bg-raised);
color: var(--fg);
cursor: pointer;
}
.danger {
background: var(--danger);
border-color: var(--danger);
color: #fff;
}
</style>
+138
View File
@@ -0,0 +1,138 @@
<script lang="ts">
import type { DuplicateGroup } from '../core/dedupe';
import type { EditNode } from '../edit/patch-tree';
import { t } from '../i18n/index.svelte';
import Button from './Button.svelte';
interface Props {
groups: readonly DuplicateGroup<EditNode>[];
onclose: () => void;
ondelete: (node: EditNode) => void;
onkeepFirst: () => void;
}
let { groups, onclose, ondelete, onkeepFirst }: Props = $props();
const extra = $derived(groups.reduce((n, group) => n + group.nodes.length - 1, 0));
</script>
<aside aria-label={t('edit.duplicates')}>
<header>
<strong>{t('edit.duplicatesFound', { groups: groups.length, extra })}</strong>
<button class="close" aria-label={t('common.cancel')} onclick={onclose}>✕</button>
</header>
{#if groups.length === 0}
<p class="muted">{t('edit.noDuplicates')}</p>
{:else}
<Button variant="danger" onclick={onkeepFirst}>{t('edit.keepFirst', { n: extra })}</Button>
<ul>
{#each groups as group (group.key)}
<li>
<p class="key">{group.key}</p>
<ul class="items">
{#each group.nodes as node, i (node.id)}
<li>
<span class="title">{node.title}</span>
{#if i === 0}
<span class="keep">{t('edit.keeps')}</span>
{:else}
<button onclick={() => ondelete(node)}>{t('edit.delete')}</button>
{/if}
</li>
{/each}
</ul>
</li>
{/each}
</ul>
{/if}
</aside>
<style>
aside {
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-3);
background: var(--bg-raised);
display: flex;
flex-direction: column;
gap: var(--sp-3);
max-height: 520px;
overflow: auto;
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-2);
}
.close {
font: inherit;
background: none;
border: none;
color: var(--fg-muted);
cursor: pointer;
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: var(--sp-3);
}
.key {
margin: 0 0 var(--sp-1);
font-size: var(--fs-0);
color: var(--fg-muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.items {
gap: var(--sp-1);
font-size: var(--fs-1);
}
.items li {
display: flex;
align-items: center;
gap: var(--sp-2);
}
.items .title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.items button {
margin-left: auto;
font: inherit;
font-size: var(--fs-0);
background: none;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
color: var(--danger);
cursor: pointer;
padding: 0 var(--sp-2);
}
.keep {
margin-left: auto;
font-size: var(--fs-0);
color: var(--success);
}
.muted {
margin: 0;
color: var(--fg-muted);
font-size: var(--fs-1);
}
</style>
+589
View File
@@ -0,0 +1,589 @@
<script lang="ts">
import { onMount } from 'svelte';
import { browser } from 'wxt/browser';
import {
create,
getRootChildren,
type LiveNode,
move,
remove,
removeTree,
subscribe,
update,
} from '../browser/bookmarks';
import { BmBrowserError } from '../browser/errors';
import { findDuplicateGroups } from '../core/dedupe';
import { searchTree } from '../core/search';
import {
changeNode,
type EditNode,
findNode,
insertNode,
moveNode,
removeNode,
} from '../edit/patch-tree';
import { canMoveInto, moveTargets } from '../edit/move-target';
import { resolveKey, visibleRows } from '../edit/tree-keyboard';
import { t } from '../i18n/index.svelte';
import Button from './Button.svelte';
import Callout from './Callout.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
import DuplicatePanel from './DuplicatePanel.svelte';
import TreeRow from './TreeRow.svelte';
let roots = $state<EditNode[]>([]);
let expanded = $state<Set<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 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 searchInput = $state<HTMLInputElement | undefined>();
let treeEl = $state<HTMLElement | undefined>();
let debounceTimer: ReturnType<typeof setTimeout> | undefined;
onMount(() => {
void load();
// Listeners attach on enter and detach on leave (docs/03 §3) — a tab left
// subscribed during an import would take one event per created node.
const unsubscribe = subscribe({
onCreated: (_id, node) => {
if (node.parentId !== undefined) {
roots = insertNode(roots, node.parentId, node.index, toEditNode(node));
}
},
onRemoved: (id) => {
roots = removeNode(roots, id);
},
onChanged: (id, changes) => {
roots = changeNode(roots, id, changes);
},
onMoved: (id, info) => {
roots = moveNode(roots, id, info.parentId, info.index);
},
});
globalThis.addEventListener('keydown', onWindowKeydown);
return () => {
unsubscribe();
globalThis.removeEventListener('keydown', onWindowKeydown);
if (debounceTimer !== undefined) clearTimeout(debounceTimer);
};
});
function toEditNode(node: LiveNode): EditNode {
return {
id: node.id,
...(node.parentId !== undefined && { parentId: node.parentId }),
title: node.title,
...(node.url !== undefined && { url: node.url }),
...(node.url === undefined && { children: (node.children ?? []).map(toEditNode) }),
...(node.unmodifiable !== undefined && { unmodifiable: node.unmodifiable }),
};
}
async function load(): Promise<void> {
try {
roots = (await getRootChildren()).map(toEditNode);
expanded = new Set(roots.map((root) => root.id));
} catch (err) {
loadError = err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN');
}
}
function onQuery(value: string): void {
query = value;
if (debounceTimer !== undefined) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
debounced = value;
}, 150);
}
const search = $derived(searchTree(roots, debounced));
const filtering = $derived(debounced.trim() !== '');
// 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.
$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]);
});
const rows = $derived(visibleRows(roots, expanded, filtering ? search.visible : undefined));
const duplicateGroups = $derived(
findDuplicateGroups(flatten(roots).filter((node) => node.url !== undefined)),
);
function flatten(nodes: readonly EditNode[], into: EditNode[] = []): EditNode[] {
for (const node of nodes) {
into.push(node);
flatten(node.children ?? [], into);
}
return into;
}
/**
* Permanent roots and policy-managed nodes reject every write, so the UI must
* not offer the affordance at all — optimistically mutating first and finding
* out on rejection is how the tree ends up disagreeing with the browser.
*/
function isEditable(node: EditNode): boolean {
if (node.unmodifiable !== undefined) return false;
return !roots.some((root) => root.id === node.id);
}
/**
* Run a mutation, and on failure resync from the browser — the only source of
* truth. A snapshot restore would resurrect rows that earlier iterations of a
* bulk operation legitimately deleted.
*/
async function guardEdit(run: () => Promise<void>): Promise<void> {
actionError = undefined;
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 };
await load();
}
}
function toggle(id: string): void {
const next = new Set(expanded);
if (next.has(id)) next.delete(id);
else next.add(id);
expanded = next;
}
function onKeydown(event: KeyboardEvent): void {
if (renamingId !== undefined) return;
// Keys aimed at a row's own button (or the rename input) belong to that
// control — stealing them cancelled the button's activation.
if (event.target !== event.currentTarget) return;
if (event.ctrlKey || event.metaKey || event.altKey) return;
const action = resolveKey(event.key, focusedId, rows);
if (action.kind === 'none') return;
event.preventDefault();
switch (action.kind) {
case 'focus':
focusedId = action.id;
scrollFocusedIntoView();
break;
case 'expand':
case 'collapse':
toggle(action.id);
break;
case 'rename': {
const node = findNode(roots, action.id);
if (node !== undefined && isEditable(node)) renamingId = action.id;
break;
}
case 'delete': {
const node = findNode(roots, action.id);
if (node !== undefined && isEditable(node)) pendingDelete = node;
break;
}
case 'activate': {
const node = findNode(roots, action.id);
if (node?.url !== undefined) void openUrl(node.url);
else if (node !== undefined) toggle(node.id);
break;
}
}
}
/**
* Only http(s) reach the browser. `javascript:` and `data:` are display-only
* (docs/09 T3) — Chromium also rejects them, but the app-side allowlist is
* the authoritative control.
*/
async function openUrl(url: string): Promise<void> {
let scheme = '';
try {
scheme = new URL(url).protocol;
} catch {
return;
}
if (scheme !== 'http:' && scheme !== 'https:') return;
await browser.tabs.create({ url });
}
async function commitRename(id: string, title: string): Promise<void> {
renamingId = undefined;
const node = findNode(roots, id);
if (node === undefined || !isEditable(node)) return;
if (node.title === title || title.trim() === '') return;
await guardEdit(async () => {
// Optimistic: the onChanged event confirms it, guardEdit resyncs on failure.
roots = changeNode(roots, id, { title });
await update(id, { title });
});
}
async function confirmDelete(): Promise<void> {
const node = pendingDelete;
pendingDelete = undefined;
if (node === undefined || !isEditable(node)) return;
await guardEdit(async () => {
roots = removeNode(roots, node.id);
if (node.url === undefined) await removeTree(node.id);
else await remove(node.id);
});
}
async function newFolder(): Promise<void> {
// Into the focused FOLDER, or alongside the focused bookmark. Using the
// focused node's parent unconditionally meant selecting a root resolved to
// the synthetic root "0", which every create rejects.
const focused = findNode(roots, focusedId ?? '');
const writableRoot = roots.find((root) => root.unmodifiable === undefined)?.id;
const parentId =
focused === undefined
? writableRoot
: focused.url === undefined
? focused.id
: (focused.parentId ?? writableRoot);
if (parentId === undefined) return;
await guardEdit(async () => {
const created = await create({ parentId, title: t('edit.newFolderTitle') });
// The row must be rendered before the inline rename input can mount —
// otherwise renamingId locks every tree key with nothing to type into.
expanded = new Set([...expanded, parentId]);
focusedId = created.id;
renamingId = created.id;
});
}
async function keepFirstInEachGroup(): Promise<void> {
pendingKeepFirst = false;
// Snapshot the ids first: duplicateGroups is $derived from `roots`, so
// reading it inside the loop would recompute mid-iteration.
const doomed = duplicateGroups.flatMap((group) => group.nodes.slice(1).map((n) => n.id));
await guardEdit(async () => {
for (const id of doomed) {
roots = removeNode(roots, id);
await remove(id);
}
});
}
/** Shared by the drag path and the keyboard "Move to…" path. */
async function moveInto(id: string, parentId: string): Promise<void> {
const node = findNode(roots, id);
if (node === undefined || !isEditable(node)) return;
if (!canMoveInto(roots, id, parentId)) return;
await guardEdit(async () => {
roots = moveNode(roots, id, parentId, undefined);
await move(id, { parentId });
});
}
function onDrop(targetId: string): void {
const id = draggingId;
draggingId = undefined;
if (id !== undefined) void moveInto(id, targetId);
}
const targets = $derived(moveTargets(roots, movingNode));
/** Keep the focused row on screen — the tree is a fixed-height scroller. */
function scrollFocusedIntoView(): void {
if (treeEl === undefined || focusedId === undefined) return;
queueMicrotask(() => {
treeEl
?.querySelector(`[data-node-id="${CSS.escape(focusedId ?? '')}"]`)
?.scrollIntoView({ block: 'nearest' });
});
}
/** ⌘/Ctrl-F focuses the search box — docs/06 §3.3. */
function onWindowKeydown(event: KeyboardEvent): void {
if (event.key !== 'f' || !(event.ctrlKey || event.metaKey)) return;
event.preventDefault();
searchInput?.focus();
searchInput?.select();
}
const descendantCount = $derived(
pendingDelete === undefined ? 0 : flatten(pendingDelete.children ?? []).length,
);
</script>
{#if loadError !== undefined}
<Callout tone="danger">{loadError}</Callout>
{:else}
<div class="toolbar">
<input
bind:this={searchInput}
type="search"
placeholder={t('edit.search')}
aria-label={t('edit.search')}
value={query}
oninput={(e) => onQuery((e.currentTarget as HTMLInputElement).value)}
/>
<Button onclick={() => void newFolder()}>{t('edit.newFolder')}</Button>
<Button onclick={() => (showDuplicates = !showDuplicates)}>{t('edit.findDuplicates')}</Button>
<Button onclick={() => (expanded = new Set(flatten(roots).map((n) => n.id)))}
>{t('edit.expandAll')}</Button
>
<Button onclick={() => (expanded = new Set())}>{t('edit.collapseAll')}</Button>
</div>
{#if actionError !== undefined}
<div class="action-error">
<Callout tone="danger">{actionError.message}</Callout>
{#if actionError.detail !== undefined}
<pre>{actionError.detail}</pre>
{/if}
</div>
{/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}`}
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 ?? '')}
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>
{#if showDuplicates}
<DuplicatePanel
groups={duplicateGroups}
onclose={() => (showDuplicates = false)}
ondelete={(node) => (pendingDelete = node)}
onkeepFirst={() => (pendingKeepFirst = true)}
/>
{/if}
</div>
{/if}
{#if movingNode !== undefined}
<div class="move-to" role="dialog" aria-label={t('edit.moveTo')}>
<p>{t('edit.moveToBody', { title: movingNode.title })}</p>
<ul>
{#each targets as target (target.id)}
<li>
<button
onclick={() => {
const id = movingNode?.id;
movingNode = undefined;
if (id !== undefined) void moveInto(id, target.id);
}}>{target.label}</button
>
</li>
{/each}
{#if targets.length === 0}
<li class="muted">{t('edit.noMoveTargets')}</li>
{/if}
</ul>
<Button onclick={() => (movingNode = undefined)}>{t('common.cancel')}</Button>
</div>
{/if}
<ConfirmDialog
open={pendingDelete !== undefined}
danger
title={t('edit.deleteTitle')}
body={descendantCount > 0
? t('edit.deleteFolderBody', { title: pendingDelete?.title ?? '', n: descendantCount })
: t('edit.deleteBody', { title: pendingDelete?.title ?? '' })}
confirmLabel={t('edit.delete')}
cancelLabel={t('common.cancel')}
onconfirm={() => void confirmDelete()}
oncancel={() => (pendingDelete = undefined)}
/>
<ConfirmDialog
open={pendingKeepFirst}
danger
title={t('edit.keepFirstTitle')}
body={t('edit.keepFirstBody', {
n: duplicateGroups.reduce((n, g) => n + g.nodes.length - 1, 0),
})}
confirmLabel={t('edit.delete')}
cancelLabel={t('common.cancel')}
onconfirm={() => void keepFirstInEachGroup()}
oncancel={() => (pendingKeepFirst = false)}
/>
<style>
.toolbar {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
margin-bottom: var(--sp-3);
}
.toolbar input {
font: inherit;
flex: 1;
min-width: 12ch;
padding: var(--sp-2) var(--sp-3);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg);
color: var(--fg);
}
.split {
display: grid;
grid-template-columns: 1fr;
gap: var(--sp-4);
align-items: start;
}
.with-panel {
grid-template-columns: 1fr 340px;
}
@media (max-width: 780px) {
.with-panel {
grid-template-columns: 1fr;
}
}
.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;
}
.move-to {
position: fixed;
inset-block-end: var(--sp-4);
inset-inline-end: var(--sp-4);
width: min(360px, calc(100vw - var(--sp-6)));
max-height: 60vh;
overflow: auto;
background: var(--bg);
border: 1px solid var(--accent);
border-radius: var(--radius);
padding: var(--sp-3);
box-shadow: 0 8px 32px rgb(0 0 0 / 0.25);
}
.move-to p {
margin: 0 0 var(--sp-2);
font-size: var(--fs-1);
color: var(--fg-muted);
}
.move-to ul {
list-style: none;
margin: 0 0 var(--sp-3);
padding: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.move-to button {
font: inherit;
width: 100%;
text-align: left;
background: none;
border: none;
border-radius: var(--radius-sm);
color: var(--fg);
cursor: pointer;
padding: var(--sp-1) var(--sp-2);
}
.move-to button:hover {
background: var(--bg-raised);
}
.muted {
color: var(--fg-muted);
font-size: var(--fs-1);
}
</style>
+164
View File
@@ -0,0 +1,164 @@
<script lang="ts">
import { onMount } from 'svelte';
import { getRootChildren, type LiveNode } from '../browser/bookmarks';
import { BmBrowserError } from '../browser/errors';
import type { ExportFormat } from '../browser/storage';
import type { CsvDelimiter } from '../core/serialize/csv';
import type { MarkdownStyle } from '../core/serialize/markdown';
import { countSelected, FORMAT_META, runExport } from '../export/run-export';
import { t } from '../i18n/index.svelte';
import { getSettings } from '../stores/settings.svelte';
import Button from './Button.svelte';
import Callout from './Callout.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 toast = $state<string | undefined>();
let csvDelimiter = $state<CsvDelimiter>(',');
let markdownStyle = $state<MarkdownStyle>('nested');
onMount(() => {
void load();
});
async function load(): Promise<void> {
try {
// runExport re-resolves the roots itself, so nothing is kept here.
roots = await getRootChildren();
const settings = getSettings();
format = settings.defaultExportFormat;
csvDelimiter = settings.csvDelimiter;
markdownStyle = settings.markdownStyle;
} catch (err) {
loadError = err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN');
}
}
/**
* Live count for the button label. Deliberately NOT buildExport() — that
* would re-serialize the entire tree on every render just to show a number,
* and would print a filename timestamped differently from the saved file.
*/
const bookmarkCount = $derived(countSelected(roots, selection));
function download(): void {
void (async () => {
try {
const result = await runExport({
format,
...(selection !== undefined && { selection }),
csvDelimiter,
markdownStyle,
now: new Date(),
});
toast = t('export.saved', { name: result.filename });
} catch (err) {
toast = err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN');
}
})();
}
</script>
{#if loadError !== undefined}
<Callout tone="danger">{loadError}</Callout>
{:else}
<div class="split">
<section aria-label={t('export.scope')}>
<FolderPickTree {roots} {selection} onchange={(next) => (selection = next)} />
</section>
<section class="side">
<FormatSelect {format} onchange={(next) => (format = next)} />
{#if !FORMAT_META[format].importable}
<Callout tone="warn">{t('export.markdownNote')}</Callout>
{/if}
{#if format === 'csv'}
<Callout tone="warn">{t('export.csvNote')}</Callout>
<label class="option">
<span>{t('export.csvDelimiter')}</span>
<select
value={csvDelimiter}
onchange={(e) => (csvDelimiter = (e.currentTarget as HTMLSelectElement).value as CsvDelimiter)}
>
<option value=",">{t('export.comma')}</option>
<option value=";">{t('export.semicolon')}</option>
</select>
</label>
{/if}
{#if format === 'markdown'}
<label class="option">
<span>{t('export.markdownStyle')}</span>
<select
value={markdownStyle}
onchange={(e) => (markdownStyle = (e.currentTarget as HTMLSelectElement).value as MarkdownStyle)}
>
<option value="nested">{t('export.nested')}</option>
<option value="flat">{t('export.flat')}</option>
</select>
</label>
{/if}
<Button
variant="primary"
disabled={bookmarkCount === 0}
onclick={download}
>
{t('export.start', { n: bookmarkCount })}
</Button>
{#if toast !== undefined}
<p class="toast" role="status">{toast}</p>
{/if}
</section>
</div>
{/if}
<style>
.split {
display: grid;
grid-template-columns: 1fr 360px;
gap: var(--sp-5);
align-items: start;
}
@media (max-width: 780px) {
.split {
grid-template-columns: 1fr;
}
}
.side {
display: flex;
flex-direction: column;
gap: var(--sp-3);
}
.option {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-2);
font-size: var(--fs-1);
}
.option select {
font: inherit;
padding: var(--sp-1) var(--sp-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg);
color: var(--fg);
}
.toast {
margin: 0;
font-size: var(--fs-1);
color: var(--success);
}
</style>
+114
View File
@@ -0,0 +1,114 @@
<script lang="ts">
import type { LiveNode } from '../browser/bookmarks';
import type { CheckState } from '../core/select';
import { t } from '../i18n/index.svelte';
import Self from './FolderPickNode.svelte';
interface Props {
node: LiveNode;
depth: number;
checkState: CheckState;
resolve: (node: LiveNode) => CheckState;
ontoggle: (node: LiveNode, checked: boolean) => void;
}
let { node, depth, checkState, resolve, ontoggle }: Props = $props();
// svelte-ignore state_referenced_locally
let expanded = $state(depth < 2);
/** Only folders are pickable — a bookmark travels with its parent. */
const folders = $derived((node.children ?? []).filter((child) => child.url === undefined));
const bookmarks = $derived((node.children ?? []).filter((child) => child.url !== undefined).length);
let input: HTMLInputElement | undefined = $state();
// `indeterminate` is a DOM property with no HTML attribute, so it has to be
// set imperatively — and re-set whenever checkState changes. A parameterless
// `use:` action would run only once at creation and never update.
$effect(() => {
if (input !== undefined) input.indeterminate = checkState === 'indeterminate';
});
</script>
<li role="treeitem" aria-expanded={folders.length > 0 ? expanded : undefined} aria-level={depth} aria-selected={checkState === 'checked'}>
<div class="row" style:padding-left="{(depth - 1) * 14}px">
{#if folders.length > 0}
<button
class="disclosure"
aria-label={expanded ? t('import.collapse') : t('import.expand')}
onclick={() => {
expanded = !expanded;
}}>{expanded ? '▾' : '▸'}</button
>
{:else}
<span class="disclosure" aria-hidden="true"></span>
{/if}
<label>
<input
type="checkbox"
bind:this={input}
checked={checkState === 'checked'}
onchange={(e) => ontoggle(node, (e.currentTarget as HTMLInputElement).checked)}
/>
<span class="title">{node.title}</span>
{#if bookmarks > 0}<span class="count">{bookmarks}</span>{/if}
</label>
</div>
{#if expanded && folders.length > 0}
<ul role="group">
{#each folders as child (child.id)}
<Self node={child} depth={depth + 1} checkState={resolve(child)} {resolve} {ontoggle} />
{/each}
</ul>
{/if}
</li>
<style>
li {
list-style: none;
}
ul {
margin: 0;
padding: 0;
}
.row {
display: flex;
align-items: center;
gap: var(--sp-1);
padding-block: 2px;
}
label {
display: flex;
align-items: center;
gap: var(--sp-2);
cursor: pointer;
min-width: 0;
}
.disclosure {
width: 1.2em;
font: inherit;
background: none;
border: none;
color: var(--fg-muted);
cursor: pointer;
padding: 0;
}
.title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.count {
font-size: var(--fs-0);
color: var(--fg-muted);
}
</style>
+74
View File
@@ -0,0 +1,74 @@
<script lang="ts">
import type { LiveNode } from '../browser/bookmarks';
import { checkStateOf, toggleSelection } from '../core/select';
import FolderPickNode from './FolderPickNode.svelte';
import { t } from '../i18n/index.svelte';
interface Props {
roots: readonly LiveNode[];
/** `undefined` ⇒ "Everything"; a Set ⇒ explicit folder selection. */
selection: ReadonlySet<string> | undefined;
onchange: (selection: ReadonlySet<string> | undefined) => void;
}
let { roots, selection, onchange }: Props = $props();
const everything = $derived(selection === undefined);
function toggleNode(node: LiveNode, checked: boolean): void {
// Leaving "Everything" materialises it into a real selection first, so the
// untick has something concrete to subtract from.
const base = selection ?? new Set(roots.map((root) => root.id));
onchange(toggleSelection(roots, node, checked, base));
}
</script>
<div class="pick">
<label class="master">
<input
type="checkbox"
checked={everything}
onchange={(e) => onchange((e.currentTarget as HTMLInputElement).checked ? undefined : new Set())}
/>
<strong>{t('export.everything')}</strong>
</label>
<ul role="tree" aria-label={t('export.scope')}>
{#each roots as root (root.id)}
<FolderPickNode
node={root}
depth={1}
checkState={everything ? 'checked' : checkStateOf(roots, root, selection ?? new Set())}
resolve={(node) =>
everything ? 'checked' : checkStateOf(roots, node, selection ?? new Set())}
ontoggle={toggleNode}
/>
{/each}
</ul>
</div>
<style>
.pick {
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-3);
max-height: 420px;
overflow: auto;
}
.master {
display: flex;
align-items: center;
gap: var(--sp-2);
padding-bottom: var(--sp-2);
border-bottom: 1px solid var(--border);
margin-bottom: var(--sp-2);
}
ul {
list-style: none;
margin: 0;
padding: 0;
font-size: var(--fs-1);
}
</style>
+74
View File
@@ -0,0 +1,74 @@
<script lang="ts">
import type { ExportFormat } from '../browser/storage';
import { t } from '../i18n/index.svelte';
import { FORMAT_META } from '../export/run-export';
interface Props {
format: ExportFormat;
onchange: (format: ExportFormat) => void;
}
let { format, onchange }: Props = $props();
const FORMATS = Object.keys(FORMAT_META) as ExportFormat[];
</script>
<fieldset>
<legend>{t('export.format')}</legend>
{#each FORMATS as value (value)}
<label class:selected={format === value}>
<input
type="radio"
name="export-format"
checked={format === value}
onchange={() => onchange(value)}
/>
<span class="body">
<strong>{t(`export.formats.${value}.name`)}</strong>
<span class="note">{t(`export.formats.${value}.note`)}</span>
</span>
</label>
{/each}
</fieldset>
<style>
fieldset {
border: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: var(--sp-2);
}
legend {
font-size: var(--fs-0);
color: var(--fg-muted);
padding: 0 0 var(--sp-2);
}
label {
display: flex;
align-items: flex-start;
gap: var(--sp-2);
padding: var(--sp-2) var(--sp-3);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
cursor: pointer;
}
.selected {
border-color: var(--accent);
background: var(--bg-raised);
}
.body {
display: flex;
flex-direction: column;
}
.note {
font-size: var(--fs-0);
color: var(--fg-muted);
}
</style>
+249
View File
@@ -0,0 +1,249 @@
<script lang="ts">
import type { EditNode } from '../edit/patch-tree';
import { t } from '../i18n/index.svelte';
interface Props {
node: EditNode;
depth: number;
expandable: boolean;
expanded: boolean;
focused: boolean;
matched: boolean;
renaming: boolean;
ontoggle: () => void;
onfocus: () => void;
onrename: (title: string) => void;
oncancelRename: () => void;
onstartRename: () => void;
ondelete: () => void;
onopen: () => void;
onmoveTo: () => void;
ondragstart: () => void;
ondropinto: () => void;
dropTarget: boolean;
draggable: boolean;
/** False for permanent roots and policy-managed nodes — docs/02 §4. */
editable: boolean;
}
let {
node,
depth,
expandable,
expanded,
focused,
matched,
renaming,
ontoggle,
onfocus,
onrename,
oncancelRename,
onstartRename,
ondelete,
onopen,
onmoveTo,
ondragstart,
ondropinto,
dropTarget,
draggable,
editable,
}: Props = $props();
const isFolder = $derived(node.url === undefined);
const domain = $derived(hostOf(node.url));
function hostOf(url: string | undefined): string {
if (url === undefined) return '';
try {
return new URL(url).host;
} catch {
// javascript:, data:, malformed — show nothing rather than guessing.
return '';
}
}
</script>
<div
class="row"
class:focused
class:matched
class:drop-target={dropTarget}
style:padding-left="{(depth - 1) * 16}px"
onclick={onfocus}
onkeydown={() => {}}
role="presentation"
{draggable}
ondragstart={(e) => {
e.dataTransfer?.setData('text/plain', node.id);
ondragstart();
}}
ondragover={(e) => {
// Only folders accept a drop; preventDefault is what marks it as valid.
if (isFolder) e.preventDefault();
}}
ondrop={(e) => {
e.preventDefault();
ondropinto();
}}
>
{#if expandable}
<button
class="disclosure"
aria-label={expanded ? t('import.collapse') : t('import.expand')}
onclick={(e) => {
e.stopPropagation();
ontoggle();
}}>{expanded ? '▾' : '▸'}</button
>
{:else}
<span class="disclosure" aria-hidden="true"></span>
{/if}
<span class="glyph" aria-hidden="true">{isFolder ? '🗀' : '🔗'}</span>
{#if renaming && editable}
<!-- svelte-ignore a11y_autofocus -->
<input
class="rename"
value={node.title}
autofocus
onkeydown={(e) => {
if (e.key === 'Enter') onrename((e.currentTarget as HTMLInputElement).value);
if (e.key === 'Escape') oncancelRename();
e.stopPropagation();
}}
onblur={(e) => onrename((e.currentTarget as HTMLInputElement).value)}
/>
{:else}
<span class="title">{node.title}</span>
{#if domain !== ''}<span class="domain">{domain}</span>{/if}
<span class="actions">
{#if editable}
<button
title={t('edit.rename')}
onclick={(e) => {
e.stopPropagation();
onstartRename();
}}>✎</button
>
{/if}
{#if !isFolder}
<button
title={t('edit.open')}
onclick={(e) => {
e.stopPropagation();
onopen();
}}>↗</button
>
{/if}
{#if editable}
<button
title={t('edit.moveTo')}
onclick={(e) => {
e.stopPropagation();
onmoveTo();
}}>⇄</button
>
<button
title={t('edit.delete')}
onclick={(e) => {
e.stopPropagation();
ondelete();
}}>🗑</button
>
{/if}
</span>
{/if}
</div>
<style>
.row {
display: flex;
align-items: center;
gap: var(--sp-2);
padding-block: 3px;
padding-right: var(--sp-2);
border-radius: var(--radius-sm);
cursor: default;
}
.row:hover {
background: var(--bg-raised);
}
.focused {
background: var(--bg-raised);
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.drop-target {
outline: 2px dashed var(--accent);
outline-offset: -2px;
}
.matched .title {
color: var(--accent);
font-weight: 600;
}
.disclosure {
width: 1.2em;
font: inherit;
background: none;
border: none;
color: var(--fg-muted);
cursor: pointer;
padding: 0;
}
.title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.domain {
font-size: var(--fs-0);
color: var(--fg-muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.rename {
font: inherit;
flex: 1;
min-width: 0;
background: var(--bg);
color: var(--fg);
border: 1px solid var(--accent);
border-radius: var(--radius-sm);
padding: 1px var(--sp-2);
}
.actions {
margin-left: auto;
display: none;
gap: var(--sp-1);
}
.row:hover .actions,
.focused .actions {
display: flex;
}
.actions button {
font: inherit;
background: none;
border: none;
color: var(--fg-muted);
cursor: pointer;
padding: 0 var(--sp-1);
}
.actions button:hover {
color: var(--accent);
}
</style>
+88
View File
@@ -0,0 +1,88 @@
/**
* Tree search — docs/05 §8.
*
* Purpose: filter the edit tree to matches plus their ancestors, so a hit deep
* in the tree is reachable without losing its context.
* Inputs: any tree of `{ id, title, url?, children? }`; a query string.
* Guarantees: pure; case-insensitive substring over `title + ' ' + url`.
* O(n) per keystroke, which is fine at our 100k cap — no fuzzy matching in
* v1 (zero-dependency rule).
*/
export interface SearchableNode {
id: string;
title: string;
url?: string;
children?: SearchableNode[];
}
export interface SearchResult {
/** Ids that matched the query themselves. */
matched: Set<string>;
/** Matches plus every ancestor of a match — the set to render. */
visible: Set<string>;
/** Ancestors of matches, which must be auto-expanded to reveal the hits. */
expand: Set<string>;
}
function matches(node: SearchableNode, needle: string): boolean {
// One haystack, not two fields tested separately — docs/05 §8 defines it as
// `title + ' ' + url`, so a query spanning the boundary still matches.
const haystack = `${node.title} ${node.url ?? ''}`.toLowerCase();
return haystack.includes(needle);
}
/**
* Find nodes matching `query`.
*
* An empty or whitespace-only query returns empty sets, which callers read as
* "no filter active" — distinct from "no results", where `matched` is empty
* but the query is not.
*/
export function searchTree(roots: readonly SearchableNode[], query: string): SearchResult {
const needle = query.trim().toLowerCase();
if (needle === '') return { matched: new Set(), visible: new Set(), expand: new Set() };
const matched = new Set<string>();
const visible = new Set<string>();
const expand = new Set<string>();
const walk = (nodes: readonly SearchableNode[], ancestors: readonly string[]): boolean => {
let anyHere = false;
for (const node of nodes) {
const self = matches(node, needle);
const trail = [...ancestors, node.id];
const below = walk(node.children ?? [], trail);
if (self) {
matched.add(node.id);
// A matching folder shows its contents, so the user can act on them.
for (const id of subtree(node)) visible.add(id);
}
if (self || below) {
visible.add(node.id);
for (const id of ancestors) {
visible.add(id);
expand.add(id);
}
// A folder that only matched via a descendant must open to show it.
if (below) expand.add(node.id);
anyHere = true;
}
}
return anyHere;
};
walk(roots, []);
return { matched, visible, expand };
}
function subtree(node: SearchableNode): string[] {
const ids: string[] = [];
const walk = (current: SearchableNode): void => {
ids.push(current.id);
for (const child of current.children ?? []) walk(child);
};
walk(node);
return ids;
}
+150
View File
@@ -0,0 +1,150 @@
/**
* Export scope selection — docs/03 §2 step 2, docs/06 §3.2.
*
* Purpose: the tri-state folder picker's model, and the filter that turns a
* selection into the subtree to serialize.
* Inputs: any tree of `{ id, children? }` — generic so `core/` stays free of
* browser types (layer rule 1) while still operating on the live tree.
* Guarantees: pure; selections are returned as new Sets, never mutated.
*
* The selection holds the *topmost* explicitly-chosen ids. A node is included
* when it, or any ancestor, is in the set — so checking "Bookmarks bar" needs
* one entry rather than one per descendant.
*/
export interface TreeLike {
id: string;
children?: TreeLike[];
}
export type CheckState = 'checked' | 'indeterminate' | 'unchecked';
function collectIds(node: TreeLike, into: Set<string>): void {
into.add(node.id);
for (const child of node.children ?? []) collectIds(child, into);
}
/** Every id at or below `node`, including its own. */
export function subtreeIds(node: TreeLike): Set<string> {
const ids = new Set<string>();
collectIds(node, ids);
return ids;
}
/** Path of nodes from a root down to `targetId`, inclusive. Empty if absent. */
export function pathTo(roots: readonly TreeLike[], targetId: string): TreeLike[] {
const walk = (nodes: readonly TreeLike[], trail: TreeLike[]): TreeLike[] | undefined => {
for (const node of nodes) {
const next = [...trail, node];
if (node.id === targetId) return next;
const found = walk(node.children ?? [], next);
if (found !== undefined) return found;
}
return undefined;
};
return walk(roots, []) ?? [];
}
/** Checked when selected outright or covered by a selected ancestor. */
export function checkStateOf(
roots: readonly TreeLike[],
node: TreeLike,
selection: ReadonlySet<string>,
): CheckState {
const path = pathTo(roots, node.id);
if (path.some((ancestor) => selection.has(ancestor.id))) return 'checked';
for (const id of subtreeIds(node)) {
if (id !== node.id && selection.has(id)) return 'indeterminate';
}
return 'unchecked';
}
/**
* Check or uncheck a node.
*
* Unchecking something covered by a selected ANCESTOR is the interesting case:
* the ancestor is expanded into its siblings-at-each-level so the rest of it
* stays selected, and only the target is dropped. Without that, unticking one
* folder inside a checked parent would silently do nothing.
*/
export function toggleSelection(
roots: readonly TreeLike[],
node: TreeLike,
checked: boolean,
selection: ReadonlySet<string>,
): Set<string> {
const next = new Set(selection);
const covered = subtreeIds(node);
if (checked) {
// Drop anything now redundant, then add the single covering id.
for (const id of covered) next.delete(id);
next.add(node.id);
return collapseRedundant(roots, next);
}
const path = pathTo(roots, node.id);
const selectedAncestor = path.find(
(ancestor) => ancestor.id !== node.id && next.has(ancestor.id),
);
if (selectedAncestor !== undefined) {
// Push the ancestor's selection down one level at a time until the target
// is expressible on its own, then remove it.
next.delete(selectedAncestor.id);
let cursor = selectedAncestor;
while (cursor.id !== node.id) {
const nextOnPath = path[path.indexOf(cursor) + 1];
if (nextOnPath === undefined) break;
for (const sibling of cursor.children ?? []) {
if (sibling.id !== nextOnPath.id) next.add(sibling.id);
}
cursor = nextOnPath;
}
}
for (const id of covered) next.delete(id);
return next;
}
/** Replace a fully-selected set of siblings with their parent, recursively. */
function collapseRedundant(roots: readonly TreeLike[], selection: Set<string>): Set<string> {
const visit = (node: TreeLike): boolean => {
if (selection.has(node.id)) return true;
const children = node.children ?? [];
if (children.length === 0) return false;
const all = children.map(visit).every(Boolean);
if (all) {
for (const child of children) selection.delete(child.id);
selection.add(node.id);
}
return all;
};
for (const root of roots) visit(root);
return selection;
}
/**
* Keep only the selected parts of a tree.
*
* A selected node brings its whole subtree. An unselected folder survives only
* as a path to something selected beneath it, so exported files keep their
* folder structure instead of flattening.
*/
export function filterBySelection<T extends { id: string; children?: T[] }>(
nodes: readonly T[],
selection: ReadonlySet<string>,
): T[] {
const out: T[] = [];
for (const node of nodes) {
if (selection.has(node.id)) {
out.push(node);
continue;
}
if (node.children === undefined) continue;
const children = filterBySelection(node.children, selection);
if (children.length > 0) out.push({ ...node, children });
}
return out;
}
+71
View File
@@ -0,0 +1,71 @@
/**
* Move destinations — docs/03 §3 "Move", docs/06 §3.3.
*
* Purpose: the folder list behind "Move to…", and the rule for whether a drop
* is legal. Pure, so the DnD and keyboard paths share one definition of
* validity rather than drifting apart.
*/
import type { EditNode } from './patch-tree';
import { findNode } from './patch-tree';
export interface MoveTarget {
id: string;
/** Indented display path, e.g. "Bookmarks bar / Dev". */
label: string;
depth: number;
}
/**
* Every folder a node may be moved into.
*
* Excludes the node itself, its own descendants (which would detach the
* subtree), its current parent (a no-op), and anything policy-managed.
*/
export function moveTargets(
roots: readonly EditNode[],
moving: EditNode | undefined,
): MoveTarget[] {
const targets: MoveTarget[] = [];
const forbidden = new Set<string>();
if (moving !== undefined) {
forbidden.add(moving.id);
const walk = (node: EditNode): void => {
forbidden.add(node.id);
for (const child of node.children ?? []) walk(child);
};
walk(moving);
}
const collect = (nodes: readonly EditNode[], trail: string[], depth: number): void => {
for (const node of nodes) {
if (node.url !== undefined) continue;
if (node.unmodifiable !== undefined) continue;
const label = [...trail, node.title];
if (!forbidden.has(node.id) && node.id !== moving?.parentId) {
targets.push({ id: node.id, label: label.join(' / '), depth });
}
collect(node.children ?? [], label, depth + 1);
}
};
collect(roots, [], 1);
return targets;
}
/** True when `movingId` may be dropped into `targetId`. */
export function canMoveInto(
roots: readonly EditNode[],
movingId: string,
targetId: string,
): boolean {
if (movingId === targetId) return false;
const target = findNode(roots, targetId);
if (target === undefined || target.url !== undefined) return false;
if (target.unmodifiable !== undefined) return false;
const moving = findNode(roots, movingId);
if (moving === undefined) return false;
// Dropping a folder inside itself would detach the whole subtree.
return findNode(moving.children ?? [], targetId) === undefined;
}
+149
View File
@@ -0,0 +1,149 @@
/**
* Live-tree patching — docs/03 §3 "Live sync".
*
* Purpose: apply `chrome.bookmarks` events to the in-memory tree so external
* changes (another window, a sync push, or our own import) appear without a
* reload.
* Inputs: the current roots plus one event payload.
* Guarantees: pure and immutable — every patch returns a new array, with
* untouched branches shared by reference so Svelte only re-renders the path
* that actually changed. Unknown ids are no-ops rather than throws: events
* for nodes outside our view (or already removed) arrive routinely.
*/
export interface EditNode {
id: string;
parentId?: string;
index?: number;
title: string;
url?: string;
dateAdded?: number;
unmodifiable?: string;
children?: EditNode[];
}
const isFolder = (node: EditNode): boolean => node.url === undefined;
/** Map over a node's children, returning the original array when nothing changed. */
function mapChildren(
node: EditNode,
fn: (children: EditNode[]) => EditNode[] | undefined,
): EditNode {
const children = node.children;
if (children === undefined) return node;
const next = fn(children);
return next === undefined ? node : { ...node, children: next };
}
/** Insert `node` under `parentId` at `index` (or append when out of range). */
export function insertNode(
roots: readonly EditNode[],
parentId: string,
index: number | undefined,
node: EditNode,
): EditNode[] {
let inserted = false;
const walk = (nodes: readonly EditNode[]): EditNode[] | undefined => {
let changed = false;
const out = nodes.map((current) => {
if (current.id === parentId && isFolder(current)) {
const children = [...(current.children ?? [])];
const at =
index === undefined || index < 0 || index > children.length ? children.length : index;
children.splice(at, 0, node);
inserted = true;
changed = true;
return { ...current, children };
}
const patched = mapChildren(current, walk);
if (patched !== current) changed = true;
return patched;
});
return changed ? out : undefined;
};
const next = walk(roots);
// A parent we do not hold (e.g. a hidden root) simply drops the event.
return inserted && next !== undefined ? next : [...roots];
}
/** Remove a node and its subtree. */
export function removeNode(roots: readonly EditNode[], id: string): EditNode[] {
let removed = false;
const walk = (nodes: readonly EditNode[]): EditNode[] | undefined => {
if (nodes.some((node) => node.id === id)) {
removed = true;
return nodes.filter((node) => node.id !== id);
}
let changed = false;
const out = nodes.map((node) => {
const patched = mapChildren(node, walk);
if (patched !== node) changed = true;
return patched;
});
return changed ? out : undefined;
};
const next = walk(roots);
return removed && next !== undefined ? next : [...roots];
}
/** Apply a title/url change in place (immutably). */
export function changeNode(
roots: readonly EditNode[],
id: string,
changes: { title?: string; url?: string },
): EditNode[] {
const walk = (nodes: readonly EditNode[]): EditNode[] | undefined => {
let changed = false;
const out = nodes.map((node) => {
if (node.id === id) {
changed = true;
return {
...node,
...(changes.title !== undefined && { title: changes.title }),
...(changes.url !== undefined && { url: changes.url }),
};
}
const patched = mapChildren(node, walk);
if (patched !== node) changed = true;
return patched;
});
return changed ? out : undefined;
};
return walk(roots) ?? [...roots];
}
/** Find a node anywhere in the tree. */
export function findNode(roots: readonly EditNode[], id: string): EditNode | undefined {
for (const node of roots) {
if (node.id === id) return node;
const found = findNode(node.children ?? [], id);
if (found !== undefined) return found;
}
return undefined;
}
/**
* Move a node to a new parent and index.
*
* Removal happens first, so a move WITHIN the same parent uses indices that
* already account for the node being gone — which is what `onMoved` reports.
*/
export function moveNode(
roots: readonly EditNode[],
id: string,
parentId: string,
index: number | undefined,
): EditNode[] {
const node = findNode(roots, id);
if (node === undefined) return [...roots];
// Moving a folder into itself would detach the subtree from the tree.
if (findNode(node.children ?? [], parentId) !== undefined || parentId === id) return [...roots];
const without = removeNode(roots, id);
return insertNode(without, parentId, index, { ...node, parentId });
}
+119
View File
@@ -0,0 +1,119 @@
/**
* WAI-ARIA tree keyboard navigation — docs/06 §5.
*
* Purpose: decide what a keypress does to the focused row, given the tree's
* flattened visible order. Pure, so the whole keyboard contract is testable
* without mounting a component.
* Guarantees: no DOM access; the caller applies the returned action.
*/
import type { EditNode } from './patch-tree';
export interface VisibleRow {
node: EditNode;
depth: number;
parentId: string | undefined;
expandable: boolean;
expanded: boolean;
}
export type TreeAction =
| { kind: 'focus'; id: string }
| { kind: 'expand'; id: string }
| { kind: 'collapse'; id: string }
| { kind: 'activate'; id: string }
| { kind: 'rename'; id: string }
| { kind: 'delete'; id: string }
| { kind: 'none' };
const NONE: TreeAction = { kind: 'none' };
/** Flatten the tree into the rows actually on screen, in visual order. */
export function visibleRows(
roots: readonly EditNode[],
expanded: ReadonlySet<string>,
visible?: ReadonlySet<string>,
): VisibleRow[] {
const rows: VisibleRow[] = [];
const walk = (nodes: readonly EditNode[], depth: number, parentId: string | undefined): void => {
for (const node of nodes) {
if (visible !== undefined && !visible.has(node.id)) continue;
const children = node.children ?? [];
const isOpen = expanded.has(node.id);
rows.push({
node,
depth,
parentId,
expandable: node.url === undefined && children.length > 0,
expanded: isOpen,
});
if (isOpen) walk(children, depth + 1, node.id);
}
};
walk(roots, 1, undefined);
return rows;
}
/**
* Resolve a keypress against the visible rows.
*
* Follows the WAI-ARIA tree pattern: → opens a closed folder or steps into an
* open one; ← closes an open folder or steps out to the parent. Type-ahead
* jumps to the next row starting with the typed letter, wrapping around.
*/
export function resolveKey(
key: string,
focusedId: string | undefined,
rows: readonly VisibleRow[],
): TreeAction {
if (rows.length === 0) return NONE;
const index = rows.findIndex((row) => row.node.id === focusedId);
const current = index === -1 ? undefined : rows[index];
switch (key) {
case 'ArrowDown':
return focusAt(rows, index === -1 ? 0 : index + 1);
case 'ArrowUp':
return focusAt(rows, index === -1 ? rows.length - 1 : index - 1);
case 'Home':
return focusAt(rows, 0);
case 'End':
return focusAt(rows, rows.length - 1);
case 'ArrowRight': {
if (current === undefined) return NONE;
if (current.expandable && !current.expanded) return { kind: 'expand', id: current.node.id };
if (current.expanded) return focusAt(rows, index + 1);
return NONE;
}
case 'ArrowLeft': {
if (current === undefined) return NONE;
if (current.expandable && current.expanded) return { kind: 'collapse', id: current.node.id };
if (current.parentId !== undefined) return { kind: 'focus', id: current.parentId };
return NONE;
}
case 'Enter':
return current === undefined ? NONE : { kind: 'activate', id: current.node.id };
case 'F2':
return current === undefined ? NONE : { kind: 'rename', id: current.node.id };
case 'Delete':
return current === undefined ? NONE : { kind: 'delete', id: current.node.id };
default:
return key.length === 1 ? typeAhead(key, index, rows) : NONE;
}
}
function focusAt(rows: readonly VisibleRow[], index: number): TreeAction {
const row = rows[Math.max(0, Math.min(index, rows.length - 1))];
return row === undefined ? NONE : { kind: 'focus', id: row.node.id };
}
/** Next row whose title starts with `letter`, searching forward and wrapping. */
function typeAhead(letter: string, from: number, rows: readonly VisibleRow[]): TreeAction {
const needle = letter.toLowerCase();
for (let step = 1; step <= rows.length; step++) {
const row = rows[(Math.max(from, 0) + step) % rows.length];
if (row?.node.title.toLowerCase().startsWith(needle) === true) {
return { kind: 'focus', id: row.node.id };
}
}
return NONE;
}
+136
View File
@@ -0,0 +1,136 @@
/**
* The export pipeline — docs/03 §2.
*
* Purpose: turn the live tree plus a scope and format into a downloaded file.
* Guarantees: pure up to the final download; no `downloads` permission (the
* anchor path is enough here — unlike the Replace backup, a failed export
* loses nothing).
*/
import { getRootChildren, getRoots, type LiveNode, toBookmarkNodes } from '../browser/bookmarks';
import { sanitizeFilename, timestampSuffix, triggerDownload } from '../browser/download';
import type { ExportFormat } from '../browser/storage';
import { filterBySelection } from '../core/select';
import { serializeBmJson } from '../core/serialize/bm-json';
import { type CsvDelimiter, serializeCsv } from '../core/serialize/csv';
import { type MarkdownStyle, serializeMarkdown } from '../core/serialize/markdown';
import { serializeNetscapeHtml } from '../core/serialize/netscape-html';
const APP_VERSION = '0.1.0';
export const FORMAT_META: Record<
ExportFormat,
{ extension: string; mimeType: string; importable: boolean }
> = {
'netscape-html': { extension: 'html', mimeType: 'text/html', importable: true },
'bm-json': { extension: 'json', mimeType: 'application/json', importable: true },
csv: { extension: 'csv', mimeType: 'text/csv', importable: true },
markdown: { extension: 'md', mimeType: 'text/markdown', importable: false },
};
export interface ExportOptions {
format: ExportFormat;
/** `undefined` ⇒ everything; otherwise the tri-state folder selection. */
selection?: ReadonlySet<string>;
csvDelimiter?: CsvDelimiter;
markdownStyle?: MarkdownStyle;
/** Passed in so this module stays free of ambient time. */
now: Date;
}
export interface ExportPreview {
content: string;
filename: string;
mimeType: string;
bookmarks: number;
}
/** ISO date for the Markdown heading — locale-independent by design (docs/07 §3). */
function isoDate(now: Date): string {
const pad = (n: number): string => String(n).padStart(2, '0');
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
}
/**
* Count the bookmarks a selection would export.
*
* Separate from `buildExport` on purpose: the UI needs this on every render to
* label the button, and serializing the whole tree just to count it would be
* O(n) work per keystroke on a 100k-node profile.
*/
export function countSelected(
roots: readonly LiveNode[],
selection: ReadonlySet<string> | undefined,
): number {
const scoped = selection === undefined ? roots : filterBySelection(roots, selection);
let total = 0;
const walk = (nodes: readonly LiveNode[]): void => {
for (const node of nodes) {
if (node.url !== undefined) total++;
walk(node.children ?? []);
}
};
walk(scoped);
return total;
}
/** Serialize a scoped tree. Split out from the download so it is testable. */
export function buildExport(
roots: readonly LiveNode[],
options: ExportOptions,
toolbarId?: string,
): ExportPreview {
const scoped =
options.selection === undefined ? [...roots] : filterBySelection(roots, options.selection);
// Carrying the toolbar marker is what lets an exported HTML file re-import
// into the Bookmarks Bar rather than under Other Bookmarks (docs/03 §1).
const nodes = toBookmarkNodes(scoped, toolbarId === undefined ? {} : { toolbarId });
let bookmarks = 0;
const count = (list: readonly { url?: string; children?: unknown[] }[]): void => {
for (const node of list) {
if (node.url !== undefined) bookmarks++;
count((node.children ?? []) as { url?: string; children?: unknown[] }[]);
}
};
count(nodes);
const meta = FORMAT_META[options.format];
const scope = options.selection === undefined ? 'all' : 'partial';
return {
content: serialize(nodes, options),
filename: sanitizeFilename(
`bookmarks-${scope}-${timestampSuffix(options.now)}.${meta.extension}`,
),
mimeType: meta.mimeType,
bookmarks,
};
}
function serialize(nodes: ReturnType<typeof toBookmarkNodes>, options: ExportOptions): string {
switch (options.format) {
case 'netscape-html':
return serializeNetscapeHtml(nodes);
case 'bm-json':
return serializeBmJson(nodes, {
version: APP_VERSION,
exportedAt: options.now.toISOString(),
});
case 'csv':
return serializeCsv(nodes, {
...(options.csvDelimiter !== undefined && { delimiter: options.csvDelimiter }),
});
case 'markdown':
return serializeMarkdown(nodes, {
date: isoDate(options.now),
...(options.markdownStyle !== undefined && { style: options.markdownStyle }),
});
}
}
/** Read the live tree, serialize per `options`, and hand the file to the browser. */
export async function runExport(options: ExportOptions): Promise<ExportPreview> {
const [roots, resolved] = await Promise.all([getRootChildren(), getRoots()]);
const preview = buildExport(roots, options, resolved.toolbarId);
triggerDownload(preview.filename, preview.content, preview.mimeType);
return preview;
}
+52
View File
@@ -71,6 +71,58 @@ const dict = {
title: '{n} warning(s)',
},
},
export: {
scope: 'What to export',
everything: 'Everything',
format: 'Format',
start: 'Export {n} bookmarks',
saved: 'Saved {name}',
markdownNote: 'Markdown is share-only — BookmarkMagic cannot import it back.',
csvNote:
'CSV is a flattened view: empty folders and which folder is the toolbar are not preserved.',
csvDelimiter: 'Delimiter',
comma: 'Comma ( , )',
semicolon: 'Semicolon ( ; )',
markdownStyle: 'Layout',
nested: 'Nested list',
flat: 'Headings per folder',
formats: {
'netscape-html': {
name: 'HTML',
note: 'Works with Chrome, Edge, Brave, Firefox, Safari, Vivaldi and Opera.',
},
'bm-json': { name: 'JSON', note: 'Lossless backup — the best choice for restoring later.' },
csv: { name: 'CSV', note: 'For spreadsheets. Flattened.' },
markdown: { name: 'Markdown', note: 'For sharing in a README, blog post or chat.' },
},
},
edit: {
search: 'Search bookmarks',
newFolder: 'New folder',
newFolderTitle: 'New folder',
findDuplicates: 'Find duplicates',
expandAll: 'Expand all',
collapseAll: 'Collapse all',
rename: 'Rename',
open: 'Open',
moveTo: 'Move to…',
moveToBody: 'Move "{title}" into which folder?',
noMoveTargets: 'No other folder is available.',
delete: 'Delete',
empty: 'No bookmarks yet — import some to get started.',
noMatches: 'Nothing matches that search.',
deleteTitle: 'Delete this item?',
deleteBody: 'Delete "{title}"? This cannot be undone.',
deleteFolderBody: 'Delete "{title}" and the {n} items inside it? This cannot be undone.',
duplicates: 'Duplicates',
duplicatesFound: '{groups} duplicated links · {extra} extra copies',
noDuplicates: 'No duplicate links found.',
keepFirst: 'Keep the first of each, delete {n}',
keeps: 'kept',
keepFirstTitle: 'Delete duplicate copies?',
keepFirstBody:
'Keep the first copy of each link and delete the other {n}? This cannot be undone.',
},
warnings: {
NO_BOOKMARKS: 'This file contains no bookmarks.',
DESCRIPTIONS_DROPPED:
+50
View File
@@ -66,6 +66,56 @@ export default {
title: '警告 {n} 件',
},
},
export: {
scope: 'エクスポートする範囲',
everything: 'すべて',
format: '形式',
start: '{n} 件のブックマークをエクスポート',
saved: '{name} を保存しました',
markdownNote: 'Markdown は共有専用です。BookmarkMagic では読み込めません。',
csvNote: 'CSV は平坦化された形式です。空のフォルダやブックマークバーの区別は保持されません。',
csvDelimiter: '区切り文字',
comma: 'カンマ ( , )',
semicolon: 'セミコロン ( ; )',
markdownStyle: 'レイアウト',
nested: '入れ子のリスト',
flat: 'フォルダごとの見出し',
formats: {
'netscape-html': {
name: 'HTML',
note: 'Chrome、Edge、Brave、Firefox、Safari、Vivaldi、Opera で利用できます。',
},
'bm-json': { name: 'JSON', note: '欠落のないバックアップ。復元にはこれが最適です。' },
csv: { name: 'CSV', note: '表計算ソフト向け。平坦化されます。' },
markdown: { name: 'Markdown', note: 'README、ブログ、チャットでの共有向け。' },
},
},
edit: {
search: 'ブックマークを検索',
newFolder: '新しいフォルダ',
newFolderTitle: '新しいフォルダ',
findDuplicates: '重複を探す',
expandAll: 'すべて展開',
collapseAll: 'すべて折りたたむ',
rename: '名前を変更',
open: '開く',
moveTo: '移動先…',
moveToBody: '「{title}」をどのフォルダへ移動しますか?',
noMoveTargets: '他に利用できるフォルダがありません。',
delete: '削除',
empty: 'ブックマークがありません。インポートして始めてください。',
noMatches: '一致するものがありません。',
deleteTitle: 'この項目を削除しますか?',
deleteBody: '「{title}」を削除しますか?元に戻せません。',
deleteFolderBody: '「{title}」と、その中の {n} 件を削除しますか?元に戻せません。',
duplicates: '重複',
duplicatesFound: '重複リンク {groups} 件 · 余分なコピー {extra} 件',
noDuplicates: '重複するリンクは見つかりませんでした。',
keepFirst: '各グループの最初を残し、{n} 件を削除',
keeps: '保持',
keepFirstTitle: '重複したコピーを削除しますか?',
keepFirstBody: '各リンクの最初のコピーを残し、他の {n} 件を削除しますか?元に戻せません。',
},
warnings: {
NO_BOOKMARKS: 'このファイルにブックマークは含まれていません。',
DESCRIPTIONS_DROPPED:
+54
View File
@@ -61,6 +61,60 @@ export default {
title: '{n} cảnh báo',
},
},
export: {
scope: 'Xuất những gì',
everything: 'Toàn bộ',
format: 'Định dạng',
start: 'Xuất {n} bookmark',
saved: 'Đã lưu {name}',
markdownNote: 'Markdown chỉ để chia sẻ — BookmarkMagic không nhập lại được.',
csvNote:
'CSV là dạng phẳng: không giữ thư mục rỗng và không biết thư mục nào là thanh dấu trang.',
csvDelimiter: 'Ký tự phân cách',
comma: 'Dấu phẩy ( , )',
semicolon: 'Dấu chấm phẩy ( ; )',
markdownStyle: 'Bố cục',
nested: 'Danh sách lồng nhau',
flat: 'Tiêu đề theo thư mục',
formats: {
'netscape-html': {
name: 'HTML',
note: 'Dùng được với Chrome, Edge, Brave, Firefox, Safari, Vivaldi và Opera.',
},
'bm-json': {
name: 'JSON',
note: 'Sao lưu không mất dữ liệu — lựa chọn tốt nhất để khôi phục.',
},
csv: { name: 'CSV', note: 'Cho bảng tính. Dạng phẳng.' },
markdown: { name: 'Markdown', note: 'Để chia sẻ trong README, bài viết hoặc chat.' },
},
},
edit: {
search: 'Tìm bookmark',
newFolder: 'Thư mục mới',
newFolderTitle: 'Thư mục mới',
findDuplicates: 'Tìm mục trùng',
expandAll: 'Mở tất cả',
collapseAll: 'Thu gọn tất cả',
rename: 'Đổi tên',
open: 'Mở',
moveTo: 'Chuyển tới…',
moveToBody: 'Chuyển "{title}" vào thư mục nào?',
noMoveTargets: 'Không có thư mục nào khác.',
delete: 'Xóa',
empty: 'Chưa có bookmark nào — hãy nhập để bắt đầu.',
noMatches: 'Không có kết quả phù hợp.',
deleteTitle: 'Xóa mục này?',
deleteBody: 'Xóa "{title}"? Không thể hoàn tác.',
deleteFolderBody: 'Xóa "{title}" và {n} mục bên trong? Không thể hoàn tác.',
duplicates: 'Mục trùng',
duplicatesFound: '{groups} liên kết bị trùng · {extra} bản dư',
noDuplicates: 'Không tìm thấy liên kết trùng.',
keepFirst: 'Giữ bản đầu tiên, xóa {n}',
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.',
},
warnings: {
NO_BOOKMARKS: 'Tệp này không chứa bookmark nào.',
DESCRIPTIONS_DROPPED: 'Đã bỏ {n} phần mô tả — mô hình bookmark không có chỗ cho chúng.',
+1
View File
@@ -26,6 +26,7 @@ describe('settings', () => {
defaultExportFormat: 'csv',
defaultMergeMode: 'merge',
csvDelimiter: ';',
markdownStyle: 'flat',
} as const;
await writeSettings({ ...settings });
expect(await readSettings()).toEqual(settings);
+87
View File
@@ -0,0 +1,87 @@
import { describe, expect, it } from 'vitest';
import { type SearchableNode, searchTree } from '@/lib/core/search';
const TREE: SearchableNode[] = [
{
id: 'bar',
title: 'Bookmarks bar',
children: [
{ id: 'a', title: 'Apple', url: 'https://apple.example/' },
{
id: 'dev',
title: 'Dev tools',
children: [
{ id: 'gh', title: 'GitHub', url: 'https://github.com/' },
{ id: 'mdn', title: 'MDN', url: 'https://developer.mozilla.example/' },
],
},
],
},
{
id: 'other',
title: 'Other',
children: [{ id: 'z', title: 'Zebra', url: 'https://z.example/' }],
},
];
describe('searchTree', () => {
it('matches on title, case-insensitively', () => {
expect([...searchTree(TREE, 'github').matched]).toEqual(['gh']);
expect([...searchTree(TREE, 'GITHUB').matched]).toEqual(['gh']);
});
it('matches on URL as well as title', () => {
expect([...searchTree(TREE, 'mozilla').matched]).toEqual(['mdn']);
});
it('keeps ancestors visible so a deep hit has context', () => {
const { visible } = searchTree(TREE, 'github');
expect([...visible].sort()).toEqual(['bar', 'dev', 'gh']);
});
it('auto-expands the ancestors of a match, but not the match itself', () => {
const { expand } = searchTree(TREE, 'github');
expect([...expand].sort()).toEqual(['bar', 'dev']);
});
it('shows the whole subtree of a matching FOLDER', () => {
// Matching "Dev tools" should reveal what is inside it, not just its name.
const { matched, visible } = searchTree(TREE, 'dev tools');
expect([...matched]).toEqual(['dev']);
expect([...visible].sort()).toEqual(['bar', 'dev', 'gh', 'mdn']);
});
it('returns empty sets for a blank query — "no filter", not "no results"', () => {
for (const query of ['', ' ']) {
const result = searchTree(TREE, query);
expect(result.matched.size).toBe(0);
expect(result.visible.size).toBe(0);
}
});
it('distinguishes no results from no filter', () => {
const result = searchTree(TREE, 'zzz-nothing-matches');
expect(result.matched.size).toBe(0);
expect(result.visible.size).toBe(0);
});
it('finds several matches across branches', () => {
const { matched, visible } = searchTree(TREE, 'e');
expect(matched.has('a')).toBe(true);
expect(matched.has('z')).toBe(true);
expect(visible.has('other')).toBe(true);
});
});
describe('searchTree — the haystack is title + url, not two fields', () => {
it('matches a query that spans the title/url boundary (docs/05 §8)', () => {
// "Apple https://apple.example/" is one string; testing the two fields
// separately would find nothing here.
expect([...searchTree(TREE, 'apple https').matched]).toEqual(['a']);
});
it('still matches within either field alone', () => {
expect([...searchTree(TREE, 'zebra').matched]).toEqual(['z']);
expect([...searchTree(TREE, 'z.example').matched]).toEqual(['z']);
});
});
+140
View File
@@ -0,0 +1,140 @@
import { describe, expect, it } from 'vitest';
import {
checkStateOf,
filterBySelection,
pathTo,
subtreeIds,
type TreeLike,
toggleSelection,
} from '@/lib/core/select';
interface Node extends TreeLike {
id: string;
title: string;
url?: string;
children?: Node[];
}
const TREE: Node[] = [
{
id: 'bar',
title: 'Bookmarks bar',
children: [
{ id: 'a', title: 'a', url: 'https://a.example/' },
{
id: 'dev',
title: 'Dev',
children: [
{ id: 'gh', title: 'GitHub', url: 'https://github.com/' },
{ id: 'mdn', title: 'MDN', url: 'https://mdn.example/' },
],
},
],
},
{ id: 'other', title: 'Other', children: [{ id: 'z', title: 'z', url: 'https://z.example/' }] },
];
const byId = (id: string): Node => {
const found = pathTo(TREE, id).at(-1);
if (found === undefined) throw new Error(`no node ${id}`);
return found as Node;
};
describe('subtreeIds / pathTo', () => {
it('collects a node and everything under it', () => {
expect([...subtreeIds(byId('dev'))].sort()).toEqual(['dev', 'gh', 'mdn']);
});
it('returns the full ancestor path, inclusive', () => {
expect(pathTo(TREE, 'gh').map((n) => n.id)).toEqual(['bar', 'dev', 'gh']);
});
it('returns nothing for an unknown id', () => {
expect(pathTo(TREE, 'nope')).toEqual([]);
});
});
describe('checkStateOf', () => {
it('reports a directly selected node as checked', () => {
expect(checkStateOf(TREE, byId('dev'), new Set(['dev']))).toBe('checked');
});
it('reports a node covered by a selected ancestor as checked', () => {
expect(checkStateOf(TREE, byId('gh'), new Set(['bar']))).toBe('checked');
});
it('reports a partially covered folder as indeterminate', () => {
expect(checkStateOf(TREE, byId('bar'), new Set(['gh']))).toBe('indeterminate');
});
it('reports an untouched folder as unchecked', () => {
expect(checkStateOf(TREE, byId('other'), new Set(['gh']))).toBe('unchecked');
});
});
describe('toggleSelection — checking', () => {
it('stores one covering id and drops redundant descendants', () => {
const selection = toggleSelection(TREE, byId('bar'), true, new Set(['gh', 'mdn']));
expect([...selection]).toEqual(['bar']);
});
it('collapses a fully selected set of siblings into the parent', () => {
let selection = toggleSelection(TREE, byId('gh'), true, new Set());
selection = toggleSelection(TREE, byId('mdn'), true, selection);
// Both children of Dev are now selected, so Dev itself is the right key.
expect(selection.has('dev')).toBe(true);
expect(selection.has('gh')).toBe(false);
});
});
describe('toggleSelection — unchecking', () => {
it('removes a directly selected node', () => {
expect([...toggleSelection(TREE, byId('dev'), false, new Set(['dev']))]).toEqual([]);
});
it('splits a selected ancestor so the rest of it stays selected', () => {
// Ticking "Bookmarks bar" then unticking "Dev" must keep "a" selected.
// Without the expansion the untick would silently do nothing.
const selection = toggleSelection(TREE, byId('dev'), false, new Set(['bar']));
expect([...selection].sort()).toEqual(['a']);
expect(checkStateOf(TREE, byId('a'), selection)).toBe('checked');
expect(checkStateOf(TREE, byId('gh'), selection)).toBe('unchecked');
expect(checkStateOf(TREE, byId('bar'), selection)).toBe('indeterminate');
});
it('splits across two levels', () => {
const selection = toggleSelection(TREE, byId('gh'), false, new Set(['bar']));
expect([...selection].sort()).toEqual(['a', 'mdn']);
expect(checkStateOf(TREE, byId('mdn'), selection)).toBe('checked');
expect(checkStateOf(TREE, byId('gh'), selection)).toBe('unchecked');
});
});
describe('filterBySelection', () => {
it('brings the whole subtree of a selected folder', () => {
expect(filterBySelection(TREE, new Set(['dev']))).toEqual([
{ id: 'bar', title: 'Bookmarks bar', children: [byId('dev')] },
]);
});
it('keeps unselected ancestors only as a path to a selection', () => {
const filtered = filterBySelection(TREE, new Set(['gh']));
expect(filtered).toHaveLength(1);
expect(filtered[0]?.id).toBe('bar');
expect(filtered[0]?.children?.[0]?.id).toBe('dev');
expect(filtered[0]?.children?.[0]?.children).toEqual([byId('gh')]);
});
it('drops branches with nothing selected', () => {
expect(filterBySelection(TREE, new Set(['z']))?.map((n) => n.id)).toEqual(['other']);
});
it('returns nothing for an empty selection', () => {
expect(filterBySelection(TREE, new Set())).toEqual([]);
});
it('does not mutate the source tree', () => {
filterBySelection(TREE, new Set(['gh']));
expect(byId('dev').children).toHaveLength(2);
});
});
+96
View File
@@ -0,0 +1,96 @@
import { describe, expect, it } from 'vitest';
import { canMoveInto, moveTargets } from '@/lib/edit/move-target';
import { type EditNode, findNode } from '@/lib/edit/patch-tree';
const TREE: EditNode[] = [
{
id: 'bar',
title: 'Bookmarks bar',
children: [
{ id: 'apple', parentId: 'bar', title: 'Apple', url: 'https://apple.example/' },
{
id: 'dev',
parentId: 'bar',
title: 'Dev',
children: [
{ id: 'gh', parentId: 'dev', title: 'GitHub', url: 'https://github.com/' },
{ id: 'deep', parentId: 'dev', title: 'Deep', children: [] },
],
},
],
},
{ id: 'other', title: 'Other', children: [] },
{ id: 'managed', title: 'Managed bookmarks', unmodifiable: 'managed', children: [] },
];
const node = (id: string): EditNode => {
const found = findNode(TREE, id);
if (found === undefined) throw new Error(`no node ${id}`);
return found;
};
describe('moveTargets', () => {
it('offers folders only, never bookmarks', () => {
expect(moveTargets(TREE, node('apple')).map((t) => t.id)).not.toContain('gh');
});
it('shows the full path so same-named folders are distinguishable', () => {
expect(moveTargets(TREE, node('apple')).map((t) => t.label)).toContain('Bookmarks bar / Dev');
});
it('excludes the current parent — moving there is a no-op', () => {
expect(moveTargets(TREE, node('apple')).map((t) => t.id)).not.toContain('bar');
});
it('excludes the node itself and its descendants', () => {
const ids = moveTargets(TREE, node('dev')).map((t) => t.id);
expect(ids).not.toContain('dev');
expect(ids).not.toContain('deep');
expect(ids).toContain('other');
});
it('excludes policy-managed folders', () => {
expect(moveTargets(TREE, node('apple')).map((t) => t.id)).not.toContain('managed');
});
it('offers every folder when nothing is being moved', () => {
expect(
moveTargets(TREE, undefined)
.map((t) => t.id)
.sort(),
).toEqual(['bar', 'deep', 'dev', 'other']);
});
});
describe('canMoveInto', () => {
it('allows a move into an unrelated folder', () => {
expect(canMoveInto(TREE, 'apple', 'other')).toBe(true);
});
it('refuses a drop onto a bookmark', () => {
expect(canMoveInto(TREE, 'apple', 'gh')).toBe(false);
});
it('refuses a folder into itself or its own descendant', () => {
expect(canMoveInto(TREE, 'dev', 'dev')).toBe(false);
expect(canMoveInto(TREE, 'dev', 'deep')).toBe(false);
});
it('refuses a managed destination', () => {
expect(canMoveInto(TREE, 'apple', 'managed')).toBe(false);
});
it('refuses unknown ids', () => {
expect(canMoveInto(TREE, 'ghost', 'other')).toBe(false);
expect(canMoveInto(TREE, 'apple', 'ghost')).toBe(false);
});
it('agrees with moveTargets about what is legal', () => {
// The DnD path and the keyboard path must not drift apart.
const legal = new Set(moveTargets(TREE, node('dev')).map((t) => t.id));
for (const candidate of ['bar', 'dev', 'deep', 'other', 'managed', 'gh']) {
if (candidate === 'bar') continue; // excluded as current parent, not as illegal
expect(canMoveInto(TREE, 'dev', candidate)).toBe(legal.has(candidate));
}
});
});
+137
View File
@@ -0,0 +1,137 @@
import { describe, expect, it } from 'vitest';
import {
changeNode,
type EditNode,
findNode,
insertNode,
moveNode,
removeNode,
} from '@/lib/edit/patch-tree';
const tree = (): EditNode[] => [
{
id: 'bar',
title: 'Bookmarks bar',
children: [
{ id: 'a', parentId: 'bar', title: 'a', url: 'https://a.example/' },
{
id: 'dev',
parentId: 'bar',
title: 'Dev',
children: [{ id: 'gh', parentId: 'dev', title: 'GitHub', url: 'https://github.com/' }],
},
],
},
{ id: 'other', title: 'Other', children: [] },
];
const ids = (nodes: readonly EditNode[]): string[] => nodes.map((n) => n.id);
describe('insertNode', () => {
it('appends when no index is given', () => {
const next = insertNode(tree(), 'other', undefined, {
id: 'new',
title: 'n',
url: 'https://n/',
});
expect(ids(findNode(next, 'other')?.children ?? [])).toEqual(['new']);
});
it('respects an explicit index', () => {
const next = insertNode(tree(), 'bar', 0, { id: 'new', title: 'n', url: 'https://n/' });
expect(ids(findNode(next, 'bar')?.children ?? [])).toEqual(['new', 'a', 'dev']);
});
it('clamps an out-of-range index to the end', () => {
const next = insertNode(tree(), 'bar', 99, { id: 'new', title: 'n', url: 'https://n/' });
expect(ids(findNode(next, 'bar')?.children ?? [])).toEqual(['a', 'dev', 'new']);
});
it('ignores an event for a parent we do not hold', () => {
const before = tree();
const next = insertNode(before, 'nonexistent', 0, { id: 'new', title: 'n' });
expect(next).toEqual(before);
});
it('never targets a bookmark as a parent', () => {
const before = tree();
expect(insertNode(before, 'a', 0, { id: 'new', title: 'n' })).toEqual(before);
});
it('is immutable and shares untouched branches', () => {
const before = tree();
const next = insertNode(before, 'other', 0, { id: 'new', title: 'n' });
expect(before[1]?.children).toEqual([]);
// The "bar" branch was not touched, so it should be the same object.
expect(next[0]).toBe(before[0]);
});
});
describe('removeNode', () => {
it('removes a leaf', () => {
const next = removeNode(tree(), 'a');
expect(ids(findNode(next, 'bar')?.children ?? [])).toEqual(['dev']);
});
it('removes a folder together with its subtree', () => {
const next = removeNode(tree(), 'dev');
expect(findNode(next, 'gh')).toBeUndefined();
});
it('ignores an unknown id — events for already-removed nodes are routine', () => {
const before = tree();
expect(removeNode(before, 'ghost')).toEqual(before);
});
it('does not mutate the input', () => {
const before = tree();
removeNode(before, 'a');
expect(ids(before[0]?.children ?? [])).toEqual(['a', 'dev']);
});
});
describe('changeNode', () => {
it('applies a title change', () => {
expect(findNode(changeNode(tree(), 'gh', { title: 'Renamed' }), 'gh')?.title).toBe('Renamed');
});
it('applies a url change without touching the title', () => {
const next = changeNode(tree(), 'gh', { url: 'https://new.example/' });
expect(findNode(next, 'gh')).toMatchObject({ title: 'GitHub', url: 'https://new.example/' });
});
it('ignores an unknown id', () => {
const before = tree();
expect(changeNode(before, 'ghost', { title: 'x' })).toEqual(before);
});
});
describe('moveNode', () => {
it('reparents a node', () => {
const next = moveNode(tree(), 'gh', 'other', 0);
expect(ids(findNode(next, 'other')?.children ?? [])).toEqual(['gh']);
expect(findNode(next, 'dev')?.children).toEqual([]);
});
it('updates parentId on the moved node', () => {
expect(findNode(moveNode(tree(), 'gh', 'other', 0), 'gh')?.parentId).toBe('other');
});
it('reorders within the same parent using post-removal indices', () => {
// onMoved reports the index the node lands at AFTER being lifted out.
const next = moveNode(tree(), 'a', 'bar', 1);
expect(ids(findNode(next, 'bar')?.children ?? [])).toEqual(['dev', 'a']);
});
it('refuses to move a folder into its own descendant', () => {
// Allowing it would detach the whole subtree from the tree.
const before = tree();
expect(moveNode(before, 'dev', 'gh', 0)).toEqual(before);
expect(moveNode(before, 'dev', 'dev', 0)).toEqual(before);
});
it('ignores an unknown id', () => {
const before = tree();
expect(moveNode(before, 'ghost', 'other', 0)).toEqual(before);
});
});
+132
View File
@@ -0,0 +1,132 @@
import { describe, expect, it } from 'vitest';
import type { EditNode } from '@/lib/edit/patch-tree';
import { resolveKey, visibleRows } from '@/lib/edit/tree-keyboard';
const TREE: EditNode[] = [
{
id: 'bar',
title: 'Bookmarks bar',
children: [
{ id: 'apple', parentId: 'bar', title: 'Apple', url: 'https://apple.example/' },
{
id: 'dev',
parentId: 'bar',
title: 'Dev',
children: [{ id: 'gh', parentId: 'dev', title: 'GitHub', url: 'https://github.com/' }],
},
],
},
{ id: 'other', title: 'Other', children: [] },
];
const rowsWith = (...open: string[]) => visibleRows(TREE, new Set(open));
describe('visibleRows', () => {
it('lists only what is on screen, in visual order', () => {
expect(rowsWith().map((r) => r.node.id)).toEqual(['bar', 'other']);
expect(rowsWith('bar').map((r) => r.node.id)).toEqual(['bar', 'apple', 'dev', 'other']);
expect(rowsWith('bar', 'dev').map((r) => r.node.id)).toEqual([
'bar',
'apple',
'dev',
'gh',
'other',
]);
});
it('reports depth, parent and expandability', () => {
const [bar, apple, dev] = rowsWith('bar');
expect(bar).toMatchObject({ depth: 1, parentId: undefined, expandable: true, expanded: true });
expect(apple).toMatchObject({ depth: 2, parentId: 'bar', expandable: false });
expect(dev).toMatchObject({ depth: 2, parentId: 'bar', expandable: true, expanded: false });
});
it('treats an empty folder as not expandable', () => {
expect(rowsWith().find((r) => r.node.id === 'other')?.expandable).toBe(false);
});
it('honours a search visibility filter', () => {
const rows = visibleRows(TREE, new Set(['bar', 'dev']), new Set(['bar', 'dev', 'gh']));
expect(rows.map((r) => r.node.id)).toEqual(['bar', 'dev', 'gh']);
});
});
describe('resolveKey — movement', () => {
const rows = rowsWith('bar');
it('moves down and up', () => {
expect(resolveKey('ArrowDown', 'bar', rows)).toEqual({ kind: 'focus', id: 'apple' });
expect(resolveKey('ArrowUp', 'apple', rows)).toEqual({ kind: 'focus', id: 'bar' });
});
it('clamps at both ends rather than wrapping', () => {
expect(resolveKey('ArrowUp', 'bar', rows)).toEqual({ kind: 'focus', id: 'bar' });
expect(resolveKey('ArrowDown', 'other', rows)).toEqual({ kind: 'focus', id: 'other' });
});
it('jumps to first and last with Home/End', () => {
expect(resolveKey('Home', 'dev', rows)).toEqual({ kind: 'focus', id: 'bar' });
expect(resolveKey('End', 'bar', rows)).toEqual({ kind: 'focus', id: 'other' });
});
});
describe('resolveKey — the WAI-ARIA expand/collapse pattern', () => {
it('right opens a closed folder, then steps into it', () => {
expect(resolveKey('ArrowRight', 'dev', rowsWith('bar'))).toEqual({ kind: 'expand', id: 'dev' });
expect(resolveKey('ArrowRight', 'dev', rowsWith('bar', 'dev'))).toEqual({
kind: 'focus',
id: 'gh',
});
});
it('left closes an open folder, then steps out to the parent', () => {
expect(resolveKey('ArrowLeft', 'dev', rowsWith('bar', 'dev'))).toEqual({
kind: 'collapse',
id: 'dev',
});
expect(resolveKey('ArrowLeft', 'dev', rowsWith('bar'))).toEqual({ kind: 'focus', id: 'bar' });
});
it('left on a bookmark goes to its parent', () => {
expect(resolveKey('ArrowLeft', 'apple', rowsWith('bar'))).toEqual({ kind: 'focus', id: 'bar' });
});
it('does nothing at the top level with nowhere to go', () => {
expect(resolveKey('ArrowLeft', 'other', rowsWith())).toEqual({ kind: 'none' });
expect(resolveKey('ArrowRight', 'other', rowsWith())).toEqual({ kind: 'none' });
});
});
describe('resolveKey — actions', () => {
const rows = rowsWith('bar');
it('maps Enter, F2 and Delete', () => {
expect(resolveKey('Enter', 'apple', rows)).toEqual({ kind: 'activate', id: 'apple' });
expect(resolveKey('F2', 'apple', rows)).toEqual({ kind: 'rename', id: 'apple' });
expect(resolveKey('Delete', 'apple', rows)).toEqual({ kind: 'delete', id: 'apple' });
});
it('ignores keys with no binding', () => {
expect(resolveKey('Escape', 'apple', rows)).toEqual({ kind: 'none' });
});
});
describe('resolveKey — type-ahead', () => {
const rows = rowsWith('bar');
it('jumps to the next row starting with the letter', () => {
expect(resolveKey('d', 'bar', rows)).toEqual({ kind: 'focus', id: 'dev' });
});
it('is case-insensitive', () => {
expect(resolveKey('A', 'bar', rows)).toEqual({ kind: 'focus', id: 'apple' });
});
it('wraps around to find a match above the cursor', () => {
expect(resolveKey('a', 'other', rows)).toEqual({ kind: 'focus', id: 'apple' });
});
it('does nothing when no row matches', () => {
expect(resolveKey('z', 'bar', rows)).toEqual({ kind: 'none' });
});
});
+43
View File
@@ -0,0 +1,43 @@
import { describe, expect, it } from 'vitest';
import type { LiveNode } from '@/lib/browser/bookmarks';
import { buildExport, countSelected } from '@/lib/export/run-export';
const LIVE: LiveNode[] = [
{
id: '1',
title: 'Bookmarks bar',
children: [
{ id: '10', title: 'Apple', url: 'https://apple.example/' },
{ id: '11', title: 'Dev', children: [{ id: '12', title: 'GH', url: 'https://gh.example/' }] },
],
},
{ id: '2', title: 'Other', children: [{ id: '20', title: 'Z', url: 'https://z.example/' }] },
];
describe('countSelected', () => {
it('counts everything when nothing is selected explicitly', () => {
expect(countSelected(LIVE, undefined)).toBe(3);
});
it('counts only the selected subtree', () => {
expect(countSelected(LIVE, new Set(['11']))).toBe(1);
expect(countSelected(LIVE, new Set(['1']))).toBe(2);
});
it('is zero for an empty selection, which disables the button', () => {
expect(countSelected(LIVE, new Set())).toBe(0);
});
it('agrees with what buildExport would actually write', () => {
// The button label and the file must never disagree.
for (const selection of [undefined, new Set(['11']), new Set(['1', '2'])]) {
expect(countSelected(LIVE, selection)).toBe(
buildExport(LIVE, {
format: 'bm-json',
...(selection !== undefined && { selection }),
now: new Date(2026, 6, 25),
}).bookmarks,
);
}
});
});
+101
View File
@@ -0,0 +1,101 @@
import { describe, expect, it } from 'vitest';
import type { LiveNode } from '@/lib/browser/bookmarks';
import { parseNetscapeHtml } from '@/lib/core/parse/netscape-html';
import { buildExport, FORMAT_META } from '@/lib/export/run-export';
const NOW = new Date(2026, 6, 25, 14, 5);
const LIVE: LiveNode[] = [
{
id: '1',
title: 'Bookmarks bar',
children: [
{ id: '10', title: 'Apple', url: 'https://apple.example/', dateAdded: 1_751_500_000_000 },
{
id: '11',
title: 'Dev',
children: [{ id: '12', title: 'GitHub', url: 'https://github.com/' }],
},
],
},
{
id: '2',
title: 'Other bookmarks',
children: [{ id: '20', title: 'Zebra', url: 'https://z.example/' }],
},
];
describe('buildExport — scope', () => {
it('exports everything when no selection is given', () => {
const preview = buildExport(LIVE, { format: 'bm-json', now: NOW }, '1');
expect(preview.bookmarks).toBe(3);
expect(preview.filename).toBe('bookmarks-all-20260725-1405.json');
});
it('exports only the selected subtree, keeping its folder path', () => {
const preview = buildExport(
LIVE,
{ format: 'bm-json', selection: new Set(['11']), now: NOW },
'1',
);
expect(preview.bookmarks).toBe(1);
expect(preview.filename).toBe('bookmarks-partial-20260725-1405.json');
expect(preview.content).toContain('GitHub');
expect(preview.content).toContain('Bookmarks bar');
expect(preview.content).not.toContain('Zebra');
});
});
describe('buildExport — formats', () => {
it.each(Object.keys(FORMAT_META) as (keyof typeof FORMAT_META)[])(
'produces the documented extension and mime type for %s',
(format) => {
const preview = buildExport(LIVE, { format, now: NOW }, '1');
expect(preview.filename.endsWith(`.${FORMAT_META[format].extension}`)).toBe(true);
expect(preview.mimeType).toBe(FORMAT_META[format].mimeType);
expect(preview.content.length).toBeGreaterThan(0);
},
);
it('honours the CSV delimiter setting', () => {
const preview = buildExport(LIVE, { format: 'csv', csvDelimiter: ';', now: NOW }, '1');
expect(preview.content).toContain('folder_path;title;url;add_date');
});
it('honours the Markdown style setting', () => {
const nested = buildExport(LIVE, { format: 'markdown', now: NOW }, '1');
const flat = buildExport(LIVE, { format: 'markdown', markdownStyle: 'flat', now: NOW }, '1');
expect(nested.content).toContain('- **Bookmarks bar**');
expect(flat.content).toContain('## Bookmarks bar');
});
it('dates the Markdown heading with an ISO date, not a locale format', () => {
expect(buildExport(LIVE, { format: 'markdown', now: NOW }, '1').content).toContain(
'# Bookmarks — 2026-07-25',
);
});
});
describe('buildExport — round trip', () => {
it('exported HTML re-imports with the toolbar intact', () => {
// The Phase 3 exit criterion: an exported file must come back losslessly,
// including which folder is the Bookmarks Bar.
const preview = buildExport(LIVE, { format: 'netscape-html', now: NOW }, '1');
const { roots, warnings } = parseNetscapeHtml(preview.content);
expect(warnings).toEqual([]);
expect(roots.map((r) => r.title)).toEqual(['Bookmarks bar', 'Other bookmarks']);
expect(roots[0]?.toolbar).toBe(true);
expect(roots[0]?.children?.[1]?.children?.[0]?.url).toBe('https://github.com/');
});
it('converts live millisecond dates to the file format seconds', () => {
const preview = buildExport(LIVE, { format: 'netscape-html', now: NOW }, '1');
expect(parseNetscapeHtml(preview.content).roots[0]?.children?.[0]?.addDate).toBe(1751500000);
});
it('does not mark a toolbar at all when none is resolved', () => {
const preview = buildExport(LIVE, { format: 'bm-json', now: NOW });
expect(preview.content).not.toContain('"toolbar"');
});
});