fix(core): a bare ? or # no longer defeats dedupe, and the export picker stops going quadratic

normalizeUrl trimmed the last character of a root URL to drop its slash, but
`x/?` and `x/#` serialize with the delimiter last, so the `?` was cut instead
and `x/?` never matched `x/`. Empty query and fragment are now removed first.
The default-port code was dead: the URL parser already drops default ports.

The export folder picker looked up each row's check state by walking the tree
from the roots - O(n) per visible row. checkStates builds the whole map in one
pass, once per selection change.

The seeded round-trip now asserts no warnings per tree as docs/11 §3 says.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 committed 2026-10-29 03:22:56 +07:00
1 parent bb2b175551
commit 7493aceefb
6 files changed
+79 -46

No files matched your search

+5 -5
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import type { LiveNode } from '../browser/bookmarks';
import { checkStateOf, toggleSelection } from '../core/select';
import { checkStates, toggleSelection } from '../core/select';
import FolderPickNode from './FolderPickNode.svelte';
import { t } from '../i18n/index.svelte';
@@ -14,6 +14,7 @@
let { roots, selection, onchange }: Props = $props();
const everything = $derived(selection === undefined);
const states = $derived(selection === undefined ? undefined : checkStates(roots, selection));
function toggleNode(node: LiveNode, checked: boolean): void {
// Leaving "Everything" materialises it into a real selection first, so the
@@ -28,7 +29,7 @@
<input
type="checkbox"
checked={everything}
onchange={(e) => onchange((e.currentTarget as HTMLInputElement).checked ? undefined : new Set())}
onchange={(e) => onchange(e.currentTarget.checked ? undefined : new Set())}
/>
<strong>{t('export.everything')}</strong>
</label>
@@ -38,9 +39,8 @@
<FolderPickNode
node={root}
depth={1}
checkState={everything ? 'checked' : checkStateOf(roots, root, selection ?? new Set())}
resolve={(node) =>
everything ? 'checked' : checkStateOf(roots, node, selection ?? new Set())}
checkState={states?.get(root.id) ?? 'checked'}
resolve={(node) => states?.get(node.id) ?? 'checked'}
ontoggle={toggleNode}
/>
{/each}
+11 -15
View File
@@ -11,20 +11,13 @@
* "aggressive dedupe" toggle.
*/
const DEFAULT_PORTS: Record<string, string> = {
'http:': '80',
'https:': '443',
'ftp:': '21',
'ws:': '80',
'wss:': '443',
};
/**
* Build the comparison key for a URL.
*
* Unparseable input (`javascript:`, `about:`, plain junk) falls back to the
* trimmed original, so such bookmarks still dedupe against each other exactly
* rather than collapsing together.
* Unparseable input (plain junk) falls back to the trimmed original, so such
* bookmarks still dedupe against each other exactly rather than collapsing
* together. The URL parser already lowercases the scheme and host and drops a
* scheme's default port, so neither needs code here.
*/
export function normalizeUrl(raw: string): string {
const trimmed = raw.trim();
@@ -35,8 +28,11 @@ export function normalizeUrl(raw: string): string {
return trimmed;
}
// The URL parser already lowercases protocol and hostname.
if (url.port !== '' && DEFAULT_PORTS[url.protocol] === url.port) url.port = '';
// An empty query or fragment (`x/?`, `x/#`) is the same link without it.
// Assigning '' removes the delimiter; reading `search`/`hash` cannot tell a
// bare `?` from none, which made the slash-trim below cut the `?` instead.
if (url.search === '') url.search = '';
if (url.hash === '') url.hash = '';
// A bare origin is the same link with or without the trailing slash.
// Drop the slash off the serialized URL rather than rebuilding from
@@ -44,9 +40,9 @@ export function normalizeUrl(raw: string): string {
// https://alice@host/ and https://bob@host/ into one key and drop one of them
// on import.
if (url.pathname === '/' && url.search === '' && url.hash === '') {
return url.toString().slice(0, -1);
return url.href.slice(0, -1);
}
// Query and fragment are kept verbatim — `?q=` and `#section` are meaningful.
return url.toString();
return url.href;
}
+22 -11
View File
@@ -45,19 +45,30 @@ export function pathTo(roots: readonly TreeLike[], targetId: string): TreeLike[]
return walk(roots, []) ?? [];
}
/** Checked when selected outright or covered by a selected ancestor. */
export function checkStateOf(
/**
* Every node's check state, in one pass: checked when selected outright or
* covered by a selected ancestor; indeterminate when only something below is.
*
* One map for the whole picker. The per-row lookup it replaces walked the tree
* from the roots for every visible row — quadratic on a large profile.
*/
export function checkStates(
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';
): Map<string, CheckState> {
const states = new Map<string, CheckState>();
/** Whether anything at or below `node` is selected or covered. */
const visit = (node: TreeLike, covered: boolean): boolean => {
const self = covered || selection.has(node.id);
let below = false;
for (const child of node.children ?? []) {
if (visit(child, self)) below = true;
}
states.set(node.id, self ? 'checked' : below ? 'indeterminate' : 'unchecked');
return self || below;
};
for (const root of roots) visit(root, false);
return states;
}
/**
+14
View File
@@ -63,3 +63,17 @@ describe('normalizeUrl', () => {
}
});
});
describe('normalizeUrl — empty query and fragment (v1.1.0)', () => {
it('treats a bare ? or # as no query or fragment at all', () => {
const key = normalizeUrl('https://a.example/');
expect(normalizeUrl('https://a.example/?')).toBe(key);
expect(normalizeUrl('https://a.example/#')).toBe(key);
expect(normalizeUrl('https://a.example/x?')).toBe(normalizeUrl('https://a.example/x'));
});
it('still keeps a real query and fragment', () => {
expect(normalizeUrl('https://a.example/?q=1')).toBe('https://a.example/?q=1');
expect(normalizeUrl('https://a.example/#top')).toBe('https://a.example/#top');
});
});
+9 -4
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { type BookmarkNode, computeStats } from '@/lib/core/model';
import { type BookmarkNode, computeStats, type ParseResult } from '@/lib/core/model';
import { parseBmJson } from '@/lib/core/parse/bm-json';
import { parseCsv } from '@/lib/core/parse/csv';
import { parseNetscapeHtml } from '@/lib/core/parse/netscape-html';
@@ -74,13 +74,18 @@ describe.each(FORMATS)('round-trip: %s', (format) => {
for (let seed = 1; seed <= 200; seed++) {
const tree = generateTree(makeRng(seed));
const expected = project(tree, format);
let actual: BookmarkNode[];
let actual: ParseResult;
try {
actual = parse(serialize(tree)).roots;
actual = parse(serialize(tree));
} catch (err) {
throw new Error(`seed ${seed} (${format}) threw: ${String(err)}`);
}
expect(actual, `seed ${seed} (${format})`).toEqual(expected);
expect(actual.roots, `seed ${seed} (${format})`).toEqual(expected);
// A parser that silently degrades must not pass (docs/11 §3). An empty
// tree is the one legitimate warning.
expect(actual.warnings, `seed ${seed} (${format}) warnings`).toEqual(
expected.length === 0 ? [{ code: 'NO_BOOKMARKS', count: 1 }] : [],
);
}
});
});
+18 -11
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import {
checkStateOf,
checkStates,
filterBySelection,
pathTo,
subtreeIds,
@@ -54,21 +54,28 @@ describe('subtreeIds / pathTo', () => {
});
});
describe('checkStateOf', () => {
const stateOf = (node: Node, selection: ReadonlySet<string>) =>
checkStates(TREE, selection).get(node.id);
describe('checkStates', () => {
it('answers for every node in the tree, in one map', () => {
expect(checkStates(TREE, new Set(['dev'])).size).toBe(7);
});
it('reports a directly selected node as checked', () => {
expect(checkStateOf(TREE, byId('dev'), new Set(['dev']))).toBe('checked');
expect(stateOf(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');
expect(stateOf(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');
expect(stateOf(byId('bar'), new Set(['gh']))).toBe('indeterminate');
});
it('reports an untouched folder as unchecked', () => {
expect(checkStateOf(TREE, byId('other'), new Set(['gh']))).toBe('unchecked');
expect(stateOf(byId('other'), new Set(['gh']))).toBe('unchecked');
});
});
@@ -97,16 +104,16 @@ describe('toggleSelection — unchecking', () => {
// 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');
expect(stateOf(byId('a'), selection)).toBe('checked');
expect(stateOf(byId('gh'), selection)).toBe('unchecked');
expect(stateOf(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');
expect(stateOf(byId('mdn'), selection)).toBe('checked');
expect(stateOf(byId('gh'), selection)).toBe('unchecked');
});
});