refactor(edit): split EditTab under the size limit and test what came out
EditTab.svelte was 589 lines against the 500-line hard limit in docs/10 §1 -- the one place in the codebase that broke it. Now 459. Extracted, in each case because the thing was genuinely cohesive rather than to hit a number: - src/lib/edit/edit-node.ts -- toEditNode, flattenTree, isEditable, resolveNewFolderParent, countDescendants, extraCopyIds. All pure, all previously inline and therefore untestable. resolveNewFolderParent in particular encodes a fixed bug (a focused root resolving to the synthetic root "0", which every create rejects) that nothing was pinning. - src/lib/browser/open-url.ts -- the docs/09 T3 scheme allowlist, which is the only thing between a crafted `javascript:` bookmark in someone's import file and the browser acting on it. It had NO test. It does now, including the case-shouting dodge and data:/file:/chrome:. - EditToolbar.svelte and MoveToDialog.svelte -- presentational, with their styles copied verbatim. This is a move, not a redesign. The script block is still 279 lines against docs/10 §1's 150-line guidance. The remainder is the mutation layer (guardEdit and the six operations), which is coupled to reactive state and would need accessor indirection to move. Adding that indirection to the app's delete paths immediately before a release is a worse trade than the line count, so it stays and is recorded in CLAUDE.md rather than quietly ignored. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
10 files changed
+510
-176
No files matched your search
@@ -90,11 +90,12 @@ install, privacy summary, donate), full manual QA (docs/11 §5), `wxt zip`
|
||||
clean-install test. Also carried in from the Phase 4 review:
|
||||
- point About's "Changelog" link at `CHANGELOG.md` once it exists
|
||||
(`src/lib/links.ts` currently targets `/releases`);
|
||||
- split `EditTab.svelte`, which is past the 500-line hard limit;
|
||||
- `Button.svelte`'s `.danger`/`.success` variants hardcode `color: #fff`, which
|
||||
measures **2.75:1** on dark-theme `--danger` (#ff6b7d) — under the 4.5:1
|
||||
docs/06 §5 requires. Phase 4 fixed the same class of bug for `--accent-fg`;
|
||||
these need `--danger-fg`/`--success-fg` tokens and a visual decision.
|
||||
- ✔ `EditTab.svelte` split (589 → 459, under the hard limit). Its script block
|
||||
is still 279 lines against the 150-line guidance; the remainder is the
|
||||
mutation layer, which is genuinely coupled to reactive state and was left
|
||||
whole rather than split behind accessors on the app's delete paths;
|
||||
- ✔ contrast tokens fixed, and `tests/unit/styles/contrast.test.ts` now fails
|
||||
the build on any text pair under 4.5:1.
|
||||
**Exit:** ready for the docs/13 §1 runbook (human performs store submission).
|
||||
|
||||
## Working style
|
||||
|
||||
@@ -89,10 +89,11 @@ bookmarkmagic/
|
||||
│ │ │ ├── download.ts # Blob → <a download>
|
||||
│ │ │ ├── app-info.ts # manifest version — the ONE source (06 §3.5)
|
||||
│ │ │ ├── errors.ts # BmBrowserError / BmBackupError / BmAborted (§7)
|
||||
│ │ │ ├── open-url.ts # http(s) allowlist before tabs.create (09 T3)
|
||||
│ │ │ └── open-manager.ts # getContexts() focus-or-create
|
||||
│ │ ├── import/run-import.ts # the import pipeline (03 §1)
|
||||
│ │ ├── export/run-export.ts # the export pipeline (03 §2)
|
||||
│ │ ├── edit/ # patch-tree, move-target, tree-keyboard (03 §3)
|
||||
│ │ ├── edit/ # edit-node, patch-tree, move-target, tree-keyboard (03 §3)
|
||||
│ │ ├── settings/options.ts # the six Settings choice tables (06 §3.4)
|
||||
│ │ ├── links.ts # repo / legal / donate URLs (14 §4, §5)
|
||||
│ │ ├── stores/ # Svelte 5 runes state (.svelte.ts)
|
||||
|
||||
+3
-2
@@ -200,8 +200,9 @@ read as a list of missing files:
|
||||
| `AboutCard` | `AboutTab.svelte`, for symmetry with the other four tab shells |
|
||||
| `TreeView` | inline in `EditTab.svelte`; the row is `TreeRow.svelte` and the flattening lives in `edit/tree-keyboard.ts` |
|
||||
| `TreeNode` | `TreePreviewNode.svelte` (import preview) + `FolderPickNode.svelte` (export picker) |
|
||||
| `ResultCard` / `SearchInput` | inline in `ImportTab` / `EditTab` |
|
||||
| — | plus `SettingsTab.svelte`, the fifth tab shell |
|
||||
| `ResultCard` | inline in `ImportTab` |
|
||||
| `SearchInput` | inside `EditToolbar.svelte` |
|
||||
| — | plus `SettingsTab.svelte` (the fifth tab shell), `EditToolbar.svelte` and `MoveToDialog.svelte` |
|
||||
|
||||
`Toast`'s queue and timers live in `stores/toast.svelte.ts`, not the component:
|
||||
one `<Toast>` mounts at the App root while the route chain below it unmounts on
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Opening a bookmarked URL — the docs/09 T3 control.
|
||||
*
|
||||
* Purpose: the single gate between a URL that came out of someone's import file
|
||||
* and the browser actually navigating to it.
|
||||
* Inputs: a URL string from untrusted file data.
|
||||
* Guarantees: only `http:` and `https:` ever reach `tabs.create`. Nothing is
|
||||
* opened for an unparseable URL, and nothing throws.
|
||||
*/
|
||||
import { browser } from 'wxt/browser';
|
||||
|
||||
/** Schemes allowed to reach the browser. Everything else is display-only. */
|
||||
const ALLOWED_SCHEMES = new Set(['http:', 'https:']);
|
||||
|
||||
/**
|
||||
* Open `url` in a new tab if its scheme is allowed.
|
||||
*
|
||||
* Returns whether it was opened, so callers and tests can tell "blocked" from
|
||||
* "opened" rather than inferring it.
|
||||
*
|
||||
* Chromium also refuses `javascript:` from `tabs.create`, but this allowlist is
|
||||
* the authoritative control: it is ours, it is testable, and it does not move
|
||||
* when a browser changes its mind. `data:`, `file:` and `chrome:` are blocked
|
||||
* here even though some are navigable, because a bookmark file is untrusted
|
||||
* input and none of them are worth the surface.
|
||||
*/
|
||||
export async function openBookmarkUrl(url: string): Promise<boolean> {
|
||||
let scheme: string;
|
||||
try {
|
||||
scheme = new URL(url).protocol;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (!ALLOWED_SCHEMES.has(scheme)) return false;
|
||||
|
||||
await browser.tabs.create({ url });
|
||||
return true;
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { browser } from 'wxt/browser';
|
||||
import {
|
||||
create,
|
||||
getRootChildren,
|
||||
type LiveNode,
|
||||
move,
|
||||
remove,
|
||||
removeTree,
|
||||
@@ -12,8 +10,17 @@
|
||||
update,
|
||||
} from '../browser/bookmarks';
|
||||
import { BmBrowserError } from '../browser/errors';
|
||||
import { openBookmarkUrl } from '../browser/open-url';
|
||||
import { findDuplicateGroups } from '../core/dedupe';
|
||||
import { searchTree } from '../core/search';
|
||||
import {
|
||||
countDescendants,
|
||||
extraCopyIds,
|
||||
flattenTree,
|
||||
isEditable as canEdit,
|
||||
resolveNewFolderParent,
|
||||
toEditNode,
|
||||
} from '../edit/edit-node';
|
||||
import {
|
||||
changeNode,
|
||||
type EditNode,
|
||||
@@ -25,10 +32,11 @@
|
||||
import { canMoveInto, moveTargets } from '../edit/move-target';
|
||||
import { resolveKey, visibleRows } from '../edit/tree-keyboard';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import Button from './Button.svelte';
|
||||
import Callout from './Callout.svelte';
|
||||
import ConfirmDialog from './ConfirmDialog.svelte';
|
||||
import DuplicatePanel from './DuplicatePanel.svelte';
|
||||
import EditToolbar from './EditToolbar.svelte';
|
||||
import MoveToDialog from './MoveToDialog.svelte';
|
||||
import TreeRow from './TreeRow.svelte';
|
||||
|
||||
let roots = $state<EditNode[]>([]);
|
||||
@@ -78,16 +86,8 @@
|
||||
};
|
||||
});
|
||||
|
||||
function toEditNode(node: LiveNode): EditNode {
|
||||
return {
|
||||
id: node.id,
|
||||
...(node.parentId !== undefined && { parentId: node.parentId }),
|
||||
title: node.title,
|
||||
...(node.url !== undefined && { url: node.url }),
|
||||
...(node.url === undefined && { children: (node.children ?? []).map(toEditNode) }),
|
||||
...(node.unmodifiable !== undefined && { unmodifiable: node.unmodifiable }),
|
||||
};
|
||||
}
|
||||
/** Bound to the current tree, so callers pass only the node. */
|
||||
const isEditable = (node: EditNode): boolean => canEdit(roots, node);
|
||||
|
||||
async function load(): Promise<void> {
|
||||
try {
|
||||
@@ -121,27 +121,9 @@
|
||||
const rows = $derived(visibleRows(roots, expanded, filtering ? search.visible : undefined));
|
||||
|
||||
const duplicateGroups = $derived(
|
||||
findDuplicateGroups(flatten(roots).filter((node) => node.url !== undefined)),
|
||||
findDuplicateGroups(flattenTree(roots).filter((node) => node.url !== undefined)),
|
||||
);
|
||||
|
||||
function flatten(nodes: readonly EditNode[], into: EditNode[] = []): EditNode[] {
|
||||
for (const node of nodes) {
|
||||
into.push(node);
|
||||
flatten(node.children ?? [], into);
|
||||
}
|
||||
return into;
|
||||
}
|
||||
|
||||
/**
|
||||
* Permanent roots and policy-managed nodes reject every write, so the UI must
|
||||
* not offer the affordance at all — optimistically mutating first and finding
|
||||
* out on rejection is how the tree ends up disagreeing with the browser.
|
||||
*/
|
||||
function isEditable(node: EditNode): boolean {
|
||||
if (node.unmodifiable !== undefined) return false;
|
||||
return !roots.some((root) => root.id === node.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a mutation, and on failure resync from the browser — the only source of
|
||||
* truth. A snapshot restore would resurrect rows that earlier iterations of a
|
||||
@@ -199,29 +181,13 @@
|
||||
}
|
||||
case 'activate': {
|
||||
const node = findNode(roots, action.id);
|
||||
if (node?.url !== undefined) void openUrl(node.url);
|
||||
if (node?.url !== undefined) void openBookmarkUrl(node.url);
|
||||
else if (node !== undefined) toggle(node.id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Only http(s) reach the browser. `javascript:` and `data:` are display-only
|
||||
* (docs/09 T3) — Chromium also rejects them, but the app-side allowlist is
|
||||
* the authoritative control.
|
||||
*/
|
||||
async function openUrl(url: string): Promise<void> {
|
||||
let scheme = '';
|
||||
try {
|
||||
scheme = new URL(url).protocol;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (scheme !== 'http:' && scheme !== 'https:') return;
|
||||
await browser.tabs.create({ url });
|
||||
}
|
||||
|
||||
async function commitRename(id: string, title: string): Promise<void> {
|
||||
renamingId = undefined;
|
||||
const node = findNode(roots, id);
|
||||
@@ -246,17 +212,7 @@
|
||||
}
|
||||
|
||||
async function newFolder(): Promise<void> {
|
||||
// Into the focused FOLDER, or alongside the focused bookmark. Using the
|
||||
// focused node's parent unconditionally meant selecting a root resolved to
|
||||
// the synthetic root "0", which every create rejects.
|
||||
const focused = findNode(roots, focusedId ?? '');
|
||||
const writableRoot = roots.find((root) => root.unmodifiable === undefined)?.id;
|
||||
const parentId =
|
||||
focused === undefined
|
||||
? writableRoot
|
||||
: focused.url === undefined
|
||||
? focused.id
|
||||
: (focused.parentId ?? writableRoot);
|
||||
const parentId = resolveNewFolderParent(roots, findNode(roots, focusedId ?? ''));
|
||||
if (parentId === undefined) return;
|
||||
|
||||
await guardEdit(async () => {
|
||||
@@ -273,7 +229,7 @@
|
||||
pendingKeepFirst = false;
|
||||
// Snapshot the ids first: duplicateGroups is $derived from `roots`, so
|
||||
// reading it inside the loop would recompute mid-iteration.
|
||||
const doomed = duplicateGroups.flatMap((group) => group.nodes.slice(1).map((n) => n.id));
|
||||
const doomed = extraCopyIds(duplicateGroups);
|
||||
await guardEdit(async () => {
|
||||
for (const id of doomed) {
|
||||
roots = removeNode(roots, id);
|
||||
@@ -319,30 +275,21 @@
|
||||
searchInput?.select();
|
||||
}
|
||||
|
||||
const descendantCount = $derived(
|
||||
pendingDelete === undefined ? 0 : flatten(pendingDelete.children ?? []).length,
|
||||
);
|
||||
const descendantCount = $derived(countDescendants(pendingDelete));
|
||||
</script>
|
||||
|
||||
{#if loadError !== undefined}
|
||||
<Callout tone="danger">{loadError}</Callout>
|
||||
{:else}
|
||||
<div class="toolbar">
|
||||
<input
|
||||
bind:this={searchInput}
|
||||
type="search"
|
||||
placeholder={t('edit.search')}
|
||||
aria-label={t('edit.search')}
|
||||
value={query}
|
||||
oninput={(e) => onQuery((e.currentTarget as HTMLInputElement).value)}
|
||||
/>
|
||||
<Button onclick={() => void newFolder()}>{t('edit.newFolder')}</Button>
|
||||
<Button onclick={() => (showDuplicates = !showDuplicates)}>{t('edit.findDuplicates')}</Button>
|
||||
<Button onclick={() => (expanded = new Set(flatten(roots).map((n) => n.id)))}
|
||||
>{t('edit.expandAll')}</Button
|
||||
>
|
||||
<Button onclick={() => (expanded = new Set())}>{t('edit.collapseAll')}</Button>
|
||||
</div>
|
||||
<EditToolbar
|
||||
bind:input={searchInput}
|
||||
{query}
|
||||
onquery={onQuery}
|
||||
onnewFolder={() => void newFolder()}
|
||||
ontoggleDuplicates={() => (showDuplicates = !showDuplicates)}
|
||||
onexpandAll={() => (expanded = new Set(flattenTree(roots).map((node) => node.id)))}
|
||||
oncollapseAll={() => (expanded = new Set())}
|
||||
/>
|
||||
|
||||
{#if actionError !== undefined}
|
||||
<div class="action-error">
|
||||
@@ -387,7 +334,7 @@
|
||||
onrename={(title) => void commitRename(row.node.id, title)}
|
||||
oncancelRename={() => (renamingId = undefined)}
|
||||
ondelete={() => (pendingDelete = row.node)}
|
||||
onopen={() => void openUrl(row.node.url ?? '')}
|
||||
onopen={() => void openBookmarkUrl(row.node.url ?? '')}
|
||||
onmoveTo={() => (movingNode = row.node)}
|
||||
ondragstart={() => (draggingId = row.node.id)}
|
||||
ondropinto={() => onDrop(row.node.id)}
|
||||
@@ -416,26 +363,16 @@
|
||||
{/if}
|
||||
|
||||
{#if movingNode !== undefined}
|
||||
<div class="move-to" role="dialog" aria-label={t('edit.moveTo')}>
|
||||
<p>{t('edit.moveToBody', { title: movingNode.title })}</p>
|
||||
<ul>
|
||||
{#each targets as target (target.id)}
|
||||
<li>
|
||||
<button
|
||||
onclick={() => {
|
||||
const id = movingNode?.id;
|
||||
movingNode = undefined;
|
||||
if (id !== undefined) void moveInto(id, target.id);
|
||||
}}>{target.label}</button
|
||||
>
|
||||
</li>
|
||||
{/each}
|
||||
{#if targets.length === 0}
|
||||
<li class="muted">{t('edit.noMoveTargets')}</li>
|
||||
{/if}
|
||||
</ul>
|
||||
<Button onclick={() => (movingNode = undefined)}>{t('common.cancel')}</Button>
|
||||
</div>
|
||||
<MoveToDialog
|
||||
node={movingNode}
|
||||
{targets}
|
||||
onpick={(parentId) => {
|
||||
const id = movingNode?.id;
|
||||
movingNode = undefined;
|
||||
if (id !== undefined) void moveInto(id, parentId);
|
||||
}}
|
||||
oncancel={() => (movingNode = undefined)}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<ConfirmDialog
|
||||
@@ -465,24 +402,6 @@
|
||||
/>
|
||||
|
||||
<style>
|
||||
.toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--sp-2);
|
||||
margin-bottom: var(--sp-3);
|
||||
}
|
||||
|
||||
.toolbar input {
|
||||
font: inherit;
|
||||
flex: 1;
|
||||
min-width: 12ch;
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
.split {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
@@ -537,53 +456,4 @@
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.move-to {
|
||||
position: fixed;
|
||||
inset-block-end: var(--sp-4);
|
||||
inset-inline-end: var(--sp-4);
|
||||
width: min(360px, calc(100vw - var(--sp-6)));
|
||||
max-height: 60vh;
|
||||
overflow: auto;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: var(--radius);
|
||||
padding: var(--sp-3);
|
||||
box-shadow: 0 8px 32px rgb(0 0 0 / 0.25);
|
||||
}
|
||||
|
||||
.move-to p {
|
||||
margin: 0 0 var(--sp-2);
|
||||
font-size: var(--fs-1);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.move-to ul {
|
||||
list-style: none;
|
||||
margin: 0 0 var(--sp-3);
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.move-to button {
|
||||
font: inherit;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
background: none;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--fg);
|
||||
cursor: pointer;
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
}
|
||||
|
||||
.move-to button:hover {
|
||||
background: var(--bg-raised);
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,61 @@
|
||||
<script lang="ts">
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import Button from './Button.svelte';
|
||||
|
||||
interface Props {
|
||||
query: string;
|
||||
/** Bound out so ⌘/Ctrl-F can focus it from the tab's window handler. */
|
||||
input?: HTMLInputElement | undefined;
|
||||
onquery: (value: string) => void;
|
||||
onnewFolder: () => void;
|
||||
ontoggleDuplicates: () => void;
|
||||
onexpandAll: () => void;
|
||||
oncollapseAll: () => void;
|
||||
}
|
||||
|
||||
let {
|
||||
query,
|
||||
input = $bindable(),
|
||||
onquery,
|
||||
onnewFolder,
|
||||
ontoggleDuplicates,
|
||||
onexpandAll,
|
||||
oncollapseAll,
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="toolbar">
|
||||
<input
|
||||
bind:this={input}
|
||||
type="search"
|
||||
placeholder={t('edit.search')}
|
||||
aria-label={t('edit.search')}
|
||||
value={query}
|
||||
oninput={(event) => onquery(event.currentTarget.value)}
|
||||
/>
|
||||
<Button onclick={onnewFolder}>{t('edit.newFolder')}</Button>
|
||||
<Button onclick={ontoggleDuplicates}>{t('edit.findDuplicates')}</Button>
|
||||
<Button onclick={onexpandAll}>{t('edit.expandAll')}</Button>
|
||||
<Button onclick={oncollapseAll}>{t('edit.collapseAll')}</Button>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Copied verbatim from EditTab — this is a move, not a redesign. */
|
||||
.toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--sp-2);
|
||||
margin-bottom: var(--sp-3);
|
||||
}
|
||||
|
||||
.toolbar input {
|
||||
font: inherit;
|
||||
flex: 1;
|
||||
min-width: 12ch;
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,84 @@
|
||||
<script lang="ts">
|
||||
import type { MoveTarget } from '../edit/move-target';
|
||||
import type { EditNode } from '../edit/patch-tree';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import Button from './Button.svelte';
|
||||
|
||||
interface Props {
|
||||
/** The node being moved. Rendering is caller-gated on this existing. */
|
||||
node: EditNode;
|
||||
targets: readonly MoveTarget[];
|
||||
onpick: (parentId: string) => void;
|
||||
oncancel: () => void;
|
||||
}
|
||||
|
||||
let { node, targets, onpick, oncancel }: Props = $props();
|
||||
</script>
|
||||
|
||||
<!-- Keyboard parity for drag & drop (docs/06 §3.3): every move reachable
|
||||
without a mouse. -->
|
||||
<div class="move-to" role="dialog" aria-label={t('edit.moveTo')}>
|
||||
<p>{t('edit.moveToBody', { title: node.title })}</p>
|
||||
<ul>
|
||||
{#each targets as target (target.id)}
|
||||
<li><button onclick={() => onpick(target.id)}>{target.label}</button></li>
|
||||
{/each}
|
||||
{#if targets.length === 0}
|
||||
<li class="muted">{t('edit.noMoveTargets')}</li>
|
||||
{/if}
|
||||
</ul>
|
||||
<Button onclick={oncancel}>{t('common.cancel')}</Button>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Copied verbatim from EditTab — this is a move, not a redesign. */
|
||||
.move-to {
|
||||
position: fixed;
|
||||
inset-block-end: var(--sp-4);
|
||||
inset-inline-end: var(--sp-4);
|
||||
width: min(360px, calc(100vw - var(--sp-6)));
|
||||
max-height: 60vh;
|
||||
overflow: auto;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: var(--radius);
|
||||
padding: var(--sp-3);
|
||||
box-shadow: 0 8px 32px rgb(0 0 0 / 0.25);
|
||||
}
|
||||
|
||||
.move-to p {
|
||||
margin: 0 0 var(--sp-2);
|
||||
font-size: var(--fs-1);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.move-to ul {
|
||||
list-style: none;
|
||||
margin: 0 0 var(--sp-3);
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.move-to button {
|
||||
font: inherit;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
background: none;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--fg);
|
||||
cursor: pointer;
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
}
|
||||
|
||||
.move-to button:hover {
|
||||
background: var(--bg-raised);
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Pure helpers over the `#edit` tree — docs/03 §3.
|
||||
*
|
||||
* Purpose: the tree logic that used to sit inline in `EditTab.svelte`, where it
|
||||
* was untestable and pushed the component past the docs/10 §1 size limits.
|
||||
* 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 type { EditNode } from './patch-tree';
|
||||
|
||||
/**
|
||||
* Project a live bookmark node onto the editable model.
|
||||
*
|
||||
* Absent keys are omitted rather than set to `undefined`, per the
|
||||
* `exactOptionalPropertyTypes` rule in docs/10 §2. `children` is set only for
|
||||
* folders, which is what makes `url === undefined` a reliable folder test.
|
||||
*/
|
||||
export function toEditNode(node: LiveNode): EditNode {
|
||||
return {
|
||||
id: node.id,
|
||||
...(node.parentId !== undefined && { parentId: node.parentId }),
|
||||
title: node.title,
|
||||
...(node.url !== undefined && { url: node.url }),
|
||||
...(node.url === undefined && { children: (node.children ?? []).map(toEditNode) }),
|
||||
...(node.unmodifiable !== undefined && { unmodifiable: node.unmodifiable }),
|
||||
};
|
||||
}
|
||||
|
||||
/** Depth-first list of every node in the forest, parents before children. */
|
||||
export function flattenTree(nodes: readonly EditNode[], into: EditNode[] = []): EditNode[] {
|
||||
for (const node of nodes) {
|
||||
into.push(node);
|
||||
flattenTree(node.children ?? [], into);
|
||||
}
|
||||
return into;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a node may be renamed, moved or deleted.
|
||||
*
|
||||
* Permanent roots and policy-managed nodes reject every write, so the UI must
|
||||
* not offer the affordance at all — mutating optimistically and finding out on
|
||||
* rejection is exactly how the tree ends up disagreeing with the browser.
|
||||
*/
|
||||
export function isEditable(roots: readonly EditNode[], node: EditNode): boolean {
|
||||
if (node.unmodifiable !== undefined) return false;
|
||||
return !roots.some((root) => root.id === node.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a new folder should be created, given what is focused.
|
||||
*
|
||||
* Into the focused FOLDER, or alongside the focused bookmark. Using the focused
|
||||
* node's parent unconditionally meant selecting a root resolved to the
|
||||
* synthetic root id `"0"`, which every `create` rejects.
|
||||
*
|
||||
* Returns `undefined` when there is nowhere writable to put it.
|
||||
*/
|
||||
export function resolveNewFolderParent(
|
||||
roots: readonly EditNode[],
|
||||
focused: EditNode | undefined,
|
||||
): string | undefined {
|
||||
const writableRoot = roots.find((root) => root.unmodifiable === undefined)?.id;
|
||||
if (focused === undefined) return writableRoot;
|
||||
if (focused.url === undefined) return focused.id;
|
||||
return focused.parentId ?? writableRoot;
|
||||
}
|
||||
|
||||
/** How many nodes sit inside `node`. Drives the delete confirmation's count. */
|
||||
export function countDescendants(node: EditNode | undefined): number {
|
||||
if (node === undefined) return 0;
|
||||
return flattenTree(node.children ?? []).length;
|
||||
}
|
||||
|
||||
/** Ids to delete so one copy of each duplicated link survives. */
|
||||
export function extraCopyIds(groups: readonly { nodes: readonly EditNode[] }[]): string[] {
|
||||
return groups.flatMap((group) => group.nodes.slice(1).map((node) => node.id));
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fakeBrowser } from 'wxt/testing';
|
||||
import { openBookmarkUrl } from '@/lib/browser/open-url';
|
||||
|
||||
/**
|
||||
* The docs/09 T3 control: bookmark URLs come from someone's import file and are
|
||||
* stored verbatim, so this allowlist is the only thing between a crafted
|
||||
* `javascript:` bookmark and the browser acting on it. It had no test.
|
||||
*/
|
||||
|
||||
let created: { url?: string }[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
fakeBrowser.reset();
|
||||
vi.restoreAllMocks();
|
||||
created = [];
|
||||
// fakeBrowser stubs tabs.* with "not implemented" throws.
|
||||
vi.spyOn(fakeBrowser.tabs, 'create').mockImplementation(async (props) => {
|
||||
created.push(props);
|
||||
// SAFETY: the caller ignores the return value; only the recorded call
|
||||
// matters, and building a full Tab here would assert nothing.
|
||||
return {} as Awaited<ReturnType<typeof fakeBrowser.tabs.create>>;
|
||||
});
|
||||
});
|
||||
|
||||
describe('openBookmarkUrl', () => {
|
||||
it.each([
|
||||
'https://example.com/',
|
||||
'http://example.com/path?q=1',
|
||||
'https://example.com:8443/#frag',
|
||||
])('opens %s', async (url) => {
|
||||
expect(await openBookmarkUrl(url)).toBe(true);
|
||||
expect(created).toEqual([{ url }]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['javascript:alert(1)', 'the classic bookmarklet payload'],
|
||||
['data:text/html,<script>alert(1)</script>', 'inline document'],
|
||||
['file:///etc/passwd', 'local file read'],
|
||||
['chrome://settings', 'privileged browser page'],
|
||||
['ftp://example.com/', 'not in the allowlist'],
|
||||
['vbscript:msgbox(1)', 'legacy script scheme'],
|
||||
])('refuses %s (%s)', async (url) => {
|
||||
expect(await openBookmarkUrl(url)).toBe(false);
|
||||
expect(created).toEqual([]);
|
||||
});
|
||||
|
||||
it('refuses an unparseable URL without throwing', async () => {
|
||||
for (const url of ['', 'not a url', '///', 'http://']) {
|
||||
await expect(openBookmarkUrl(url)).resolves.toBe(false);
|
||||
}
|
||||
expect(created).toEqual([]);
|
||||
});
|
||||
|
||||
it('is case-insensitive about the scheme, as the URL parser is', async () => {
|
||||
// `new URL('JavaScript:…').protocol` normalizes to lowercase, so an
|
||||
// attacker cannot dodge the allowlist by shouting.
|
||||
expect(await openBookmarkUrl('JaVaScRiPt:alert(1)')).toBe(false);
|
||||
expect(await openBookmarkUrl('HTTPS://example.com/')).toBe(true);
|
||||
expect(created).toEqual([{ url: 'HTTPS://example.com/' }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { LiveNode } from '@/lib/browser/bookmarks';
|
||||
import {
|
||||
countDescendants,
|
||||
extraCopyIds,
|
||||
flattenTree,
|
||||
isEditable,
|
||||
resolveNewFolderParent,
|
||||
toEditNode,
|
||||
} from '@/lib/edit/edit-node';
|
||||
import type { EditNode } from '@/lib/edit/patch-tree';
|
||||
|
||||
const BAR: EditNode = {
|
||||
id: '1',
|
||||
title: 'Bookmarks bar',
|
||||
children: [
|
||||
{
|
||||
id: '10',
|
||||
parentId: '1',
|
||||
title: 'Docs',
|
||||
children: [{ id: '11', parentId: '10', title: 'A', url: 'https://a.test/' }],
|
||||
},
|
||||
{ id: '12', parentId: '1', title: 'B', url: 'https://b.test/' },
|
||||
],
|
||||
};
|
||||
const MANAGED: EditNode = { id: '2', title: 'Managed', unmodifiable: 'managed', children: [] };
|
||||
const ROOTS: EditNode[] = [BAR, MANAGED];
|
||||
|
||||
describe('toEditNode', () => {
|
||||
it('omits absent keys rather than setting them undefined', () => {
|
||||
// exactOptionalPropertyTypes (docs/10 §2): an explicit undefined is a type
|
||||
// error at every construction site, and `'url' in node` must stay reliable.
|
||||
const live = { id: '5', title: 'Folder', children: [] } as LiveNode;
|
||||
const node = toEditNode(live);
|
||||
expect(Object.hasOwn(node, 'url')).toBe(false);
|
||||
expect(Object.hasOwn(node, 'parentId')).toBe(false);
|
||||
expect(Object.hasOwn(node, 'unmodifiable')).toBe(false);
|
||||
});
|
||||
|
||||
it('gives folders children and bookmarks none, which is what folder tests rely on', () => {
|
||||
const folder = toEditNode({ id: '5', title: 'F', children: [] } as LiveNode);
|
||||
const link = toEditNode({ id: '6', title: 'L', url: 'https://x.test/' } as LiveNode);
|
||||
expect(folder.children).toEqual([]);
|
||||
expect(Object.hasOwn(link, 'children')).toBe(false);
|
||||
});
|
||||
|
||||
it('recurses, preserving order', () => {
|
||||
const live = {
|
||||
id: '1',
|
||||
title: 'root',
|
||||
children: [
|
||||
{ id: '2', parentId: '1', title: 'first', url: 'https://1.test/' },
|
||||
{ id: '3', parentId: '1', title: 'second', children: [] },
|
||||
],
|
||||
} as LiveNode;
|
||||
expect(toEditNode(live).children?.map((child) => child.id)).toEqual(['2', '3']);
|
||||
});
|
||||
|
||||
it('carries unmodifiable through, since it gates every destructive affordance', () => {
|
||||
const live = { id: '2', title: 'Managed', unmodifiable: 'managed', children: [] } as LiveNode;
|
||||
expect(toEditNode(live).unmodifiable).toBe('managed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('flattenTree', () => {
|
||||
it('lists every node depth-first, parents before children', () => {
|
||||
expect(flattenTree(ROOTS).map((node) => node.id)).toEqual(['1', '10', '11', '12', '2']);
|
||||
});
|
||||
|
||||
it('handles an empty forest', () => {
|
||||
expect(flattenTree([])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isEditable', () => {
|
||||
it('refuses the permanent roots', () => {
|
||||
expect(isEditable(ROOTS, BAR)).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses policy-managed nodes', () => {
|
||||
expect(isEditable(ROOTS, MANAGED)).toBe(false);
|
||||
});
|
||||
|
||||
it('allows ordinary descendants', () => {
|
||||
expect(isEditable(ROOTS, ROOTS[0]?.children?.[0] as EditNode)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveNewFolderParent', () => {
|
||||
it('nests inside the focused folder', () => {
|
||||
expect(resolveNewFolderParent(ROOTS, ROOTS[0]?.children?.[0])).toBe('10');
|
||||
});
|
||||
|
||||
it('puts it beside a focused bookmark, not inside it', () => {
|
||||
expect(resolveNewFolderParent(ROOTS, ROOTS[0]?.children?.[1])).toBe('1');
|
||||
});
|
||||
|
||||
it('falls back to the first WRITABLE root when nothing is focused', () => {
|
||||
// Using the focused node's parent unconditionally resolved a selected root
|
||||
// to the synthetic root "0", which every create rejects.
|
||||
expect(resolveNewFolderParent(ROOTS, undefined)).toBe('1');
|
||||
expect(resolveNewFolderParent([MANAGED, BAR], undefined)).toBe('1');
|
||||
});
|
||||
|
||||
it('returns undefined when every root is unmodifiable', () => {
|
||||
expect(resolveNewFolderParent([MANAGED], undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('treats a focused root as the target folder itself', () => {
|
||||
expect(resolveNewFolderParent(ROOTS, BAR)).toBe('1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('countDescendants', () => {
|
||||
it('counts everything inside, at any depth', () => {
|
||||
expect(countDescendants(BAR)).toBe(3);
|
||||
});
|
||||
|
||||
it('is 0 for a bookmark and for nothing', () => {
|
||||
expect(countDescendants(ROOTS[0]?.children?.[1])).toBe(0);
|
||||
expect(countDescendants(undefined)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('extraCopyIds', () => {
|
||||
it('keeps the first of each group and names the rest', () => {
|
||||
const groups = [
|
||||
{ nodes: [{ id: 'a1' }, { id: 'a2' }, { id: 'a3' }] as EditNode[] },
|
||||
{ nodes: [{ id: 'b1' }, { id: 'b2' }] as EditNode[] },
|
||||
];
|
||||
expect(extraCopyIds(groups)).toEqual(['a2', 'a3', 'b2']);
|
||||
});
|
||||
|
||||
it('names nothing for a group of one', () => {
|
||||
expect(extraCopyIds([{ nodes: [{ id: 'only' }] as EditNode[] }])).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user