feat(firefox): the right roots, the Bookmarks Menu, separators and move index
What made Firefox more than a build target (docs/02 §4, 03, 04, 05 §10):
- Roots. getRoots (now browser/roots.ts) tries Firefox's GUIDs after
folderType and the Chromium ids, and never takes the Bookmarks Menu by
position — Firefox lists it first, and the old fallback took it for the
bar, so a Replace emptied the Menu and the toolbar and restored into the
wrong roots. The Menu is a fourth destination Replace also empties.
- The Menu in the file model: root "menu" (BM JSON, additive); HTML writes
its entries loose at the top level, as Firefox's own export does; on
Firefox loose top-level entries are routed into the Menu, elsewhere a menu
folder stays a folder under Other. New-folder mode is unchanged.
- Separators come back as { type: "separator", url: "data:" }. Recognised by
type (browser/live-tree.ts): left out of exports and backups, of every
count, of the dedupe index and the duplicate finder, never a search match;
in #edit they are aria-hidden lines that take no focus or command, with
posinset counting items only, Alt+↑/↓ stepping past one as one place, and
Sort A→Z sorting each run between them. The Replace confirmation says how
many will go and that nothing brings them back; files' separators are
counted (SEPARATORS_SKIPPED).
- Move index: Chromium counts a rightward same-folder move before removal,
Firefox after. The adapter sends each its own number and the reply's index
is checked — a mismatch re-reads the tree. Before this, every rightward drag
on Firefox landed one place too far and Alt+↓ moved two.
- Firefox refuses addresses over 65 536 characters, mid-write: dropped before
planning on Firefox (URL_TOO_LONG); nothing changes on Chromium.
- Strings true in every browser: the date note says "the browser", the About
link is "Store listing" and goes to the listing the copy came from (AMO by
gecko id, the Chrome Web Store by item id, else the README's install
section); the smart-bookmark note drops "dead link". Diagnostics names the
browser. All five locales (ja/zh-CN/ro best-effort).
bookmarks.ts was over the 300-line target, so its pure half moved to
live-tree.ts and root resolution to roots.ts before anything was added.
Tests run the root, Replace, export and #edit paths over a Firefox flavour of
the fake (docs/11 §4). Also fixes the last Qodana finding, a redundant escape
in the i18n interpolation regex.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
779335802a
commit
2eaa1acce4
60 files changed
+1643
-383
No files matched your search
@@ -49,7 +49,7 @@
|
||||
never deleted (API forbids it). On Firefox the deletion includes the
|
||||
**separators** in those roots, and nothing restores them — no format
|
||||
BookmarkMagic writes keeps one — so the confirmation says how many will go
|
||||
(`import.replace.separators`, shown only when there are any). The counts in
|
||||
(`import.replaceSeparators`, shown only when there are any). The counts in
|
||||
that confirmation never include separators among the bookmarks.
|
||||
- **Root routing** (`core/route.ts`), top-level nodes only — deeper, markers
|
||||
are data. A folder that *is* a browser root is **unwrapped**: its children go
|
||||
|
||||
+2
-2
@@ -244,8 +244,8 @@ that were not true everywhere, in all five languages:
|
||||
| `warnings.PLACE_QUERIES_SKIPPED` | "…skipped — here they would be dead links." | "…skipped." (on Firefox they are not dead links; BookmarkMagic still does not write them) |
|
||||
|
||||
and added, with Romanian's `few` form where a count is involved (§5):
|
||||
`warnings.URL_TOO_LONG`, `warnings.SEPARATORS_SKIPPED` and
|
||||
`import.replace.separators`. The JA, ZH-CN and RO versions are best-effort and
|
||||
`warnings.URL_TOO_LONG`, `warnings.SEPARATORS_SKIPPED`,
|
||||
`import.replaceSeparators` and `import.target.menu`. The JA, ZH-CN and RO versions are best-effort and
|
||||
carry the usual `TODO(review-…)` marker.
|
||||
|
||||
## 5. Locale-sensitive edge cases
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { onMount } from 'svelte';
|
||||
import { getAppVersion } from '@/lib/browser/app-info';
|
||||
import { getRootChildren } from '@/lib/browser/bookmarks';
|
||||
import { countLive } from '@/lib/browser/live-tree';
|
||||
import { type ManagerRoute, openManager } from '@/lib/browser/open-manager';
|
||||
import Icon, { type IconName } from '@/lib/components/icons/Icon.svelte';
|
||||
import { num, t, tPlural } from '@/lib/i18n/index.svelte';
|
||||
@@ -27,21 +28,10 @@
|
||||
*/
|
||||
async function countTree(): Promise<void> {
|
||||
try {
|
||||
let bookmarks = 0;
|
||||
let folders = 0;
|
||||
const stack: { url?: string; children?: unknown[] }[] = [];
|
||||
for (const root of await getRootChildren()) {
|
||||
// A loop, not push(...spread): Other Bookmarks can hold 100k children.
|
||||
for (const child of root.children ?? []) stack.push(child);
|
||||
}
|
||||
while (stack.length > 0) {
|
||||
const node = stack.pop();
|
||||
if (node === undefined) break;
|
||||
if (node.url === undefined) folders++;
|
||||
else bookmarks++;
|
||||
// SAFETY: children of a LiveNode are LiveNodes, which have this shape.
|
||||
for (const child of (node.children ?? []) as typeof stack) stack.push(child);
|
||||
}
|
||||
// Inside the roots, separators (Firefox) apart: a separator's url is
|
||||
// "data:", and counting by url called every one a bookmark.
|
||||
const inside = (await getRootChildren()).flatMap((root) => root.children ?? []);
|
||||
const { bookmarks, folders } = countLive(inside);
|
||||
counts = { bookmarks, folders };
|
||||
} catch {
|
||||
counts = undefined;
|
||||
|
||||
@@ -25,6 +25,15 @@ export function getAppVersion(): string {
|
||||
}
|
||||
}
|
||||
|
||||
/** This install's extension id, or `''` when it cannot be read. Never throws. */
|
||||
export function getExtensionId(): string {
|
||||
try {
|
||||
return browser.runtime.id;
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The `generator` string written into exported and backup BM JSON.
|
||||
*
|
||||
|
||||
+36
-187
@@ -3,60 +3,20 @@
|
||||
*
|
||||
* Purpose: the single audited surface where the extension talks to the
|
||||
* bookmarks API. Components never call `chrome.*` directly.
|
||||
* Inputs / guarantees: raw rejections are mapped to `BmBrowserError`; the live
|
||||
* tree is converted into the pure `BookmarkNode` file model here, including
|
||||
* the millisecond→second conversion (`chrome.bookmarks` reports `dateAdded`
|
||||
* in ms; `BookmarkNode.addDate` is seconds — docs/05 §4).
|
||||
* Inputs / guarantees: raw rejections are mapped to `BmBrowserError`. The
|
||||
* pure half — the node shape, separators, counts and the conversion into the
|
||||
* `BookmarkNode` file model — is `live-tree.ts`; which folders are the roots
|
||||
* is `roots.ts`. Firefox's API differs from Chromium's in ways this file
|
||||
* absorbs (docs/02 §4): its move index (below) and its missing events.
|
||||
*/
|
||||
import { browser } from 'wxt/browser';
|
||||
import type { BookmarkNode } from '../core/model';
|
||||
import { millisToSeconds } from '../core/timestamps';
|
||||
import { BmAborted, BmBrowserError, BmEnvError, BmPartialWrite } from './errors';
|
||||
import { BmAborted, BmBrowserError, BmPartialWrite } from './errors';
|
||||
import { type LiveNode, type MoveDestination, type MoveIndexRule, moveIndexFor } from './live-tree';
|
||||
|
||||
/** The live-tree node. Unlike `BookmarkNode` it carries browser identity. */
|
||||
export interface LiveNode {
|
||||
id: string;
|
||||
parentId?: string;
|
||||
index?: number;
|
||||
title: string;
|
||||
url?: string;
|
||||
dateAdded?: number;
|
||||
dateGroupModified?: number;
|
||||
/** Set by Chrome on policy-managed nodes; such nodes reject writes. */
|
||||
unmodifiable?: string;
|
||||
/**
|
||||
* Chrome 134+: which permanent folder a root is ('bookmarks-bar', 'other',
|
||||
* 'mobile', 'managed'), and whether it is in the signed-in account's storage
|
||||
* rather than this device's. Both exist from the 136 floor up.
|
||||
*/
|
||||
folderType?: string;
|
||||
syncing?: boolean;
|
||||
children?: LiveNode[];
|
||||
}
|
||||
|
||||
export interface BookmarkRoots {
|
||||
/** Bookmarks Bar. */
|
||||
toolbarId: string;
|
||||
/** Other Bookmarks. */
|
||||
otherId: string;
|
||||
/** Mobile Bookmarks, when the profile has one. */
|
||||
mobileId: string | undefined;
|
||||
/** The same three roots as nodes, children included — Merge matches inside them. */
|
||||
toolbar: LiveNode;
|
||||
other: LiveNode;
|
||||
mobile: LiveNode | undefined;
|
||||
/** Writable top-level folders, in tree order, excluding managed ones. */
|
||||
writable: LiveNode[];
|
||||
/**
|
||||
* The roots Replace backs up and empties: exactly the destinations above.
|
||||
* Never an account-storage root this import does not write back into —
|
||||
* deleting one would sync the deletion to every device, and the restore
|
||||
* would land its bookmarks in local storage.
|
||||
*/
|
||||
replaceable: LiveNode[];
|
||||
/** Every top-level folder, managed ones included — what "already in this browser" means. */
|
||||
all: LiveNode[];
|
||||
}
|
||||
// The node shape and the move-index rule live with the pure helpers
|
||||
// (live-tree.ts); re-exported so the adapter stays the one import for code
|
||||
// that talks to the browser.
|
||||
export type { LiveNode, MoveDestination } from './live-tree';
|
||||
|
||||
async function guard<T>(operation: string, run: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
@@ -72,139 +32,6 @@ export async function getRootChildren(): Promise<LiveNode[]> {
|
||||
return (tree[0]?.children ?? []) as LiveNode[];
|
||||
}
|
||||
|
||||
const FOLDER_IDS = { 'bookmarks-bar': '1', other: '2', mobile: '3' } as const;
|
||||
|
||||
/**
|
||||
* Desktop Chrome leaves an EMPTY Mobile root out of `getTree()`, so a restore
|
||||
* into a fresh profile found no Mobile root and nested those bookmarks under
|
||||
* Other. The node still exists, and accepts writes; ask for it by id.
|
||||
*/
|
||||
async function hiddenMobileRoot(): Promise<LiveNode | undefined> {
|
||||
try {
|
||||
const [node] = (await browser.bookmarks.get(FOLDER_IDS.mobile)) as LiveNode[];
|
||||
const usable =
|
||||
node !== undefined &&
|
||||
node.url === undefined &&
|
||||
node.unmodifiable === undefined &&
|
||||
node.syncing !== true &&
|
||||
(node.folderType === undefined || node.folderType === 'mobile');
|
||||
return usable ? { ...node, children: node.children ?? [] } : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the destination roots.
|
||||
*
|
||||
* By `folderType` first — Chrome 134+ can list a signed-in account's own bar,
|
||||
* Other and Mobile beside this device's, and the old by-id-then-by-position
|
||||
* rule mixed the two sets up. This device's roots are the destinations;
|
||||
* account roots are never written to or emptied. The ids "1"/"2"/"3" and then
|
||||
* position remain as fallbacks for a browser without `folderType`. Nodes
|
||||
* carrying `unmodifiable` (the enterprise "Managed bookmarks" folder) are
|
||||
* excluded everywhere — writing to or removing them rejects.
|
||||
*/
|
||||
export async function getRoots(): Promise<BookmarkRoots> {
|
||||
const children = await getRootChildren();
|
||||
const writable = children.filter((node) => node.unmodifiable === undefined);
|
||||
const local = writable.filter((node) => node.syncing !== true);
|
||||
const typed = local.some((node) => node.folderType !== undefined);
|
||||
|
||||
const pick = (type: keyof typeof FOLDER_IDS): LiveNode | undefined =>
|
||||
local.find((node) => node.folderType === type) ??
|
||||
local.find((node) => node.id === FOLDER_IDS[type]);
|
||||
const toolbar = pick('bookmarks-bar') ?? (typed ? undefined : local[0]);
|
||||
const other = pick('other') ?? (typed ? undefined : local.find((n) => n !== toolbar));
|
||||
const mobile =
|
||||
pick('mobile') ??
|
||||
(typed ? undefined : local.find((n) => n !== toolbar && n !== other)) ??
|
||||
(await hiddenMobileRoot());
|
||||
|
||||
if (toolbar === undefined || other === undefined) {
|
||||
// Not a BmBrowserError: nothing refused anything. Every root this profile
|
||||
// has is policy-managed, so there is nowhere an extension may write, and
|
||||
// "the browser refused a bookmark operation" would be actively misleading.
|
||||
throw new BmEnvError('NO_WRITABLE_ROOTS', `${children.length} root(s), none writable`);
|
||||
}
|
||||
|
||||
return {
|
||||
toolbarId: toolbar.id,
|
||||
otherId: other.id,
|
||||
mobileId: mobile?.id,
|
||||
toolbar,
|
||||
other,
|
||||
mobile,
|
||||
writable,
|
||||
replaceable: mobile === undefined ? [toolbar, other] : [toolbar, other, mobile],
|
||||
all: children,
|
||||
};
|
||||
}
|
||||
|
||||
export interface ToNodesOptions {
|
||||
/**
|
||||
* Id of the Bookmarks Bar. The matching node is marked `toolbar: true`.
|
||||
*
|
||||
* Without this the marker is lost, and re-importing the file (including the
|
||||
* Replace safety backup) lands the entire toolbar under Other Bookmarks —
|
||||
* `03 §1` routes purely on that flag.
|
||||
*/
|
||||
toolbarId?: string;
|
||||
/**
|
||||
* Ids of Other and Mobile Bookmarks, marked `root: 'other'`/`'mobile'` for
|
||||
* the same reason: without them a restore nested both one level too deep.
|
||||
*/
|
||||
otherId?: string;
|
||||
mobileId?: string;
|
||||
}
|
||||
|
||||
/** The marker ids for a whole-tree conversion — what an export or backup passes. */
|
||||
export function rootMarkersOf(roots: BookmarkRoots): ToNodesOptions {
|
||||
return {
|
||||
toolbarId: roots.toolbarId,
|
||||
otherId: roots.otherId,
|
||||
...(roots.mobileId !== undefined && { mobileId: roots.mobileId }),
|
||||
};
|
||||
}
|
||||
|
||||
function markerOf(id: string, options: ToNodesOptions): Pick<BookmarkNode, 'toolbar' | 'root'> {
|
||||
if (id === options.toolbarId) return { toolbar: true };
|
||||
if (id === options.otherId) return { root: 'other' };
|
||||
if (id === options.mobileId) return { root: 'mobile' };
|
||||
return {};
|
||||
}
|
||||
|
||||
/** Convert the live tree into the pure file model (ms → s, ids dropped). */
|
||||
export function toBookmarkNodes(
|
||||
nodes: readonly LiveNode[],
|
||||
options: ToNodesOptions = {},
|
||||
): BookmarkNode[] {
|
||||
return nodes.map((node) => {
|
||||
const addDate = millisToSeconds(node.dateAdded);
|
||||
const isFolderNode = node.url === undefined;
|
||||
// dateGroupModified is a FOLDER field — Chrome does not set it on
|
||||
// bookmarks, and our HTML serializer only emits LAST_MODIFIED on <H3>.
|
||||
const lastModified = isFolderNode ? millisToSeconds(node.dateGroupModified) : undefined;
|
||||
return {
|
||||
title: node.title,
|
||||
...(node.url !== undefined && { url: node.url }),
|
||||
...(addDate !== undefined && { addDate }),
|
||||
...(lastModified !== undefined && { lastModified }),
|
||||
...(isFolderNode && markerOf(node.id, options)),
|
||||
...(isFolderNode && { children: toBookmarkNodes(node.children ?? [], options) }),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Flatten a live tree, parents before children. Used by dedupe and #edit. */
|
||||
export function flattenLive(nodes: readonly LiveNode[], into: LiveNode[] = []): LiveNode[] {
|
||||
for (const node of nodes) {
|
||||
into.push(node);
|
||||
if (node.children !== undefined) flattenLive(node.children, into);
|
||||
}
|
||||
return into;
|
||||
}
|
||||
|
||||
/** The current children of one folder — what a bulk command re-plans from. */
|
||||
export async function getChildren(id: string): Promise<LiveNode[]> {
|
||||
return (await guard('bookmarks.getChildren', () =>
|
||||
@@ -226,11 +53,33 @@ export async function update(id: string, changes: { title?: string; url?: string
|
||||
await guard('bookmarks.update', () => browser.bookmarks.update(id, changes));
|
||||
}
|
||||
|
||||
const MOVE_INDEX_RULE: MoveIndexRule = import.meta.env.FIREFOX ? 'firefox' : 'chromium';
|
||||
|
||||
/**
|
||||
* The longest address this browser accepts in a bookmark, or `undefined` for
|
||||
* none. Firefox refuses anything over 65 536 characters (Places'
|
||||
* `MAX_URL_LENGTH`) — mid-write, so the import drops such addresses up front
|
||||
* (docs/04 §1.2); Chromium has no limit an import can reach.
|
||||
*/
|
||||
export const MAX_URL_LENGTH: number | undefined = import.meta.env.FIREFOX ? 65_536 : undefined;
|
||||
|
||||
/**
|
||||
* Move a node. Resolves to the index the browser says the node now has, which
|
||||
* the caller compares with `position.local` — a disagreement means the tree on
|
||||
* screen no longer matches the browser's, and it is re-read (docs/03 §3).
|
||||
*/
|
||||
export async function move(
|
||||
id: string,
|
||||
destination: { parentId?: string; index?: number },
|
||||
): Promise<void> {
|
||||
await guard('bookmarks.move', () => browser.bookmarks.move(id, destination));
|
||||
destination: MoveDestination,
|
||||
rule: MoveIndexRule = MOVE_INDEX_RULE,
|
||||
): Promise<number | undefined> {
|
||||
const { parentId, position } = destination;
|
||||
const details = {
|
||||
...(parentId !== undefined && { parentId }),
|
||||
...(position !== undefined && { index: moveIndexFor(position, rule) }),
|
||||
};
|
||||
const moved = await guard('bookmarks.move', () => browser.bookmarks.move(id, details));
|
||||
return (moved as { index?: number } | undefined)?.index;
|
||||
}
|
||||
|
||||
/** Remove a single bookmark. Folders need `removeTree`. */
|
||||
|
||||
@@ -102,14 +102,28 @@ export interface DiagnosticsContext {
|
||||
theme: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The browser and its major version from the user agent: "Firefox 160",
|
||||
* "Edge 142", "Chrome 142", or "unknown". Edge's agent also says Chrome, so it
|
||||
* is read first. Since v1.3.0 — until then the report carried `chromeMajor`,
|
||||
* which said "unknown" on Firefox.
|
||||
*/
|
||||
export function browserOf(userAgent: string): string {
|
||||
for (const [name, pattern] of [
|
||||
['Firefox', /Firefox\/(\d+)/],
|
||||
['Edge', /Edg\/(\d+)/],
|
||||
['Chrome', /Chrome\/(\d+)/],
|
||||
] as const) {
|
||||
const major = pattern.exec(userAgent)?.[1];
|
||||
if (major !== undefined) return `${name} ${major}`;
|
||||
}
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
/** The report the About tab copies: context first, then the events, oldest first. */
|
||||
export function snapshot(context: DiagnosticsContext): string {
|
||||
const chrome = /Chrome\/(\d+)/.exec(globalThis.navigator?.userAgent ?? '')?.[1] ?? 'unknown';
|
||||
return JSON.stringify(
|
||||
{ app: 'BookmarkMagic', ...context, chromeMajor: chrome, events: entries },
|
||||
null,
|
||||
2,
|
||||
);
|
||||
const browser = browserOf(globalThis.navigator?.userAgent ?? '');
|
||||
return JSON.stringify({ app: 'BookmarkMagic', ...context, browser, events: entries }, null, 2);
|
||||
}
|
||||
|
||||
/** Test teardown — module state outlives a single `it()`. */
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* The live bookmark tree as the browser reports it — docs/02 §4.
|
||||
*
|
||||
* Purpose: the pure half of the bookmarks adapter — the node shape, Firefox's
|
||||
* separators, the counts, and the conversion into the file model. No
|
||||
* browser call lives here, so every line is tested directly.
|
||||
* Guarantees: separators are recognised by `type` alone. Firefox gives them
|
||||
* `url: "data:"`, so every "has a url, so it is a bookmark" test in the code
|
||||
* would otherwise count, export, dedupe and open them as bookmarks.
|
||||
*/
|
||||
import type { BookmarkNode } from '../core/model';
|
||||
import { millisToSeconds } from '../core/timestamps';
|
||||
|
||||
/** The live-tree node. Unlike `BookmarkNode` it carries browser identity. */
|
||||
export interface LiveNode {
|
||||
id: string;
|
||||
parentId?: string;
|
||||
index?: number;
|
||||
title: string;
|
||||
url?: string;
|
||||
dateAdded?: number;
|
||||
dateGroupModified?: number;
|
||||
/** Set by Chrome on policy-managed nodes; such nodes reject writes. */
|
||||
unmodifiable?: string;
|
||||
/**
|
||||
* Chrome 134+: which permanent folder a root is ('bookmarks-bar', 'other',
|
||||
* 'mobile', 'managed'), and whether it is in the signed-in account's storage
|
||||
* rather than this device's. Both exist from the 136 floor up; Firefox has
|
||||
* neither.
|
||||
*/
|
||||
folderType?: string;
|
||||
syncing?: boolean;
|
||||
/** Firefox: 'bookmark', 'folder' or 'separator'. Chromium does not send it. */
|
||||
type?: string;
|
||||
children?: LiveNode[];
|
||||
}
|
||||
|
||||
/** A Firefox separator. By `type`, never by url: a separator's url is "data:". */
|
||||
export function isSeparator(node: { type?: string }): boolean {
|
||||
return node.type === 'separator';
|
||||
}
|
||||
|
||||
/**
|
||||
* The forest without its separators — for everything that reads bookmarks as
|
||||
* bookmarks (the dedupe index, Merge's folder matching). Untouched branches
|
||||
* are returned as they are.
|
||||
*/
|
||||
export function withoutSeparators(nodes: readonly LiveNode[]): LiveNode[] {
|
||||
const out: LiveNode[] = [];
|
||||
for (const node of nodes) {
|
||||
if (isSeparator(node)) continue;
|
||||
out.push(
|
||||
node.children === undefined ? node : { ...node, children: withoutSeparators(node.children) },
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface LiveCounts {
|
||||
bookmarks: number;
|
||||
folders: number;
|
||||
/** Firefox only; always 0 in a Chromium browser. */
|
||||
separators: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count what a forest holds, separators apart. Iterative: Other Bookmarks can
|
||||
* hold 100k children, and the live tree has no depth cap.
|
||||
*/
|
||||
export function countLive(nodes: readonly LiveNode[]): LiveCounts {
|
||||
const counts: LiveCounts = { bookmarks: 0, folders: 0, separators: 0 };
|
||||
const stack: LiveNode[] = [];
|
||||
for (const node of nodes) stack.push(node);
|
||||
while (stack.length > 0) {
|
||||
const node = stack.pop();
|
||||
if (node === undefined) break;
|
||||
if (isSeparator(node)) counts.separators++;
|
||||
else if (node.url === undefined) counts.folders++;
|
||||
else counts.bookmarks++;
|
||||
for (const child of node.children ?? []) stack.push(child);
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
export interface ToNodesOptions {
|
||||
/**
|
||||
* Id of the Bookmarks Bar. The matching node is marked `toolbar: true`.
|
||||
*
|
||||
* Without this the marker is lost, and re-importing the file (including the
|
||||
* Replace safety backup) lands the entire toolbar under Other Bookmarks —
|
||||
* `03 §1` routes purely on that flag.
|
||||
*/
|
||||
toolbarId?: string;
|
||||
/**
|
||||
* Ids of Other and Mobile Bookmarks, and of Firefox's Bookmarks Menu,
|
||||
* marked `root: 'other'`/`'mobile'`/`'menu'` for the same reason: without
|
||||
* them a restore nested each one level too deep.
|
||||
*/
|
||||
otherId?: string;
|
||||
mobileId?: string;
|
||||
menuId?: string;
|
||||
}
|
||||
|
||||
function markerOf(id: string, options: ToNodesOptions): Pick<BookmarkNode, 'toolbar' | 'root'> {
|
||||
if (id === options.toolbarId) return { toolbar: true };
|
||||
if (id === options.otherId) return { root: 'other' };
|
||||
if (id === options.mobileId) return { root: 'mobile' };
|
||||
if (id === options.menuId) return { root: 'menu' };
|
||||
return {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the live tree into the pure file model (ms → s, ids dropped).
|
||||
* Separators are left out: no format BookmarkMagic writes can hold one
|
||||
* (docs/04).
|
||||
*/
|
||||
export function toBookmarkNodes(
|
||||
nodes: readonly LiveNode[],
|
||||
options: ToNodesOptions = {},
|
||||
): BookmarkNode[] {
|
||||
const out: BookmarkNode[] = [];
|
||||
for (const node of nodes) {
|
||||
if (isSeparator(node)) continue;
|
||||
const addDate = millisToSeconds(node.dateAdded);
|
||||
const isFolderNode = node.url === undefined;
|
||||
// dateGroupModified is a FOLDER field — Chrome does not set it on
|
||||
// bookmarks, and our HTML serializer only emits LAST_MODIFIED on <H3>.
|
||||
const lastModified = isFolderNode ? millisToSeconds(node.dateGroupModified) : undefined;
|
||||
out.push({
|
||||
title: node.title,
|
||||
...(node.url !== undefined && { url: node.url }),
|
||||
...(addDate !== undefined && { addDate }),
|
||||
...(lastModified !== undefined && { lastModified }),
|
||||
...(isFolderNode && markerOf(node.id, options)),
|
||||
...(isFolderNode && { children: toBookmarkNodes(node.children ?? [], options) }),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* How a browser counts `bookmarks.move`'s index for a move inside one folder
|
||||
* (docs/05 §10). Chromium counts as if the node were still in place; Firefox
|
||||
* counts after removing it, because Places stores the final position. Moving
|
||||
* `a` after `c` in `[a, b, c]` is index 3 in Chrome and 2 in Firefox — and
|
||||
* sending Chrome's number to Firefox made every rightward drag land one place
|
||||
* too far and Alt+↓ move two places.
|
||||
*/
|
||||
export type MoveIndexRule = 'chromium' | 'firefox';
|
||||
|
||||
/** Where a node goes: a folder, and optionally a place in it counted both ways (`planDrop`). */
|
||||
export interface MoveDestination {
|
||||
parentId?: string;
|
||||
/** `api` counted before the node's removal (Chromium's rule), `local` after it. */
|
||||
position?: { api: number; local: number };
|
||||
}
|
||||
|
||||
/** The index to send under a browser's rule. */
|
||||
export function moveIndexFor(
|
||||
position: { api: number; local: number },
|
||||
rule: MoveIndexRule,
|
||||
): number {
|
||||
return rule === 'firefox' ? position.local : position.api;
|
||||
}
|
||||
|
||||
/** Flatten a live tree, parents before children. Used by dedupe and #edit. */
|
||||
export function flattenLive(nodes: readonly LiveNode[], into: LiveNode[] = []): LiveNode[] {
|
||||
for (const node of nodes) {
|
||||
into.push(node);
|
||||
if (node.children !== undefined) flattenLive(node.children, into);
|
||||
}
|
||||
return into;
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Which live folders are the browser's permanent roots — docs/02 §4.
|
||||
*
|
||||
* Purpose: find the import's destinations — the bar, Other, Mobile, and on
|
||||
* Firefox the Bookmarks Menu — in whatever browser this runs in.
|
||||
* Guarantees: this device's roots only (a signed-in Chrome account's own roots
|
||||
* are listed but never written to or emptied); policy-managed roots never;
|
||||
* and on Firefox the Menu is never mistaken for the bar.
|
||||
*/
|
||||
import { browser } from 'wxt/browser';
|
||||
import { getRootChildren } from './bookmarks';
|
||||
import { BmEnvError } from './errors';
|
||||
import type { LiveNode, ToNodesOptions } from './live-tree';
|
||||
|
||||
export interface BookmarkRoots {
|
||||
/** Bookmarks Bar. */
|
||||
toolbarId: string;
|
||||
/** Other Bookmarks. */
|
||||
otherId: string;
|
||||
/** Mobile Bookmarks, when the profile has one. */
|
||||
mobileId: string | undefined;
|
||||
/** Firefox's Bookmarks Menu. No Chromium browser has one. */
|
||||
menuId: string | undefined;
|
||||
/** The same roots as nodes, children included — Merge matches inside them. */
|
||||
toolbar: LiveNode;
|
||||
other: LiveNode;
|
||||
mobile: LiveNode | undefined;
|
||||
menu: LiveNode | undefined;
|
||||
/** Writable top-level folders, in tree order, excluding managed ones. */
|
||||
writable: LiveNode[];
|
||||
/**
|
||||
* The roots Replace backs up and empties: exactly the destinations above.
|
||||
* Never an account-storage root this import does not write back into —
|
||||
* deleting one would sync the deletion to every device, and the restore
|
||||
* would land its bookmarks in local storage.
|
||||
*/
|
||||
replaceable: LiveNode[];
|
||||
/** Every top-level folder, managed ones included — what "already in this browser" means. */
|
||||
all: LiveNode[];
|
||||
}
|
||||
|
||||
/** Chromium's stable ids for the three permanent folders. */
|
||||
const CHROMIUM_IDS = { 'bookmarks-bar': '1', other: '2', mobile: '3' } as const;
|
||||
|
||||
/** Firefox's permanent folders — Places GUIDs, the same in every profile. */
|
||||
const FIREFOX_IDS = {
|
||||
'bookmarks-bar': 'toolbar_____',
|
||||
other: 'unfiled_____',
|
||||
mobile: 'mobile______',
|
||||
} as const;
|
||||
const FIREFOX_MENU_ID = 'menu________';
|
||||
|
||||
/**
|
||||
* Desktop Chrome leaves an EMPTY Mobile root out of `getTree()`, so a restore
|
||||
* into a fresh profile found no Mobile root and nested those bookmarks under
|
||||
* Other. The node still exists, and accepts writes; ask for it by id. (Firefox
|
||||
* always lists its Mobile root, and rejects the id "3" — caught here.)
|
||||
*/
|
||||
async function hiddenMobileRoot(): Promise<LiveNode | undefined> {
|
||||
try {
|
||||
const [node] = (await browser.bookmarks.get(CHROMIUM_IDS.mobile)) as LiveNode[];
|
||||
const usable =
|
||||
node !== undefined &&
|
||||
node.url === undefined &&
|
||||
node.unmodifiable === undefined &&
|
||||
node.syncing !== true &&
|
||||
(node.folderType === undefined || node.folderType === 'mobile');
|
||||
return usable ? { ...node, children: node.children ?? [] } : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the destination roots.
|
||||
*
|
||||
* By `folderType` first — Chrome 134+ can list a signed-in account's own bar,
|
||||
* Other and Mobile beside this device's, and the old by-id-then-by-position
|
||||
* rule mixed the two sets up. Then the stable Chromium ids, then Firefox's
|
||||
* GUIDs, and position last. The Bookmarks Menu is never a candidate for a
|
||||
* position: Firefox lists it first, and until v1.3.0 the position fallback
|
||||
* took it for the bar — Replace would have emptied the Menu and the toolbar
|
||||
* and restored the bar's bookmarks into the Menu. Nodes carrying
|
||||
* `unmodifiable` (the enterprise "Managed bookmarks" folder) are excluded
|
||||
* everywhere — writing to or removing them rejects.
|
||||
*/
|
||||
export async function getRoots(): Promise<BookmarkRoots> {
|
||||
const children = await getRootChildren();
|
||||
const writable = children.filter((node) => node.unmodifiable === undefined);
|
||||
const local = writable.filter((node) => node.syncing !== true);
|
||||
const typed = local.some((node) => node.folderType !== undefined);
|
||||
const menu = local.find((node) => node.id === FIREFOX_MENU_ID);
|
||||
const positional = local.filter((node) => node !== menu);
|
||||
|
||||
const pick = (type: keyof typeof CHROMIUM_IDS): LiveNode | undefined =>
|
||||
local.find((node) => node.folderType === type) ??
|
||||
local.find((node) => node.id === CHROMIUM_IDS[type]) ??
|
||||
local.find((node) => node.id === FIREFOX_IDS[type]);
|
||||
const toolbar = pick('bookmarks-bar') ?? (typed ? undefined : positional[0]);
|
||||
const other = pick('other') ?? (typed ? undefined : positional.find((n) => n !== toolbar));
|
||||
const mobile =
|
||||
pick('mobile') ??
|
||||
(typed ? undefined : positional.find((n) => n !== toolbar && n !== other)) ??
|
||||
(await hiddenMobileRoot());
|
||||
|
||||
if (toolbar === undefined || other === undefined) {
|
||||
// Not a BmBrowserError: nothing refused anything. Every root this profile
|
||||
// has is policy-managed, so there is nowhere an extension may write, and
|
||||
// "the browser refused a bookmark operation" would be actively misleading.
|
||||
throw new BmEnvError('NO_WRITABLE_ROOTS', `${children.length} root(s), none writable`);
|
||||
}
|
||||
|
||||
const replaceable = [toolbar, other];
|
||||
if (mobile !== undefined) replaceable.push(mobile);
|
||||
if (menu !== undefined) replaceable.push(menu);
|
||||
return {
|
||||
toolbarId: toolbar.id,
|
||||
otherId: other.id,
|
||||
mobileId: mobile?.id,
|
||||
menuId: menu?.id,
|
||||
toolbar,
|
||||
other,
|
||||
mobile,
|
||||
menu,
|
||||
writable,
|
||||
replaceable,
|
||||
all: children,
|
||||
};
|
||||
}
|
||||
|
||||
/** The marker ids for a whole-tree conversion — what an export or backup passes. */
|
||||
export function rootMarkersOf(roots: BookmarkRoots): ToNodesOptions {
|
||||
return {
|
||||
toolbarId: roots.toolbarId,
|
||||
otherId: roots.otherId,
|
||||
...(roots.mobileId !== undefined && { mobileId: roots.mobileId }),
|
||||
...(roots.menuId !== undefined && { menuId: roots.menuId }),
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { getAppVersion } from '../browser/app-info';
|
||||
import { getAppVersion, getExtensionId } from '../browser/app-info';
|
||||
import { dateTime, t } from '../i18n/index.svelte';
|
||||
import {
|
||||
ACCESSIBILITY_URL,
|
||||
@@ -8,7 +8,7 @@
|
||||
ISSUES_URL,
|
||||
LEGAL_URLS,
|
||||
REPO_URL,
|
||||
STORE_URL,
|
||||
storeUrlFor,
|
||||
} from '../links';
|
||||
import { copyToClipboard } from '../browser/clipboard';
|
||||
import { snapshot } from '../browser/diagnostics';
|
||||
@@ -19,6 +19,9 @@
|
||||
import Icon from './icons/Icon.svelte';
|
||||
|
||||
const version = getAppVersion();
|
||||
// The listing this copy came from (docs/06 §3.5): AMO for the Firefox build,
|
||||
// the Chrome Web Store for its own id, the install page for anything else.
|
||||
const storeUrl = storeUrlFor({ firefox: import.meta.env.FIREFOX, extensionId: getExtensionId() });
|
||||
const acceptance = $derived(getAcceptance());
|
||||
// undefined when acceptedAt is missing or unparseable — storage coerces a
|
||||
// missing timestamp to '', and formatting that would throw inside the render.
|
||||
@@ -60,7 +63,7 @@
|
||||
{t('about.accessibility')}<Icon name="external" size={12} />
|
||||
</a>
|
||||
</li>
|
||||
<li><a href={STORE_URL} target="_blank" rel="noopener noreferrer">{t('about.store')}<Icon name="external" size={12} /></a></li>
|
||||
<li><a href={storeUrl} target="_blank" rel="noopener noreferrer">{t('about.store')}<Icon name="external" size={12} /></a></li>
|
||||
</ul>
|
||||
|
||||
<h2 class="eyebrow">{t('about.thirdParty')}</h2>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { LiveNode } from '../browser/bookmarks';
|
||||
import { isSeparator } from '../browser/live-tree';
|
||||
import type { CheckState } from '../core/select';
|
||||
import { num, t, tPlural } from '../i18n/index.svelte';
|
||||
import Disclosure from './Disclosure.svelte';
|
||||
@@ -24,7 +25,10 @@
|
||||
|
||||
/** 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);
|
||||
// A Firefox separator has a url ("data:") but is not a bookmark (docs/02 §4).
|
||||
const bookmarks = $derived(
|
||||
(node.children ?? []).filter((child) => child.url !== undefined && !isSeparator(child)).length,
|
||||
);
|
||||
const shown = $derived(folders.length > limit ? folders.slice(0, limit) : folders);
|
||||
|
||||
let input: HTMLInputElement | undefined = $state();
|
||||
|
||||
@@ -191,11 +191,19 @@
|
||||
open={confirmingReplace}
|
||||
danger
|
||||
title={t('import.replaceConfirmTitle')}
|
||||
body={t('import.replaceConfirmBody', {
|
||||
current: counts(prepared?.current.bookmarks ?? 0, prepared?.current.folders ?? 0),
|
||||
incoming: counts(forecast?.stats.bookmarkCount ?? 0, forecast?.stats.folderCount ?? 0),
|
||||
name: session.filename,
|
||||
})}
|
||||
body={[
|
||||
t('import.replaceConfirmBody', {
|
||||
current: counts(prepared?.current.bookmarks ?? 0, prepared?.current.folders ?? 0),
|
||||
incoming: counts(forecast?.stats.bookmarkCount ?? 0, forecast?.stats.folderCount ?? 0),
|
||||
name: session.filename,
|
||||
}),
|
||||
// Firefox only: separators go with the rest, and nothing brings them back.
|
||||
(prepared?.current.separators ?? 0) > 0
|
||||
? tPlural('import.replaceSeparators', prepared?.current.separators ?? 0)
|
||||
: '',
|
||||
]
|
||||
.filter((sentence) => sentence !== '')
|
||||
.join(' ')}
|
||||
confirmLabel={t('import.replaceConfirm')}
|
||||
cancelLabel={t('common.cancel')}
|
||||
onconfirm={() => void start(session.filename)}
|
||||
|
||||
@@ -110,18 +110,27 @@
|
||||
onfocus={onFocus}
|
||||
>
|
||||
{#each shown as row (row.node.id)}
|
||||
<li
|
||||
id="node-{row.node.id}"
|
||||
data-node-id={row.node.id}
|
||||
role="treeitem"
|
||||
aria-level={row.depth}
|
||||
aria-setsize={row.setSize}
|
||||
aria-posinset={row.posInSet}
|
||||
aria-expanded={row.expandable ? row.expanded : undefined}
|
||||
aria-selected={session.focusedId === row.node.id}
|
||||
>
|
||||
<TreeRow {row} {session} {onopen} {oncopy} {onsort} />
|
||||
</li>
|
||||
{#if row.node.separator === true}
|
||||
<!-- A Firefox separator (docs/06 §5): a line, and aria-hidden, so it is
|
||||
outside the accessibility tree and the tree still owns only
|
||||
treeitems. It takes no focus and no drop. -->
|
||||
<li class="separator" aria-hidden="true" style:--depth={row.depth - 1}>
|
||||
<span class="rule"></span>
|
||||
</li>
|
||||
{:else}
|
||||
<li
|
||||
id="node-{row.node.id}"
|
||||
data-node-id={row.node.id}
|
||||
role="treeitem"
|
||||
aria-level={row.depth}
|
||||
aria-setsize={row.setSize}
|
||||
aria-posinset={row.posInSet}
|
||||
aria-expanded={row.expandable ? row.expanded : undefined}
|
||||
aria-selected={session.focusedId === row.node.id}
|
||||
>
|
||||
<TreeRow {row} {session} {onopen} {oncopy} {onsort} />
|
||||
</li>
|
||||
{/if}
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
@@ -156,6 +165,21 @@
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
/* Indented like a row: 18px per level, plus the row's own inset and a
|
||||
disclosure-sized gap, so the line starts where its siblings' titles do. */
|
||||
.separator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 12px;
|
||||
padding-left: calc(var(--depth) * 18px + var(--sp-1) + 18px);
|
||||
padding-right: var(--sp-2);
|
||||
}
|
||||
|
||||
.separator .rule {
|
||||
flex: 1;
|
||||
border-top: 1px solid var(--border-strong);
|
||||
}
|
||||
|
||||
.tree:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
|
||||
@@ -36,7 +36,11 @@
|
||||
? 'unfiled'
|
||||
: node.root === 'mobile'
|
||||
? 'mobile'
|
||||
: undefined,
|
||||
: // Only Firefox has a Bookmarks Menu to unwrap into; elsewhere a
|
||||
// menu folder stays a folder, so it gets no pill (docs/03 §1).
|
||||
node.root === 'menu' && import.meta.env.FIREFOX
|
||||
? 'menu'
|
||||
: undefined,
|
||||
);
|
||||
</script>
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
* censor; they are never rendered as links).
|
||||
*/
|
||||
|
||||
import { type BookmarkNode, computeStats, isFolder, type ParseResult } from './model';
|
||||
|
||||
export type HrefVerdict = 'ok' | 'missing' | 'invalid' | 'place-query';
|
||||
|
||||
/**
|
||||
@@ -31,3 +33,42 @@ export function classifyHref(raw: string | null | undefined): HrefVerdict {
|
||||
if (/^place:/i.test(trimmed)) return 'place-query';
|
||||
return 'ok';
|
||||
}
|
||||
|
||||
/** Bookmarks under `nodes` whose address is longer than `max`, removed. */
|
||||
function withoutLongUrls(
|
||||
nodes: readonly BookmarkNode[],
|
||||
max: number,
|
||||
dropped: { count: number },
|
||||
): BookmarkNode[] {
|
||||
const out: BookmarkNode[] = [];
|
||||
for (const node of nodes) {
|
||||
if (!isFolder(node)) {
|
||||
if ((node.url ?? '').length > max) dropped.count++;
|
||||
else out.push(node);
|
||||
continue;
|
||||
}
|
||||
out.push({ ...node, children: withoutLongUrls(node.children ?? [], max, dropped) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop the bookmarks a browser would refuse for their length — docs/04 §1.2.
|
||||
*
|
||||
* Firefox refuses an address longer than 65 536 characters, and refuses it in
|
||||
* the middle of a write, possibly after a Replace has cleared the tree. The
|
||||
* browser layer passes its limit; Chromium has none and passes `undefined`,
|
||||
* which returns the result untouched. Applied once after parsing, so every
|
||||
* format meets one rule, and before the preview, so its counts include it.
|
||||
*/
|
||||
export function capUrlLength(result: ParseResult, max: number | undefined): ParseResult {
|
||||
if (max === undefined) return result;
|
||||
const dropped = { count: 0 };
|
||||
const roots = withoutLongUrls(result.roots, max, dropped);
|
||||
if (dropped.count === 0) return result;
|
||||
return {
|
||||
roots,
|
||||
stats: computeStats(roots),
|
||||
warnings: [...result.warnings, { code: 'URL_TOO_LONG', count: dropped.count }],
|
||||
};
|
||||
}
|
||||
@@ -11,8 +11,11 @@
|
||||
* OMITTING absent keys, never by assigning `undefined`.
|
||||
*/
|
||||
|
||||
/** A top-level folder that stands for a browser root other than the bar (docs/04 §1.1, §2). */
|
||||
export type RootMarker = 'other' | 'mobile';
|
||||
/**
|
||||
* A top-level folder that stands for a browser root other than the bar
|
||||
* (docs/04 §1.1, §2). `menu` is Firefox's Bookmarks Menu (since v1.3.0).
|
||||
*/
|
||||
export type RootMarker = 'other' | 'mobile' | 'menu';
|
||||
|
||||
export interface BookmarkNode {
|
||||
title: string;
|
||||
@@ -56,6 +59,8 @@ export const PARSE_WARNING_CODES = [
|
||||
'PLACE_QUERIES_SKIPPED',
|
||||
'EXTRA_ROOTS_SKIPPED',
|
||||
'UNREADABLE_ENTRIES',
|
||||
'SEPARATORS_SKIPPED',
|
||||
'URL_TOO_LONG',
|
||||
] as const;
|
||||
|
||||
export type ParseWarningCode = (typeof PARSE_WARNING_CODES)[number];
|
||||
|
||||
@@ -47,7 +47,9 @@ function readDate(value: unknown, warnings: WarningBag): number | undefined {
|
||||
|
||||
function readRootMarker(raw: Record<string, unknown>): RootMarker | undefined {
|
||||
if (raw.toolbar === true) return undefined; // the toolbar wins
|
||||
return raw.root === 'other' || raw.root === 'mobile' ? raw.root : undefined;
|
||||
return raw.root === 'other' || raw.root === 'mobile' || raw.root === 'menu'
|
||||
? raw.root
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function readNode(
|
||||
|
||||
@@ -9,18 +9,12 @@
|
||||
* by shape), plus display titles for the roots Firefox names only by key.
|
||||
* Guarantees: emits the same tree Firefox's own HTML export describes for the
|
||||
* same profile (docs/04 §2b parity rule), with the Mobile root added.
|
||||
* Separators are skipped silently, as `<HR>` is; `place:` smart bookmarks
|
||||
* Separators are skipped and counted, as `<HR>` is; `place:` smart bookmarks
|
||||
* are skipped and counted; the tags root is dropped, because it is a view
|
||||
* over bookmarks the other roots already hold.
|
||||
*/
|
||||
import { classifyHref } from '../href';
|
||||
import {
|
||||
BmParseError,
|
||||
type BookmarkNode,
|
||||
computeStats,
|
||||
type ParseResult,
|
||||
type RootMarker,
|
||||
} from '../model';
|
||||
import { BmParseError, type BookmarkNode, computeStats, type ParseResult } from '../model';
|
||||
import { microsToSeconds } from '../timestamps';
|
||||
import { bookmarkTitle, isRecord, NodeBudget, type RootTitles, WarningBag } from './shared';
|
||||
|
||||
@@ -141,6 +135,8 @@ function readNode(raw: unknown, depth: number, ctx: ReadContext): BookmarkNode |
|
||||
case 'bookmark':
|
||||
return readBookmark(raw, ctx);
|
||||
case 'separator':
|
||||
// No format BookmarkMagic writes holds one; counted, as <HR> is (docs/04 §2b).
|
||||
ctx.warnings.add('SEPARATORS_SKIPPED');
|
||||
return null;
|
||||
case 'unknown':
|
||||
ctx.warnings.add('UNREADABLE_ENTRIES');
|
||||
@@ -162,7 +158,7 @@ function countBookmarks(root: unknown): number {
|
||||
}
|
||||
|
||||
/** A Map, not an object literal: `root: "toString"` must not find a prototype method. */
|
||||
const ROOT_KEYS = new Map<unknown, 'toolbar' | RootMarker>([
|
||||
const ROOT_KEYS = new Map<unknown, 'toolbar' | 'other' | 'mobile'>([
|
||||
['toolbarFolder', 'toolbar'],
|
||||
['unfiledBookmarksFolder', 'other'],
|
||||
['mobileFolder', 'mobile'],
|
||||
@@ -180,7 +176,7 @@ function readPlacesRoot(
|
||||
ctx: ReadContext,
|
||||
): BookmarkNode[] {
|
||||
const menu: BookmarkNode[] = [];
|
||||
const special: Partial<Record<'toolbar' | RootMarker, BookmarkNode>> = {};
|
||||
const special: Partial<Record<'toolbar' | 'other' | 'mobile', BookmarkNode>> = {};
|
||||
|
||||
for (const child of children) {
|
||||
if (!isRecord(child)) {
|
||||
|
||||
@@ -128,9 +128,9 @@ function walkDl(dl: Element, depth: number, ctx: WalkContext): BookmarkNode[] {
|
||||
const out: BookmarkNode[] = [];
|
||||
for (const child of entryElements(dl)) {
|
||||
const tag = tagOf(child);
|
||||
// <HR> separators (Firefox) are skipped silently — docs/04 §1.2. The HTML
|
||||
// parser usually nests them inside the preceding <DT>; either way they
|
||||
// are never read as an entry.
|
||||
// <HR> separators (Firefox) are never read as an entry — docs/04 §1.2.
|
||||
// The HTML parser usually nests them inside the preceding <DT>, so they
|
||||
// are counted once for the whole document instead (SEPARATORS_SKIPPED).
|
||||
if (tag === 'dd') ctx.warnings.add('DESCRIPTIONS_DROPPED');
|
||||
if (tag !== 'dt') continue;
|
||||
// Checked per entry, not per list: an EMPTY list one level past the cap is
|
||||
@@ -287,6 +287,9 @@ export function parseNetscapeHtml(text: string): ParseResult {
|
||||
}
|
||||
|
||||
const ctx: WalkContext = { warnings: new WarningBag(), budget: new NodeBudget() };
|
||||
// The file model has no separator (docs/04 §1.2): count what is left out.
|
||||
const separators = doc.getElementsByTagName('hr').length;
|
||||
if (separators > 0) ctx.warnings.add('SEPARATORS_SKIPPED', separators);
|
||||
let roots = body === null || !hasEntries ? [] : collectRoots(body, ctx);
|
||||
if (roots.length === 0 && hasEntries) roots = outermostLists(doc, ctx);
|
||||
|
||||
|
||||
@@ -26,6 +26,8 @@ export interface PlanDestinations {
|
||||
other: LiveFolderLike;
|
||||
/** Absent when the profile has none; Mobile-marked folders then land under Other. */
|
||||
mobile?: LiveFolderLike;
|
||||
/** Firefox's Bookmarks Menu; absent in every Chromium browser (docs/03 §1). */
|
||||
menu?: LiveFolderLike;
|
||||
}
|
||||
|
||||
export interface BuildPlanOptions {
|
||||
@@ -70,8 +72,12 @@ function planSplit(
|
||||
destinations: PlanDestinations,
|
||||
mode: 'merge' | 'replace',
|
||||
): { segments: PlanSegment[]; reusedFolders: number } {
|
||||
const routed = routeTopLevel(nodes, { hasMobileRoot: destinations.mobile !== undefined });
|
||||
const routed = routeTopLevel(nodes, {
|
||||
hasMobileRoot: destinations.mobile !== undefined,
|
||||
hasMenuRoot: destinations.menu !== undefined,
|
||||
});
|
||||
const targets: [BookmarkNode[], LiveFolderLike | undefined][] = [
|
||||
[routed.menu, destinations.menu],
|
||||
[routed.toolbar, destinations.toolbar],
|
||||
[routed.other, destinations.other],
|
||||
[routed.mobile, destinations.mobile],
|
||||
|
||||
+18
-5
@@ -2,7 +2,8 @@
|
||||
* Top-level routing — docs/03 §1 step 7, docs/02 §4.
|
||||
*
|
||||
* Purpose: decide which browser root each top-level node of a file lands in.
|
||||
* Inputs: the (deduped) top-level nodes; whether the profile has a Mobile root.
|
||||
* Inputs: the (deduped) top-level nodes; whether the profile has a Mobile root,
|
||||
* and whether it has a Bookmarks Menu (Firefox).
|
||||
* Guarantees: pure. Markers are read on TOP-LEVEL nodes only — deeper they are
|
||||
* carried as data. A marked folder IS that root, so it is unwrapped: its
|
||||
* children go into the root and the folder itself is never written, which is
|
||||
@@ -14,6 +15,8 @@ export interface RoutedNodes {
|
||||
toolbar: BookmarkNode[];
|
||||
other: BookmarkNode[];
|
||||
mobile: BookmarkNode[];
|
||||
/** Firefox's Bookmarks Menu; always empty without one. */
|
||||
menu: BookmarkNode[];
|
||||
/** Marked folders that were unwrapped rather than written. */
|
||||
unwrapped: number;
|
||||
}
|
||||
@@ -30,13 +33,17 @@ function append(target: BookmarkNode[], list: readonly BookmarkNode[] | undefine
|
||||
* - `root: 'other'` folder → its children into Other, in its place in the order;
|
||||
* - `root: 'mobile'` folder → its children into Mobile; a profile with no
|
||||
* Mobile root keeps it as an ordinary folder under Other instead;
|
||||
* - everything else → Other.
|
||||
* - `root: 'menu'` folder → its children into the Bookmarks Menu; a browser
|
||||
* with none (every Chromium one) keeps it as an ordinary folder under Other;
|
||||
* - everything else → the Bookmarks Menu where there is one — what Firefox's
|
||||
* own import does with the loose entries its own export writes — else Other.
|
||||
*/
|
||||
export function routeTopLevel(
|
||||
nodes: readonly BookmarkNode[],
|
||||
options: { hasMobileRoot: boolean },
|
||||
options: { hasMobileRoot: boolean; hasMenuRoot?: boolean },
|
||||
): RoutedNodes {
|
||||
const routed: RoutedNodes = { toolbar: [], other: [], mobile: [], unwrapped: 0 };
|
||||
const routed: RoutedNodes = { toolbar: [], other: [], mobile: [], menu: [], unwrapped: 0 };
|
||||
const loose = options.hasMenuRoot === true ? routed.menu : routed.other;
|
||||
for (const node of nodes) {
|
||||
if (node.toolbar === true) {
|
||||
if (isFolder(node)) {
|
||||
@@ -51,8 +58,14 @@ export function routeTopLevel(
|
||||
} else if (isFolder(node) && node.root === 'mobile' && options.hasMobileRoot) {
|
||||
append(routed.mobile, node.children);
|
||||
routed.unwrapped++;
|
||||
} else {
|
||||
} else if (isFolder(node) && node.root === 'menu' && options.hasMenuRoot === true) {
|
||||
append(routed.menu, node.children);
|
||||
routed.unwrapped++;
|
||||
} else if (isFolder(node) && (node.root === 'menu' || node.root === 'mobile')) {
|
||||
// A root this browser does not have stays a folder, under Other.
|
||||
routed.other.push(node);
|
||||
} else {
|
||||
loose.push(node);
|
||||
}
|
||||
}
|
||||
return routed;
|
||||
|
||||
@@ -13,6 +13,8 @@ export interface SearchableNode {
|
||||
id: string;
|
||||
title: string;
|
||||
url?: string;
|
||||
/** A Firefox separator: shown, never a match — its url is "data:" (docs/03 §3). */
|
||||
separator?: true;
|
||||
children?: SearchableNode[];
|
||||
}
|
||||
|
||||
@@ -50,7 +52,7 @@ export function searchTree(roots: readonly SearchableNode[], query: string): Sea
|
||||
const walk = (nodes: readonly SearchableNode[], ancestors: readonly string[]): boolean => {
|
||||
let anyHere = false;
|
||||
for (const node of nodes) {
|
||||
const self = matches(node, needle);
|
||||
const self = node.separator !== true && matches(node, needle);
|
||||
const trail = [...ancestors, node.id];
|
||||
const below = walk(node.children ?? [], trail);
|
||||
|
||||
|
||||
@@ -78,10 +78,23 @@ function writeNode(node: BookmarkNode, depth: number, out: string[]): void {
|
||||
);
|
||||
}
|
||||
|
||||
/** Serialize a tree to Netscape bookmark HTML (UTF-8, LF line endings). */
|
||||
/**
|
||||
* Serialize a tree to Netscape bookmark HTML (UTF-8, LF line endings).
|
||||
*
|
||||
* Firefox's Bookmarks Menu has no attribute in this format: Firefox writes the
|
||||
* menu's entries as the file's top level and reads loose top-level entries
|
||||
* back into the menu. A top-level `root: 'menu'` folder is therefore
|
||||
* unwrapped here, its children written in its place (docs/04 §1.1).
|
||||
*/
|
||||
export function serializeNetscapeHtml(roots: readonly BookmarkNode[]): string {
|
||||
const out: string[] = ['<DL><p>'];
|
||||
for (const node of roots) writeNode(node, 1, out);
|
||||
for (const node of roots) {
|
||||
if (node.root === 'menu' && node.toolbar !== true && !isBookmark(node)) {
|
||||
for (const child of node.children ?? []) writeNode(child, 1, out);
|
||||
} else {
|
||||
writeNode(node, 1, out);
|
||||
}
|
||||
}
|
||||
out.push('</DL><p>');
|
||||
return `${HEADER}${out.join('\n')}\n`;
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
* Inputs: `EditNode` trees, plus `LiveNode`s straight from the bookmarks API.
|
||||
* Guarantees: pure — no `chrome.*`, no Svelte, no mutation of the input.
|
||||
*/
|
||||
import type { LiveNode } from '../browser/bookmarks';
|
||||
import { isSeparator, type LiveNode } from '../browser/live-tree';
|
||||
import type { EditNode } from './patch-tree';
|
||||
|
||||
/**
|
||||
@@ -17,13 +17,18 @@ import type { EditNode } from './patch-tree';
|
||||
* folders, which is what makes `url === undefined` a reliable folder test.
|
||||
*/
|
||||
export function toEditNode(node: LiveNode): EditNode {
|
||||
const separator = isSeparator(node);
|
||||
// A separator keeps a url — Firefox sends "data:" — so that no "no url ⇒
|
||||
// folder" test anywhere mistakes it for an empty folder.
|
||||
const url = separator ? (node.url ?? 'data:') : node.url;
|
||||
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) }),
|
||||
...(url !== undefined && { url }),
|
||||
...(url === undefined && { children: (node.children ?? []).map(toEditNode) }),
|
||||
...(node.unmodifiable !== undefined && { unmodifiable: node.unmodifiable }),
|
||||
...(separator && { separator: true as const }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -45,6 +50,8 @@ export function flattenTree(nodes: readonly EditNode[], into: EditNode[] = []):
|
||||
*/
|
||||
export function isEditable(roots: readonly EditNode[], node: EditNode): boolean {
|
||||
if (node.unmodifiable !== undefined) return false;
|
||||
// Separators are shown and left alone: none of the row commands applies.
|
||||
if (node.separator === true) return false;
|
||||
return !roots.some((root) => root.id === node.id);
|
||||
}
|
||||
|
||||
@@ -87,10 +94,13 @@ export function hostOf(url: string | undefined): string {
|
||||
return new URL(url).host;
|
||||
}
|
||||
|
||||
/** How many nodes sit inside `node`. Drives the delete confirmation's count. */
|
||||
/**
|
||||
* How many bookmarks and folders sit inside `node` — the delete confirmation's
|
||||
* count. Separators (Firefox) go too, but are not "items" to anyone reading it.
|
||||
*/
|
||||
export function countDescendants(node: EditNode | undefined): number {
|
||||
if (node === undefined) return 0;
|
||||
return flattenTree(node.children ?? []).length;
|
||||
return flattenTree(node.children ?? []).filter((child) => child.separator !== true).length;
|
||||
}
|
||||
|
||||
/** Ids to delete so one copy of each duplicated link survives. */
|
||||
|
||||
@@ -19,6 +19,11 @@ export interface EditNode {
|
||||
url?: string;
|
||||
dateAdded?: number;
|
||||
unmodifiable?: string;
|
||||
/**
|
||||
* A Firefox separator (docs/03 §3): a row of its own that no command touches.
|
||||
* It keeps its `url` ("data:"), so every "no url ⇒ folder" test stays right.
|
||||
*/
|
||||
separator?: true;
|
||||
children?: EditNode[];
|
||||
}
|
||||
|
||||
|
||||
+31
-5
@@ -22,11 +22,9 @@ function sortKey(node: EditNode): string {
|
||||
return node.title.trim() === '' && node.url !== undefined ? node.url : node.title;
|
||||
}
|
||||
|
||||
/** The children in sorted order, without moving anything. */
|
||||
export function sortedOrder(children: readonly EditNode[], locale: string): EditNode[] {
|
||||
const collator = new Intl.Collator(locale, { numeric: true, sensitivity: 'base' });
|
||||
return children
|
||||
.map((node, position) => ({ node, position }))
|
||||
/** One run of children between separators, sorted: folders first, then by name. */
|
||||
function sortRun(run: readonly { node: EditNode; position: number }[], collator: Intl.Collator) {
|
||||
return [...run]
|
||||
.sort((a, b) => {
|
||||
const aFolder = a.node.url === undefined;
|
||||
const bFolder = b.node.url === undefined;
|
||||
@@ -36,6 +34,34 @@ export function sortedOrder(children: readonly EditNode[], locale: string): Edit
|
||||
.map(({ node }) => node);
|
||||
}
|
||||
|
||||
/**
|
||||
* The children in sorted order, without moving anything.
|
||||
*
|
||||
* Firefox's separators split a folder into runs the user made on purpose, so
|
||||
* each run is sorted on its own and every separator keeps its place (docs/05
|
||||
* §10). Chromium has no separators: one run, as before.
|
||||
*/
|
||||
export function sortedOrder(children: readonly EditNode[], locale: string): EditNode[] {
|
||||
const collator = new Intl.Collator(locale, { numeric: true, sensitivity: 'base' });
|
||||
const out: EditNode[] = [];
|
||||
// A loop, not push(...spread): a folder can hold 100k children.
|
||||
const flush = (items: readonly { node: EditNode; position: number }[]): void => {
|
||||
for (const node of sortRun(items, collator)) out.push(node);
|
||||
};
|
||||
let run: { node: EditNode; position: number }[] = [];
|
||||
for (const [position, node] of children.entries()) {
|
||||
if (node.separator === true) {
|
||||
flush(run);
|
||||
out.push(node);
|
||||
run = [];
|
||||
} else {
|
||||
run.push({ node, position });
|
||||
}
|
||||
}
|
||||
flush(run);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The moves, left to right: each fills the next position with the child that
|
||||
* belongs there. Every move takes a child from further right, so moving it to
|
||||
|
||||
@@ -17,7 +17,9 @@ export interface VisibleRow {
|
||||
/**
|
||||
* Position among the visible siblings, 1-based, and how many there are. The
|
||||
* rows render flat, so the browser cannot count siblings itself — without
|
||||
* these, a screen reader announced "1 of 1" on every row.
|
||||
* these, a screen reader announced "1 of 1" on every row. Separators
|
||||
* (Firefox) are rows but not items: they are not counted, and their own
|
||||
* values mean nothing (docs/06 §5).
|
||||
*/
|
||||
posInSet: number;
|
||||
setSize: number;
|
||||
@@ -44,17 +46,20 @@ export function visibleRows(
|
||||
const rows: VisibleRow[] = [];
|
||||
const walk = (nodes: readonly EditNode[], depth: number, parentId: string | undefined): void => {
|
||||
const shown = visible === undefined ? nodes : nodes.filter((node) => visible.has(node.id));
|
||||
for (const [index, node] of shown.entries()) {
|
||||
const setSize = shown.filter((node) => node.separator !== true).length;
|
||||
let position = 0;
|
||||
for (const node of shown) {
|
||||
const children = node.children ?? [];
|
||||
const isOpen = expanded.has(node.id);
|
||||
if (node.separator !== true) position++;
|
||||
rows.push({
|
||||
node,
|
||||
depth,
|
||||
parentId,
|
||||
expandable: node.url === undefined && children.length > 0,
|
||||
expanded: isOpen,
|
||||
posInSet: index + 1,
|
||||
setSize: shown.length,
|
||||
posInSet: position,
|
||||
setSize,
|
||||
});
|
||||
if (isOpen) walk(children, depth + 1, node.id);
|
||||
}
|
||||
@@ -73,8 +78,10 @@ export function visibleRows(
|
||||
export function resolveKey(
|
||||
key: string,
|
||||
focusedId: string | undefined,
|
||||
rows: readonly VisibleRow[],
|
||||
allRows: readonly VisibleRow[],
|
||||
): TreeAction {
|
||||
// Separators take no focus, so every key moves over the rows that can.
|
||||
const rows = allRows.filter((row) => row.node.separator !== true);
|
||||
if (rows.length === 0) return NONE;
|
||||
const index = rows.findIndex((row) => row.node.id === focusedId);
|
||||
const current = index === -1 ? undefined : rows[index];
|
||||
@@ -123,6 +130,8 @@ export function resolveKey(
|
||||
* The VISIBLE siblings: under a search only the matches count, because the
|
||||
* user places the row relative to one they can see, exactly as a drag does. A
|
||||
* collapsed neighbour's children are not rows, so they are skipped for free.
|
||||
* A separator IS a neighbour: stepping past one is one place, as a drag beside
|
||||
* it would be — skipping it would move the row two places at once.
|
||||
*
|
||||
* @returns the neighbour's id, or `undefined` at either end of the folder.
|
||||
*/
|
||||
|
||||
@@ -8,15 +8,10 @@
|
||||
*/
|
||||
|
||||
import { getGeneratorVersion } from '../browser/app-info';
|
||||
import {
|
||||
getRootChildren,
|
||||
getRoots,
|
||||
type LiveNode,
|
||||
rootMarkersOf,
|
||||
type ToNodesOptions,
|
||||
toBookmarkNodes,
|
||||
} from '../browser/bookmarks';
|
||||
import { getRootChildren, type LiveNode } from '../browser/bookmarks';
|
||||
import { sanitizeFilename, timestampSuffix, triggerDownload } from '../browser/download';
|
||||
import { countLive, type ToNodesOptions, toBookmarkNodes } from '../browser/live-tree';
|
||||
import { getRoots, rootMarkersOf } from '../browser/roots';
|
||||
import type { ExportFormat } from '../browser/storage';
|
||||
import type { CsvDelimiter } from '../core/csv-dialect';
|
||||
import { filterBySelection } from '../core/select';
|
||||
@@ -75,15 +70,8 @@ export function countSelected(
|
||||
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;
|
||||
// Separators (Firefox) carry a url too, "data:" — never a bookmark here.
|
||||
return countLive(scoped).bookmarks;
|
||||
}
|
||||
|
||||
/** Serialize a scoped tree. Split out from the download so it is testable. */
|
||||
|
||||
@@ -83,7 +83,7 @@ export function tPlural(
|
||||
|
||||
function interpolate(raw: string, params?: Record<string, string | number>): string {
|
||||
if (params === undefined) return raw;
|
||||
return raw.replace(/\{(\w+)\}/g, (match, token: string) =>
|
||||
return raw.replace(/\{(\w+)}/g, (match, token: string) =>
|
||||
Object.hasOwn(params, token) ? String(params[token]) : match,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,13 @@ export const importTab = {
|
||||
replaceConfirmBody:
|
||||
'{current} in this browser will be deleted, after a safety backup is saved. Then {incoming} from {name} are written.',
|
||||
replaceConfirm: 'Back up and replace',
|
||||
target: { bar: 'bar', unfiled: 'Other', mobile: 'Mobile' },
|
||||
// Firefox only (docs/03 §1): Replace deletes separators and no file keeps one.
|
||||
replaceSeparators: {
|
||||
one: '{n} separator line will be deleted too, and cannot come back — the backup, like every file BookmarkMagic writes, cannot hold one.',
|
||||
other:
|
||||
'{n} separator lines will be deleted too, and cannot come back — the backup, like every file BookmarkMagic writes, cannot hold one.',
|
||||
},
|
||||
target: { bar: 'bar', unfiled: 'Other', mobile: 'Mobile', menu: 'Menu' },
|
||||
targetNote:
|
||||
'In Merge and Replace, this folder’s contents go straight into that browser folder instead of a copy of it.',
|
||||
reused: {
|
||||
@@ -67,7 +73,7 @@ export const importTab = {
|
||||
cancelledAfterClear:
|
||||
'You cancelled after your existing bookmarks had already been deleted, so what is left is only the part that was rebuilt.',
|
||||
dateNotice:
|
||||
'Imported bookmarks are dated today. Chrome does not let an extension set a bookmark’s original date — your exported files keep the real ones.',
|
||||
'Imported bookmarks are dated today. The browser does not let an extension set a bookmark’s original date — your exported files keep the real ones.',
|
||||
partialCreated: {
|
||||
one: '{n} item had already been created before this failed, and was left in place.',
|
||||
other: '{n} items had already been created before this failed, and were left in place.',
|
||||
|
||||
@@ -46,9 +46,8 @@ export const warnings = {
|
||||
other: '{n} entries have addresses the browser cannot store, so they were skipped.',
|
||||
},
|
||||
PLACE_QUERIES_SKIPPED: {
|
||||
one: '{n} Firefox smart bookmark (a saved search, not a web page) was skipped — here it would be a dead link.',
|
||||
other:
|
||||
'{n} Firefox smart bookmarks (saved searches, not web pages) were skipped — here they would be dead links.',
|
||||
one: '{n} Firefox smart bookmark (a saved search, not a web page) was skipped.',
|
||||
other: '{n} Firefox smart bookmarks (saved searches, not web pages) were skipped.',
|
||||
},
|
||||
EXTRA_ROOTS_SKIPPED: {
|
||||
one: '{n} bookmark in a browser-specific folder (such as Opera’s Speed Dial or Trash) was not imported.',
|
||||
@@ -59,6 +58,16 @@ export const warnings = {
|
||||
one: '{n} entry in this file could not be read and was skipped.',
|
||||
other: '{n} entries in this file could not be read and were skipped.',
|
||||
},
|
||||
SEPARATORS_SKIPPED: {
|
||||
one: '{n} separator line was left out — BookmarkMagic keeps bookmarks and folders, not separators.',
|
||||
other:
|
||||
'{n} separator lines were left out — BookmarkMagic keeps bookmarks and folders, not separators.',
|
||||
},
|
||||
URL_TOO_LONG: {
|
||||
one: '{n} bookmark was skipped: its address is longer than the 65,536 characters this browser accepts.',
|
||||
other:
|
||||
'{n} bookmarks were skipped: their addresses are longer than the 65,536 characters this browser accepts.',
|
||||
},
|
||||
};
|
||||
|
||||
export const errors = {
|
||||
|
||||
@@ -193,7 +193,7 @@ const dict = {
|
||||
issues: 'Report an issue',
|
||||
changelog: 'Releases and changelog',
|
||||
accessibility: 'Accessibility',
|
||||
store: 'Chrome Web Store listing',
|
||||
store: 'Store listing',
|
||||
thirdParty: 'Third-party code',
|
||||
thirdPartyNote:
|
||||
'No runtime dependencies are installed. A few small MIT-licensed pieces are compiled into the extension: the Svelte runtime with its clsx helper, and WXT’s one-line browser shim — see THIRD_PARTY_NOTICES.txt in the package.',
|
||||
|
||||
@@ -38,7 +38,12 @@ export const importTab = {
|
||||
replaceConfirmBody:
|
||||
'バックアップを保存した後、このブラウザの{current}を削除し、{name} から{incoming}を書き込みます。',
|
||||
replaceConfirm: 'バックアップして置き換え',
|
||||
target: { bar: 'バー', unfiled: 'その他', mobile: 'モバイル' },
|
||||
replaceSeparators: {
|
||||
one: '区切り線 {n} 本も削除され、元に戻せません。バックアップを含め、BookmarkMagic が書き出すファイルは区切り線を保存できないためです。',
|
||||
other:
|
||||
'区切り線 {n} 本も削除され、元に戻せません。バックアップを含め、BookmarkMagic が書き出すファイルは区切り線を保存できないためです。',
|
||||
},
|
||||
target: { bar: 'バー', unfiled: 'その他', mobile: 'モバイル', menu: 'メニュー' },
|
||||
targetNote:
|
||||
'統合と置き換えでは、このフォルダの中身はコピーを作らず、ブラウザの対応するフォルダに直接入ります。',
|
||||
reused: {
|
||||
@@ -57,7 +62,7 @@ export const importTab = {
|
||||
cancelledAfterClear:
|
||||
'既存のブックマークが削除された後にキャンセルされたため、残っているのは再作成された分だけです。',
|
||||
dateNotice:
|
||||
'インポートしたブックマークの日付は本日になります。拡張機能がブックマークの元の作成日を設定することを Chrome が許可していないためです。エクスポートしたファイルには本来の日付が残ります。',
|
||||
'インポートしたブックマークの日付は本日になります。拡張機能がブックマークの元の作成日を設定することをブラウザが許可していないためです。エクスポートしたファイルには本来の日付が残ります。',
|
||||
partialCreated: {
|
||||
one: 'エラーの前に {n} 件が作成済みで、そのまま残されています。',
|
||||
other: 'エラーの前に {n} 件が作成済みで、そのまま残されています。',
|
||||
|
||||
@@ -37,9 +37,9 @@ export const warnings = {
|
||||
other: 'ブラウザが保存できないアドレスの項目が {n} 件あったため、スキップしました。',
|
||||
},
|
||||
PLACE_QUERIES_SKIPPED: {
|
||||
one: 'Firefox のスマートブックマーク(ウェブページではなく保存された検索)を {n} 件スキップしました。ここではリンク切れになるためです。',
|
||||
one: 'Firefox のスマートブックマーク(ウェブページではなく保存された検索)を {n} 件スキップしました。',
|
||||
other:
|
||||
'Firefox のスマートブックマーク(ウェブページではなく保存された検索)を {n} 件スキップしました。ここではリンク切れになるためです。',
|
||||
'Firefox のスマートブックマーク(ウェブページではなく保存された検索)を {n} 件スキップしました。',
|
||||
},
|
||||
EXTRA_ROOTS_SKIPPED: {
|
||||
one: 'ブラウザ固有のフォルダ(Opera のスピードダイヤルやゴミ箱など)にあるブックマーク {n} 件はインポートしませんでした。',
|
||||
@@ -50,6 +50,16 @@ export const warnings = {
|
||||
one: '読み取れない項目が {n} 件あったため、スキップしました。',
|
||||
other: '読み取れない項目が {n} 件あったため、スキップしました。',
|
||||
},
|
||||
SEPARATORS_SKIPPED: {
|
||||
one: '区切り線 {n} 本を省きました。BookmarkMagic が保持するのはブックマークとフォルダで、区切り線は保持しません。',
|
||||
other:
|
||||
'区切り線 {n} 本を省きました。BookmarkMagic が保持するのはブックマークとフォルダで、区切り線は保持しません。',
|
||||
},
|
||||
URL_TOO_LONG: {
|
||||
one: 'アドレスがこのブラウザの上限(65,536 文字)を超えるブックマーク {n} 件をスキップしました。',
|
||||
other:
|
||||
'アドレスがこのブラウザの上限(65,536 文字)を超えるブックマーク {n} 件をスキップしました。',
|
||||
},
|
||||
} satisfies Dict['warnings'];
|
||||
|
||||
export const errors = {
|
||||
|
||||
@@ -179,7 +179,7 @@ export default {
|
||||
issues: '問題を報告',
|
||||
changelog: 'リリースと変更履歴',
|
||||
accessibility: 'アクセシビリティ',
|
||||
store: 'Chrome ウェブストアのページ',
|
||||
store: 'ストアのページ',
|
||||
thirdParty: 'サードパーティのコード',
|
||||
thirdPartyNote:
|
||||
'実行時の依存関係はインストールされません。MIT ライセンスの小さなコード(Svelte のランタイムとその clsx ヘルパー、WXT の 1 行のブラウザ互換層)が拡張機能に組み込まれています。パッケージ内の THIRD_PARTY_NOTICES.txt をご覧ください。',
|
||||
|
||||
@@ -42,7 +42,13 @@ export const importTab = {
|
||||
replaceConfirmBody:
|
||||
'Vor fi șterse din acest browser: {current}, după salvarea unei copii de rezervă de siguranță. Apoi se scrie conținutul din {name}: {incoming}.',
|
||||
replaceConfirm: 'Salvați copia și înlocuiți',
|
||||
target: { bar: 'bară', unfiled: 'Alte marcaje', mobile: 'Mobile' },
|
||||
replaceSeparators: {
|
||||
one: 'Va fi ștearsă și {n} linie de separare, care nu mai poate fi restaurată — copia de rezervă, ca orice fișier scris de BookmarkMagic, nu poate păstra separatoare.',
|
||||
few: 'Vor fi șterse și {n} linii de separare, care nu mai pot fi restaurate — copia de rezervă, ca orice fișier scris de BookmarkMagic, nu poate păstra separatoare.',
|
||||
other:
|
||||
'Vor fi șterse și {n} de linii de separare, care nu mai pot fi restaurate — copia de rezervă, ca orice fișier scris de BookmarkMagic, nu poate păstra separatoare.',
|
||||
},
|
||||
target: { bar: 'bară', unfiled: 'Alte marcaje', mobile: 'Mobile', menu: 'Meniul de marcaje' },
|
||||
targetNote:
|
||||
'La îmbinare și la înlocuire, conținutul acestui dosar ajunge direct în dosarul respectiv al browserului, nu într-o copie a lui.',
|
||||
reused: {
|
||||
@@ -65,7 +71,7 @@ export const importTab = {
|
||||
cancelledAfterClear:
|
||||
'Ați anulat după ce marcajele existente fuseseră deja șterse, așa că a rămas doar partea care a fost refăcută.',
|
||||
dateNotice:
|
||||
'Marcajele importate poartă data de azi. Chrome nu permite unei extensii să seteze data originală a unui marcaj — fișierele exportate păstrează datele reale.',
|
||||
'Marcajele importate poartă data de azi. Browserul nu permite unei extensii să seteze data originală a unui marcaj — fișierele exportate păstrează datele reale.',
|
||||
partialCreated: {
|
||||
one: '{n} element fusese deja creat înainte de eroare și a rămas pe loc.',
|
||||
few: '{n} elemente fuseseră deja create înainte de eroare și au rămas pe loc.',
|
||||
|
||||
@@ -49,10 +49,9 @@ export const warnings = {
|
||||
other: '{n} de intrări au adrese pe care browserul nu le poate stoca, așa că au fost omise.',
|
||||
},
|
||||
PLACE_QUERIES_SKIPPED: {
|
||||
one: '{n} marcaj inteligent Firefox (o căutare salvată, nu o pagină web) a fost omis — aici ar fi un link nefuncțional.',
|
||||
few: '{n} marcaje inteligente Firefox (căutări salvate, nu pagini web) au fost omise — aici ar fi linkuri nefuncționale.',
|
||||
other:
|
||||
'{n} de marcaje inteligente Firefox (căutări salvate, nu pagini web) au fost omise — aici ar fi linkuri nefuncționale.',
|
||||
one: '{n} marcaj inteligent Firefox (o căutare salvată, nu o pagină web) a fost omis.',
|
||||
few: '{n} marcaje inteligente Firefox (căutări salvate, nu pagini web) au fost omise.',
|
||||
other: '{n} de marcaje inteligente Firefox (căutări salvate, nu pagini web) au fost omise.',
|
||||
},
|
||||
EXTRA_ROOTS_SKIPPED: {
|
||||
one: '{n} marcaj dintr-un dosar specific unui browser (cum ar fi Speed Dial sau Coșul de gunoi din Opera) nu a fost importat.',
|
||||
@@ -65,6 +64,18 @@ export const warnings = {
|
||||
few: '{n} intrări din acest fișier nu au putut fi citite și au fost omise.',
|
||||
other: '{n} de intrări din acest fișier nu au putut fi citite și au fost omise.',
|
||||
},
|
||||
SEPARATORS_SKIPPED: {
|
||||
one: '{n} linie de separare a fost omisă — BookmarkMagic păstrează marcaje și dosare, nu separatoare.',
|
||||
few: '{n} linii de separare au fost omise — BookmarkMagic păstrează marcaje și dosare, nu separatoare.',
|
||||
other:
|
||||
'{n} de linii de separare au fost omise — BookmarkMagic păstrează marcaje și dosare, nu separatoare.',
|
||||
},
|
||||
URL_TOO_LONG: {
|
||||
one: '{n} marcaj a fost omis: adresa lui depășește cele 65.536 de caractere acceptate de acest browser.',
|
||||
few: '{n} marcaje au fost omise: adresele lor depășesc cele 65.536 de caractere acceptate de acest browser.',
|
||||
other:
|
||||
'{n} de marcaje au fost omise: adresele lor depășesc cele 65.536 de caractere acceptate de acest browser.',
|
||||
},
|
||||
} satisfies Dict['warnings'];
|
||||
|
||||
export const errors = {
|
||||
|
||||
@@ -210,7 +210,7 @@ export default {
|
||||
issues: 'Raportați o problemă',
|
||||
changelog: 'Versiuni și jurnalul modificărilor',
|
||||
accessibility: 'Accesibilitate',
|
||||
store: 'Pagina din Magazinul Chrome Web',
|
||||
store: 'Pagina din magazin',
|
||||
thirdParty: 'Cod terț',
|
||||
thirdPartyNote:
|
||||
'Nu este instalată nicio dependență de rulare. Câteva componente mici cu licență MIT sunt compilate în extensie: runtime-ul Svelte cu utilitarul său clsx și adaptorul de browser de o linie al WXT — consultați THIRD_PARTY_NOTICES.txt din pachet.',
|
||||
|
||||
@@ -37,7 +37,12 @@ export const importTab = {
|
||||
replaceConfirmBody:
|
||||
'{current} trong trình duyệt này sẽ bị xóa, sau khi bản sao lưu an toàn được lưu. Sau đó {incoming} từ {name} sẽ được ghi vào.',
|
||||
replaceConfirm: 'Sao lưu rồi thay thế',
|
||||
target: { bar: 'thanh dấu trang', unfiled: 'Khác', mobile: 'Di động' },
|
||||
replaceSeparators: {
|
||||
one: '{n} đường phân cách cũng sẽ bị xóa và không thể khôi phục — bản sao lưu, như mọi tệp BookmarkMagic ghi ra, không lưu được đường phân cách.',
|
||||
other:
|
||||
'{n} đường phân cách cũng sẽ bị xóa và không thể khôi phục — bản sao lưu, như mọi tệp BookmarkMagic ghi ra, không lưu được đường phân cách.',
|
||||
},
|
||||
target: { bar: 'thanh dấu trang', unfiled: 'Khác', mobile: 'Di động', menu: 'Menu dấu trang' },
|
||||
targetNote:
|
||||
'Ở chế độ Gộp và Thay thế, nội dung thư mục này được đưa thẳng vào thư mục tương ứng của trình duyệt, không tạo bản sao của nó.',
|
||||
reused: {
|
||||
@@ -56,7 +61,7 @@ export const importTab = {
|
||||
cancelledAfterClear:
|
||||
'Bạn đã hủy sau khi bookmark cũ đã bị xóa, nên những gì còn lại chỉ là phần đã được tạo lại.',
|
||||
dateNotice:
|
||||
'Bookmark được nhập vào sẽ mang ngày hôm nay. Chrome không cho phép tiện ích đặt lại ngày tạo gốc của bookmark — các tệp bạn xuất ra vẫn giữ ngày thật.',
|
||||
'Bookmark được nhập vào sẽ mang ngày hôm nay. Trình duyệt không cho phép tiện ích đặt lại ngày tạo gốc của bookmark — các tệp bạn xuất ra vẫn giữ ngày thật.',
|
||||
partialCreated: {
|
||||
one: '{n} mục đã được tạo trước khi lỗi xảy ra và vẫn được giữ lại.',
|
||||
other: '{n} mục đã được tạo trước khi lỗi xảy ra và vẫn được giữ lại.',
|
||||
|
||||
@@ -36,9 +36,8 @@ export const warnings = {
|
||||
other: '{n} mục có địa chỉ mà trình duyệt không lưu được nên đã bị bỏ qua.',
|
||||
},
|
||||
PLACE_QUERIES_SKIPPED: {
|
||||
one: 'Đã bỏ qua {n} bookmark thông minh của Firefox (một truy vấn đã lưu, không phải trang web) — ở đây nó sẽ là liên kết hỏng.',
|
||||
other:
|
||||
'Đã bỏ qua {n} bookmark thông minh của Firefox (truy vấn đã lưu, không phải trang web) — ở đây chúng sẽ là liên kết hỏng.',
|
||||
one: 'Đã bỏ qua {n} bookmark thông minh của Firefox (một truy vấn đã lưu, không phải trang web).',
|
||||
other: 'Đã bỏ qua {n} bookmark thông minh của Firefox (truy vấn đã lưu, không phải trang web).',
|
||||
},
|
||||
EXTRA_ROOTS_SKIPPED: {
|
||||
one: '{n} bookmark nằm trong thư mục riêng của trình duyệt (như Speed Dial hay Thùng rác của Opera) nên không được nhập.',
|
||||
@@ -49,6 +48,15 @@ export const warnings = {
|
||||
one: '{n} mục trong tệp không đọc được và đã bị bỏ qua.',
|
||||
other: '{n} mục trong tệp không đọc được và đã bị bỏ qua.',
|
||||
},
|
||||
SEPARATORS_SKIPPED: {
|
||||
one: 'Đã bỏ qua {n} đường phân cách — BookmarkMagic giữ bookmark và thư mục, không giữ đường phân cách.',
|
||||
other:
|
||||
'Đã bỏ qua {n} đường phân cách — BookmarkMagic giữ bookmark và thư mục, không giữ đường phân cách.',
|
||||
},
|
||||
URL_TOO_LONG: {
|
||||
one: 'Đã bỏ qua {n} bookmark: địa chỉ dài hơn 65.536 ký tự mà trình duyệt này chấp nhận.',
|
||||
other: 'Đã bỏ qua {n} bookmark: địa chỉ dài hơn 65.536 ký tự mà trình duyệt này chấp nhận.',
|
||||
},
|
||||
} satisfies Dict['warnings'];
|
||||
|
||||
export const errors = {
|
||||
|
||||
@@ -177,7 +177,7 @@ export default {
|
||||
issues: 'Báo lỗi',
|
||||
changelog: 'Bản phát hành và nhật ký thay đổi',
|
||||
accessibility: 'Hỗ trợ tiếp cận',
|
||||
store: 'Trang trên Chrome Web Store',
|
||||
store: 'Trang trên cửa hàng',
|
||||
thirdParty: 'Mã của bên thứ ba',
|
||||
thirdPartyNote:
|
||||
'Không cài thêm thư viện nào khi chạy. Vài phần mã nhỏ theo giấy phép MIT được biên dịch vào tiện ích: bộ chạy của Svelte cùng hàm trợ giúp clsx của nó, và lớp tương thích trình duyệt một dòng của WXT — xem THIRD_PARTY_NOTICES.txt trong gói.',
|
||||
|
||||
@@ -36,7 +36,12 @@ export const importTab = {
|
||||
replaceConfirmBody:
|
||||
'保存安全备份后,将删除此浏览器中的 {current}。然后写入 {name} 中的 {incoming}。',
|
||||
replaceConfirm: '备份并替换',
|
||||
target: { bar: '书签栏', unfiled: '其他书签', mobile: '移动设备书签' },
|
||||
replaceSeparators: {
|
||||
one: '还会删除 {n} 条分隔线,且无法恢复——备份与 BookmarkMagic 写出的其他文件一样,无法保存分隔线。',
|
||||
other:
|
||||
'还会删除 {n} 条分隔线,且无法恢复——备份与 BookmarkMagic 写出的其他文件一样,无法保存分隔线。',
|
||||
},
|
||||
target: { bar: '书签栏', unfiled: '其他书签', mobile: '移动设备书签', menu: '书签菜单' },
|
||||
targetNote:
|
||||
'在合并和替换模式下,此文件夹中的内容会直接放入对应的浏览器文件夹,而不是创建它的副本。',
|
||||
reused: {
|
||||
@@ -55,7 +60,7 @@ export const importTab = {
|
||||
},
|
||||
cancelledAfterClear: '您是在现有书签已被删除之后取消的,因此剩下的只有已重建的部分。',
|
||||
dateNotice:
|
||||
'导入的书签日期均为今天。Chrome 不允许扩展程序设置书签的原始日期——您导出的文件会保留真实日期。',
|
||||
'导入的书签日期均为今天。浏览器不允许扩展程序设置书签的原始日期——您导出的文件会保留真实日期。',
|
||||
partialCreated: {
|
||||
one: '操作失败前已创建 {n} 项,这些项保持原样。',
|
||||
other: '操作失败前已创建 {n} 项,这些项保持原样。',
|
||||
|
||||
@@ -36,8 +36,8 @@ export const warnings = {
|
||||
other: '{n} 个条目的地址无法存入浏览器,因此已跳过。',
|
||||
},
|
||||
PLACE_QUERIES_SKIPPED: {
|
||||
one: '已跳过 {n} 个 Firefox 智能书签(已保存的搜索,而非网页)——在这里它会成为失效链接。',
|
||||
other: '已跳过 {n} 个 Firefox 智能书签(已保存的搜索,而非网页)——在这里它们会成为失效链接。',
|
||||
one: '已跳过 {n} 个 Firefox 智能书签(已保存的搜索,而非网页)。',
|
||||
other: '已跳过 {n} 个 Firefox 智能书签(已保存的搜索,而非网页)。',
|
||||
},
|
||||
EXTRA_ROOTS_SKIPPED: {
|
||||
one: '浏览器专用文件夹(例如 Opera 的快速拨号或回收站)中的 {n} 个书签未导入。',
|
||||
@@ -47,6 +47,14 @@ export const warnings = {
|
||||
one: '此文件中有 {n} 个条目无法读取,已跳过。',
|
||||
other: '此文件中有 {n} 个条目无法读取,已跳过。',
|
||||
},
|
||||
SEPARATORS_SKIPPED: {
|
||||
one: '已略去 {n} 条分隔线——BookmarkMagic 保存书签和文件夹,不保存分隔线。',
|
||||
other: '已略去 {n} 条分隔线——BookmarkMagic 保存书签和文件夹,不保存分隔线。',
|
||||
},
|
||||
URL_TOO_LONG: {
|
||||
one: '已跳过 {n} 个书签:其地址超过了此浏览器接受的 65,536 个字符。',
|
||||
other: '已跳过 {n} 个书签:其地址超过了此浏览器接受的 65,536 个字符。',
|
||||
},
|
||||
} satisfies Dict['warnings'];
|
||||
|
||||
export const errors = {
|
||||
|
||||
@@ -175,7 +175,7 @@ export default {
|
||||
issues: '报告问题',
|
||||
changelog: '版本发布与更新日志',
|
||||
accessibility: '无障碍',
|
||||
store: 'Chrome 网上应用店页面',
|
||||
store: '商店页面',
|
||||
thirdParty: '第三方代码',
|
||||
thirdPartyNote:
|
||||
'未安装任何运行时依赖项。扩展程序中编译了几个采用 MIT 许可的小组件:Svelte 运行时及其 clsx 辅助函数,以及 WXT 的一行浏览器适配代码——详见软件包中的 THIRD_PARTY_NOTICES.txt。',
|
||||
|
||||
@@ -11,14 +11,7 @@
|
||||
* is written, downloaded or deleted.
|
||||
*/
|
||||
import { getGeneratorVersion } from '../browser/app-info';
|
||||
import {
|
||||
type BookmarkRoots,
|
||||
clearRoots,
|
||||
getRoots,
|
||||
type LiveNode,
|
||||
rootMarkersOf,
|
||||
toBookmarkNodes,
|
||||
} from '../browser/bookmarks';
|
||||
import { clearRoots, type LiveNode, MAX_URL_LENGTH } from '../browser/bookmarks';
|
||||
import { record } from '../browser/diagnostics';
|
||||
import {
|
||||
discardTarget,
|
||||
@@ -30,17 +23,19 @@ import {
|
||||
writeToTarget,
|
||||
} from '../browser/download';
|
||||
import { BmAborted, BmBackupError } from '../browser/errors';
|
||||
import { countLive, toBookmarkNodes, withoutSeparators } from '../browser/live-tree';
|
||||
import { type BookmarkRoots, getRoots, rootMarkersOf } from '../browser/roots';
|
||||
import type { ImportMode } from '../browser/storage';
|
||||
import { withWriteLock } from '../browser/write-lock';
|
||||
import { type WriteProgress, writeTree } from '../browser/write-queue';
|
||||
import { textCapsBreach, treeCapsBreach } from '../core/caps';
|
||||
import { buildUrlIndex } from '../core/dedupe';
|
||||
import { diffAgainstBrowser, type NodeStatus } from '../core/diff';
|
||||
import { capUrlLength } from '../core/href';
|
||||
import { MAX_FILE_BYTES, MAX_WRITE_DEPTH } from '../core/limits';
|
||||
import {
|
||||
BmParseError,
|
||||
type BookmarkNode,
|
||||
computeStats,
|
||||
type FileFormat,
|
||||
type ImportPlan,
|
||||
type MergeMode,
|
||||
@@ -63,8 +58,12 @@ export interface PreparedImport {
|
||||
browserIndex: Set<string>;
|
||||
/** The live roots at preview time — what the Start button's preview plan is built against. */
|
||||
destinations: PlanDestinations;
|
||||
/** Everything inside the writable roots: what Replace would delete (docs/09 T4). */
|
||||
current: { bookmarks: number; folders: number };
|
||||
/**
|
||||
* Everything inside the writable roots: what Replace would delete (docs/09
|
||||
* T4). Separators (Firefox) are counted apart — never as bookmarks — so the
|
||||
* confirmation can say they will not come back (docs/03 §1).
|
||||
*/
|
||||
current: { bookmarks: number; folders: number; separators: number };
|
||||
}
|
||||
|
||||
export interface PrepareOptions {
|
||||
@@ -90,7 +89,11 @@ export async function prepareImport(
|
||||
|
||||
// Blob.text() is UTF-8 decode, which consumes a leading BOM for us.
|
||||
const text = await file.text();
|
||||
const { format, result } = parseBookmarkFile(text, options);
|
||||
const parsed = parseBookmarkFile(text, options);
|
||||
const { format } = parsed;
|
||||
// What this browser would refuse for its length goes before the preview, so
|
||||
// the counts the user confirms already leave it out (docs/04 §1.2).
|
||||
const result = capUrlLength(parsed.result, MAX_URL_LENGTH);
|
||||
record({
|
||||
kind: 'import',
|
||||
phase: 'parsed',
|
||||
@@ -101,9 +104,9 @@ export async function prepareImport(
|
||||
// One read: getRoots walks the whole tree, so the index and the counts come
|
||||
// from the same snapshot instead of a second getTree().
|
||||
const roots = await getRoots();
|
||||
const browserIndex = buildUrlIndex(roots.all);
|
||||
const browserIndex = buildUrlIndex(withoutSeparators(roots.all));
|
||||
const { existsCount, status } = diffAgainstBrowser(result.roots, browserIndex);
|
||||
const inside = computeStats(roots.writable.flatMap((root) => root.children ?? []));
|
||||
const inside = countLive(roots.writable.flatMap((root) => root.children ?? []));
|
||||
|
||||
return {
|
||||
format,
|
||||
@@ -112,7 +115,11 @@ export async function prepareImport(
|
||||
status,
|
||||
browserIndex,
|
||||
destinations: destinationsOf(roots),
|
||||
current: { bookmarks: inside.bookmarks, folders: inside.folders },
|
||||
current: {
|
||||
bookmarks: inside.bookmarks,
|
||||
folders: inside.folders,
|
||||
separators: inside.separators,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -169,6 +176,7 @@ function destinationsOf(roots: BookmarkRoots): PlanDestinations {
|
||||
toolbar: roots.toolbar,
|
||||
other: roots.other,
|
||||
...(roots.mobile !== undefined && { mobile: roots.mobile }),
|
||||
...(roots.menu !== undefined && { menu: roots.menu }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -233,7 +241,8 @@ async function writeAll(
|
||||
mode,
|
||||
dedupe,
|
||||
// Fresh, not the preview's: anything bookmarked since must not be added twice.
|
||||
browserIndex: dedupe && mode !== 'replace' ? buildUrlIndex(roots.all) : new Set(),
|
||||
browserIndex:
|
||||
dedupe && mode !== 'replace' ? buildUrlIndex(withoutSeparators(roots.all)) : new Set(),
|
||||
destinations: destinationsOf(roots),
|
||||
newFolderTitle,
|
||||
});
|
||||
@@ -244,7 +253,7 @@ async function writeAll(
|
||||
if (plan.stats.writeDepth > MAX_WRITE_DEPTH) {
|
||||
throw new BmParseError(
|
||||
'TOO_DEEP',
|
||||
`the import would nest folders ${plan.stats.writeDepth} deep; Chrome stores at most ${MAX_WRITE_DEPTH}`,
|
||||
`the import would nest folders ${plan.stats.writeDepth} deep; at most ${MAX_WRITE_DEPTH} are written, in every browser (Chrome's own storage limit)`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -282,6 +291,9 @@ async function backUpThenFreeze(
|
||||
backup: BackupState,
|
||||
first: BookmarkRoots,
|
||||
): Promise<LiveNode[]> {
|
||||
// Separators are not in the snapshot (no format holds one), so a change
|
||||
// that only moves or adds separators is not seen here; Replace deletes them
|
||||
// and says so before it starts (docs/03 §1).
|
||||
const snapshotOf = (roots: BookmarkRoots) =>
|
||||
toBookmarkNodes(roots.replaceable, rootMarkersOf(roots));
|
||||
let roots = first;
|
||||
|
||||
+25
-4
@@ -27,11 +27,30 @@ export const CHANGELOG_URL = `${REPO_URL}/blob/main/CHANGELOG.md`;
|
||||
*/
|
||||
export const ACCESSIBILITY_URL = `${REPO_URL}/blob/main/ACCESSIBILITY.md`;
|
||||
|
||||
/** The Chrome Web Store item id (docs/00 §9) — also the CHROME_EXTENSION_ID secret. */
|
||||
const CWS_ITEM_ID = 'eghnciphhegekmnofffpgbdfefckdhmg';
|
||||
|
||||
/** The published Chrome Web Store listing. */
|
||||
const CWS_URL = `https://chromewebstore.google.com/detail/bookmarkmagic/${CWS_ITEM_ID}`;
|
||||
|
||||
/**
|
||||
* The published Chrome Web Store listing (item id — docs/00 §9).
|
||||
* The Firefox Add-ons listing, addressed by the gecko id, which AMO resolves
|
||||
* (docs/13 §8). The "@" is percent-encoded on purpose: AMO decodes it, and the
|
||||
* source then holds nothing that reads as an email address (see below).
|
||||
*/
|
||||
const AMO_URL = 'https://addons.mozilla.org/firefox/addon/bookmarkmagic%40poli0981.dev/';
|
||||
|
||||
/** Every store, listed: the README's install section. */
|
||||
const INSTALL_URL = `${REPO_URL}#install`;
|
||||
|
||||
/**
|
||||
* The listing this copy was installed from — docs/06 §3.5.
|
||||
*
|
||||
* The only route from inside the product to rating or reviewing it, which
|
||||
* docs/13 §6 lists as a post-launch channel.
|
||||
* docs/13 §6 lists as a post-launch channel. One Chromium package serves the
|
||||
* Chrome Web Store and Edge Add-ons, so the Chromium choice is made at run
|
||||
* time, by extension id: the Chrome Web Store's own id gets its listing, any
|
||||
* other (an Edge Add-ons install, an unpacked build) the install section.
|
||||
*
|
||||
* There is deliberately **no support email here.** Putting an address on an
|
||||
* in-product surface invites users to mail their real bookmarks file, which is
|
||||
@@ -40,8 +59,10 @@ export const ACCESSIBILITY_URL = `${REPO_URL}/blob/main/ACCESSIBILITY.md`;
|
||||
* SECURITY.md, CONTRIBUTING.md and the privacy policy, where it arrives with
|
||||
* the instruction to sanitize first (docs/15 decision log, 2026-08-03).
|
||||
*/
|
||||
export const STORE_URL =
|
||||
'https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg';
|
||||
export function storeUrlFor(install: { firefox: boolean; extensionId: string }): string {
|
||||
if (install.firefox) return AMO_URL;
|
||||
return install.extensionId === CWS_ITEM_ID ? CWS_URL : INSTALL_URL;
|
||||
}
|
||||
|
||||
export interface LabelledLink {
|
||||
labelKey: string;
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
getChildren,
|
||||
getRootChildren,
|
||||
type LiveNode,
|
||||
type MoveDestination,
|
||||
move,
|
||||
remove,
|
||||
removeTree,
|
||||
@@ -41,7 +42,8 @@ export interface EditApi {
|
||||
getChildren: (id: string) => Promise<LiveNode[]>;
|
||||
create: (details: { parentId: string; title: string }) => Promise<LiveNode>;
|
||||
update: (id: string, changes: { title?: string }) => Promise<void>;
|
||||
move: (id: string, destination: { parentId?: string; index?: number }) => Promise<void>;
|
||||
/** Resolves to the index the browser reports the node now has (`browser/bookmarks.ts`). */
|
||||
move: (id: string, destination: MoveDestination) => Promise<number | undefined>;
|
||||
remove: (id: string) => Promise<void>;
|
||||
removeTree: (id: string) => Promise<void>;
|
||||
}
|
||||
@@ -229,13 +231,22 @@ export class EditCommands extends EditView {
|
||||
if (node === undefined || !this.isEditable(node)) return false;
|
||||
if (!canMoveInto(this.roots, id, plan.parentId)) return false;
|
||||
const { parentId, position } = plan;
|
||||
return this.guard(async () => {
|
||||
let landed: number | undefined;
|
||||
const moved = await this.guard(async () => {
|
||||
this.roots = moveNode(this.roots, id, parentId, position?.local);
|
||||
await this.api.move(
|
||||
landed = await this.api.move(
|
||||
id,
|
||||
position === undefined ? { parentId } : { parentId, index: position.api },
|
||||
position === undefined ? { parentId } : { parentId, position },
|
||||
);
|
||||
});
|
||||
// The browser says where the node really went. If that is not where the
|
||||
// tree put it, the two disagree — re-read rather than show a wrong order
|
||||
// (docs/03 §3). The adapter already sends each browser its own index, so
|
||||
// this only fires if a browser changes its rule.
|
||||
if (moved && position !== undefined && landed !== undefined && landed !== position.local) {
|
||||
await this.load();
|
||||
}
|
||||
return moved;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -96,7 +96,14 @@ export class EditSession extends EditCommands {
|
||||
record({ kind: 'edit', action: 'sort', count: moves.length });
|
||||
const outcome = await applySort(
|
||||
moves,
|
||||
(step) => this.api.move(step.id, { parentId: folder.id, index: step.index }),
|
||||
// Every sort move goes LEFT, where both browsers' index rules agree
|
||||
// (docs/05 §10): the same number serves as both.
|
||||
async (step) => {
|
||||
await this.api.move(step.id, {
|
||||
parentId: folder.id,
|
||||
position: { api: step.index, local: step.index },
|
||||
});
|
||||
},
|
||||
(step) => {
|
||||
this.roots = moveNode(this.roots, step.id, folder.id, step.index);
|
||||
},
|
||||
|
||||
@@ -171,8 +171,12 @@ export class EditView {
|
||||
if (index === -1) return undefined;
|
||||
// Skip the node's own descendants, which disappear with it.
|
||||
const depth = this.rows[index]?.depth ?? 0;
|
||||
const after = this.rows.slice(index + 1).find((row) => row.depth <= depth);
|
||||
return after?.node.id ?? this.rows[index - 1]?.node.id;
|
||||
// Separators (Firefox) take no focus, so they are never the neighbour.
|
||||
const after = this.rows
|
||||
.slice(index + 1)
|
||||
.find((row) => row.depth <= depth && row.node.separator !== true);
|
||||
const before = this.rows.slice(0, index).findLast((row) => row.node.separator !== true);
|
||||
return after?.node.id ?? before?.node.id;
|
||||
};
|
||||
|
||||
dispose = (): void => {
|
||||
|
||||
+102
-13
@@ -1,23 +1,46 @@
|
||||
import type { LiveNode } from '@/lib/browser/bookmarks';
|
||||
import { type LiveNode, type MoveDestination, moveIndexFor } from '@/lib/browser/live-tree';
|
||||
|
||||
/**
|
||||
* Hand-rolled `chrome.bookmarks` mock — docs/11 §4.
|
||||
* Hand-rolled `bookmarks` mock — docs/11 §4.
|
||||
*
|
||||
* WXT's fakeBrowser stubs `bookmarks.*` with "not implemented" throws, so this
|
||||
* is an in-memory tree with call recording and failure injection. It models the
|
||||
* behaviours the write queue depends on: create appends when no index is given,
|
||||
* and ids are handed out in creation order.
|
||||
*
|
||||
* Two flavours (since v1.3.0, docs/11 §4). `chromium` — the default — has the
|
||||
* synthetic root "0" and the roots "1"/"2"/"3" with `folderType`, hides an
|
||||
* empty Mobile root as desktop Chrome does, and counts a same-folder move's
|
||||
* index before the node's removal. `firefox` behaves as Firefox's source says
|
||||
* its API does (ext-bookmarks.js, Places' Bookmarks.sys.mjs): GUID roots in
|
||||
* the order Menu, Toolbar, Other, Mobile, all four always listed, no
|
||||
* `folderType`, a `type` on every node, separators as `{ type: 'separator',
|
||||
* url: 'data:' }`, a same-folder move's index read as the final position, and
|
||||
* addresses over 65 536 characters refused.
|
||||
*/
|
||||
export interface FakeBookmarksOptions {
|
||||
/** Throw on the Nth create (1-based), to test partial-failure reporting. */
|
||||
failOnCreate?: number;
|
||||
/** Throw on the Nth removeTree (1-based) — the Replace path's equivalent. */
|
||||
failOnRemoveTree?: number;
|
||||
flavour?: 'chromium' | 'firefox';
|
||||
}
|
||||
|
||||
/** Firefox's permanent folders, in `getTree()` order. */
|
||||
export const FIREFOX_ROOTS = {
|
||||
menu: 'menu________',
|
||||
toolbar: 'toolbar_____',
|
||||
other: 'unfiled_____',
|
||||
mobile: 'mobile______',
|
||||
} as const;
|
||||
|
||||
const FIREFOX_MAX_URL = 65_536;
|
||||
|
||||
export class FakeBookmarks {
|
||||
readonly calls: string[] = [];
|
||||
readonly flavour: 'chromium' | 'firefox';
|
||||
private readonly nodes = new Map<string, LiveNode>();
|
||||
private readonly rootId: string;
|
||||
private nextId = 100;
|
||||
private createCount = 0;
|
||||
private removeCount = 0;
|
||||
@@ -27,6 +50,23 @@ export class FakeBookmarks {
|
||||
|
||||
constructor(options: FakeBookmarksOptions = {}) {
|
||||
this.options = options;
|
||||
this.flavour = options.flavour ?? 'chromium';
|
||||
if (this.flavour === 'firefox') {
|
||||
this.rootId = 'root________';
|
||||
this.nodes.set(this.rootId, { id: this.rootId, title: '', type: 'folder', children: [] });
|
||||
for (const [id, title] of [
|
||||
[FIREFOX_ROOTS.menu, 'Bookmarks Menu'],
|
||||
[FIREFOX_ROOTS.toolbar, 'Bookmarks Toolbar'],
|
||||
[FIREFOX_ROOTS.other, 'Other Bookmarks'],
|
||||
[FIREFOX_ROOTS.mobile, 'Mobile Bookmarks'],
|
||||
] as const) {
|
||||
const node: LiveNode = { id, parentId: this.rootId, title, type: 'folder', children: [] };
|
||||
this.nodes.set(id, node);
|
||||
this.root.children?.push(node);
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.rootId = '0';
|
||||
// The synthetic root and the three Chromium roots.
|
||||
this.nodes.set('0', { id: '0', title: '', children: [] });
|
||||
for (const [id, title, folderType] of [
|
||||
@@ -41,14 +81,14 @@ export class FakeBookmarks {
|
||||
}
|
||||
|
||||
private get root(): LiveNode {
|
||||
return this.nodes.get('0') as LiveNode;
|
||||
return this.nodes.get(this.rootId) as LiveNode;
|
||||
}
|
||||
|
||||
/** Add a policy-managed root, which every write path must skip. */
|
||||
addManagedRoot(): LiveNode {
|
||||
const node: LiveNode = {
|
||||
id: 'managed',
|
||||
parentId: '0',
|
||||
parentId: this.rootId,
|
||||
title: 'Managed bookmarks',
|
||||
unmodifiable: 'managed',
|
||||
children: [],
|
||||
@@ -64,6 +104,24 @@ export class FakeBookmarks {
|
||||
return created.id;
|
||||
}
|
||||
|
||||
/** Firefox only: a separator line under a parent, returning its id. */
|
||||
addSeparator(parentId: string, index?: number): string {
|
||||
if (this.flavour !== 'firefox') throw new Error('Chromium has no separators');
|
||||
const parent = this.nodes.get(parentId);
|
||||
if (parent?.children === undefined) throw new Error(`no such parent: ${parentId}`);
|
||||
const node: LiveNode = {
|
||||
id: String(this.nextId++),
|
||||
parentId,
|
||||
title: '',
|
||||
type: 'separator',
|
||||
url: 'data:',
|
||||
};
|
||||
this.nodes.set(node.id, node);
|
||||
if (index === undefined) parent.children.push(node);
|
||||
else parent.children.splice(index, 0, node);
|
||||
return node.id;
|
||||
}
|
||||
|
||||
private createSync(details: {
|
||||
parentId: string;
|
||||
title: string;
|
||||
@@ -77,6 +135,9 @@ export class FakeBookmarks {
|
||||
// parser refuses is rejected — mid-write, which is why readers skip them.
|
||||
const url = details.url === '' ? undefined : details.url;
|
||||
if (url !== undefined && !URL.canParse(url)) throw new Error('Invalid URL.');
|
||||
if (this.flavour === 'firefox' && url !== undefined && url.length > FIREFOX_MAX_URL) {
|
||||
throw new Error('URL too long.');
|
||||
}
|
||||
|
||||
const node: LiveNode = {
|
||||
id: String(this.nextId++),
|
||||
@@ -84,6 +145,7 @@ export class FakeBookmarks {
|
||||
title: details.title,
|
||||
...(url !== undefined && { url }),
|
||||
...(url === undefined && { children: [] }),
|
||||
...(this.flavour === 'firefox' && { type: url === undefined ? 'folder' : 'bookmark' }),
|
||||
};
|
||||
this.nodes.set(node.id, node);
|
||||
|
||||
@@ -98,8 +160,9 @@ export class FakeBookmarks {
|
||||
// --- the API surface the adapter uses -------------------------------------
|
||||
|
||||
/**
|
||||
* Like desktop Chrome, an EMPTY Mobile root is left out of the tree (it
|
||||
* still exists, accepts writes, and `get('3')` returns it).
|
||||
* Like desktop Chrome, an EMPTY Mobile root is left out of the Chromium tree
|
||||
* (it still exists, accepts writes, and `get('3')` returns it). Firefox lists
|
||||
* all four of its roots, always.
|
||||
*/
|
||||
getTree = async (): Promise<LiveNode[]> => {
|
||||
this.calls.push('getTree');
|
||||
@@ -148,7 +211,15 @@ export class FakeBookmarks {
|
||||
this.nodes.delete(id);
|
||||
};
|
||||
|
||||
move = async (id: string, destination: { parentId?: string; index?: number }): Promise<void> => {
|
||||
/**
|
||||
* `bookmarks.move` as the browser has it: resolves to the moved node, with
|
||||
* its new `index`. Chromium reads a same-parent index as counted BEFORE the
|
||||
* node was removed; Firefox reads it as the final position.
|
||||
*/
|
||||
move = async (
|
||||
id: string,
|
||||
destination: { parentId?: string; index?: number },
|
||||
): Promise<LiveNode> => {
|
||||
this.calls.push(`move:${id}:${destination.parentId ?? ''}:${destination.index ?? ''}`);
|
||||
const node = this.nodes.get(id);
|
||||
if (node === undefined) throw new Error(`no such node: ${id}`);
|
||||
@@ -160,11 +231,27 @@ export class FakeBookmarks {
|
||||
from.children.splice(oldIndex, 1);
|
||||
const siblings = to.children ?? [];
|
||||
let index = destination.index ?? siblings.length;
|
||||
// Chrome reads a same-parent index as counted BEFORE the node was removed.
|
||||
if (from === to && index > oldIndex) index--;
|
||||
siblings.splice(Math.min(index, siblings.length), 0, node);
|
||||
if (this.flavour === 'chromium' && from === to && index > oldIndex) index--;
|
||||
const at = Math.min(index, siblings.length);
|
||||
siblings.splice(at, 0, node);
|
||||
to.children = siblings;
|
||||
node.parentId = to.id;
|
||||
const { children: _children, ...bare } = node;
|
||||
return structuredClone({ ...bare, index: at });
|
||||
};
|
||||
|
||||
/**
|
||||
* The adapter's `move` (`browser/bookmarks.ts`) over this fake: sends the
|
||||
* index this flavour's rule expects and resolves to where the node landed —
|
||||
* what an `EditApi` built on the fake passes as its `move`.
|
||||
*/
|
||||
moveTo = async (id: string, destination: MoveDestination): Promise<number | undefined> => {
|
||||
const { parentId, position } = destination;
|
||||
const moved = await this.move(id, {
|
||||
...(parentId !== undefined && { parentId }),
|
||||
...(position !== undefined && { index: moveIndexFor(position, this.flavour) }),
|
||||
});
|
||||
return moved.index;
|
||||
};
|
||||
|
||||
update = async (id: string, changes: { title?: string; url?: string }): Promise<void> => {
|
||||
@@ -187,8 +274,10 @@ export class FakeBookmarks {
|
||||
|
||||
/** The writable roots as a title/url outline, ids dropped — for whole-tree comparisons. */
|
||||
outline(): unknown[] {
|
||||
const shape = (node: LiveNode): unknown =>
|
||||
node.url === undefined ? { [node.title]: (node.children ?? []).map(shape) } : node.url;
|
||||
const shape = (node: LiveNode): unknown => {
|
||||
if (node.type === 'separator') return '---';
|
||||
return node.url === undefined ? { [node.title]: (node.children ?? []).map(shape) } : node.url;
|
||||
};
|
||||
return (this.root.children ?? []).map(shape);
|
||||
}
|
||||
|
||||
@@ -202,7 +291,7 @@ export class FakeBookmarks {
|
||||
return (this.nodes.get(parentId)?.children ?? []).map((child) => child.title);
|
||||
}
|
||||
|
||||
/** Total nodes created since construction (excludes the four roots). */
|
||||
/** Total nodes created since construction (excludes the roots). */
|
||||
get created(): number {
|
||||
return this.nodes.size - (this.root.children?.length ?? 0) - 1;
|
||||
}
|
||||
|
||||
@@ -19,9 +19,9 @@ vi.mock('wxt/browser', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const { clearRoots, flattenLive, getRoots, toBookmarkNodes } = await import(
|
||||
'@/lib/browser/bookmarks'
|
||||
);
|
||||
const { clearRoots } = await import('@/lib/browser/bookmarks');
|
||||
const { flattenLive, toBookmarkNodes } = await import('@/lib/browser/live-tree');
|
||||
const { getRoots } = await import('@/lib/browser/roots');
|
||||
|
||||
beforeEach(() => {
|
||||
current = new FakeBookmarks();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { describeError } from '@/lib/browser/describe-error';
|
||||
import {
|
||||
browserOf,
|
||||
clearDiagnostics,
|
||||
errorName,
|
||||
installCrashHooks,
|
||||
@@ -29,14 +30,25 @@ describe('diagnostics', () => {
|
||||
it('puts the context first and nothing personal anywhere', () => {
|
||||
const report = JSON.parse(snapshot(CONTEXT));
|
||||
expect(report).toMatchObject({ app: 'BookmarkMagic', ...CONTEXT });
|
||||
expect(Object.keys(report)).toEqual([
|
||||
'app',
|
||||
'version',
|
||||
'locale',
|
||||
'theme',
|
||||
'chromeMajor',
|
||||
'events',
|
||||
]);
|
||||
expect(Object.keys(report)).toEqual(['app', 'version', 'locale', 'theme', 'browser', 'events']);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:160.0) Gecko/20100101 Firefox/160.0',
|
||||
'Firefox 160',
|
||||
],
|
||||
[
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 Edg/142.0.0.0',
|
||||
'Edge 142',
|
||||
],
|
||||
[
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36',
|
||||
'Chrome 142',
|
||||
],
|
||||
['', 'unknown'],
|
||||
])('names the browser from %j', (userAgent, expected) => {
|
||||
expect(browserOf(userAgent)).toBe(expected);
|
||||
});
|
||||
|
||||
it('logs every described failure by code — never by its detail text', () => {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
countLive,
|
||||
isSeparator,
|
||||
type LiveNode,
|
||||
moveIndexFor,
|
||||
toBookmarkNodes,
|
||||
withoutSeparators,
|
||||
} from '@/lib/browser/live-tree';
|
||||
|
||||
/**
|
||||
* The pure half of the bookmarks adapter — docs/02 §4. Firefox's separators
|
||||
* come with `url: "data:"`, so every "has a url, so it is a bookmark" test
|
||||
* would count, export and dedupe them as bookmarks; these pin the one
|
||||
* recognition rule (`type`) and everything built on it.
|
||||
*/
|
||||
|
||||
const separator = (id: string): LiveNode => ({ id, title: '', type: 'separator', url: 'data:' });
|
||||
const bookmark = (id: string, url = `https://${id}.example/`): LiveNode => ({
|
||||
id,
|
||||
title: id,
|
||||
url,
|
||||
type: 'bookmark',
|
||||
});
|
||||
|
||||
const FIREFOX_TREE: LiveNode[] = [
|
||||
{
|
||||
id: 'menu________',
|
||||
title: 'Bookmarks Menu',
|
||||
type: 'folder',
|
||||
children: [bookmark('a'), separator('s1'), bookmark('b')],
|
||||
},
|
||||
{
|
||||
id: 'toolbar_____',
|
||||
title: 'Bookmarks Toolbar',
|
||||
type: 'folder',
|
||||
children: [
|
||||
{ id: 'f', title: 'Dev', type: 'folder', children: [separator('s2'), bookmark('c')] },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
describe('isSeparator', () => {
|
||||
it('goes by type, never by url', () => {
|
||||
expect(isSeparator(separator('x'))).toBe(true);
|
||||
// A real bookmark to a data: address is still a bookmark.
|
||||
expect(isSeparator(bookmark('d', 'data:text/plain,hi'))).toBe(false);
|
||||
expect(isSeparator({ id: 'chrome', title: 'no type at all' } as LiveNode)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('withoutSeparators', () => {
|
||||
it('removes separators at every depth and keeps everything else in order', () => {
|
||||
const out = withoutSeparators(FIREFOX_TREE);
|
||||
expect(out[0]?.children?.map((n) => n.id)).toEqual(['a', 'b']);
|
||||
expect(out[1]?.children?.[0]?.children?.map((n) => n.id)).toEqual(['c']);
|
||||
});
|
||||
|
||||
it('returns untouched leaves as they are', () => {
|
||||
const leaf = bookmark('z');
|
||||
expect(withoutSeparators([leaf])[0]).toBe(leaf);
|
||||
});
|
||||
});
|
||||
|
||||
describe('countLive', () => {
|
||||
it('counts separators apart from bookmarks and folders', () => {
|
||||
expect(countLive(FIREFOX_TREE)).toEqual({ bookmarks: 3, folders: 3, separators: 2 });
|
||||
});
|
||||
|
||||
it('is all zero on an empty forest', () => {
|
||||
expect(countLive([])).toEqual({ bookmarks: 0, folders: 0, separators: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('toBookmarkNodes', () => {
|
||||
it('leaves separators out — no format BookmarkMagic writes can hold one', () => {
|
||||
const nodes = toBookmarkNodes(FIREFOX_TREE);
|
||||
expect(JSON.stringify(nodes)).not.toContain('data:');
|
||||
expect(nodes[0]?.children?.map((n) => n.url)).toEqual([
|
||||
'https://a.example/',
|
||||
'https://b.example/',
|
||||
]);
|
||||
});
|
||||
|
||||
it('marks the Bookmarks Menu as root "menu" (docs/04 §2)', () => {
|
||||
const [menu, toolbar] = toBookmarkNodes(FIREFOX_TREE, {
|
||||
toolbarId: 'toolbar_____',
|
||||
menuId: 'menu________',
|
||||
});
|
||||
expect(menu?.root).toBe('menu');
|
||||
expect(toolbar?.toolbar).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('moveIndexFor — each browser its own rule (docs/05 §10)', () => {
|
||||
// Moving `a` after `c` in [a, b, c]: before removal 3, after removal 2.
|
||||
const position = { api: 3, local: 2 };
|
||||
|
||||
it('sends Chromium the index counted before the node is removed', () => {
|
||||
expect(moveIndexFor(position, 'chromium')).toBe(3);
|
||||
});
|
||||
|
||||
it('sends Firefox the final position', () => {
|
||||
expect(moveIndexFor(position, 'firefox')).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,196 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { capUrlLength } from '@/lib/core/href';
|
||||
import type { BookmarkNode, ParseResult } from '@/lib/core/model';
|
||||
import { computeStats } from '@/lib/core/model';
|
||||
import { parseBmJson } from '@/lib/core/parse/bm-json';
|
||||
import { readFirefoxJson } from '@/lib/core/parse/firefox-json';
|
||||
import { parseNetscapeHtml } from '@/lib/core/parse/netscape-html';
|
||||
import { buildImportPlan } from '@/lib/core/plan';
|
||||
import { routeTopLevel } from '@/lib/core/route';
|
||||
import { serializeBmJson } from '@/lib/core/serialize/bm-json';
|
||||
import { serializeNetscapeHtml } from '@/lib/core/serialize/netscape-html';
|
||||
|
||||
/**
|
||||
* Firefox's Bookmarks Menu, separators and address limit in the pure core —
|
||||
* docs/03 §1, docs/04 (since v1.3.0).
|
||||
*/
|
||||
|
||||
const link = (title: string): BookmarkNode => ({ title, url: `https://${title}.example/` });
|
||||
|
||||
/** A Firefox profile's export as BookmarkMagic models it: four marked roots. */
|
||||
const FIREFOX_EXPORT: BookmarkNode[] = [
|
||||
{ title: 'Bookmarks Menu', root: 'menu', children: [link('m1'), link('m2')] },
|
||||
{ title: 'Bookmarks Toolbar', toolbar: true, children: [link('t1')] },
|
||||
{ title: 'Other Bookmarks', root: 'other', children: [link('o1')] },
|
||||
{ title: 'Mobile Bookmarks', root: 'mobile', children: [link('p1')] },
|
||||
];
|
||||
|
||||
const titles = (nodes: readonly BookmarkNode[]): string[] => nodes.map((n) => n.title);
|
||||
|
||||
describe('routeTopLevel — the Bookmarks Menu', () => {
|
||||
it('unwraps a menu folder into the menu, and sends loose entries there, on Firefox', () => {
|
||||
const routed = routeTopLevel([...FIREFOX_EXPORT, link('loose')], {
|
||||
hasMobileRoot: true,
|
||||
hasMenuRoot: true,
|
||||
});
|
||||
expect(titles(routed.menu)).toEqual(['m1', 'm2', 'loose']);
|
||||
expect(titles(routed.toolbar)).toEqual(['t1']);
|
||||
expect(titles(routed.other)).toEqual(['o1']);
|
||||
expect(titles(routed.mobile)).toEqual(['p1']);
|
||||
expect(routed.unwrapped).toBe(4);
|
||||
});
|
||||
|
||||
it('keeps a menu folder as a folder under Other where there is no menu (Chromium)', () => {
|
||||
const routed = routeTopLevel([...FIREFOX_EXPORT, link('loose')], { hasMobileRoot: true });
|
||||
expect(routed.menu).toEqual([]);
|
||||
expect(titles(routed.other)).toEqual(['Bookmarks Menu', 'o1', 'loose']);
|
||||
expect(routed.unwrapped).toBe(3);
|
||||
});
|
||||
|
||||
it('still keeps a Mobile folder under Other when the profile has no Mobile root', () => {
|
||||
const routed = routeTopLevel(FIREFOX_EXPORT, { hasMobileRoot: false, hasMenuRoot: true });
|
||||
expect(titles(routed.other)).toEqual(['o1', 'Mobile Bookmarks']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildImportPlan — a fourth destination', () => {
|
||||
const destinations = {
|
||||
menu: { id: 'menu________', title: 'Bookmarks Menu', children: [] },
|
||||
toolbar: { id: 'toolbar_____', title: 'Bookmarks Toolbar', children: [] },
|
||||
other: { id: 'unfiled_____', title: 'Other Bookmarks', children: [] },
|
||||
mobile: { id: 'mobile______', title: 'Mobile Bookmarks', children: [] },
|
||||
};
|
||||
|
||||
it('writes the menu into the menu, first, in Merge and Replace', () => {
|
||||
for (const mode of ['merge', 'replace'] as const) {
|
||||
const plan = buildImportPlan({
|
||||
roots: FIREFOX_EXPORT,
|
||||
mode,
|
||||
dedupe: false,
|
||||
browserIndex: new Set(),
|
||||
destinations,
|
||||
newFolderTitle: 'Imported',
|
||||
});
|
||||
expect(plan.segments.map((s) => s.parentId)).toEqual([
|
||||
'menu________',
|
||||
'toolbar_____',
|
||||
'unfiled_____',
|
||||
'mobile______',
|
||||
]);
|
||||
expect(plan.stats.bookmarkCount).toBe(5);
|
||||
}
|
||||
});
|
||||
|
||||
it('puts the New-folder wrapper under Other Bookmarks, as on Chrome', () => {
|
||||
const plan = buildImportPlan({
|
||||
roots: FIREFOX_EXPORT,
|
||||
mode: 'new-folder',
|
||||
dedupe: false,
|
||||
browserIndex: new Set(),
|
||||
destinations,
|
||||
newFolderTitle: 'Imported',
|
||||
});
|
||||
expect(plan.segments.map((s) => s.parentId)).toEqual(['unfiled_____']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BM JSON — root "menu"', () => {
|
||||
it('round-trips the marker (additive; the version stays 1)', () => {
|
||||
const text = serializeBmJson(FIREFOX_EXPORT, {
|
||||
version: '1.3.0',
|
||||
exportedAt: '2026-11-18T00:00:00Z',
|
||||
});
|
||||
expect(JSON.parse(text).version).toBe(1);
|
||||
const { roots } = parseBmJson(text);
|
||||
expect(roots[0]?.root).toBe('menu');
|
||||
expect(roots[0]?.children?.map((n) => n.title)).toEqual(['m1', 'm2']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Netscape HTML — the menu is written loose, as Firefox writes it', () => {
|
||||
it('unwraps a top-level menu folder and keeps the marked roots', () => {
|
||||
const html = serializeNetscapeHtml(FIREFOX_EXPORT);
|
||||
expect(html).not.toContain('Bookmarks Menu');
|
||||
const { roots } = parseNetscapeHtml(html);
|
||||
// The menu's entries come back loose, first, and route into the menu on
|
||||
// Firefox (above) — the file round-trips there.
|
||||
expect(titles(roots).slice(0, 2)).toEqual(['m1', 'm2']);
|
||||
expect(roots[2]?.toolbar).toBe(true);
|
||||
expect(roots[3]?.root).toBe('other');
|
||||
expect(roots[4]?.root).toBe('mobile');
|
||||
});
|
||||
|
||||
it('leaves a deeper folder called "menu" alone: markers count at the top only', () => {
|
||||
const nested: BookmarkNode[] = [
|
||||
{ title: 'Folder', children: [{ title: 'Inner', root: 'menu', children: [link('x')] }] },
|
||||
];
|
||||
expect(parseNetscapeHtml(serializeNetscapeHtml(nested)).roots[0]?.children?.[0]?.title).toBe(
|
||||
'Inner',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('separators a file holds are counted (docs/04 §1.2, §2b)', () => {
|
||||
it('counts <HR> in HTML', () => {
|
||||
const html =
|
||||
'<!DOCTYPE NETSCAPE-Bookmark-file-1><DL><p><DT><A HREF="https://a.example/">a</A><HR><HR>' +
|
||||
'<DT><A HREF="https://b.example/">b</A></DL><p>';
|
||||
expect(parseNetscapeHtml(html).warnings).toEqual([{ code: 'SEPARATORS_SKIPPED', count: 2 }]);
|
||||
});
|
||||
|
||||
it('counts separator entries in a Firefox JSON backup', () => {
|
||||
const doc = {
|
||||
guid: 'root________',
|
||||
title: '',
|
||||
type: 'text/x-moz-place-container',
|
||||
root: 'placesRoot',
|
||||
children: [
|
||||
{
|
||||
guid: 'menu________',
|
||||
title: 'menu',
|
||||
type: 'text/x-moz-place-container',
|
||||
root: 'bookmarksMenuFolder',
|
||||
children: [
|
||||
{ title: 'a', type: 'text/x-moz-place', uri: 'https://a.example/' },
|
||||
{ type: 'text/x-moz-place-separator' },
|
||||
{ title: 'b', type: 'text/x-moz-place', uri: 'https://b.example/' },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = readFirefoxJson(doc);
|
||||
expect(titles(result.roots)).toEqual(['a', 'b']);
|
||||
expect(result.warnings).toContainEqual({ code: 'SEPARATORS_SKIPPED', count: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('capUrlLength — what Firefox refuses for its length (docs/04 §1.2)', () => {
|
||||
const long = `https://long.example/${'x'.repeat(65_536)}`;
|
||||
const parsed = (roots: BookmarkNode[]): ParseResult => ({
|
||||
roots,
|
||||
stats: computeStats(roots),
|
||||
warnings: [],
|
||||
});
|
||||
|
||||
it('drops addresses over the limit, at any depth, and says how many', () => {
|
||||
const result = capUrlLength(
|
||||
parsed([
|
||||
link('ok'),
|
||||
{ title: 'long', url: long },
|
||||
{ title: 'F', children: [{ title: 'deep', url: long }, link('kept')] },
|
||||
]),
|
||||
65_536,
|
||||
);
|
||||
expect(result.roots.map((n) => n.title)).toEqual(['ok', 'F']);
|
||||
expect(result.roots[1]?.children?.map((n) => n.title)).toEqual(['kept']);
|
||||
expect(result.stats.bookmarks).toBe(2);
|
||||
expect(result.warnings).toEqual([{ code: 'URL_TOO_LONG', count: 2 }]);
|
||||
});
|
||||
|
||||
it('changes nothing without a limit (Chromium) or when nothing is too long', () => {
|
||||
const input = parsed([{ title: 'long', url: long }]);
|
||||
expect(capUrlLength(input, undefined)).toBe(input);
|
||||
const short = parsed([link('a')]);
|
||||
expect(capUrlLength(short, 65_536)).toBe(short);
|
||||
});
|
||||
});
|
||||
@@ -75,7 +75,7 @@ describe('parseNetscapeHtml — tolerated shapes', () => {
|
||||
expect(roots[0]?.children?.[0]?.url).toBe('https://sibling.example/');
|
||||
});
|
||||
|
||||
it('skips <HR> separators silently and keeps both neighbours (docs/04 §1.2)', () => {
|
||||
it('skips <HR> separators, counts them, and keeps both neighbours (docs/04 §1.2)', () => {
|
||||
const withHr = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://a.example/">A</A>
|
||||
@@ -84,7 +84,8 @@ describe('parseNetscapeHtml — tolerated shapes', () => {
|
||||
</DL><p>`;
|
||||
const { roots, warnings } = parseNetscapeHtml(withHr);
|
||||
expect(roots.map((r) => r.url)).toEqual(['https://a.example/', 'https://b.example/']);
|
||||
expect(warnings).toEqual([]);
|
||||
// Counted since v1.3.0: once Firefox users import, a silent loss is not acceptable.
|
||||
expect(warnings).toEqual([{ code: 'SEPARATORS_SKIPPED', count: 1 }]);
|
||||
});
|
||||
|
||||
it('looks past a <DD> that has no nested <DL> to a later sibling list', () => {
|
||||
|
||||
@@ -33,7 +33,7 @@ beforeEach(async () => {
|
||||
getChildren: async (id: string) => fake.children(id),
|
||||
create: fake.create,
|
||||
update: fake.update,
|
||||
move: fake.move,
|
||||
move: fake.moveTo,
|
||||
remove: fake.remove,
|
||||
removeTree: fake.removeTree,
|
||||
},
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { ImportMode } from '@/lib/browser/storage';
|
||||
import { FakeBookmarks, FIREFOX_ROOTS } from '../../helpers/fake-bookmarks';
|
||||
|
||||
/**
|
||||
* The import, Replace and export on Firefox — docs/03 §1, docs/02 §4 (since
|
||||
* v1.3.0), against the Firefox flavour of the fake (docs/11 §4).
|
||||
*
|
||||
* Until v1.3.0 `getRoots` fell back to POSITION on Firefox, which lists the
|
||||
* Bookmarks Menu first: the Menu was taken for the bar, the bar for Other and
|
||||
* Other for Mobile. A Replace emptied the wrong roots and restored into them.
|
||||
*/
|
||||
let current = new FakeBookmarks({ flavour: 'firefox' });
|
||||
|
||||
vi.mock('wxt/browser', () => ({
|
||||
browser: {
|
||||
bookmarks: {
|
||||
getTree: () => current.getTree(),
|
||||
get: (id: string) => current.get(id),
|
||||
create: (details: Parameters<FakeBookmarks['create']>[0]) => current.create(details),
|
||||
removeTree: (id: string) => current.removeTree(id),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
const { getRoots, rootMarkersOf } = await import('@/lib/browser/roots');
|
||||
const { prepareImport, runImport } = await import('@/lib/import/run-import');
|
||||
const { buildExport, countSelected } = await import('@/lib/export/run-export');
|
||||
|
||||
type PickerHost = { showSaveFilePicker?: unknown };
|
||||
let backups: string[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
current = new FakeBookmarks({ flavour: 'firefox' });
|
||||
backups = [];
|
||||
(globalThis as PickerHost).showSaveFilePicker = async () => ({
|
||||
createWritable: async () => ({
|
||||
write: async (data: string) => {
|
||||
backups.push(data);
|
||||
},
|
||||
close: async () => undefined,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete (globalThis as PickerHost).showSaveFilePicker;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const { menu: MENU, toolbar: TOOLBAR, other: OTHER, mobile: MOBILE } = FIREFOX_ROOTS;
|
||||
|
||||
async function importText(text: string, mode: ImportMode) {
|
||||
const prepared = await prepareImport(new File([text], 'bookmarks'));
|
||||
const outcome = await runImport({
|
||||
prepared,
|
||||
mode,
|
||||
dedupe: false,
|
||||
newFolderTitle: 'Imported',
|
||||
now: new Date(2026, 10, 18, 12, 0),
|
||||
signal: new AbortController().signal,
|
||||
onProgress: () => undefined,
|
||||
});
|
||||
return { prepared, outcome };
|
||||
}
|
||||
|
||||
/** Something in all four roots, and separators in two of them. */
|
||||
function seedProfile(): void {
|
||||
current.seed(MENU, { title: 'm', url: 'https://m.example/' });
|
||||
current.addSeparator(MENU);
|
||||
current.seed(MENU, { title: 'm2', url: 'https://m2.example/' });
|
||||
current.seed(TOOLBAR, { title: 't', url: 'https://t.example/' });
|
||||
const dev = current.seed(TOOLBAR, { title: 'Dev' });
|
||||
current.addSeparator(dev);
|
||||
current.seed(dev, { title: 'd', url: 'https://d.example/' });
|
||||
current.seed(OTHER, { title: 'o', url: 'https://o.example/' });
|
||||
current.seed(MOBILE, { title: 'p', url: 'https://p.example/' });
|
||||
}
|
||||
|
||||
/** A file with each kind of root, as a BookmarkMagic HTML export writes it. */
|
||||
const HTML = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://loose.example/">loose</A>
|
||||
<DT><H3 PERSONAL_TOOLBAR_FOLDER="true">Bookmarks bar</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://bar.example/">bar</A>
|
||||
</DL><p>
|
||||
<DT><H3 UNFILED_BOOKMARKS_FOLDER="true">Other bookmarks</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://other.example/">other</A>
|
||||
</DL><p>
|
||||
</DL><p>`;
|
||||
|
||||
describe('getRoots on Firefox', () => {
|
||||
it('finds each root by its GUID — never the Menu as the bar', async () => {
|
||||
const roots = await getRoots();
|
||||
expect(roots.toolbarId).toBe(TOOLBAR);
|
||||
expect(roots.otherId).toBe(OTHER);
|
||||
expect(roots.mobileId).toBe(MOBILE);
|
||||
expect(roots.menuId).toBe(MENU);
|
||||
expect(roots.replaceable.map((root) => root.id)).toEqual([TOOLBAR, OTHER, MOBILE, MENU]);
|
||||
expect(rootMarkersOf(roots)).toEqual({
|
||||
toolbarId: TOOLBAR,
|
||||
otherId: OTHER,
|
||||
mobileId: MOBILE,
|
||||
menuId: MENU,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('import on Firefox', () => {
|
||||
it('Merge puts each marked root in its own root and loose entries in the Menu', async () => {
|
||||
await importText(HTML, 'merge');
|
||||
expect(current.childTitles(MENU)).toEqual(['loose']);
|
||||
expect(current.childTitles(TOOLBAR)).toEqual(['bar']);
|
||||
expect(current.childTitles(OTHER)).toEqual(['other']);
|
||||
});
|
||||
|
||||
it('New-folder mode puts the wrapper under Other Bookmarks', async () => {
|
||||
await importText(HTML, 'new-folder');
|
||||
expect(current.childTitles(OTHER)).toEqual(['Imported']);
|
||||
expect(current.childTitles(MENU)).toEqual([]);
|
||||
});
|
||||
|
||||
it('counts separators apart, and never as bookmarks, for the Replace confirmation', async () => {
|
||||
seedProfile();
|
||||
const prepared = await prepareImport(new File([HTML], 'bookmarks'));
|
||||
expect(prepared.current).toEqual({ bookmarks: 6, folders: 1, separators: 2 });
|
||||
});
|
||||
|
||||
it('Replace empties all four roots, separators included, and restores its backup twice', async () => {
|
||||
seedProfile();
|
||||
const withoutSeparators = JSON.stringify(current.outline()).replaceAll('"---",', '');
|
||||
|
||||
await importText(HTML, 'replace');
|
||||
expect(JSON.stringify(current.outline())).not.toContain('---');
|
||||
expect(current.childTitles(MENU)).toEqual(['loose']);
|
||||
const backup = backups.at(-1) ?? '';
|
||||
// The backup holds the Menu as a marked root and no separator at all.
|
||||
expect(backup).toContain('"root":"menu"');
|
||||
expect(backup).not.toContain('data:');
|
||||
|
||||
await importText(backup, 'replace');
|
||||
expect(JSON.stringify(current.outline())).toBe(withoutSeparators);
|
||||
await importText(backup, 'replace');
|
||||
expect(JSON.stringify(current.outline())).toBe(withoutSeparators);
|
||||
});
|
||||
});
|
||||
|
||||
describe('export on Firefox', () => {
|
||||
it('writes no separator, counts none as a bookmark, and leaves the Menu loose in HTML', async () => {
|
||||
seedProfile();
|
||||
const roots = await getRoots();
|
||||
const live = (await current.getTree())[0]?.children ?? [];
|
||||
expect(countSelected(live, undefined)).toBe(6);
|
||||
|
||||
const html = buildExport(
|
||||
live,
|
||||
{ format: 'netscape-html', now: new Date() },
|
||||
rootMarkersOf(roots),
|
||||
);
|
||||
expect(html.content).not.toContain('data:');
|
||||
expect(html.content).not.toContain('Bookmarks Menu');
|
||||
expect(html.content.indexOf('https://m.example/')).toBeLessThan(
|
||||
html.content.indexOf('PERSONAL_TOOLBAR_FOLDER'),
|
||||
);
|
||||
|
||||
const json = buildExport(live, { format: 'bm-json', now: new Date() }, rootMarkersOf(roots));
|
||||
expect(json.content).toContain('"root": "menu"');
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
ISSUES_URL,
|
||||
LEGAL_URLS,
|
||||
REPO_URL,
|
||||
STORE_URL,
|
||||
storeUrlFor,
|
||||
} from '@/lib/links';
|
||||
|
||||
/** Vitest runs with cwd at the project root, which is where `legal/` lives. */
|
||||
@@ -103,10 +103,25 @@ describe('store listing', () => {
|
||||
it('is the published item, and is the only in-product route to a review', () => {
|
||||
// docs/13 §6 counts store ratings as a post-launch channel; before this
|
||||
// there was no way to reach the listing from inside the extension at all.
|
||||
expect(STORE_URL.startsWith('https://chromewebstore.google.com/detail/')).toBe(true);
|
||||
const cws = storeUrlFor({ firefox: false, extensionId: 'eghnciphhegekmnofffpgbdfefckdhmg' });
|
||||
expect(cws.startsWith('https://chromewebstore.google.com/detail/')).toBe(true);
|
||||
// The item id doubles as the CHROME_EXTENSION_ID secret (docs/00 §9), so a
|
||||
// typo here is a typo in two places.
|
||||
expect(STORE_URL).toContain('eghnciphhegekmnofffpgbdfefckdhmg');
|
||||
expect(cws).toContain('eghnciphhegekmnofffpgbdfefckdhmg');
|
||||
});
|
||||
|
||||
it('sends each install to the listing it came from (docs/06 §3.5)', () => {
|
||||
// Firefox: AMO, by the gecko id — percent-encoded, so no address-shaped
|
||||
// string sits in src/ (the next test).
|
||||
const amo = storeUrlFor({ firefox: true, extensionId: 'anything' });
|
||||
expect(amo).toBe('https://addons.mozilla.org/firefox/addon/bookmarkmagic%40poli0981.dev/');
|
||||
expect(decodeURIComponent(amo)).toContain('bookmarkmagic@poli0981.dev');
|
||||
// A Chromium copy with any other id — Edge Add-ons assigns its own, an
|
||||
// unpacked build gets a random one — goes to the list of every store.
|
||||
expect(storeUrlFor({ firefox: false, extensionId: 'abcdefghijklmnopabcdefghijklmnop' })).toBe(
|
||||
`${REPO_URL}#install`,
|
||||
);
|
||||
expect(storeUrlFor({ firefox: false, extensionId: '' })).toBe(`${REPO_URL}#install`);
|
||||
});
|
||||
|
||||
it('puts no email address on any in-product surface', () => {
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { searchTree } from '@/lib/core/search';
|
||||
import { countDescendants, isEditable, toEditNode } from '@/lib/edit/edit-node';
|
||||
import type { EditNode } from '@/lib/edit/patch-tree';
|
||||
import { planSort, sortedOrder } from '@/lib/edit/sort';
|
||||
import { nudgeTarget, resolveKey, visibleRows } from '@/lib/edit/tree-keyboard';
|
||||
import type { EditApi } from '@/lib/stores/edit-commands.svelte';
|
||||
import { EditSession } from '@/lib/stores/edit-session.svelte';
|
||||
import { FakeBookmarks, FIREFOX_ROOTS } from '../../helpers/fake-bookmarks';
|
||||
|
||||
/**
|
||||
* #edit on Firefox — docs/03 §3, docs/05 §10, docs/06 §5 (since v1.3.0).
|
||||
*
|
||||
* Separators are rows no command touches, and a same-folder move is sent with
|
||||
* Firefox's own index. Against the Firefox flavour of the fake, which behaves
|
||||
* the way Firefox's source says its API does (docs/11 §4).
|
||||
*/
|
||||
|
||||
let fake: FakeBookmarks;
|
||||
let session: EditSession;
|
||||
|
||||
function api(f: FakeBookmarks): EditApi {
|
||||
return {
|
||||
getRootChildren: async () => (await f.getTree())[0]?.children ?? [],
|
||||
getChildren: async (id: string) => f.children(id),
|
||||
create: f.create,
|
||||
update: f.update,
|
||||
move: f.moveTo,
|
||||
remove: f.remove,
|
||||
removeTree: f.removeTree,
|
||||
};
|
||||
}
|
||||
|
||||
const MENU = FIREFOX_ROOTS.menu;
|
||||
|
||||
/** Menu: a, ——, b, c */
|
||||
function seedMenu(): { a: string; sep: string; b: string; c: string } {
|
||||
const a = fake.seed(MENU, { title: 'a', url: 'https://a.example/' });
|
||||
const sep = fake.addSeparator(MENU);
|
||||
const b = fake.seed(MENU, { title: 'b', url: 'https://b.example/' });
|
||||
const c = fake.seed(MENU, { title: 'c', url: 'https://c.example/' });
|
||||
return { a, sep, b, c };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
fake = new FakeBookmarks({ flavour: 'firefox' });
|
||||
session = new EditSession(api(fake), () => 'en');
|
||||
});
|
||||
|
||||
describe('the edit model', () => {
|
||||
it('marks a separator, keeps its url so it is never mistaken for a folder', () => {
|
||||
const node = toEditNode({ id: 's', title: '', type: 'separator', url: 'data:' });
|
||||
expect(node).toMatchObject({ separator: true, url: 'data:' });
|
||||
expect(node.children).toBeUndefined();
|
||||
// Even without the url Firefox sends today, it stays a non-folder.
|
||||
expect(toEditNode({ id: 's', title: '', type: 'separator' }).url).toBe('data:');
|
||||
});
|
||||
|
||||
it('offers no command on a separator, and does not count it as an item', () => {
|
||||
const roots: EditNode[] = [
|
||||
{
|
||||
id: 'r',
|
||||
title: 'root',
|
||||
children: [
|
||||
{ id: 's', title: '', url: 'data:', separator: true, parentId: 'r' },
|
||||
{ id: 'x', title: 'x', url: 'https://x/', parentId: 'r' },
|
||||
],
|
||||
},
|
||||
];
|
||||
expect(isEditable(roots, roots[0]?.children?.[0] as EditNode)).toBe(false);
|
||||
expect(isEditable(roots, roots[0]?.children?.[1] as EditNode)).toBe(true);
|
||||
expect(countDescendants(roots[0])).toBe(1);
|
||||
});
|
||||
|
||||
it('never matches a separator in a search, "data" included', () => {
|
||||
const roots = [
|
||||
{ id: 's', title: '', url: 'data:', separator: true as const },
|
||||
{ id: 'd', title: 'data sheet', url: 'https://d/' },
|
||||
];
|
||||
expect([...searchTree(roots, 'data').matched]).toEqual(['d']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('keyboard and positions', () => {
|
||||
const folder: EditNode = {
|
||||
id: 'f',
|
||||
title: 'F',
|
||||
children: [
|
||||
{ id: 'a', title: 'alpha', url: 'https://a/', parentId: 'f' },
|
||||
{ id: 's', title: '', url: 'data:', separator: true, parentId: 'f' },
|
||||
{ id: 'b', title: 'beta', url: 'https://b/', parentId: 'f' },
|
||||
],
|
||||
};
|
||||
const rows = visibleRows([folder], new Set(['f']));
|
||||
|
||||
it('counts items, not separators, in posinset and setsize', () => {
|
||||
const byId = new Map(rows.map((row) => [row.node.id, row]));
|
||||
expect(byId.get('a')).toMatchObject({ posInSet: 1, setSize: 2 });
|
||||
expect(byId.get('b')).toMatchObject({ posInSet: 2, setSize: 2 });
|
||||
});
|
||||
|
||||
it('moves focus over a separator, never onto it', () => {
|
||||
expect(resolveKey('ArrowDown', 'a', rows)).toEqual({ kind: 'focus', id: 'b' });
|
||||
expect(resolveKey('ArrowUp', 'b', rows)).toEqual({ kind: 'focus', id: 'a' });
|
||||
expect(resolveKey('End', 'a', rows)).toEqual({ kind: 'focus', id: 'b' });
|
||||
});
|
||||
|
||||
it('lets Alt+↑/↓ step past a separator as one place', () => {
|
||||
expect(nudgeTarget(rows, 'b', -1)).toBe('s');
|
||||
expect(nudgeTarget(rows, 'a', 1)).toBe('s');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Sort A→Z with separators', () => {
|
||||
const node = (id: string, separator = false): EditNode =>
|
||||
separator
|
||||
? { id, title: '', url: 'data:', separator: true }
|
||||
: { id, title: id, url: `https://${id}/` };
|
||||
|
||||
it('sorts each run on its own and leaves every separator in place', () => {
|
||||
const children = [node('d'), node('b'), node('s1', true), node('z'), node('a')];
|
||||
expect(sortedOrder(children, 'en').map((n) => n.id)).toEqual(['b', 'd', 's1', 'a', 'z']);
|
||||
});
|
||||
|
||||
it('plans only leftward moves that reproduce that order', () => {
|
||||
const children = [node('d'), node('b'), node('s1', true), node('z'), node('a')];
|
||||
const current = [...children];
|
||||
for (const move of planSort(children, 'en')) {
|
||||
const from = current.findIndex((n) => n.id === move.id);
|
||||
expect(from).toBeGreaterThan(move.index);
|
||||
const [moved] = current.splice(from, 1);
|
||||
current.splice(move.index, 0, moved as EditNode);
|
||||
}
|
||||
expect(current.map((n) => n.id)).toEqual(['b', 'd', 's1', 'a', 'z']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('EditSession on Firefox', () => {
|
||||
it('drops a row after a later sibling exactly where it was dropped', async () => {
|
||||
const { a, b, c } = seedMenu();
|
||||
await session.load();
|
||||
session.draggingId = a;
|
||||
await session.drop(b, 'after');
|
||||
// Sent with Chrome's index, Firefox put it one place further, after c.
|
||||
expect(fake.childTitles(MENU)).toEqual(['', 'b', 'a', 'c']);
|
||||
expect(session.roots[0]?.children?.map((n) => n.title)).toEqual(['', 'b', 'a', 'c']);
|
||||
expect(c).toBeDefined();
|
||||
});
|
||||
|
||||
it('moves one place with Alt+↓, past a separator too', async () => {
|
||||
const { a } = seedMenu();
|
||||
await session.load();
|
||||
await session.nudge(a, 1);
|
||||
expect(fake.childTitles(MENU)).toEqual(['', 'a', 'b', 'c']);
|
||||
await session.nudge(a, 1);
|
||||
expect(fake.childTitles(MENU)).toEqual(['', 'b', 'a', 'c']);
|
||||
});
|
||||
|
||||
it('sorts a folder around its separators', async () => {
|
||||
fake.seed(MENU, { title: 'z', url: 'https://z.example/' });
|
||||
fake.seed(MENU, { title: 'y', url: 'https://y.example/' });
|
||||
fake.addSeparator(MENU);
|
||||
fake.seed(MENU, { title: 'k', url: 'https://k.example/' });
|
||||
fake.seed(MENU, { title: 'j', url: 'https://j.example/' });
|
||||
await session.load();
|
||||
const menu = session.roots[0] as EditNode;
|
||||
expect(session.requestSort(menu)).toBe(true);
|
||||
await session.confirmSort();
|
||||
expect(fake.childTitles(MENU)).toEqual(['y', 'z', '', 'j', 'k']);
|
||||
});
|
||||
|
||||
it('never lists separators as duplicates of each other', async () => {
|
||||
fake.addSeparator(MENU);
|
||||
fake.addSeparator(MENU);
|
||||
fake.seed(MENU, { title: 'x', url: 'https://x.example/' });
|
||||
fake.seed(MENU, { title: 'x again', url: 'https://x.example/' });
|
||||
await session.load();
|
||||
session.showDuplicates = true;
|
||||
expect(session.duplicateGroups).toHaveLength(1);
|
||||
expect(session.duplicateGroups[0]?.nodes.map((n) => n.title)).toEqual(['x', 'x again']);
|
||||
});
|
||||
|
||||
it('re-reads the tree when the browser reports a different landing place', async () => {
|
||||
const { a, b } = seedMenu();
|
||||
// A browser whose rule changed under us: it reports where it REALLY put
|
||||
// the node, and the session must believe it over its own patch.
|
||||
const lying: EditApi = {
|
||||
...api(fake),
|
||||
move: async (id, destination) => {
|
||||
await fake.moveTo(id, destination);
|
||||
return 99;
|
||||
},
|
||||
};
|
||||
session = new EditSession(lying, () => 'en');
|
||||
await session.load();
|
||||
let reads = 0;
|
||||
const load = session.load;
|
||||
session.load = async () => {
|
||||
reads++;
|
||||
await load();
|
||||
};
|
||||
session.draggingId = a;
|
||||
await session.drop(b, 'after');
|
||||
expect(reads).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -73,7 +73,7 @@ beforeEach(async () => {
|
||||
getChildren: async (id: string) => fake.children(id),
|
||||
create: fake.create,
|
||||
update: fake.update,
|
||||
move: fake.move,
|
||||
move: fake.moveTo,
|
||||
remove: fake.remove,
|
||||
removeTree: fake.removeTree,
|
||||
},
|
||||
|
||||
@@ -15,7 +15,7 @@ function api(f: FakeBookmarks) {
|
||||
getChildren: async (id: string) => f.children(id),
|
||||
create: f.create,
|
||||
update: f.update,
|
||||
move: f.move,
|
||||
move: f.moveTo,
|
||||
remove: f.remove,
|
||||
removeTree: f.removeTree,
|
||||
};
|
||||
@@ -89,7 +89,7 @@ describe('EditSession — sort A→Z', () => {
|
||||
const move = fake.move;
|
||||
fake.move = async (...args) => {
|
||||
if (++calls === 2) throw new Error('refused');
|
||||
await move(...args);
|
||||
return move(...args);
|
||||
};
|
||||
session = new EditSession(api(fake), () => 'en');
|
||||
await session.load();
|
||||
@@ -187,7 +187,7 @@ describe('EditSession — Alt+↑ / Alt+↓ (v1.2.1)', () => {
|
||||
const move = fake.move;
|
||||
fake.move = async (...args) => {
|
||||
await gate;
|
||||
await move(...args);
|
||||
return move(...args);
|
||||
};
|
||||
session = new EditSession(api(fake), () => 'en');
|
||||
await session.load();
|
||||
@@ -371,7 +371,7 @@ describe('EditSession — one bulk command at a time (v1.1.0 review)', () => {
|
||||
const move = fake.move;
|
||||
fake.move = async (...args) => {
|
||||
await gate;
|
||||
await move(...args);
|
||||
return move(...args);
|
||||
};
|
||||
session = new EditSession(api(fake), () => 'en');
|
||||
await session.load();
|
||||
|
||||
Reference in new issue
Block a user