Compare commits

...
10 Commits
Author SHA1 Message Date
poli0981andClaude Opus 5 4cb075820f docs: record the Phase 4 browser verification and the resolved contact email
Phase 4 is now verified on a real browser, which every earlier phase had been
and this one had not: the gate's block/reach/persist behaviour, EN→VI→JA live
switching with localized numbers and dates, the theme control, settings
surviving an immediate tab close (the path the $state-proxy DataCloneError
would have broken), and the Phase 2–3 flows still working after Phase 4 touched
their tabs and the settings store.

docs/00 §10 item 4 closes: the contact email in legal/PRIVACY.md is filled in
and confirmed live. That was the last thing standing between the repo and the
docs/13 §1 store runbook that is not Phase 5 work.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:51:41 +07:00
poli0981andClaude Opus 5 3c25eaf8cf docs: record the Phase 4 review outcome
The plural helper docs/07 §5 asked for now exists, so §5 names it and the two
shape tests that enforce it. The decision log gains the five design choices
the review forced, and the progress note records that 19 of 33 findings
survived verification -- including the first-run dead-end where the gate was
reachable only from the routes it blocked.

Adds one measured defect to the Phase 5 list rather than fixing it silently:
Button's .danger/.success hardcode white, which is 2.75:1 on dark-theme
--danger. Same class of bug as the --accent-fg one Phase 4 fixed, but it needs
new tokens and a visual decision rather than a mechanical change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:38:48 +07:00
poli0981andClaude Opus 5 21fd11ce30 fix(i18n): plural forms, the count the retrofit missed, and error text that re-translates
Last batch from the Phase 4 adversarial review, including one the completeness
critic caught that none of the six lenses looked for.

The num() retrofit was incomplete: FolderPickNode rendered its per-folder count
raw, so a Vietnamese user saw "12345" in the export pick tree while StatsCard
showed "12.345" on the adjacent tab. docs/07 §3, written in this same phase,
enumerates exactly three exemptions and this was on none of them.

ImportTab resolved t('errors.…') inside a catch block and stored the resulting
STRING in the session store. t() is only reactive where it is called, so the
error message froze in whatever language was active when it happened and never
followed a language switch. Phase 4 is what makes that observable -- until now
there was no way to switch language at runtime. The store holds the key now.

docs/07 §5 specifies plural keys as { one, other } objects in every locale with
a helper that selects by locale. No such helper existed and the dictionaries
used "(s)" instead, which produced "1 unreadable date(s) were left blank." --
wrong in more ways than the parenthesis. selectPluralForm uses Intl.PluralRules
(en gives one/other, vi/ja only ever other, so two forms cover every locale we
ship) and tPlural supplies a locale-grouped {n} so callers pass a raw count.
All seven warning codes are plural keys, including the two that interpolate no
count, so WarningList can call tPlural unconditionally instead of maintaining a
list of which codes count things.

Also splits getGeneratorVersion from getAppVersion: the UI hides an unknown
version, but a file field cannot be hidden, and "BookmarkMagic " with a
trailing space is a worse artifact in an export -- and in the forced Replace
safety backup -- than the bare product name.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:37:31 +07:00
poli0981andClaude Opus 5 2937f4edf0 fix(a11y): contrast, focus ring, radiogroup keys, live region and document language
Five findings from the Phase 4 adversarial review, all of them things a green
build cannot see.

tokens.css redefined --accent in both dark blocks but never --accent-fg, so
dark mode painted white on #8b6dff -- 3.67:1, under the 4.5:1 docs/06 §5
requires. That hit the ThemeToggle's selected chip and every primary button.
Dark ink on the same violet measures 4.84:1.

ThemeToggle's `overflow: hidden` clipped the global :focus-visible ring, which
base.css draws at outline-offset: 2px, i.e. entirely outside the clip region.
The theme control had no keyboard focus indicator at all. Corner rounding is
per-child now and the ring is inset.

ThemeToggle also claimed role="radiogroup"/"radio" while implementing neither
roving tabindex nor arrow keys, so a screen reader announced "radio button,
1 of 3", switched to forms mode, and then the arrows did nothing while all
three stayed separate tab stops -- the inverse of the pattern (WCAG 4.1.2).
Arrow/Home/End now work and only the selected radio is a tab stop. The handler
sits on the radios, not the group: a keydown handler on a non-focusable
container never fires.

Toast built its role="status" region and its text in one DOM insertion. Screen
readers derive announcements from mutations to a region that was ALREADY
present, so success toasts were never announced. Two permanently-mounted
regions now, polite and assertive, with only their text changing -- two rather
than one with a swapped aria-live, because changing politeness at runtime is
not reliably picked up.

applyLocale never touched <html lang>, and both entrypoints ship lang="en", so
a screen reader read Vietnamese and Japanese with an English voice. It also
fixes the toast's dismiss button, which was labelled "Cancel" -- there is
nothing to call off, the operation already finished.

Also routes the last three hardcoded English aria-labels ("Sections",
"Preview" x2) through the dictionary. They date from Phase 2, but full EN/VI/JA
coverage is this phase's exit criterion.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:33:00 +07:00
poli0981andClaude Opus 5 16bbba371d fix(i18n): show the localized failure message, not the raw browser error
Found by the Phase 4 adversarial review; three lenses filed it.

Every failure path was written `outcome.detail ?? t('...saveFailed')`. But
`detail` is set for any rejection that is an Error, which is the normal case
for chrome.storage.local.set -- so the `??` almost never fell through and the
localized sentence was dead code in all three locales. A Vietnamese user over
quota saw "QUOTA_BYTES quota exceeded".

The worst instance was legal.saveFailed: "Your acceptance could not be saved,
so nothing was recorded. Check that this browser allows extension storage,
then try again." Translated into VI and JA, and unreachable -- at the one
moment a first-run user most needs an actionable instruction.

docs/02 §7 already specified the right shape: "human-readable, localized
messages + a copyable technical detail block", which ImportTab has done since
Phase 2. The message is now the translated sentence and the raw error moves
into a <pre class="detail"> beside it, in both #settings and the gate. The
header controls show the sentence alone -- there is no room for a detail block
there, and #settings has one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:28:58 +07:00
poli0981andClaude Opus 5 0a14fb4257 fix(legal): make the gate reachable from every route, and stop About lying after a bump
Found by the Phase 4 adversarial review; four of six lenses filed it
independently.

The gate rendered only on #import/#export/#edit, and TabBar rendered exactly
those three tabs `disabled` while it was up. But they are the only in-app
navigation to a gated route, and the footer only offers #settings and #about.
So a first-run user who reached #settings -- the flow docs/14 §2 explicitly
prescribes, "so a VI/JA user can switch language and theme first" -- had no
enabled control that led back to the accept UI.

Worst path, introduced by the popup gear this same phase: fresh profile, no
Manager tab, click ⚙. openManager creates a NEW tab at #settings, so there is
no history entry to go Back to. Reopening from the popup does not rescue it
either -- open-manager deliberately focuses the existing tab without touching
its hash (docs/02 §6). The only escapes were editing the URL fragment or
closing the tab.

The fix is that disabling was never what blocked anything: App.svelte already
substitutes <LegalGate> for the tab body on any gated route, which is what
keeps Import/Export/Edit from mounting pre-acceptance. So the tabs are now
clickable and clicking one shows the gate. They carry legal.blocked as their
title -- a key that was translated into all three locales and rendered
nowhere, which is its own half of the same defect: the dead tabs gave no
reason at all.

Separately: decideLegalStatus dropped the stored record on the `updated` path,
so the first time LEGAL_VERSION is bumped, About would tell a user who
accepted v1 that they have never accepted anything. It now carries the
superseded acceptance. Dead code today (LEGAL_VERSION is 1), a wrong statement
about consent the day it is not.

Also clears LegalGate's close timer before setting a new one; repeated clicks
stacked timers and only the last was ever cleaned up.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:26:57 +07:00
poli0981andClaude Opus 5 c44c813aec docs: reconcile the spec with Phase 4
The docs are binding, so where Phase 4 diverged from them the divergence has
to be written down rather than left as an undocumented difference between
spec and code.

Three owner decisions recorded: six settings rows (markdownStyle was persisted
but only editable as a transient #export control), all five donate handles in
About, and a three-way segmented theme control rather than a cycling glyph.

One genuine conflict resolved: docs/06 §3 called the Legal Gate "a full
overlay" while docs/14 §2 -- echoed in docs/03 §4 and the decision log --
requires #settings and #about to stay reachable while it is up. Those cannot
both be satisfied literally, so docs/06 now says the gate fills the content
region and explains why.

Also: docs/02's directory tree had been stale since Phase 2 (it predated
lib/edit, lib/export and lib/import entirely); docs/03 §4 documented a
five-field Settings shape that had six fields in code; docs/07 §3 now names
where the Intl helpers live and, more usefully, the three sites that
deliberately do NOT use them; docs/11 §5 gains the QA items Phase 4 created.

The decision log gains fifteen rows, including the cross-tab sync limitation,
recorded as a known limitation rather than left to be rediscovered in review.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:03:05 +07:00
poli0981andClaude Opus 5 372741142e feat(legal): the first-run Legal Gate
docs/14 §1: the Chrome Web Store has no pre-install acceptance mechanism, so a
first-run gate is what makes the terms reachable at all. Without it the
extension cannot be submitted.

acceptLegal writes, awaits, and flips to `accepted` ONLY once the write
resolves. Getting this backwards is the exact defect shape the last three
phase reviews kept finding: dismiss optimistically, await a chrome.* call that
can reject, never handle the rejection. Here that would leave the user
accepted in the UI and unaccepted on disk, so the gate would silently return
next launch with no explanation. There is a test that rejects the write and
asserts the gate stays up and storage stays empty.

It fails CLOSED: an unreadable store gates. Showing the gate to someone who
already accepted costs one click; skipping it for someone who has not is not
recoverable. A stored version NEWER than LEGAL_VERSION still counts as
accepted -- re-gating on a downgrade is noise, not consent.

The gate 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,
and a literal inset:0 scrim buries the footer links that get you there. The
docs edit reconciling this follows in the docs commit. A side effect worth
keeping: Import/Export/Edit never mount before acceptance, so nothing touches
chrome.bookmarks until the user has agreed.

"Close tab" does not bet the decline path on window.close(): the Manager is
opened by tabs.create, so window.opener is null and close() may no-op. It
waits 150 ms and says so plainly if the document is still there. tabs.remove
is not an option -- that needs the `tabs` permission docs/08 §2 forbids.

Also finally consumes TabBar's `blocked` prop, which has sat unused since
Phase 2, and adds About's acceptance line -- showing the version the user
ACCEPTED, not the current constant.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 12:57:56 +07:00
poli0981andClaude Opus 5 2c2d8347ae feat(about): the #about tab, manifest version, and outbound links
Completes docs/06 §3.5: identity, tagline, GitHub/issues/changelog links, the
"Third-party dependencies: None" statement, all five donate handles from
.github/FUNDING.yml (docs/14 §5), and the four legal documents. The
acceptance-date line follows in the Legal Gate commit, which owns that store.

The displayed version now comes from the manifest, as docs/06 §3.5 requires.
It was hardcoded as "0.1.0" in THREE places -- the Manager footer, run-export
and run-import -- so a release bump had three chances to leave a stale number
in a footer users quote in bug reports, and two chances to write a lying
`generator` field into an exported backup. getAppVersion() returns '' rather
than a plausible fallback, and every render site hides the line instead.

Static links are <a target="_blank" rel="noopener noreferrer">. docs/09 T3
bans <a href> for *imported* bookmark URLs, which is untrusted data and keeps
using tabs.create in #edit; these are compile-time literals in one module.
Using tabs.create here would add an awaited call that can reject, for nothing.

Changelog points at /releases: CHANGELOG.md is Phase 5 work, and a 404 opened
from a legal-adjacent surface is worse than an empty releases page. A test
pins it, and another asserts every legal URL resolves to a file that actually
exists in legal/ -- a rename would otherwise ship four dead links inside the
legal gate with nothing else noticing.

Also drops common.comingSoon now that no route falls through to a placeholder.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 12:54:47 +07:00
poli0981andClaude Opus 5 f897a711bd feat(settings): the #settings tab, header controls, and a save path that tells the truth
Six rows per docs/06 §3.4 as amended -- the doc drew five, but Settings has
carried markdownStyle since Phase 3 and #export was the only place to change
it, so it never actually persisted. Plus the header language/theme controls
from the docs/06 §3 layout, which have been missing since Phase 0.

Three defects in the store had to be fixed for any of this to work, and none
of them could fail before, because updateSettings and resetSettings had zero
callers in src/:

- writeSettings handed the Svelte $state proxy to chrome.storage.local.set,
  which structured-clones its argument. Proxies are not cloneable, so every
  save would have thrown DataCloneError in a real browser. fakeBrowser stores
  the reference without cloning, which is why 338 green tests never saw it;
  the new test clones explicitly to reproduce Chrome.
- updateSettings replaced the settings object rather than mutating it, so any
  component capturing getSettings() into a local would silently stop updating.
  Four new components read this store. Now in-place, with an identity test.
- resetSettings left the pending debounce running, so a reset within 200 ms of
  a change wrote twice -- the first write persisting values just discarded.

updateSettings now returns a SaveOutcome that resolves when the write settles
and never rejects, so the "Saved" toast reports what happened instead of
assuming. flushSettings on visibilitychange shrinks the loss window from
200 ms to roughly nothing; the comment is explicit that it does not reach zero.

Both entrypoints now await settings before mount() and drop the unguarded
browser.i18n.getUILanguage() call at module scope, which could blank the page
on a throw. Awaiting means the pre-load frame is an empty #app rather than
content painted in the wrong locale and theme. Verified top-level await
survives wxt build.

Also gates the footer nav on isWriting(): navigating away during `attesting`
unmounts ImportTab and strands its attestation resolver, deadlocking the
import until reload. TabBar already guarded this; the footer was the way
around it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 12:50:25 +07:00
46 changed files with 2376 additions and 148 deletions

No files matched your search

+8 -1
View File
@@ -87,7 +87,14 @@ performance budgets docs/11 §6, CI workflows per docs/12 §2 (explicit
`permissions:` blocks on every caller — and note the ops repo has **no**
`browser-extension-*` family), CHANGELOG, README (badges, screenshots ⚠,
install, privacy summary, donate), full manual QA (docs/11 §5), `wxt zip`
clean-install test.
clean-install test. Also carried in from the Phase 4 review:
- point About's "Changelog" link at `CHANGELOG.md` once it exists
(`src/lib/links.ts` currently targets `/releases`);
- split `EditTab.svelte`, which is past the 500-line hard limit;
- `Button.svelte`'s `.danger`/`.success` variants hardcode `color: #fff`, which
measures **2.75:1** on dark-theme `--danger` (#ff6b7d) — under the 4.5:1
docs/06 §5 requires. Phase 4 fixed the same class of bug for `--accent-fg`;
these need `--danger-fg`/`--success-fg` tokens and a visual decision.
**Exit:** ready for the docs/13 §1 runbook (human performs store submission).
## Working style
+7 -6
View File
@@ -5,11 +5,11 @@
> **Owner:** poli0981 (GitHub) / SkullMute
> **Repo:** `poli0981/bookmarkmagic` ✔
> **License:** GPL-3.0-or-later
> **Status:** In development — **Phases 0–3 complete** (scaffold, core library,
> browser layer + import, export + edit). Verified working on real Chrome and
> Brave, 2026-07-25. Next: Phase 4 (i18n wiring, theming, Settings, About,
> Legal Gate). Sequencing lives in `/CLAUDE.md`.
> **Doc suite version:** 1.2 (2026-07-25 — reality pass)
> **Status:** In development — **Phases 0–4 complete** (scaffold, core library,
> browser layer + import, export + edit, and i18n/theming/Settings/About/Legal
> Gate). Verified working on real Chrome and Brave, 2026-07-25. Next: Phase 5
> (hardening + release prep). Sequencing lives in `/CLAUDE.md`.
> **Doc suite version:** 1.3 (2026-07-26 — Phase 4 reconciliation)
---
@@ -123,7 +123,8 @@ Derived identifiers (canonical across docs and code):
`scripts/gen-icons.mjs` (ported from the portfolio precedent, zero-dep) emits
placeholder PNGs in the accent violet so the manifest loads from Phase 0.
4. ✔ Donate URLs resolved from `.github/FUNDING.yml` (`14 §5`).
Still open: contact email in `legal/PRIVACY.md`.
✔ Contact email filled in and confirmed live: `contact@poli0981.dev`
(`legal/PRIVACY.md`), alongside the GitHub Issues link.
5. Chrome Web Store: developer account already paid ✔ — create the item,
fill the Privacy tab per `08_MV3_COMPLIANCE.md`.
6. Repo secrets + settings per `12 §5` (incl. disabling CodeQL "Default setup").
+14
View File
@@ -77,20 +77,34 @@ bookmarkmagic/
│ │ │ ├── dedupe.ts
│ │ │ ├── diff.ts
│ │ │ ├── detect-format.ts
│ │ │ ├── plan.ts # buildImportPlan → segments (§4)
│ │ │ ├── search.ts # #edit filter + ancestor expansion
│ │ │ ├── select.ts # tri-state export selection → subtree
│ │ │ ├── csv-path.ts # folder-path encoding shared by CSV both ways
│ │ │ └── limits.ts # MAX_FILE_BYTES, MAX_NODES, MAX_DEPTH, LEGAL_VERSION
│ │ ├── browser/
│ │ │ ├── bookmarks.ts # getTree/create/move/update/remove wrappers
│ │ │ ├── write-queue.ts # sequential tree writer + progress + abort
│ │ │ ├── storage.ts # typed settings/legal accessors
│ │ │ ├── download.ts # Blob → <a download>
│ │ │ ├── app-info.ts # manifest version — the ONE source (06 §3.5)
│ │ │ ├── errors.ts # BmBrowserError / BmBackupError / BmAborted (§7)
│ │ │ └── open-manager.ts # getContexts() focus-or-create
│ │ ├── import/run-import.ts # the import pipeline (03 §1)
│ │ ├── export/run-export.ts # the export pipeline (03 §2)
│ │ ├── edit/ # patch-tree, move-target, tree-keyboard (03 §3)
│ │ ├── 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)
│ │ │ ├── settings.svelte.ts # locale, theme, defaults (persisted)
│ │ │ ├── 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
│ │ ├── 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)
│ └── styles/
+16 -1
View File
@@ -129,7 +129,18 @@ import) appear without reload. Listeners attach on tab enter, detach on leave.
- Settings writes go through `stores/settings.svelte.ts` →
`chrome.storage.local` (debounced 200 ms). Shape:
`{ locale, theme, defaultExportFormat, defaultMergeMode, csvDelimiter }`.
`{ locale, theme, defaultExportFormat, defaultMergeMode, csvDelimiter,
markdownStyle }` — **six** fields, one `<SettingRow>` each (`06 §3.4`).
- `updateSettings(patch)` returns a `SaveOutcome` that resolves when the
debounced write has **settled**, and never rejects. UI feedback follows the
write; it never precedes it, or a failed save still says "Saved".
- The store object is **mutated in place**, never replaced, so a component that
reads `getSettings()` into a local cannot silently go stale. Writes pass a
plain snapshot — `chrome.storage.local.set` structured-clones its argument and
a Svelte `$state` proxy is not cloneable.
- `flushSettings()` runs on `visibilitychange` → hidden (not `beforeunload`,
which is cancellable). It shrinks the window in which an unwritten change is
lost from 200 ms to roughly nothing — not to zero.
- Legal gate: on Manager mount read `legal.acceptedVersion`; if
`< LEGAL_VERSION` render `<LegalGate>` overlay blocking **#import / #export /
#edit** — **#settings and #about stay reachable**, so a VI/JA user can switch
@@ -137,6 +148,10 @@ import) appear without reload. Listeners attach on tab enter, detach on leave.
switcher of its own. Accept → write version + timestamp → unlock.
This three-route set is normative; `14 §2` states the same list.
Details: `14_LEGAL_GATE.md`.
- The gate's accept path writes **first**, awaits, and only then reflects
acceptance in state. Dismissing optimistically would leave the user accepted
in the UI and unaccepted on disk, so the gate would silently reappear next
launch. A storage read failure fails **closed** (gate shown).
## 5. State machines (informal)
+63 -6
View File
@@ -58,7 +58,24 @@ there). No heavy work in the popup, ever.
```
Max content width 960px, centered. Settings/About open as tabs too (footer
links = same routes). `<LegalGate>` renders as a full overlay when required.
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.
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.
`<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.
### 3.1 #import
@@ -106,19 +123,44 @@ Empty state: friendly illustration + "Import some bookmarks →".
### 3.4 #settings
Single column of `<SettingRow>`s: Language (EN/VI/JA select) · Theme
Single column of **six** `<SettingRow>`s: Language · Theme
(System/Light/Dark segmented) · Default export format · Default import mode ·
CSV delimiter. Auto-save + saved toast. Footer: "Reset to defaults".
CSV delimiter · Markdown layout.
- The Language select offers **four** options, not three: `Settings.locale` is
`'auto' | 'en' | 'vi' | 'ja'` and `DEFAULT_SETTINGS.locale === 'auto'`, so
"Automatic (follow the browser)" has to be selectable or the default is
unreachable. The three language labels are **endonyms**, identical in all
three dictionaries — a Japanese user hunting for Vietnamese looks for
"Tiếng Việt".
- Markdown layout is the sixth row because `markdownStyle` is a persisted
field; without it the only place to change it was a transient `#export`
control that never wrote back.
- Four of the six rows reuse the Export/Import tabs' own i18n keys rather than
inventing parallel wording, so the two surfaces cannot describe the same
choice differently.
Auto-save + saved toast — the toast reports the resolved `SaveOutcome`, so a
failed write says so rather than claiming success. Footer: "Reset to defaults",
behind a `<ConfirmDialog>` (six preferences is enough to be worth a confirm).
### 3.5 #about
`<AboutCard>`: logo, name, version (from manifest at runtime), tagline;
links: **GitHub repo ↗** · Report an issue ↗ · Changelog ↗;
**Third-party dependencies: None 🎉** (statement, satisfies the requirement);
Donate: GitHub Sponsors (`poli0981`) ↗ · Ko-fi (`skullmute`) ↗ — full handle
list in `14 §5`, sourced from `.github/FUNDING.yml`;
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`);
Legal block: EULA · License (GPL-3.0) · Disclaimer · Privacy Policy — each →
GitHub `legal/` file; "Legal terms accepted on <date> · version n".
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.
"Changelog" points at the repo's **releases** page until `CHANGELOG.md` exists
(Phase 5) — an empty releases page beats a 404 opened from a legal surface.
## 4. Component inventory (`src/lib/components/`)
@@ -132,6 +174,21 @@ auto-dismiss 4s, ARIA `status`) · `SettingRow` · `AboutCard` · `LegalGate` ·
Rule: components ≤ 300 lines; recursive tree logic isolated in `TreeNode`.
As built, some inventory names map differently — recorded so the list is not
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` |
| `TreeNode` | `TreePreviewNode.svelte` (import preview) + `FolderPickNode.svelte` (export picker) |
| `ResultCard` / `SearchInput` | inline in `ImportTab` / `EditTab` |
| — | plus `SettingsTab.svelte`, the fifth tab shell |
`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.
## 5. Accessibility & keyboard
- Tree uses `role="tree"/"treeitem"`, `aria-expanded`, `aria-level`; arrow
+34
View File
@@ -88,6 +88,26 @@ export function setLocale(l: Locale) { locale = l; } // settings store persists
- Dates in UI: `new Intl.DateTimeFormat(localeTag, { dateStyle:'medium', timeStyle:'short' })`
with tags `en-US` / `vi-VN` / `ja-JP`.
- Numbers (counts): `Intl.NumberFormat(localeTag)` — VI uses `.` thousands.
Where these live: pure `localeTag` / `formatCount` / `formatDateTime` in
`src/lib/i18n/format.ts` (formatters cached per tag — `StatsCard` alone formats
four counts per paint), plus reactive `num()` / `dateTime()` wrappers in
`index.svelte.ts` that read the current locale. `formatDateTime` returns
`undefined` rather than a string on an unparseable input: `readLegal` coerces a
missing `acceptedAt` to `''`, and `Intl.format(new Date(''))` throws a
`RangeError` *inside a render*, which would blank the About tab.
Three rendered numbers deliberately do **not** go through `num()`, each with a
comment at the site so the next reader does not "finish the job":
| Site | Why |
|---|---|
| `ProgressBar`'s `{n}%` | 0–100; no locale groups two digits, and it is the hottest render path in the app |
| `import.folderName`'s date | this bullet list already pins it to the localized *word* + an **ISO** date; localizing it would rename folders written into the user's browser |
| Export filenames and file contents | locale-independent so a file means the same thing whoever opens it |
ARIA numeric attributes (`aria-level`, `aria-valuenow`) are not display text and
stay raw.
- File names & file contents stay locale-independent (ISO dates, English
"Imported" folder prefix? **No** — the auto-folder title uses the localized
word + ISO date, e.g. `Đã nhập 2026-07-03`, key `import.folderName`).
@@ -109,6 +129,20 @@ export function setLocale(l: Locale) { locale = l; } // settings store persists
a tiny helper selects by locale. VI/JA have one grammatical form, so they set
`one` and `other` to the same string. They must still carry both keys, or the
`satisfies Dict` shape check that §2 relies on for completeness fails.
Implemented as `selectPluralForm(count, tag)` in `i18n/format.ts` (backed by
`Intl.PluralRules`, narrowed to the two forms — en yields `one`/`other`, vi
and ja only ever `other`, so two forms cover every locale we ship) and
`tPlural(path, count, params?)` in `index.svelte.ts`, which supplies `{n}`
already grouped for the locale so callers pass a raw count. Two tests in
`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.
- 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
+10 -1
View File
@@ -130,8 +130,17 @@ generate-huge.ts # script: emits 100k+1 node file on demand
panel bulk-keep-first.
- [ ] Keyboard-only pass of the tree (WAI-ARIA pattern) + dialogs.
- [ ] Language switch EN→VI→JA live-updates all tabs; dates/numbers
localized; restart persists.
localized; restart persists. Header switcher and the `#settings` row
agree at all times (one state, two views).
- [ ] Theme: system/light/dark; contrast spot-check.
- [ ] 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.
- [ ] Legal Gate "Close tab" either closes the tab or shows the
manual-close message — never appears to do nothing.
- [ ] Two Manager tabs open: accepting or changing a setting in one is
reflected in the other (or record it as the known limitation it is —
`15` decision log).
- [ ] chrome://extensions → no errors logged during the whole pass.
- [ ] Edge (or Brave): smoke test install + import/export.
+49 -4
View File
@@ -16,19 +16,45 @@ Build-phase breakdown lives in `CLAUDE.md` (single source for sequencing).
| 1 — Core library | ✔ 2026-07-25 | 3 parsers, 4 serializers, dedupe/diff/plan; 600 seeded round-trips |
| 2 — Browser layer + #import | ✔ 2026-07-25 | adapter, write queue, stores, full import flow incl. forced backup |
| 3 — #export + #edit | ✔ 2026-07-25 | tri-state picker, tree CRUD, search, duplicates, DnD + keyboard parity |
| 4 — i18n, theming, Settings, About, Legal Gate | next | dictionaries already exist in EN/VI/JA; the switcher UI does not |
| 5 — Hardening + release prep | pending | CI stubs per `12 §2`, CHANGELOG, README, full QA, `wxt zip` clean install |
| 4 — i18n, theming, Settings, About, Legal Gate | ✔ 2026-07-26 | switcher + theme controls, six-row `#settings`, `#about`, first-run gate; Intl retrofit; store-backed Toast |
| 5 — Hardening + release prep | next | CI stubs per `12 §2`, CHANGELOG, README, full QA, `wxt zip` clean install |
**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
`chrome.bookmarks` mock, because WXT's `fakeBrowser` stubs that API with
"not implemented" throws (`11 §4`).
Each of phases 1–3 was adversarially reviewed after implementation and each
review found real defects (7, 13 and 14 respectively) — several in the paths
**Phase 4 verified on a real browser 2026-07-26**, after the review fixes
landed. Covered: the Legal Gate (appears once, blocks the three routes, leaves
`#settings`/`#about` reachable pre-accept, re-renders in the language chosen
before accepting, and persists across a restart); EN→VI→JA live switching with
localized numbers and dates, and the header and `#settings` controls staying in
agreement; theme system/light/dark; settings surviving an immediate tab close —
the path the `$state`-proxy `DataCloneError` would have broken; and the Phase
2–3 import/export/edit flows still working after Phase 4 touched their tabs and
the settings store.
Each of phases 1–4 was adversarially reviewed after implementation and each
review found real defects (7, 13 and 14 in phases 1–3) — several in the paths
that delete bookmarks. Budget that review into the remaining phases; a green
test run has not once meant "done" on this project.
Phase 4's own review filed 33 findings across six lenses; 19 survived
adversarial verification. The most serious was a first-run dead-end: the gate
rendered only on the three routes it blocked, and those three tabs were the
only in-app navigation to them — so a user who reached `#settings` (via the
popup's new gear, which opens a fresh tab with no history) could never get
back to the accept UI.
Phase 4 also found three latent defects in code that 338 green tests had
already signed off, all unreachable until Phase 4 gave them a caller:
`writeSettings` handed a `$state` proxy to `chrome.storage.local.set` (would
throw `DataCloneError` in a real browser — `fakeBrowser` stores the reference
without cloning, so the suite could not see it); `updateSettings` replaced the
settings object rather than mutating it, which would strand any component that
captured it; and footer navigation during `attesting` stranded the import's
attestation resolver, deadlocking it until reload.
## v1.0.x — stabilization
- Parser-tolerance fixes from real user files (fixture + test per report).
@@ -93,3 +119,22 @@ test run has not once meant "done" on this project.
| 2026-07-25 | CI: ops repo has no `browser-extension-*` family; callers use `reusable-chrome-extension.yml` + a local quality job, release is standalone | 12 §2 |
| 2026-07-25 | Replace deletes nothing until the backup is **proven** — picker `close()` resolving, or an explicit user attestation on the anchor fallback | 03 §1 6b |
| 2026-07-25 | Every `#edit` mutation resyncs from the browser on rejection; roots and `unmodifiable` nodes offer no destructive affordance at all | 03 §3 |
| 2026-07-26 | Legal Gate renders **inside the content region**, not as a viewport overlay — `06 §3`'s "full overlay" reconciled in favour of `14 §2`'s reachable `#settings`/`#about` | 06 §3 |
| 2026-07-26 | Settings state mutates **in place**; every storage write passes a plain snapshot (a `$state` proxy is not structured-cloneable, so the old code would have thrown `DataCloneError` in a real browser) | 03 §4 |
| 2026-07-26 | `updateSettings` / `acceptLegal` return non-rejecting outcomes; UI feedback follows the write, never precedes it | 03 §4 |
| 2026-07-26 | Toast queue + timers live in a store, so they survive the route chain unmounting | 06 §4 |
| 2026-07-26 | Static outbound links use `<a target="_blank" rel="noopener noreferrer">`; imported bookmark URLs keep `tabs.create` (`09` T3 unchanged). Two mechanisms for two trust classes — do not harmonize | 09 T3 |
| 2026-07-26 | `#settings` has **six** rows: `markdownStyle` was persisted but only editable as a transient `#export` control | 06 §3.4 |
| 2026-07-26 | `locale: 'auto'` is a first-class fourth option in the switcher — it is the default, so it must be selectable | 06 §3.4 |
| 2026-07-26 | Language labels are endonyms, duplicated identically across the three dicts (the `common.appName` precedent) | 07 §4 |
| 2026-07-26 | Theme control is a three-way segmented control in both header and `#settings`, not a cycling `◐` | 06 §3 |
| 2026-07-26 | Version comes from the manifest at runtime; three hardcoded `0.1.0` literals removed (footer, `run-export`, `run-import`) | 06 §3.5 |
| 2026-07-26 | About's "Changelog" points at GitHub Releases until `CHANGELOG.md` exists in Phase 5 | 06 §3.5 |
| 2026-07-26 | The gate's acceptance checkbox deliberately resets if the user navigates away and back — an un-submitted legal affirmation is not worth persisting | 14 §2 |
| 2026-07-26 | Both entrypoints await settings (Manager also legal) **before** `mount()`, trading a blank frame for no locale/theme/gate flicker | 02 §2 |
| 2026-07-26 | **Known limitation:** two open Manager tabs do not sync settings or acceptance to each other; last write wins. No `storage.onChanged` listener in v1 | 03 §4 |
| 2026-07-26 | Gate-blocked tabs stay **clickable**; what blocks a route is the gate replacing the tab body, not an inert button. Disabling them removed the only in-app path back to the accept UI | 06 §3 |
| 2026-07-26 | Failure UI shows the localized sentence and puts the raw browser error in a separate detail block — `detail ?? t(key)` made every translation dead code | 02 §7 |
| 2026-07-26 | `--accent-fg` is redefined in the dark blocks alongside `--accent`; white on the lightened violet measured 3.67:1 | 06 §5 |
| 2026-07-26 | Plural keys implemented per `07 §5` (`selectPluralForm` + `tPlural`); `import.warnings.title` and all seven `warnings.*` codes converted | 07 §5 |
| 2026-07-26 | The import session stores an i18n **key**, not a resolved string — `t()` is only reactive where it is called, so a stored sentence never follows a language switch | 03 §5 |
+1 -1
View File
@@ -41,5 +41,5 @@ inside the Extension.
## Contact
⚠️ contact email — or open an issue at
Email: contact@poli0981.dev — or open an issue at
<https://github.com/poli0981/bookmarkmagic/issues>
+98 -15
View File
@@ -1,17 +1,38 @@
<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';
import ImportTab from '@/lib/components/ImportTab.svelte';
import LanguageSwitcher from '@/lib/components/LanguageSwitcher.svelte';
import LegalGate from '@/lib/components/LegalGate.svelte';
import SettingsTab from '@/lib/components/SettingsTab.svelte';
import TabBar from '@/lib/components/TabBar.svelte';
import ThemeToggle from '@/lib/components/ThemeToggle.svelte';
import Toast from '@/lib/components/Toast.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 { loadSettings } from '@/lib/stores/settings.svelte';
import { flushSettings, getSettings, updateSettings } from '@/lib/stores/settings.svelte';
import { pushToast } from '@/lib/stores/toast.svelte';
// 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();
onMount(() => {
void loadSettings();
const stopRouting = startRouting();
// Leaving mid-write would kill the queue with the tab (docs/03 §5).
@@ -19,13 +40,37 @@
if (!isWriting()) return;
event.preventDefault();
};
// Fires on tab close, navigation and backgrounding — unlike beforeunload it
// cannot be cancelled, so it is the right place to shorten the 200 ms
// window in which a just-changed setting is still unwritten.
const onVisibilityChange = (): void => {
if (globalThis.document?.visibilityState === 'hidden') void flushSettings();
};
globalThis.addEventListener('beforeunload', onBeforeUnload);
globalThis.document?.addEventListener('visibilitychange', onVisibilityChange);
return () => {
stopRouting();
globalThis.removeEventListener('beforeunload', onBeforeUnload);
globalThis.document?.removeEventListener('visibilitychange', onVisibilityChange);
};
});
/**
* Shared by the header controls so a silent failure there is impossible.
*
* The toast carries the LOCALIZED sentence, never the raw browser error —
* `detail` is essentially always present for a storage rejection, so putting
* it first made every translation of settings.saveFailed unreachable. The
* header has no room for a detail block; #settings shows one.
*/
function save(patch: Parameters<typeof updateSettings>[0]): void {
void updateSettings(patch).then((outcome) => {
pushToast(t(outcome.ok ? 'settings.saved' : 'settings.saveFailed'), outcome.ok ? 'success' : 'danger');
});
}
</script>
<header>
@@ -33,27 +78,58 @@
<span class="mark" aria-hidden="true">◆</span>
<strong>{t('common.appName')}</strong>
</div>
<TabBar />
<TabBar blocked={getBlockedRoutes()} />
<div class="controls">
<LanguageSwitcher compact value={settings.locale} onchange={(locale) => save({ locale })} />
<ThemeToggle compact value={settings.theme} onchange={(theme) => save({ theme })} />
</div>
</header>
<main>
{#if getRoute() === 'import'}
<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. -->
<LegalGate status={legal} onaccepted={() => mainEl?.focus()} />
{:else if getRoute() === 'import'}
<ImportTab />
{:else if getRoute() === 'export'}
<ExportTab />
{:else if getRoute() === 'edit'}
<EditTab />
{:else if getRoute() === 'settings'}
<SettingsTab />
{:else}
<!-- Phases 3-4 fill these in; the routes exist now so the shell is real. -->
<p class="placeholder">{t('common.comingSoon', { tab: t(`common.${getRoute()}`) })}</p>
<AboutTab />
{/if}
</main>
<footer>
<span>v0.1.0 · GPL-3.0</span>
<span>
{#if version !== ''}v{version} · {/if}GPL-3.0 ·
<a href={REPO_URL} target="_blank" rel="noopener noreferrer">GitHub ↗</a>
</span>
<nav>
<button onclick={() => navigate('settings')}>{t('common.settings')}</button>
<button onclick={() => navigate('about')}>{t('common.about')}</button>
<!-- 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>
@@ -89,6 +165,12 @@
gap: var(--sp-2);
}
.controls {
display: flex;
align-items: center;
gap: var(--sp-2);
}
.mark {
color: var(--accent);
}
@@ -100,10 +182,6 @@
min-height: 60vh;
}
.placeholder {
color: var(--fg-muted);
}
footer nav {
display: flex;
gap: var(--sp-3);
@@ -118,7 +196,12 @@
padding: 0;
}
footer button:hover {
footer button:hover:not(:disabled) {
color: var(--accent);
}
footer button:disabled {
opacity: 0.4;
cursor: not-allowed;
}
</style>
+15 -7
View File
@@ -1,16 +1,24 @@
import { mount } from 'svelte';
import { browser } from 'wxt/browser';
import { setLocale } from '@/lib/i18n/index.svelte';
import { resolveLocale } from '@/lib/i18n/resolve-locale';
import { loadLegal } from '@/lib/stores/legal.svelte';
import { loadSettings } from '@/lib/stores/settings.svelte';
import '@/styles/base.css';
import App from './App.svelte';
// Phase 0: browser UI language only. Phase 4 hydrates from the persisted
// Settings value first, falling back to this (docs/07 §2).
setLocale(resolveLocale(browser.i18n.getUILanguage()));
// 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;
// Both reads happen BEFORE the first render, on purpose. The alternative --
// mount, then hydrate -- paints one frame in the browser's UI language and the
// system theme, then flips to the persisted ones, and flashes the legal gate at
// users who accepted it long ago. Awaiting means that frame holds an empty #app
// instead: a blank moment rather than visible EN->VI, light->dark or gate
// flicker.
//
// Neither loader can throw: readSettings and readLegal both swallow storage
// failures (browser/storage.ts) and applyLocale guards the i18n lookup. No
// timeout race either — storage.local.get always settles, and racing it would
// just re-introduce the wrong-locale render this exists to prevent.
await Promise.all([loadSettings(), loadLegal()]);
export default mount(App, { target });
+43 -5
View File
@@ -1,14 +1,15 @@
<script lang="ts">
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 { loadSettings } from '@/lib/stores/settings.svelte';
let counts = $state<{ bookmarks: number; folders: number } | undefined>();
const version = getAppVersion();
// Settings are loaded and awaited in main.ts, before this ever mounts.
onMount(() => {
void loadSettings();
void countTree();
});
@@ -39,6 +40,7 @@
<header>
<span class="mark" aria-hidden="true">◆</span>
<strong>{t('common.appName')}</strong>
{#if version !== ''}<span class="version">v{version}</span>{/if}
</header>
<div class="actions">
@@ -48,9 +50,19 @@
</div>
<footer>
{#if counts !== undefined}
{t('popup.counts', { bookmarks: num(counts.bookmarks), folders: num(counts.folders) })}
{/if}
<span>
{#if counts !== undefined}
{t('popup.counts', { bookmarks: num(counts.bookmarks), folders: num(counts.folders) })}
{/if}
</span>
<button
class="settings"
aria-label={t('common.settings')}
title={t('common.settings')}
onclick={() => void openManager('#settings')}
>
⚙
</button>
</footer>
</main>
@@ -95,10 +107,36 @@
}
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;
}
.version {
margin-left: auto;
color: var(--fg-muted);
font-size: var(--fs-0);
font-variant-numeric: tabular-nums;
}
.settings {
font: inherit;
flex-shrink: 0;
padding: 0 var(--sp-1);
border: none;
background: none;
color: var(--fg-muted);
cursor: pointer;
font-size: var(--fs-2);
}
.settings:hover {
color: var(--accent);
}
</style>
+6 -7
View File
@@ -1,16 +1,15 @@
import { mount } from 'svelte';
import { browser } from 'wxt/browser';
import { setLocale } from '@/lib/i18n/index.svelte';
import { resolveLocale } from '@/lib/i18n/resolve-locale';
import { loadSettings } from '@/lib/stores/settings.svelte';
import '@/styles/base.css';
import App from './App.svelte';
// Phase 0: browser UI language only. Phase 4 hydrates from the persisted
// Settings value first, falling back to this (docs/07 §2).
setLocale(resolveLocale(browser.i18n.getUILanguage()));
// 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;
// Awaited before mount for the same reason as the Manager: the popup is small
// and fast, so a locale or theme flip here is proportionally more visible.
// The popup is never gated (docs/14 §2), so there is no legal read to make.
await loadSettings();
export default mount(App, { target });
+39
View File
@@ -0,0 +1,39 @@
/**
* Runtime metadata about the built extension.
*
* Purpose: the ONE place the displayed version comes from (docs/06 §3.5). It
* used to be hardcoded in three files, which is three chances to ship a
* number that disagrees with the manifest.
* Inputs: none — reads the packaged manifest.
* Guarantees: synchronous, so there is no version race and no loading state;
* never throws.
*/
import { browser } from 'wxt/browser';
/**
* The manifest version, or `''` when it cannot be read.
*
* Empty rather than a plausible fallback like `'0.0.0'`: callers hide the line
* entirely, and no version at all is better than a wrong one in a footer users
* quote in bug reports.
*/
export function getAppVersion(): string {
try {
return browser.runtime.getManifest().version;
} catch {
return '';
}
}
/**
* The `generator` string written into exported and backup BM JSON.
*
* Separate from `getAppVersion` because the UI and a file want different
* fallbacks: the UI hides an unknown version, but a file field cannot be
* hidden, and `"BookmarkMagic "` with a trailing space is a worse artifact
* than the bare product name.
*/
export function getGeneratorVersion(): string {
const version = getAppVersion();
return version === '' ? 'unknown' : version;
}
+128
View File
@@ -0,0 +1,128 @@
<script lang="ts">
import { getAppVersion } from '../browser/app-info';
import { dateTime, t } from '../i18n/index.svelte';
import { CHANGELOG_URL, DONATE_LINKS, ISSUES_URL, LEGAL_URLS, REPO_URL } from '../links';
import { getAcceptance } from '../stores/legal.svelte';
const version = getAppVersion();
const acceptance = $derived(getAcceptance());
// undefined when acceptedAt is missing or unparseable — storage coerces a
// missing timestamp to '', and formatting that would throw inside the render.
const acceptedOn = $derived(
acceptance === undefined ? undefined : dateTime(acceptance.acceptedAt),
);
</script>
<section aria-label={t('common.about')}>
<header>
<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}
</div>
</header>
<p class="tagline">{t('about.tagline')}</p>
<h2>{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={CHANGELOG_URL} target="_blank" rel="noopener noreferrer">
{t('about.changelog')} ↗
</a>
</li>
</ul>
<h2>{t('about.thirdParty')}</h2>
<p class="muted">{t('about.thirdPartyNote')}</p>
<h2>{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>
{/each}
</ul>
<h2>{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>
</li>
{/each}
</ul>
<p class="muted">{t('legal.englishNote')}</p>
<p class="muted">
<!-- The version the user ACCEPTED, not LEGAL_VERSION: if they differ the
gate is up anyway, and showing the current constant here would claim
consent that was never given (docs/06 §3.5). -->
{#if acceptance === undefined}
{t('about.notAccepted')}
{:else if acceptedOn === undefined}
{t('about.acceptedUndated', { version: acceptance.acceptedVersion })}
{:else}
{t('about.accepted', {
date: acceptedOn,
version: acceptance.acceptedVersion,
})}
{/if}
</p>
</section>
<style>
section {
max-width: 640px;
}
header {
display: flex;
align-items: center;
gap: var(--sp-3);
padding-bottom: var(--sp-3);
border-bottom: 1px solid var(--border);
}
header div {
display: flex;
flex-direction: column;
}
header strong {
font-size: var(--fs-3);
}
.version {
font-size: var(--fs-0);
color: var(--fg-muted);
font-variant-numeric: tabular-nums;
}
.tagline {
color: var(--fg-muted);
font-size: var(--fs-1);
}
h2 {
margin: var(--sp-5) 0 var(--sp-2);
font-size: var(--fs-2);
}
.muted {
margin: 0;
color: var(--fg-muted);
font-size: var(--fs-1);
}
.links {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2) var(--sp-4);
margin: var(--sp-2) 0 0;
padding: 0;
list-style: none;
font-size: var(--fs-1);
}
</style>
+19 -6
View File
@@ -7,6 +7,11 @@
import type { MarkdownStyle } from '../core/serialize/markdown';
import { countSelected, FORMAT_META, runExport } from '../export/run-export';
import { num, t } from '../i18n/index.svelte';
import {
CSV_DELIMITER_CHOICES,
MARKDOWN_STYLE_CHOICES,
parseChoice,
} from '../settings/options';
import { getSettings } from '../stores/settings.svelte';
import { pushToast } from '../stores/toast.svelte';
import Button from './Button.svelte';
@@ -85,10 +90,14 @@
<span>{t('export.csvDelimiter')}</span>
<select
value={csvDelimiter}
onchange={(e) => (csvDelimiter = (e.currentTarget as HTMLSelectElement).value as CsvDelimiter)}
onchange={(e) => {
const next = parseChoice(e.currentTarget.value, CSV_DELIMITER_CHOICES);
if (next !== undefined) csvDelimiter = next;
}}
>
<option value=",">{t('export.comma')}</option>
<option value=";">{t('export.semicolon')}</option>
{#each CSV_DELIMITER_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
</label>
{/if}
@@ -98,10 +107,14 @@
<span>{t('export.markdownStyle')}</span>
<select
value={markdownStyle}
onchange={(e) => (markdownStyle = (e.currentTarget as HTMLSelectElement).value as MarkdownStyle)}
onchange={(e) => {
const next = parseChoice(e.currentTarget.value, MARKDOWN_STYLE_CHOICES);
if (next !== undefined) markdownStyle = next;
}}
>
<option value="nested">{t('export.nested')}</option>
<option value="flat">{t('export.flat')}</option>
{#each MARKDOWN_STYLE_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
</label>
{/if}
+2 -2
View File
@@ -1,7 +1,7 @@
<script lang="ts">
import type { LiveNode } from '../browser/bookmarks';
import type { CheckState } from '../core/select';
import { t } from '../i18n/index.svelte';
import { num, t } from '../i18n/index.svelte';
import Self from './FolderPickNode.svelte';
interface Props {
@@ -53,7 +53,7 @@
onchange={(e) => ontoggle(node, (e.currentTarget as HTMLInputElement).checked)}
/>
<span class="title">{node.title}</span>
{#if bookmarks > 0}<span class="count">{bookmarks}</span>{/if}
{#if bookmarks > 0}<span class="count">{num(bookmarks)}</span>{/if}
</label>
</div>
+16 -7
View File
@@ -41,17 +41,26 @@
attestResolve = undefined;
}
function describeError(err: unknown): { message: string; detail: string | undefined } {
/**
* Map an error onto an i18n KEY plus a raw detail — never a resolved string.
* The session store outlives this component, and `t()` only re-runs where it
* is called, so a translated sentence stored here would never follow a
* language switch.
*/
function describeError(err: unknown): { messageKey: string; detail: string | undefined } {
if (err instanceof BmParseError) {
return { message: t(`errors.${err.code}`), detail: err.detail };
return { messageKey: `errors.${err.code}`, detail: err.detail };
}
if (err instanceof BmBackupError) {
return { message: t(`errors.${err.code}`), detail: err.message };
return { messageKey: `errors.${err.code}`, detail: err.message };
}
if (err instanceof BmBrowserError) {
return { message: t('errors.BROWSER'), detail: err.detail };
return { messageKey: 'errors.BROWSER', detail: err.detail };
}
return { message: t('errors.UNKNOWN'), detail: err instanceof Error ? err.message : undefined };
return {
messageKey: 'errors.UNKNOWN',
detail: err instanceof Error ? err.message : undefined,
};
}
async function onFile(file: File): Promise<void> {
@@ -143,7 +152,7 @@
<p class="muted">{t('import.reading', { name: session.filename })}</p>
{:else if session.kind === 'parsed'}
<div class="split">
<section aria-label="Preview">
<section aria-label={t('import.preview')}>
<TreePreview roots={session.result.roots} status={prepared?.status ?? new WeakMap()} />
</section>
<section class="side">
@@ -209,7 +218,7 @@
onclick={resetImport}>{t('import.another')}</Button
>
{:else if session.kind === 'error'}
<Callout tone="danger">{session.message}</Callout>
<Callout tone="danger">{t(session.messageKey)}</Callout>
{#if session.detail !== undefined}
<pre class="detail">{session.detail}</pre>
{/if}
@@ -0,0 +1,70 @@
<script lang="ts">
import { t } from '../i18n/index.svelte';
import type { Locale } from '../i18n/resolve-locale';
import { LOCALE_CHOICES, parseChoice } from '../settings/options';
interface Props {
/**
* The stored *preference*, which includes `'auto'` — never `getLocale()`.
* Binding this to the resolved locale would make choosing "Automatic" snap
* the control straight to "English".
*/
value: Locale | 'auto';
onchange: (next: Locale | 'auto') => void;
/** Header variant: hides the visible label, keeps the accessible one. */
compact?: boolean;
}
let { value, onchange, compact = false }: Props = $props();
function select(raw: string): void {
const next = parseChoice(raw, LOCALE_CHOICES);
if (next === undefined) return;
onchange(next);
}
</script>
<label class:compact>
<span class="label">{t('settings.language')}</span>
<select
aria-label={compact ? t('settings.language') : undefined}
{value}
onchange={(event) => select(event.currentTarget.value)}
>
{#each LOCALE_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
</label>
<style>
label {
display: flex;
align-items: center;
gap: var(--sp-2);
font-size: var(--fs-1);
}
.compact .label {
/* Visually hidden, still read aloud and still the select's accessible name. */
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
select {
font: inherit;
padding: var(--sp-1) var(--sp-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg);
color: var(--fg);
}
select:hover {
border-color: var(--accent);
}
</style>
+201
View File
@@ -0,0 +1,201 @@
<script lang="ts">
import { t } from '../i18n/index.svelte';
import { LEGAL_URLS } from '../links';
import { acceptLegal, type LegalStatus } from '../stores/legal.svelte';
import Button from './Button.svelte';
import Callout from './Callout.svelte';
interface Props {
status: Extract<LegalStatus, { kind: 'required' }>;
/** Lets the shell move focus into the tab that mounts underneath. */
onaccepted: () => void;
}
let { status, onaccepted }: Props = $props();
/** How long to wait for `close()` before admitting it did nothing. */
const CLOSE_GRACE_MS = 150;
let checked = $state(false);
let saving = $state(false);
let saveFailed = $state(false);
let saveDetail = $state<string | undefined>();
let closeFailed = $state(false);
let heading: HTMLHeadingElement | undefined = $state();
let closeTimer: ReturnType<typeof setTimeout> | undefined;
// Replacing <main>'s content without moving focus leaves a screen-reader user
// reading the page they navigated away from (docs/06 §5).
$effect(() => {
heading?.focus();
return () => {
if (closeTimer !== undefined) clearTimeout(closeTimer);
};
});
function accept(): void {
if (!checked || saving) return;
saving = true;
saveFailed = false;
saveDetail = undefined;
// Timestamp taken at click time and passed down, so the store stays free of
// ambient time. Nothing is dismissed until the write resolves.
void acceptLegal(new Date().toISOString()).then((outcome) => {
saving = false;
if (outcome.ok) {
onaccepted();
return;
}
// The localized recovery sentence is the message; the raw browser error
// is the separate technical detail (docs/02 §7). Showing `detail` in its
// place made legal.saveFailed dead in all three locales — at the one
// moment a first-run user most needs an actionable instruction.
saveFailed = true;
saveDetail = outcome.detail;
});
}
/**
* Decline is "close the tab" (docs/14 §2) — nothing is written either way.
*
* The Manager is opened by `tabs.create` or by Chrome's options mechanism, so
* `window.opener` is null and close() is not guaranteed to work. Rather than
* bet the decline path on it, wait a beat and tell the user plainly if the
* document is still here. `tabs.remove` is not an option: it needs the `tabs`
* permission, which docs/08 §2 forbids.
*/
function closeTab(): void {
// Clear first: repeated clicks would otherwise stack timers, and only the
// last one would ever be cleaned up.
if (closeTimer !== undefined) clearTimeout(closeTimer);
globalThis.close();
closeTimer = setTimeout(() => {
closeTimer = undefined;
closeFailed = true;
}, CLOSE_GRACE_MS);
}
</script>
<section class="gate" aria-labelledby="legal-gate-title">
<header>
<img src="/icon/48.png" alt="" width="48" height="48" />
<h1 id="legal-gate-title" bind:this={heading} tabindex="-1">
{status.reason === 'updated' ? t('legal.updatedTitle') : t('legal.title')}
</h1>
</header>
{#if status.reason === 'updated'}
<Callout tone="warn">{t('legal.updatedBody')}</Callout>
{/if}
<p class="summary">{t('legal.summary')}</p>
<h2>{t('legal.documents')}</h2>
<ul>
{#each LEGAL_URLS as link (link.url)}
<li>
<a href={link.url} target="_blank" rel="noopener noreferrer">{t(link.labelKey)} ↗</a>
</li>
{/each}
</ul>
<p class="note">{t('legal.englishNote')}</p>
<label class="accept">
<input type="checkbox" bind:checked disabled={saving} />
<span>{t('legal.accept')}</span>
</label>
{#if saveFailed}
<Callout tone="danger">{t('legal.saveFailed')}</Callout>
{#if saveDetail !== undefined}
<pre class="detail">{saveDetail}</pre>
{/if}
{/if}
<div class="actions">
<Button variant="primary" disabled={!checked || saving} onclick={accept}>
{t('legal.continue')}
</Button>
<Button disabled={saving} onclick={closeTab}>{t('legal.close')}</Button>
</div>
{#if closeFailed}
<p class="note">{t('legal.closeManually')}</p>
{/if}
</section>
<style>
.gate {
display: flex;
flex-direction: column;
gap: var(--sp-3);
max-width: 56ch;
margin: 0 auto;
padding: var(--sp-5);
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--bg-raised);
}
header {
display: flex;
align-items: center;
gap: var(--sp-3);
}
h1 {
margin: 0;
font-size: var(--fs-4);
}
h2 {
margin: var(--sp-2) 0 0;
font-size: var(--fs-2);
}
.summary {
margin: 0;
font-size: var(--fs-1);
}
ul {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2) var(--sp-4);
margin: 0;
padding: 0;
list-style: none;
font-size: var(--fs-1);
}
.note {
margin: 0;
color: var(--fg-muted);
font-size: var(--fs-0);
}
.accept {
display: flex;
align-items: center;
gap: var(--sp-2);
margin-top: var(--sp-2);
font-size: var(--fs-1);
}
.detail {
margin: 0;
padding: var(--sp-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg);
color: var(--fg-muted);
font-size: var(--fs-0);
white-space: pre-wrap;
overflow-x: auto;
}
.actions {
display: flex;
gap: var(--sp-2);
}
</style>
+58
View File
@@ -0,0 +1,58 @@
<script lang="ts">
import type { Snippet } from 'svelte';
interface Props {
label: string;
/** Explicit `| undefined` — exactOptionalPropertyTypes rejects the short form. */
description?: string | undefined;
control: Snippet;
}
let { label, description, control }: Props = $props();
</script>
<div class="row">
<div class="text">
<span class="label">{label}</span>
{#if description !== undefined}<span class="description">{description}</span>{/if}
</div>
<div class="control">{@render control()}</div>
</div>
<style>
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-4);
padding: var(--sp-3) 0;
border-bottom: 1px solid var(--border);
}
.text {
display: flex;
flex-direction: column;
gap: var(--sp-1);
}
.label {
font-size: var(--fs-2);
}
.description {
font-size: var(--fs-0);
color: var(--fg-muted);
}
.control {
flex-shrink: 0;
}
@media (max-width: 560px) {
.row {
flex-direction: column;
align-items: stretch;
gap: var(--sp-2);
}
}
</style>
+216
View File
@@ -0,0 +1,216 @@
<script lang="ts">
import type { Settings } from '../browser/storage';
import { t } from '../i18n/index.svelte';
import {
CSV_DELIMITER_CHOICES,
EXPORT_FORMAT_CHOICES,
IMPORT_MODE_CHOICES,
MARKDOWN_STYLE_CHOICES,
parseChoice,
type SettingChoice,
} from '../settings/options';
import { getSettings, resetSettings, updateSettings } from '../stores/settings.svelte';
import { pushToast } from '../stores/toast.svelte';
import Button from './Button.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
import LanguageSwitcher from './LanguageSwitcher.svelte';
import SettingRow from './SettingRow.svelte';
import ThemeToggle from './ThemeToggle.svelte';
const settings = $derived(getSettings());
let confirmingReset = $state(false);
/** Raw browser error behind the last failed save, if any. */
let saveDetail = $state<string | undefined>();
/**
* Every write reports what actually happened. The toast used to be the only
* feedback and fired before the write settled, which meant a failed save
* still said "Saved".
*/
function save(patch: Partial<Settings>, successKey = 'settings.saved'): void {
void updateSettings(patch).then((outcome) => {
if (outcome.ok) {
pushToast(t(successKey), 'success');
saveDetail = undefined;
return;
}
// The LOCALIZED sentence is the message; the raw browser error is the
// separate technical detail docs/02 §7 asks for. Putting `detail` first
// made every translation of settings.saveFailed dead code and showed a
// VI/JA user an untranslated Chrome string.
pushToast(t('settings.saveFailed'), 'danger');
saveDetail = outcome.detail;
});
}
/** Narrow a `<select>` value, then save — bailing before the patch is built. */
function saveChoice<K extends keyof Settings & string>(
key: K,
raw: string,
choices: readonly SettingChoice<Settings[K] & string>[],
): void {
const next = parseChoice(raw, choices);
if (next === undefined) return;
// SAFETY: `next` came out of a table typed against Settings[K], so this
// narrowing only re-states what parseChoice already proved.
save({ [key]: next } as Partial<Settings>);
}
function confirmReset(): void {
confirmingReset = false;
void resetSettings().then((outcome) => {
if (outcome.ok) {
pushToast(t('settings.resetDone'), 'success');
saveDetail = undefined;
return;
}
pushToast(t('settings.saveFailed'), 'danger');
saveDetail = outcome.detail;
});
}
</script>
<section aria-label={t('common.settings')}>
<p class="muted">{t('settings.autosave')}</p>
<SettingRow label={t('settings.language')} description={t('settings.languageNote')}>
{#snippet control()}
<LanguageSwitcher
compact
value={settings.locale}
onchange={(locale) => save({ locale })}
/>
{/snippet}
</SettingRow>
<SettingRow label={t('settings.theme')}>
{#snippet control()}
<ThemeToggle value={settings.theme} onchange={(theme) => save({ theme })} />
{/snippet}
</SettingRow>
<SettingRow
label={t('settings.defaultExportFormat')}
description={t('settings.defaultExportFormatNote')}
>
{#snippet control()}
<select
aria-label={t('settings.defaultExportFormat')}
value={settings.defaultExportFormat}
onchange={(event) =>
saveChoice('defaultExportFormat', event.currentTarget.value, EXPORT_FORMAT_CHOICES)}
>
{#each EXPORT_FORMAT_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
{/snippet}
</SettingRow>
<SettingRow
label={t('settings.defaultImportMode')}
description={t('settings.defaultImportModeNote')}
>
{#snippet control()}
<select
aria-label={t('settings.defaultImportMode')}
value={settings.defaultMergeMode}
onchange={(event) =>
saveChoice('defaultMergeMode', event.currentTarget.value, IMPORT_MODE_CHOICES)}
>
{#each IMPORT_MODE_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
{/snippet}
</SettingRow>
<SettingRow label={t('settings.csvDelimiter')} description={t('settings.csvDelimiterNote')}>
{#snippet control()}
<select
aria-label={t('settings.csvDelimiter')}
value={settings.csvDelimiter}
onchange={(event) =>
saveChoice('csvDelimiter', event.currentTarget.value, CSV_DELIMITER_CHOICES)}
>
{#each CSV_DELIMITER_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
{/snippet}
</SettingRow>
<SettingRow label={t('settings.markdownStyle')} description={t('settings.markdownStyleNote')}>
{#snippet control()}
<select
aria-label={t('settings.markdownStyle')}
value={settings.markdownStyle}
onchange={(event) =>
saveChoice('markdownStyle', event.currentTarget.value, MARKDOWN_STYLE_CHOICES)}
>
{#each MARKDOWN_STYLE_CHOICES as choice (choice.value)}
<option value={choice.value}>{t(choice.labelKey)}</option>
{/each}
</select>
{/snippet}
</SettingRow>
{#if saveDetail !== undefined}
<pre class="detail">{saveDetail}</pre>
{/if}
<footer>
<Button onclick={() => (confirmingReset = true)}>{t('settings.reset')}</Button>
</footer>
</section>
<ConfirmDialog
open={confirmingReset}
title={t('settings.resetTitle')}
body={t('settings.resetBody')}
confirmLabel={t('settings.resetConfirm')}
cancelLabel={t('common.cancel')}
onconfirm={confirmReset}
oncancel={() => (confirmingReset = false)}
/>
<style>
section {
max-width: 640px;
}
.muted {
margin: 0 0 var(--sp-3);
color: var(--fg-muted);
font-size: var(--fs-1);
}
select {
font: inherit;
padding: var(--sp-1) var(--sp-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg);
color: var(--fg);
}
select:hover {
border-color: var(--accent);
}
.detail {
margin: var(--sp-3) 0 0;
padding: var(--sp-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg-raised);
color: var(--fg-muted);
font-size: var(--fs-0);
white-space: pre-wrap;
overflow-x: auto;
}
footer {
padding-top: var(--sp-4);
}
</style>
+27 -4
View File
@@ -4,7 +4,15 @@
import { getRoute, navigate, type Route } from '../stores/route.svelte';
interface Props {
/** Routes the legal gate is currently blocking (docs/14 §2). */
/**
* Routes the legal gate is currently blocking (docs/14 §2).
*
* These stay CLICKABLE. What blocks them is App.svelte rendering the gate
* in place of the tab body, so the tab never mounts pre-acceptance. Making
* the buttons inert instead was a dead end: they are the only in-app
* navigation to a gated route, so a first-run user who reached #settings —
* the flow docs/14 §2 explicitly wants — had no way back to the accept UI.
*/
blocked?: readonly Route[];
}
@@ -17,13 +25,18 @@
];
</script>
<nav aria-label="Sections">
<nav aria-label={t('common.sections')}>
{#each TABS as tab (tab.route)}
<button
class:active={getRoute() === tab.route}
aria-current={getRoute() === tab.route ? 'page' : undefined}
disabled={blocked.includes(tab.route) || (isWriting() && getRoute() !== tab.route)}
title={isWriting() && getRoute() !== tab.route ? t('common.busy') : undefined}
class:locked={blocked.includes(tab.route)}
disabled={isWriting() && getRoute() !== tab.route}
title={blocked.includes(tab.route)
? t('legal.blocked')
: isWriting() && getRoute() !== tab.route
? t('common.busy')
: undefined}
onclick={() => navigate(tab.route)}
>
{t(tab.key)}
@@ -56,6 +69,16 @@
cursor: not-allowed;
}
/* Reachable, but visibly not yet usable — clicking shows the gate. */
.locked {
opacity: 0.65;
}
.locked::after {
content: ' 🔒';
font-size: var(--fs-0);
}
.active {
background: var(--bg-raised);
border-color: var(--border);
+134
View File
@@ -0,0 +1,134 @@
<script lang="ts">
import type { ThemePreference } from '../browser/storage';
import { t } from '../i18n/index.svelte';
import { THEME_CHOICES } from '../settings/options';
interface Props {
value: ThemePreference;
onchange: (next: ThemePreference) => void;
/** Header variant: glyphs instead of words, labels moved to aria-label. */
compact?: boolean;
}
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".
const GLYPH: Record<ThemePreference, string> = {
system: '◐',
light: '☀',
dark: '☾',
};
let buttons: HTMLButtonElement[] = $state([]);
/**
* The radiogroup keyboard pattern, which the ARIA roles above promise.
*
* Without this the roles are a lie: a screen reader announces "radio button,
* 1 of 3" and switches to forms mode, then the arrow keys do nothing and all
* three are separate tab stops — the inverse of the pattern (WCAG 4.1.2).
*
* Bound to each radio rather than the group, because only the radios are
* focusable — a keyboard handler on a non-focusable container never fires,
* which is exactly what svelte-check's `a11y_interactive_supports_focus`
* warns about.
*/
function onKeyDown(event: KeyboardEvent): void {
const index = THEME_CHOICES.findIndex((choice) => choice.value === value);
if (index === -1) return;
let next: number | undefined;
if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
next = (index + 1) % THEME_CHOICES.length;
} else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
next = (index - 1 + THEME_CHOICES.length) % THEME_CHOICES.length;
} else if (event.key === 'Home') {
next = 0;
} else if (event.key === 'End') {
next = THEME_CHOICES.length - 1;
}
if (next === undefined) return;
event.preventDefault();
const choice = THEME_CHOICES[next];
if (choice === undefined) return;
onchange(choice.value);
buttons[next]?.focus();
}
</script>
<div class="group" class:compact role="radiogroup" aria-label={t('settings.theme')}>
{#each THEME_CHOICES as choice, index (choice.value)}
<button
bind:this={buttons[index]}
type="button"
role="radio"
aria-checked={value === choice.value}
aria-label={compact ? t(choice.labelKey) : undefined}
tabindex={value === choice.value ? 0 : -1}
class:selected={value === choice.value}
onclick={() => onchange(choice.value)}
onkeydown={onKeyDown}
>
{#if compact}
<span aria-hidden="true">{GLYPH[choice.value]}</span>
{:else}
{t(choice.labelKey)}
{/if}
</button>
{/each}
</div>
<style>
/* No `overflow: hidden` here. It clipped the global :focus-visible ring,
which base.css draws at outline-offset: 2px — entirely outside the clip
region — leaving the theme control with no keyboard focus indicator at all.
The corner rounding it was for is done per-child instead. */
.group {
display: inline-flex;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
}
button {
font: inherit;
padding: var(--sp-1) var(--sp-3);
border: none;
border-right: 1px solid var(--border);
background: var(--bg);
color: var(--fg-muted);
cursor: pointer;
font-size: var(--fs-1);
}
button:first-child {
border-top-left-radius: var(--radius-sm);
border-bottom-left-radius: var(--radius-sm);
}
button:last-child {
border-right: none;
border-top-right-radius: var(--radius-sm);
border-bottom-right-radius: var(--radius-sm);
}
/* Inset so the ring stays inside the group's own border box. */
button:focus-visible {
outline-offset: -2px;
}
button:hover {
color: var(--fg);
}
.selected {
background: var(--accent);
color: var(--accent-fg);
}
.compact button {
padding: var(--sp-1) var(--sp-2);
}
</style>
+32 -4
View File
@@ -5,15 +5,43 @@
const toast = $derived(getVisibleToast());
</script>
<!-- Both live regions are ALWAYS in the DOM and only their text changes.
A live region inserted into the page already populated is not reliably
announced — screen readers derive announcements from mutations to a region
that was already present, so the earlier "whole thing inside {#if}" shape
meant success toasts were silently skipped.
Two fixed regions rather than one with a swapped aria-live, because
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>
{#if toast !== undefined}
<!-- role follows Callout's convention: an error interrupts, a status waits. -->
<div class="toast {toast.tone}" role={toast.tone === 'danger' ? 'alert' : 'status'}>
<span>{toast.message}</span>
<button aria-label={t('common.cancel')} onclick={() => dismissToast(toast.id)}>✕</button>
<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>
</div>
{/if}
<style>
.sr-only {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.toast {
position: fixed;
right: var(--sp-4);
+2 -1
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import type { BookmarkNode } from '../core/model';
import type { NodeStatus } from '../core/diff';
import { t } from '../i18n/index.svelte';
import TreePreviewNode from './TreePreviewNode.svelte';
interface Props {
@@ -13,7 +14,7 @@
<!-- 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="Preview">
<ul class="tree" role="tree" aria-label={t('import.preview')}>
{#each roots as node, i (i)}
<TreePreviewNode {node} {status} depth={1} />
{/each}
+3 -3
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { num, t } from '../i18n/index.svelte';
import { tPlural } from '../i18n/index.svelte';
import type { ParseWarning } from '../core/model';
interface Props {
@@ -11,10 +11,10 @@
{#if warnings.length > 0}
<details>
<summary>{t('import.warnings.title', { n: num(warnings.length) })}</summary>
<summary>{tPlural('import.warnings.title', warnings.length)}</summary>
<ul>
{#each warnings as warning (warning.code)}
<li>{t(`warnings.${warning.code}`, { n: num(warning.count) })}</li>
<li>{tPlural(`warnings.${warning.code}`, warning.count)}</li>
{/each}
</ul>
</details>
+3 -3
View File
@@ -6,6 +6,8 @@
* anchor path is enough here — unlike the Replace backup, a failed export
* loses nothing).
*/
import { getGeneratorVersion } from '../browser/app-info';
import { getRootChildren, getRoots, type LiveNode, toBookmarkNodes } from '../browser/bookmarks';
import { sanitizeFilename, timestampSuffix, triggerDownload } from '../browser/download';
import type { ExportFormat } from '../browser/storage';
@@ -15,8 +17,6 @@ import { type CsvDelimiter, serializeCsv } from '../core/serialize/csv';
import { type MarkdownStyle, serializeMarkdown } from '../core/serialize/markdown';
import { serializeNetscapeHtml } from '../core/serialize/netscape-html';
const APP_VERSION = '0.1.0';
export const FORMAT_META: Record<
ExportFormat,
{ extension: string; mimeType: string; importable: boolean }
@@ -117,7 +117,7 @@ function serialize(nodes: ReturnType<typeof toBookmarkNodes>, options: ExportOpt
return serializeNetscapeHtml(nodes);
case 'bm-json':
return serializeBmJson(nodes, {
version: APP_VERSION,
version: getGeneratorVersion(),
exportedAt: options.now.toISOString(),
});
case 'csv':
+21
View File
@@ -22,6 +22,27 @@ const TAGS: Record<Locale, LocaleTag> = {
// StatsCard alone formats four counts per paint — so cache per tag.
const numberFormats = new Map<LocaleTag, Intl.NumberFormat>();
const dateFormats = new Map<LocaleTag, Intl.DateTimeFormat>();
const pluralRules = new Map<LocaleTag, Intl.PluralRules>();
/** The two forms docs/07 §5 requires every plural key to carry. */
export type PluralForm = 'one' | 'other';
/**
* Pick a plural form for a count.
*
* Narrowed to `one`/`other` deliberately: `Intl.PluralRules` can return `zero`,
* `two`, `few` and `many` for other languages, but en yields only one/other and
* vi/ja only ever yield other — so the two-form dictionaries docs/07 §5
* specifies are sufficient for exactly the locales we ship.
*/
export function selectPluralForm(count: number, tag: LocaleTag): PluralForm {
let rules = pluralRules.get(tag);
if (rules === undefined) {
rules = new Intl.PluralRules(tag);
pluralRules.set(tag, rules);
}
return rules.select(count) === 'one' ? 'one' : 'other';
}
export function localeTag(locale: Locale): LocaleTag {
return TAGS[locale];
+28 -1
View File
@@ -1,4 +1,4 @@
import { formatCount, formatDateTime, localeTag } from './format';
import { formatCount, formatDateTime, localeTag, selectPluralForm } from './format';
import en from './locales/en';
import ja from './locales/ja';
import vi from './locales/vi';
@@ -48,6 +48,33 @@ export function dateTime(iso: string): string | undefined {
*/
export function t(path: string, params?: Record<string, string | number>): string {
const raw = lookup(dicts[locale], path) ?? lookup(dicts.en, path) ?? path;
return interpolate(raw, params);
}
/**
* Resolve a plural key — an object of `{ one, other }` per docs/07 §5.
*
* `{n}` is supplied automatically, already grouped for the locale, so callers
* pass the raw count and never have to format it themselves. VI and JA carry
* both forms with the same text (one grammatical form), which is what keeps the
* `satisfies Dict` shape check meaningful.
*/
export function tPlural(
path: string,
count: number,
params?: Record<string, string | number>,
): string {
const form = selectPluralForm(count, localeTag(locale));
const raw =
lookup(dicts[locale], `${path}.${form}`) ??
lookup(dicts[locale], `${path}.other`) ??
lookup(dicts.en, `${path}.${form}`) ??
lookup(dicts.en, `${path}.other`) ??
path;
return interpolate(raw, { n: num(count), ...params });
}
function interpolate(raw: string, params?: Record<string, string | number>): string {
if (params === undefined) return raw;
return raw.replace(/\{(\w+)\}/g, (match, token: string) =>
Object.hasOwn(params, token) ? String(params[token]) : match,
+41 -10
View File
@@ -21,7 +21,10 @@ const dict = {
about: 'About',
busy: 'An import is in progress',
cancel: 'Cancel',
comingSoon: '{tab} arrives in a later build.',
// Distinct from `cancel`: this only hides a notification about something
// that already finished — there is nothing left to call off.
dismiss: 'Dismiss',
sections: 'Sections',
},
popup: {
import: 'Import bookmarks…',
@@ -32,6 +35,7 @@ const dict = {
import: {
dropHint: 'Drop a bookmark file or click to browse — .html, .json, .csv · max {size}',
reading: 'Reading {name}…',
preview: 'Preview',
folderName: 'Imported {date}',
start: 'Import {n} bookmarks',
backingUp:
@@ -68,7 +72,8 @@ const dict = {
replace: 'Replace everything',
},
warnings: {
title: '{n} warning(s)',
// Plural keys are `{ one, other }` objects in EVERY locale (docs/07 §5).
title: { one: '{n} warning', other: '{n} warnings' },
},
},
export: {
@@ -196,15 +201,41 @@ const dict = {
'Your acceptance could not be saved, so nothing was recorded. Check that this browser allows extension storage, then try again.',
blocked: 'Accept the terms to use the Import, Export and Edit tabs.',
},
/**
* Every code is a plural key, including the two that interpolate no count —
* `ParseWarning` always carries one, so a uniform shape lets `WarningList`
* call `tPlural` unconditionally instead of maintaining a list of which
* codes count things.
*/
warnings: {
NO_BOOKMARKS: 'This file contains no bookmarks.',
DESCRIPTIONS_DROPPED:
'{n} description(s) were dropped — they have no place in the bookmark model.',
FAVICONS_IGNORED: '{n} favicon(s) ignored — the bookmarks API cannot set favicons.',
INVALID_DATE: '{n} unreadable date(s) were left blank.',
MISSING_URL: '{n} entries had no address and were skipped.',
NEWER_VERSION: 'This file was written by a newer version — reading it as best we can.',
EMPTY_TITLE: '{n} bookmark(s) had no title; their address is shown instead.',
NO_BOOKMARKS: {
one: 'This file contains no bookmarks.',
other: 'This file contains no bookmarks.',
},
DESCRIPTIONS_DROPPED: {
one: '{n} description was dropped — it has no place in the bookmark model.',
other: '{n} descriptions were dropped — they have no place in the bookmark model.',
},
FAVICONS_IGNORED: {
one: '{n} favicon ignored — the bookmarks API cannot set favicons.',
other: '{n} favicons ignored — the bookmarks API cannot set favicons.',
},
INVALID_DATE: {
one: '{n} unreadable date was left blank.',
other: '{n} unreadable dates were left blank.',
},
MISSING_URL: {
one: '{n} entry had no address and was skipped.',
other: '{n} entries had no address and were skipped.',
},
NEWER_VERSION: {
one: 'This file was written by a newer version — reading it as best we can.',
other: 'This file was written by a newer version — reading it as best we can.',
},
EMPTY_TITLE: {
one: '{n} bookmark had no title; its address is shown instead.',
other: '{n} bookmarks had no title; their address is shown instead.',
},
},
errors: {
NOT_NETSCAPE: 'This does not look like a bookmark HTML file.',
+34 -11
View File
@@ -14,7 +14,8 @@ export default {
about: '概要',
busy: 'インポートを実行中です',
cancel: 'キャンセル',
comingSoon: '{tab}は今後のビルドで利用できます。',
dismiss: '閉じる',
sections: 'セクション',
},
popup: {
import: 'ブックマークをインポート…',
@@ -26,6 +27,7 @@ export default {
dropHint:
'ブックマークファイルをドロップするかクリックして選択してください — .html、.json、.csv · 最大 {size}',
reading: '{name} を読み込んでいます…',
preview: 'プレビュー',
folderName: 'インポート {date}',
start: '{n} 件のブックマークをインポート',
backingUp:
@@ -63,7 +65,9 @@ export default {
replace: 'すべて置き換える',
},
warnings: {
title: '警告 {n} 件',
// 日本語は単複の区別がありませんが、docs/07 §5 に従い両方のキーを
// 保持します(`satisfies Dict` の形状チェックを成立させるため)。
title: { one: '警告 {n} 件', other: '警告 {n} 件' },
},
},
export: {
@@ -189,15 +193,34 @@ export default {
blocked: 'インポート・エクスポート・編集タブを使うには規約に同意してください。',
},
warnings: {
NO_BOOKMARKS: 'このファイルにブックマークは含まれていません。',
DESCRIPTIONS_DROPPED:
'説明 {n} 件を破棄しました。ブックマークのモデルに該当する項目がありません。',
FAVICONS_IGNORED:
'ファビコン {n} 件を無視しました。ブックマーク API はファビコンを設定できません。',
INVALID_DATE: '読み取れない日付 {n} 件を空欄にしました。',
MISSING_URL: 'アドレスのない項目 {n} 件をスキップしました。',
NEWER_VERSION: 'このファイルは新しいバージョンで作成されています。可能な範囲で読み込みます。',
EMPTY_TITLE: 'タイトルのないブックマークが {n} 件あり、代わりにアドレスを表示します。',
NO_BOOKMARKS: {
one: 'このファイルにブックマークは含まれていません。',
other: 'このファイルにブックマークは含まれていません。',
},
DESCRIPTIONS_DROPPED: {
one: '説明 {n} 件を破棄しました。ブックマークのモデルに該当する項目がありません。',
other: '説明 {n} 件を破棄しました。ブックマークのモデルに該当する項目がありません。',
},
FAVICONS_IGNORED: {
one: 'ファビコン {n} 件を無視しました。ブックマーク API はファビコンを設定できません。',
other: 'ファビコン {n} 件を無視しました。ブックマーク API はファビコンを設定できません。',
},
INVALID_DATE: {
one: '読み取れない日付 {n} 件を空欄にしました。',
other: '読み取れない日付 {n} 件を空欄にしました。',
},
MISSING_URL: {
one: 'アドレスのない項目 {n} 件をスキップしました。',
other: 'アドレスのない項目 {n} 件をスキップしました。',
},
NEWER_VERSION: {
one: 'このファイルは新しいバージョンで作成されています。可能な範囲で読み込みます。',
other: 'このファイルは新しいバージョンで作成されています。可能な範囲で読み込みます。',
},
EMPTY_TITLE: {
one: 'タイトルのないブックマークが {n} 件あり、代わりにアドレスを表示します。',
other: 'タイトルのないブックマークが {n} 件あり、代わりにアドレスを表示します。',
},
},
errors: {
NOT_NETSCAPE: 'ブックマークの HTML ファイルではないようです。',
+34 -9
View File
@@ -11,7 +11,8 @@ export default {
about: 'Giới thiệu',
busy: 'Đang có tiến trình nhập',
cancel: 'Hủy',
comingSoon: '{tab} sẽ có ở bản sau.',
dismiss: 'Đóng',
sections: 'Các mục',
},
popup: {
import: 'Nhập bookmark…',
@@ -22,6 +23,7 @@ export default {
import: {
dropHint: 'Kéo thả tệp bookmark hoặc bấm để chọn — .html, .json, .csv · tối đa {size}',
reading: 'Đang đọc {name}…',
preview: 'Xem trước',
folderName: 'Đã nhập {date}',
start: 'Nhập {n} bookmark',
backingUp:
@@ -58,7 +60,9 @@ export default {
replace: 'Thay thế toàn bộ',
},
warnings: {
title: '{n} cảnh báo',
// Tiếng Việt chỉ có một dạng số, nhưng vẫn phải mang đủ hai khóa
// (docs/07 §5) để phép kiểm tra `satisfies Dict` còn ý nghĩa.
title: { one: '{n} cảnh báo', other: '{n} cảnh báo' },
},
},
export: {
@@ -187,13 +191,34 @@ export default {
blocked: 'Hãy chấp nhận điều khoản để dùng các thẻ Nhập, Xuất và Chỉnh sửa.',
},
warnings: {
NO_BOOKMARKS: 'Tệp này không chứa bookmark nào.',
DESCRIPTIONS_DROPPED: 'Đã bỏ {n} phần mô tả — mô hình bookmark không có chỗ cho chúng.',
FAVICONS_IGNORED: 'Đã bỏ qua {n} favicon — API bookmark không thể đặt favicon.',
INVALID_DATE: 'Đã để trống {n} ngày không đọc được.',
MISSING_URL: 'Đã bỏ qua {n} mục không có địa chỉ.',
NEWER_VERSION: 'Tệp này được tạo bởi phiên bản mới hơn — đang đọc ở mức tốt nhất có thể.',
EMPTY_TITLE: '{n} bookmark không có tiêu đề; địa chỉ được hiển thị thay thế.',
NO_BOOKMARKS: {
one: 'Tệp này không chứa bookmark nào.',
other: 'Tệp này không chứa bookmark nào.',
},
DESCRIPTIONS_DROPPED: {
one: 'Đã bỏ {n} phần mô tả — mô hình bookmark không có chỗ cho chúng.',
other: 'Đã bỏ {n} phần mô tả — mô hình bookmark không có chỗ cho chúng.',
},
FAVICONS_IGNORED: {
one: 'Đã bỏ qua {n} favicon — API bookmark không thể đặt favicon.',
other: 'Đã bỏ qua {n} favicon — API bookmark không thể đặt favicon.',
},
INVALID_DATE: {
one: 'Đã để trống {n} ngày không đọc được.',
other: 'Đã để trống {n} ngày không đọc được.',
},
MISSING_URL: {
one: 'Đã bỏ qua {n} mục không có địa chỉ.',
other: 'Đã bỏ qua {n} mục không có địa chỉ.',
},
NEWER_VERSION: {
one: 'Tệp này được tạo bởi phiên bản mới hơn — đang đọc ở mức tốt nhất có thể.',
other: 'Tệp này được tạo bởi phiên bản mới hơn — đang đọc ở mức tốt nhất có thể.',
},
EMPTY_TITLE: {
one: '{n} bookmark không có tiêu đề; địa chỉ được hiển thị thay thế.',
other: '{n} bookmark không có tiêu đề; địa chỉ được hiển thị thay thế.',
},
},
errors: {
NOT_NETSCAPE: 'Đây có vẻ không phải tệp HTML bookmark.',
+5 -3
View File
@@ -8,6 +8,7 @@
* picker resolving, or by the user explicitly confirming the fallback
* download (docs/03 §1 step 6b).
*/
import { getGeneratorVersion } from '../browser/app-info';
import { clearRoots, getRootChildren, getRoots, toBookmarkNodes } from '../browser/bookmarks';
import {
isPickerAvailable,
@@ -37,8 +38,6 @@ const PARSERS = {
csv: parseCsv,
} as const;
const APP_VERSION = '0.1.0';
export interface PreparedImport {
result: ParseResult;
/** Bookmarks in the file whose URL already exists in the browser. */
@@ -160,7 +159,10 @@ export async function proveBackup(
): Promise<void> {
let content: string;
try {
content = serializeBmJson(snapshot, { version: APP_VERSION, exportedAt: now.toISOString() });
content = serializeBmJson(snapshot, {
version: getGeneratorVersion(),
exportedAt: now.toISOString(),
});
} catch (cause) {
throw new BmBackupError(
'BACKUP_SERIALIZE_FAILED',
+58
View File
@@ -0,0 +1,58 @@
/**
* Every outbound URL the product shows — docs/14 §4, docs/06 §3.5.
*
* Purpose: one place for the repo, legal and donate links, so the About tab and
* the Legal Gate cannot drift apart.
* Inputs: none — compile-time literals.
* Guarantees: no requests are made from here. These are hrefs the user chooses
* to follow; the extension itself stays offline (docs/09 §1).
*
* They are rendered as `<a target="_blank" rel="noopener noreferrer">`, unlike
* bookmark URLs, which docs/09 T3 forbids putting in an href and which #edit
* opens through `tabs.create` instead. Two mechanisms for two trust classes:
* these are literals in this file, those are untrusted data from a user's
* import file. Do not "harmonize" them.
*/
export const REPO_URL = 'https://github.com/poli0981/bookmarkmagic';
export const ISSUES_URL = `${REPO_URL}/issues`;
/**
* Releases, not `blob/main/CHANGELOG.md` — the changelog is authored in Phase 5
* and the file does not exist yet. A releases page renders as a valid (empty)
* page; a missing blob is a 404 shown from inside a legal-adjacent surface.
*/
export const CHANGELOG_URL = `${REPO_URL}/releases`;
export interface LabelledLink {
labelKey: string;
url: string;
}
/**
* The four documents the gate and About link to (docs/14 §2).
*
* `blob/main/` and not a pinned tag on purpose: the gate asks the user to
* accept the *current* documents, and LEGAL_VERSION is the re-consent
* mechanism. Pinning would show terms that are no longer the ones in force.
*/
export const LEGAL_URLS: readonly LabelledLink[] = [
{ labelKey: 'legal.eula', url: `${REPO_URL}/blob/main/legal/EULA.md` },
{ labelKey: 'legal.license', url: `${REPO_URL}/blob/main/LICENSE` },
{ labelKey: 'legal.disclaimer', url: `${REPO_URL}/blob/main/legal/DISCLAIMER.md` },
{ labelKey: 'legal.privacy', url: `${REPO_URL}/blob/main/legal/PRIVACY.md` },
];
/**
* Donation platforms, from `.github/FUNDING.yml` (docs/14 §5).
*
* Labels are literals rather than i18n keys: these are brand names, which
* docs/07 §4 leaves untranslated. Only the section heading is localized.
*/
export const DONATE_LINKS: readonly { label: string; url: string }[] = [
{ label: 'GitHub Sponsors', url: 'https://github.com/sponsors/poli0981' },
{ label: 'Ko-fi', url: 'https://ko-fi.com/skullmute' },
{ label: 'Buy Me a Coffee', url: 'https://www.buymeacoffee.com/skullmute' },
{ label: 'Patreon', url: 'https://www.patreon.com/skullmute' },
{ label: 'PayPal', url: 'https://paypal.me/DungDang212' },
];
+76
View File
@@ -0,0 +1,76 @@
/**
* The choices each Settings row offers — docs/06 §3.4.
*
* Purpose: keep the six option tables out of the component so they can be
* asserted against the storage allow-lists, and give `<select>` handlers a
* way to narrow a raw string without an unexplained cast.
* Inputs: none — static tables plus one pure narrowing helper.
* Guarantees: pure. Lives in `settings/` rather than `core/` because it takes
* its types from `browser/storage.ts`, which `core/` may not touch
* (docs/02 §3 rule 1).
*/
import type { ExportFormat, ImportMode, ThemePreference } from '../browser/storage';
import type { CsvDelimiter } from '../core/serialize/csv';
import type { MarkdownStyle } from '../core/serialize/markdown';
import type { Locale } from '../i18n/resolve-locale';
export interface SettingChoice<T extends string> {
value: T;
/** Dotted i18n path — resolved at render time so it follows the locale. */
labelKey: string;
}
/** `'auto'` is a first-class option: it is what `DEFAULT_SETTINGS.locale` is. */
export const LOCALE_CHOICES: readonly SettingChoice<Locale | 'auto'>[] = [
{ value: 'auto', labelKey: 'settings.localeAuto' },
{ value: 'en', labelKey: 'settings.lang.en' },
{ value: 'vi', labelKey: 'settings.lang.vi' },
{ value: 'ja', labelKey: 'settings.lang.ja' },
];
export const THEME_CHOICES: readonly SettingChoice<ThemePreference>[] = [
{ value: 'system', labelKey: 'settings.themes.system' },
{ value: 'light', labelKey: 'settings.themes.light' },
{ value: 'dark', labelKey: 'settings.themes.dark' },
];
// The next four reuse the Export/Import tabs' own keys rather than inventing
// parallel wording. That is ~14 keys × 3 locales not written, and it makes it
// impossible for #settings and #export to describe the same choice differently.
export const EXPORT_FORMAT_CHOICES: readonly SettingChoice<ExportFormat>[] = [
{ value: 'netscape-html', labelKey: 'export.formats.netscape-html.name' },
{ value: 'bm-json', labelKey: 'export.formats.bm-json.name' },
{ value: 'csv', labelKey: 'export.formats.csv.name' },
{ value: 'markdown', labelKey: 'export.formats.markdown.name' },
];
export const IMPORT_MODE_CHOICES: readonly SettingChoice<ImportMode>[] = [
{ value: 'new-folder', labelKey: 'import.mode.newFolder' },
{ value: 'merge', labelKey: 'import.mode.merge' },
{ value: 'replace', labelKey: 'import.mode.replace' },
];
export const CSV_DELIMITER_CHOICES: readonly SettingChoice<CsvDelimiter>[] = [
{ value: ',', labelKey: 'export.comma' },
{ value: ';', labelKey: 'export.semicolon' },
];
export const MARKDOWN_STYLE_CHOICES: readonly SettingChoice<MarkdownStyle>[] = [
{ value: 'nested', labelKey: 'export.nested' },
{ value: 'flat', labelKey: 'export.flat' },
];
/**
* Narrow a raw control value against a choice table.
*
* Exists so `<select>` handlers never need `as SomeUnion`, which docs/10 §2
* would require a `// SAFETY:` comment for. Returns `undefined` for anything
* not in the table; callers must bail before building a settings patch, since
* `exactOptionalPropertyTypes` rejects an explicit `undefined` in the patch.
*/
export function parseChoice<T extends string>(
raw: string,
choices: readonly SettingChoice<T>[],
): T | undefined {
return choices.find((choice) => choice.value === raw)?.value;
}
+9 -1
View File
@@ -32,7 +32,15 @@ export type ImportState =
| { kind: 'writing'; filename: string; progress: WriteProgress }
| { kind: 'done'; filename: string; created: number; plan: ImportPlan }
| { kind: 'cancelled'; filename: string; created: number }
| { kind: 'error'; filename: string; message: string; detail: string | undefined };
/**
* `messageKey` is a dotted i18n path, NOT a resolved string.
*
* `t()` is only reactive where it is called, and this state outlives the
* component; storing the translated sentence froze it in whatever language
* was active when the error happened, so switching language left the error
* message behind in the old one.
*/
| { kind: 'error'; filename: string; messageKey: string; detail: string | undefined };
let state = $state<ImportState>({ kind: 'idle' });
let options = $state<ImportOptionsState>({ mode: 'new-folder', dedupe: true });
+118
View File
@@ -0,0 +1,118 @@
/**
* First-run legal acceptance — docs/14 §2.
*
* Purpose: decide whether the gate is required, and record acceptance.
* Inputs: `chrome.storage.local` via `browser/storage.ts`.
* Guarantees: never throws and never rejects — a storage failure fails CLOSED
* (gate shown), and `acceptLegal` returns an outcome instead of rejecting.
* Acceptance is only reflected in state AFTER the write resolves.
*/
import { type LegalAcceptance, readLegal, writeLegal } from '../browser/storage';
import { LEGAL_VERSION } from '../core/limits';
import type { Route } from './route.svelte';
import type { SaveOutcome } from './settings.svelte';
export type LegalStatus =
| { kind: 'loading' }
| { kind: 'accepted'; acceptance: LegalAcceptance }
/**
* `previous` carries the superseded record on the `updated` path. Without it
* the About tab would tell a user who accepted v1 that they have never
* accepted anything, the moment LEGAL_VERSION is bumped to 2.
*/
| { kind: 'required'; reason: 'first-run' | 'updated'; previous?: LegalAcceptance };
/**
* The three routes the gate blocks.
*
* Normative and stated identically in docs/03 §4, docs/14 §2 and the docs/15
* decision log: `#settings` and `#about` stay reachable, `#about` so the linked
* documents can be read before accepting and `#settings` so a VI/JA user can
* switch language first — which is why the gate carries no switcher of its own.
*/
const GATED_ROUTES: readonly Route[] = Object.freeze(['import', 'export', 'edit']);
const UNGATED: readonly Route[] = Object.freeze([]);
let status = $state<LegalStatus>({ kind: 'loading' });
/**
* Pure gate decision, so the rule is testable without touching storage.
*
* A stored version GREATER than the current one still counts as accepted: it
* means the user ran a newer build, and re-gating them on a downgrade would be
* noise, not consent.
*/
export function decideLegalStatus(
acceptance: LegalAcceptance | null,
currentVersion: number,
): LegalStatus {
if (acceptance === null) return { kind: 'required', reason: 'first-run' };
if (acceptance.acceptedVersion < currentVersion) {
return { kind: 'required', reason: 'updated', previous: acceptance };
}
return { kind: 'accepted', acceptance };
}
export function getLegalStatus(): LegalStatus {
return status;
}
export function isGateRequired(): boolean {
return status.kind === 'required';
}
/**
* The most recent acceptance on record, current or superseded.
*
* About renders this, so it must survive a `LEGAL_VERSION` bump — the user did
* accept the older terms, and saying otherwise is simply false.
*/
export function getAcceptance(): LegalAcceptance | undefined {
if (status.kind === 'accepted') return status.acceptance;
if (status.kind === 'required') return status.previous;
return undefined;
}
/** `[]` unless the gate is up. Never `undefined`, so the TabBar prop is simple. */
export function getBlockedRoutes(): readonly Route[] {
return status.kind === 'required' ? GATED_ROUTES : UNGATED;
}
export function isGatedRoute(route: Route): boolean {
return GATED_ROUTES.includes(route);
}
/**
* Read the stored acceptance. Call once per page, before the first render.
*
* `readLegal` already swallows storage failures and returns null, so an
* unreadable store lands on `required`. That is the correct direction: showing
* the gate to someone who accepted is recoverable in one click; skipping it for
* someone who has not is not recoverable at all.
*/
export async function loadLegal(): Promise<void> {
status = decideLegalStatus(await readLegal(), LEGAL_VERSION);
}
/**
* Record acceptance.
*
* The ordering is the whole point: write, await, and flip to `accepted` ONLY
* once the write resolves. Dismissing optimistically would leave the user
* accepted in the UI and unaccepted on disk, so the gate would silently
* reappear on the next launch with no explanation.
*
* @param nowIso supplied by the caller so this module stays free of ambient
* time, matching the discipline `browser/storage.ts` set up.
*/
export async function acceptLegal(nowIso: string): Promise<SaveOutcome> {
try {
await writeLegal(LEGAL_VERSION, nowIso);
} catch (err) {
// Returned, not thrown: a rejection here would need a .catch() at every
// call site, and one miss is an unhandled rejection with the gate stuck.
return { ok: false, ...(err instanceof Error && { detail: err.message }) };
}
status = { kind: 'accepted', acceptance: { acceptedVersion: LEGAL_VERSION, acceptedAt: nowIso } };
return { ok: true };
}
+111 -15
View File
@@ -1,9 +1,13 @@
/**
* Persisted settings — docs/03 §4.
*
* Writes are debounced 200 ms so dragging a control does not hammer storage.
* Theme is applied to <html data-theme> here, because that is the one place
* that knows both the preference and when it changed.
* Purpose: the single source of truth for locale, theme and the per-tab
* defaults, plus the only path that writes them to storage.
* Inputs: `updateSettings` patches from the Settings tab and header controls.
* Guarantees: writes are debounced 200 ms; the returned promise resolves when
* that write has actually *settled*, and never rejects — so UI feedback can
* report what happened instead of guessing. Theme and locale apply
* synchronously, before the write is even scheduled.
*/
import { browser } from 'wxt/browser';
import {
@@ -13,14 +17,22 @@ import {
type ThemePreference,
writeSettings,
} from '../browser/storage';
import { setLocale } from '../i18n/index.svelte';
import { getLocale, setLocale } from '../i18n/index.svelte';
import { resolveLocale } from '../i18n/resolve-locale';
const SAVE_DEBOUNCE_MS = 200;
let settings = $state<Settings>({ ...DEFAULT_SETTINGS });
/** What a persistence attempt actually did. Never thrown, always returned. */
export interface SaveOutcome {
ok: boolean;
detail?: string;
}
const settings = $state<Settings>({ ...DEFAULT_SETTINGS });
let loaded = $state(false);
let saveTimer: ReturnType<typeof setTimeout> | undefined;
/** Everyone who called `updateSettings` since the last write shares this. */
let pending: { promise: Promise<SaveOutcome>; resolve: (outcome: SaveOutcome) => void } | undefined;
export function getSettings(): Settings {
return settings;
@@ -32,37 +44,107 @@ export function isSettingsLoaded(): boolean {
/** Read persisted settings and apply locale + theme. Call once per page. */
export async function loadSettings(): Promise<void> {
settings = await readSettings();
Object.assign(settings, await readSettings());
applyLocale();
applyTheme(settings.theme);
loaded = true;
}
export function updateSettings(patch: Partial<Settings>): void {
settings = { ...settings, ...patch };
/**
* Apply a patch now, persist it shortly.
*
* Returns the outcome of the resulting write rather than firing and forgetting,
* so the Settings tab's "Saved" toast cannot claim a persistence that failed.
*/
export function updateSettings(patch: Partial<Settings>): Promise<SaveOutcome> {
// Mutated in place, never replaced. A replacement would strand any component
// that captured `getSettings()` into a local, and four components read this.
Object.assign(settings, patch);
if (patch.theme !== undefined) applyTheme(patch.theme);
if (patch.locale !== undefined) applyLocale();
scheduleSave();
return scheduleSave();
}
export async function resetSettings(): Promise<void> {
settings = { ...DEFAULT_SETTINGS };
/**
* Restore every documented default and persist immediately.
*
* The pending debounced write is cancelled rather than allowed to fire first —
* otherwise a reset issued within 200 ms of a change writes twice, and the
* first write persists values the user just discarded.
*/
export function resetSettings(): Promise<SaveOutcome> {
if (saveTimer !== undefined) clearTimeout(saveTimer);
saveTimer = undefined;
Object.assign(settings, DEFAULT_SETTINGS);
applyLocale();
applyTheme(settings.theme);
await writeSettings(settings);
return flushNow();
}
function scheduleSave(): void {
/**
* Write any pending change immediately.
*
* Called on `visibilitychange` → hidden, which fires on tab close, navigation
* and backgrounding. It shrinks the window in which a just-made change is lost
* from 200 ms to roughly nothing — it does not make it zero, because an async
* write started while the document is hidden is not guaranteed to finish.
*/
export function flushSettings(): Promise<SaveOutcome> {
if (saveTimer === undefined && pending === undefined) return Promise.resolve({ ok: true });
return flushNow();
}
function scheduleSave(): Promise<SaveOutcome> {
if (saveTimer !== undefined) clearTimeout(saveTimer);
// Rapid changes coalesce onto one promise, so every caller awaiting a save
// learns the outcome of the single write that actually happened.
if (pending === undefined) {
let resolve!: (outcome: SaveOutcome) => void;
const promise = new Promise<SaveOutcome>((r) => {
resolve = r;
});
pending = { promise, resolve };
}
saveTimer = setTimeout(() => {
saveTimer = undefined;
void writeSettings(settings);
void flushNow();
}, SAVE_DEBOUNCE_MS);
return pending.promise;
}
/** Write now and settle whoever is waiting on the coalesced promise. */
async function flushNow(): Promise<SaveOutcome> {
if (saveTimer !== undefined) clearTimeout(saveTimer);
saveTimer = undefined;
const waiting = pending;
pending = undefined;
const outcome = await save();
waiting?.resolve(outcome);
return outcome;
}
async function save(): Promise<SaveOutcome> {
try {
// $state proxies are not structured-cloneable, and chrome.storage.local.set
// clones its argument — passing the proxy straight through throws
// DataCloneError in a real browser. Settings is flat primitives, so a
// spread is a provably sufficient snapshot.
await writeSettings({ ...settings });
return { ok: true };
} catch (err) {
// Conditional spread, not `detail: undefined` — exactOptionalPropertyTypes
// makes an explicit undefined a type error (docs/10 §2).
return { ok: false, ...(err instanceof Error && { detail: err.message }) };
}
}
function applyLocale(): void {
if (settings.locale !== 'auto') {
setLocale(settings.locale);
applyDocumentLanguage();
return;
}
// A failing i18n lookup must not stop settings from loading — fall back to
@@ -74,6 +156,20 @@ function applyLocale(): void {
uiLanguage = 'en';
}
setLocale(resolveLocale(uiLanguage));
applyDocumentLanguage();
}
/**
* Keep `<html lang>` in step with the UI language.
*
* Both entrypoint documents ship `lang="en"`, so without this a screen reader
* reads Vietnamese and Japanese text with an English voice and pronunciation
* rules — the strings change and the announced language does not.
*/
function applyDocumentLanguage(): void {
const root = globalThis.document?.documentElement;
if (root === undefined) return;
root.lang = getLocale();
}
/**
+6
View File
@@ -38,6 +38,10 @@
--fg: #e8eaee;
--fg-muted: #9aa3b0;
--accent: #8b6dff;
/* Dark mode lightens --accent for contrast against --bg, which drops white
ink on it to 3.67:1 — under the 4.5:1 docs/06 §5 requires. --accent-fg must
be redefined alongside it; dark ink on #8b6dff measures 4.84:1. */
--accent-fg: #16181d;
--danger: #ff6b7d;
--success: #3ecf8e;
--warn: #e2b93b;
@@ -51,6 +55,8 @@
--fg: #e8eaee;
--fg-muted: #9aa3b0;
--accent: #8b6dff;
/* Keep in step with the [data-theme='dark'] block above. */
--accent-fg: #16181d;
--danger: #ff6b7d;
--success: #3ecf8e;
--warn: #e2b93b;
+23 -7
View File
@@ -72,13 +72,29 @@ describe('dictionary completeness', () => {
expect(empty).toEqual([]);
});
it('has no plural keys yet, so no plural helper is owed', () => {
// docs/07 §5: a plural key is an object `{ one, other }` in EVERY locale and
// needs a selector helper. None exist today, and knip would fail an unused
// helper — so this fails loudly the day someone adds the first one.
const plurals = [...branches(en as Node)]
.filter(([, keys]) => keys.length === 2 && keys.includes('one') && keys.includes('other'))
it('carries every plural key as { one, other } in all three locales', () => {
// docs/07 §5. VI/JA have one grammatical form and repeat the same string,
// but they must still carry both keys or the `satisfies Dict` shape check
// §2 relies on for completeness stops proving anything.
const pluralPaths = [...branches(en as Node)]
.filter(([, keys]) => keys.includes('one') && keys.includes('other'))
.map(([path]) => path);
expect(plurals).toEqual([]);
expect(pluralPaths.length).toBeGreaterThan(0);
for (const [name, dict] of LOCALES) {
const leaves = flatten(dict);
for (const path of pluralPaths) {
expect(leaves.get(`${path}.one`), `${name}: ${path}.one`).toBeTypeOf('string');
expect(leaves.get(`${path}.other`), `${name}: ${path}.other`).toBeTypeOf('string');
}
}
});
it('gives every plural key exactly the two forms, and no stray siblings', () => {
const malformed = [...branches(en as Node)]
.filter(([, keys]) => keys.includes('one') || keys.includes('other'))
.filter(([, keys]) => keys.length !== 2)
.map(([path]) => path);
expect(malformed).toEqual([]);
});
});
+44 -2
View File
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it } from 'vitest';
import { formatCount, formatDateTime, localeTag } from '@/lib/i18n/format';
import { dateTime, getLocale, num, setLocale } from '@/lib/i18n/index.svelte';
import { formatCount, formatDateTime, localeTag, selectPluralForm } from '@/lib/i18n/format';
import { dateTime, getLocale, num, setLocale, tPlural } from '@/lib/i18n/index.svelte';
afterEach(() => {
setLocale('en');
@@ -63,6 +63,48 @@ describe('formatDateTime', () => {
});
});
describe('selectPluralForm', () => {
it('distinguishes one from other in English', () => {
expect(selectPluralForm(1, 'en-US')).toBe('one');
expect(selectPluralForm(0, 'en-US')).toBe('other');
expect(selectPluralForm(2, 'en-US')).toBe('other');
});
it('always returns other for vi and ja, which have one grammatical form', () => {
for (const count of [0, 1, 2, 100]) {
expect(selectPluralForm(count, 'vi-VN')).toBe('other');
expect(selectPluralForm(count, 'ja-JP')).toBe('other');
}
});
});
describe('tPlural', () => {
it('picks the singular form and supplies a formatted {n}', () => {
setLocale('en');
expect(tPlural('warnings.INVALID_DATE', 1)).toBe('1 unreadable date was left blank.');
});
it('picks the plural form and groups the count', () => {
setLocale('en');
expect(tPlural('warnings.INVALID_DATE', 1234)).toBe('1,234 unreadable dates were left blank.');
});
it('resolves in vi and ja without falling back to English', () => {
for (const locale of ['vi', 'ja'] as const) {
setLocale(locale);
const text = tPlural('warnings.INVALID_DATE', 3);
expect(text).not.toBe('warnings.INVALID_DATE');
expect(text).not.toContain('unreadable');
expect(text).toContain('3');
}
});
it('returns the path itself for an unknown key rather than throwing', () => {
setLocale('en');
expect(tPlural('warnings.NOT_A_REAL_CODE', 2)).toBe('warnings.NOT_A_REAL_CODE');
});
});
describe('reactive wrappers', () => {
it('getLocale() reports the resolved locale, not the stored preference', () => {
// The preference (getSettings().locale) also carries 'auto'; this never
+87
View File
@@ -0,0 +1,87 @@
import { existsSync } from 'node:fs';
import { basename, join } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { getAppVersion } from '@/lib/browser/app-info';
import { setLocale, t } from '@/lib/i18n/index.svelte';
import type { Locale } from '@/lib/i18n/resolve-locale';
import { CHANGELOG_URL, DONATE_LINKS, ISSUES_URL, LEGAL_URLS, REPO_URL } from '@/lib/links';
const LOCALES: Locale[] = ['en', 'vi', 'ja'];
/** Vitest runs with cwd at the project root, which is where `legal/` lives. */
const REPO_ROOT = process.cwd();
afterEach(() => {
setLocale('en');
});
describe('outbound links', () => {
it('are all absolute https URLs', () => {
const urls = [
REPO_URL,
ISSUES_URL,
CHANGELOG_URL,
...LEGAL_URLS.map((link) => link.url),
...DONATE_LINKS.map((link) => link.url),
];
for (const url of urls) {
expect(() => new URL(url)).not.toThrow();
expect(new URL(url).protocol).toBe('https:');
}
});
it('points every legal link at a file that exists in the repo', () => {
// A rename would otherwise ship four dead links from inside a legal gate,
// and nothing else in the build would notice.
for (const link of LEGAL_URLS) {
const path = new URL(link.url).pathname.replace('/poli0981/bookmarkmagic/blob/main/', '');
expect(existsSync(join(REPO_ROOT, path)), `missing ${path}`).toBe(true);
expect(basename(path)).not.toBe('');
}
});
it('labels every legal link in all three locales', () => {
const missing: string[] = [];
for (const locale of LOCALES) {
setLocale(locale);
for (const link of LEGAL_URLS) {
if (t(link.labelKey) === link.labelKey) missing.push(`${locale}: ${link.labelKey}`);
}
}
expect(missing).toEqual([]);
});
it('lists exactly the four documents docs/14 §2 requires', () => {
expect(LEGAL_URLS.map((link) => link.labelKey)).toEqual([
'legal.eula',
'legal.license',
'legal.disclaimer',
'legal.privacy',
]);
});
it('lists all five funding handles from .github/FUNDING.yml (docs/14 §5)', () => {
expect(DONATE_LINKS).toHaveLength(5);
expect(DONATE_LINKS.map((link) => link.label)).toEqual([
'GitHub Sponsors',
'Ko-fi',
'Buy Me a Coffee',
'Patreon',
'PayPal',
]);
});
it('avoids linking a CHANGELOG.md that does not exist yet', () => {
// Phase 5 authors it; until then the releases page is the honest target.
expect(CHANGELOG_URL.endsWith('/releases')).toBe(true);
});
});
describe('getAppVersion', () => {
it('returns an empty string rather than throwing when the manifest is unreadable', () => {
// fakeBrowser has no packaged manifest, so this exercises the fallback.
// A wrong-but-plausible version in a footer users quote in bug reports is
// worse than no version at all.
expect(() => getAppVersion()).not.toThrow();
expect(typeof getAppVersion()).toBe('string');
});
});
+86
View File
@@ -0,0 +1,86 @@
import { afterEach, describe, expect, it } from 'vitest';
import { DEFAULT_SETTINGS } from '@/lib/browser/storage';
import { setLocale, t } from '@/lib/i18n/index.svelte';
import type { Locale } from '@/lib/i18n/resolve-locale';
import {
CSV_DELIMITER_CHOICES,
EXPORT_FORMAT_CHOICES,
IMPORT_MODE_CHOICES,
LOCALE_CHOICES,
MARKDOWN_STYLE_CHOICES,
parseChoice,
type SettingChoice,
THEME_CHOICES,
} from '@/lib/settings/options';
const TABLES: [name: string, choices: readonly SettingChoice<string>[]][] = [
['LOCALE_CHOICES', LOCALE_CHOICES],
['THEME_CHOICES', THEME_CHOICES],
['EXPORT_FORMAT_CHOICES', EXPORT_FORMAT_CHOICES],
['IMPORT_MODE_CHOICES', IMPORT_MODE_CHOICES],
['CSV_DELIMITER_CHOICES', CSV_DELIMITER_CHOICES],
['MARKDOWN_STYLE_CHOICES', MARKDOWN_STYLE_CHOICES],
];
const LOCALES: Locale[] = ['en', 'vi', 'ja'];
afterEach(() => {
setLocale('en');
});
describe('choice labels', () => {
it.each(TABLES)('%s resolves every labelKey in all three locales', (_name, choices) => {
// t() falls back to the key path on a miss, so a typo renders as literal
// "settings.markdownStyle" in the UI and nothing else would catch it.
const missing: string[] = [];
for (const locale of LOCALES) {
setLocale(locale);
for (const choice of choices) {
if (t(choice.labelKey) === choice.labelKey) missing.push(`${locale}: ${choice.labelKey}`);
}
}
expect(missing).toEqual([]);
});
});
describe('choice values match the storage allow-lists', () => {
// coerceSettings in browser/storage.ts is the gatekeeper for what can be
// persisted. If a value can be stored but has no row, it is unreachable; if a
// row offers a value coerceSettings rejects, choosing it silently does
// nothing. Both are caught here.
it.each([
['locale', LOCALE_CHOICES, ['auto', 'en', 'vi', 'ja']],
['theme', THEME_CHOICES, ['system', 'light', 'dark']],
['defaultExportFormat', EXPORT_FORMAT_CHOICES, ['netscape-html', 'bm-json', 'csv', 'markdown']],
['defaultMergeMode', IMPORT_MODE_CHOICES, ['new-folder', 'merge', 'replace']],
['csvDelimiter', CSV_DELIMITER_CHOICES, [',', ';']],
['markdownStyle', MARKDOWN_STYLE_CHOICES, ['nested', 'flat']],
] as [string, readonly SettingChoice<string>[], string[]][])('%s', (_key, choices, allowed) => {
expect(choices.map((choice) => choice.value).sort()).toEqual([...allowed].sort());
});
it('offers a row for every field the default settings carry', () => {
// Six persisted fields, six rows (docs/06 §3.4 as amended in Phase 4).
expect(Object.keys(DEFAULT_SETTINGS).sort()).toEqual([
'csvDelimiter',
'defaultExportFormat',
'defaultMergeMode',
'locale',
'markdownStyle',
'theme',
]);
});
});
describe('parseChoice', () => {
it('returns the narrowed value for a known option', () => {
expect(parseChoice('dark', THEME_CHOICES)).toBe('dark');
expect(parseChoice(';', CSV_DELIMITER_CHOICES)).toBe(';');
});
it('returns undefined for anything not in the table', () => {
expect(parseChoice('klingon', LOCALE_CHOICES)).toBeUndefined();
expect(parseChoice('', CSV_DELIMITER_CHOICES)).toBeUndefined();
expect(parseChoice('DARK', MARKDOWN_STYLE_CHOICES)).toBeUndefined();
});
});
+161
View File
@@ -0,0 +1,161 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fakeBrowser } from 'wxt/testing';
import { LEGAL_VERSION } from '@/lib/core/limits';
import {
acceptLegal,
decideLegalStatus,
getAcceptance,
getBlockedRoutes,
getLegalStatus,
isGatedRoute,
isGateRequired,
loadLegal,
} from '@/lib/stores/legal.svelte';
const ACCEPTED_AT = '2026-07-25T10:00:00.000Z';
beforeEach(() => {
fakeBrowser.reset();
// reset() clears data but leaves spies, so a rejecting storage.local.set
// would otherwise leak into every later test in this file.
vi.restoreAllMocks();
});
describe('decideLegalStatus', () => {
it('gates a fresh profile as first-run', () => {
expect(decideLegalStatus(null, 1)).toEqual({ kind: 'required', reason: 'first-run' });
});
it('gates an older acceptance as an update, KEEPING the superseded record', () => {
// Without `previous`, the About tab tells a user who accepted v1 that they
// have never accepted anything the moment LEGAL_VERSION becomes 2.
const previous = { acceptedVersion: 0, acceptedAt: ACCEPTED_AT };
expect(decideLegalStatus(previous, 1)).toEqual({
kind: 'required',
reason: 'updated',
previous,
});
});
it('accepts a matching version', () => {
const acceptance = { acceptedVersion: 1, acceptedAt: ACCEPTED_AT };
expect(decideLegalStatus(acceptance, 1)).toEqual({ kind: 'accepted', acceptance });
});
it('accepts a version NEWER than the current one', () => {
// The user ran a newer build. Re-gating them on a downgrade would be noise,
// not consent.
const acceptance = { acceptedVersion: 2, acceptedAt: ACCEPTED_AT };
expect(decideLegalStatus(acceptance, 1)).toEqual({ kind: 'accepted', acceptance });
});
});
describe('blocked routes', () => {
it('names exactly the three routes docs/14 §2 blocks', async () => {
await loadLegal();
expect(isGateRequired()).toBe(true);
expect([...getBlockedRoutes()]).toEqual(['import', 'export', 'edit']);
});
it('leaves #settings and #about reachable', () => {
// Normative in docs/03 §4, docs/14 §2 and the docs/15 decision log:
// #about so the documents can be read first, #settings so a VI/JA user can
// switch language -- which is why the gate has no switcher of its own.
expect(isGatedRoute('settings')).toBe(false);
expect(isGatedRoute('about')).toBe(false);
expect(isGatedRoute('import')).toBe(true);
});
it('blocks nothing once accepted', async () => {
await fakeBrowser.storage.local.set({
legal: { acceptedVersion: LEGAL_VERSION, acceptedAt: ACCEPTED_AT },
});
await loadLegal();
expect(isGateRequired()).toBe(false);
expect([...getBlockedRoutes()]).toEqual([]);
});
});
describe('loadLegal', () => {
it('fails closed on a malformed record', async () => {
await fakeBrowser.storage.local.set({ legal: { acceptedVersion: 'yes' } });
await loadLegal();
expect(isGateRequired()).toBe(true);
});
it('fails closed, without throwing, when the read rejects', async () => {
vi.spyOn(fakeBrowser.storage.local, 'get').mockRejectedValue(new Error('storage disabled'));
await expect(loadLegal()).resolves.toBeUndefined();
expect(getLegalStatus()).toEqual({ kind: 'required', reason: 'first-run' });
});
it('still reports the superseded acceptance after a version bump', async () => {
await fakeBrowser.storage.local.set({
legal: { acceptedVersion: LEGAL_VERSION - 1, acceptedAt: ACCEPTED_AT },
});
await loadLegal();
expect(isGateRequired()).toBe(true);
expect(getAcceptance()).toEqual({
acceptedVersion: LEGAL_VERSION - 1,
acceptedAt: ACCEPTED_AT,
});
});
it('reports no acceptance at all on a fresh profile', async () => {
await loadLegal();
expect(getAcceptance()).toBeUndefined();
});
it('exposes the stored acceptance for the About tab', async () => {
await fakeBrowser.storage.local.set({
legal: { acceptedVersion: LEGAL_VERSION, acceptedAt: ACCEPTED_AT },
});
await loadLegal();
expect(getAcceptance()).toEqual({ acceptedVersion: LEGAL_VERSION, acceptedAt: ACCEPTED_AT });
});
});
describe('acceptLegal', () => {
it('persists the version and timestamp, then unlocks', async () => {
await loadLegal();
expect(await acceptLegal(ACCEPTED_AT)).toEqual({ ok: true });
const stored = await fakeBrowser.storage.local.get('legal');
expect(stored.legal).toEqual({ acceptedVersion: LEGAL_VERSION, acceptedAt: ACCEPTED_AT });
expect(isGateRequired()).toBe(false);
});
it('KEEPS THE GATE UP when the write rejects, and writes nothing', async () => {
// The flagship test of this phase. The recurring defect shape in this
// project is: dismiss optimistically, await a chrome.* call that can
// reject, never handle it. Here that would leave the user accepted in the
// UI and unaccepted on disk, with the gate silently back next launch.
await loadLegal();
vi.spyOn(fakeBrowser.storage.local, 'set').mockRejectedValue(
new Error('QUOTA_BYTES quota exceeded'),
);
const outcome = await acceptLegal(ACCEPTED_AT);
expect(outcome.ok).toBe(false);
expect(outcome.detail).toContain('QUOTA_BYTES');
expect(isGateRequired()).toBe(true);
expect(getAcceptance()).toBeUndefined();
const stored = await fakeBrowser.storage.local.get('legal');
expect(stored.legal).toBeUndefined();
});
it('never rejects, so no call site can leak an unhandled rejection', async () => {
vi.spyOn(fakeBrowser.storage.local, 'set').mockRejectedValue(new Error('nope'));
await expect(acceptLegal(ACCEPTED_AT)).resolves.toMatchObject({ ok: false });
});
it('writes nothing at all when the user declines', async () => {
// docs/14 §2: "no nagging -- closing the tab is the decline. Nothing is
// written." Closing is a component action; the contract is that merely
// showing the gate never touches the legal key.
await loadLegal();
const all = await fakeBrowser.storage.local.get(null);
expect(Object.keys(all)).not.toContain('legal');
});
});
+120 -5
View File
@@ -1,8 +1,10 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fakeBrowser } from 'wxt/testing';
import { DEFAULT_SETTINGS } from '@/lib/browser/storage';
import { getLocale } from '@/lib/i18n/index.svelte';
import {
applyTheme,
flushSettings,
getSettings,
isSettingsLoaded,
loadSettings,
@@ -12,6 +14,9 @@ import {
beforeEach(async () => {
fakeBrowser.reset();
// fakeBrowser.reset() clears stored data but leaves spies in place, so a
// rejecting storage.local.set would leak into every later test in the file.
vi.restoreAllMocks();
// fakeBrowser stubs i18n with a throwing "not implemented".
vi.spyOn(fakeBrowser.i18n, 'getUILanguage').mockReturnValue('en-US');
document.documentElement.removeAttribute('data-theme');
@@ -45,16 +50,16 @@ describe('settings store', () => {
});
it('applies a theme change immediately, before the debounced save', () => {
updateSettings({ theme: 'light' });
void updateSettings({ theme: 'light' });
expect(document.documentElement.getAttribute('data-theme')).toBe('light');
});
it('debounces writes — rapid changes produce one save', async () => {
vi.useFakeTimers();
try {
updateSettings({ theme: 'dark' });
updateSettings({ theme: 'light' });
updateSettings({ csvDelimiter: ';' });
void updateSettings({ theme: 'dark' });
void updateSettings({ theme: 'light' });
void updateSettings({ csvDelimiter: ';' });
// Storage still holds what the beforeEach reset wrote — none of the three
// changes has been flushed yet.
@@ -69,6 +74,98 @@ describe('settings store', () => {
}
});
it('writes a plain object, not the $state proxy', async () => {
// chrome.storage.local.set structured-clones its argument, and a Proxy is
// not cloneable — passing the reactive object straight through throws
// DataCloneError in a real browser. fakeBrowser stores the reference
// without cloning, so only an explicit clone here reproduces Chrome.
vi.useFakeTimers();
try {
void updateSettings({ theme: 'dark' });
await vi.advanceTimersByTimeAsync(250);
const stored = await fakeBrowser.storage.local.get('settings');
expect(() => structuredClone(stored.settings)).not.toThrow();
} finally {
vi.useRealTimers();
}
});
it('keeps a stable object identity so a captured reference cannot go stale', () => {
// The store mutates in place rather than replacing. A replacement would
// strand any component that read getSettings() into a local.
const before = getSettings();
void updateSettings({ theme: 'dark' });
expect(getSettings()).toBe(before);
expect(before.theme).toBe('dark');
});
it('resolves the outcome of the write, and never rejects, when storage fails', async () => {
vi.useFakeTimers();
try {
vi.spyOn(fakeBrowser.storage.local, 'set').mockRejectedValue(
new Error('QUOTA_BYTES quota exceeded'),
);
const saving = updateSettings({ theme: 'dark' });
await vi.advanceTimersByTimeAsync(250);
const outcome = await saving;
expect(outcome.ok).toBe(false);
expect(outcome.detail).toContain('QUOTA_BYTES');
// The in-session choice is still honoured — only persistence failed.
expect(getSettings().theme).toBe('dark');
} finally {
vi.useRealTimers();
}
});
it('reports success once the debounced write lands', async () => {
vi.useFakeTimers();
try {
const saving = updateSettings({ csvDelimiter: ';' });
await vi.advanceTimersByTimeAsync(250);
expect(await saving).toEqual({ ok: true });
} finally {
vi.useRealTimers();
}
});
it('flushSettings writes immediately without waiting out the debounce', async () => {
vi.useFakeTimers();
try {
const saving = updateSettings({ csvDelimiter: ';' });
expect(await flushSettings()).toEqual({ ok: true });
const stored = await fakeBrowser.storage.local.get('settings');
expect(stored.settings).toMatchObject({ csvDelimiter: ';' });
// The caller awaiting the debounced promise is settled by the flush too.
expect(await saving).toEqual({ ok: true });
} finally {
vi.useRealTimers();
}
});
it('flushSettings is a no-op when nothing is pending', async () => {
expect(await flushSettings()).toEqual({ ok: true });
});
it('resolves "auto" against the browser UI language', async () => {
vi.spyOn(fakeBrowser.i18n, 'getUILanguage').mockReturnValue('ja-JP');
await updateSettings({ locale: 'auto' });
expect(getLocale()).toBe('ja');
});
it('keeps <html lang> in step with the UI language', async () => {
// Both entrypoint documents ship lang="en"; without this a screen reader
// reads VI/JA text with an English voice and pronunciation rules.
await updateSettings({ locale: 'vi' });
expect(document.documentElement.lang).toBe('vi');
await updateSettings({ locale: 'ja' });
expect(document.documentElement.lang).toBe('ja');
vi.spyOn(fakeBrowser.i18n, 'getUILanguage').mockReturnValue('en-GB');
await updateSettings({ locale: 'auto' });
expect(document.documentElement.lang).toBe('en');
});
it('still loads when the browser i18n lookup throws', async () => {
vi.spyOn(fakeBrowser.i18n, 'getUILanguage').mockImplementation(() => {
throw new Error('not implemented');
@@ -78,10 +175,28 @@ describe('settings store', () => {
});
it('reset restores the documented defaults and persists them at once', async () => {
updateSettings({ theme: 'dark', csvDelimiter: ';' });
void updateSettings({ theme: 'dark', csvDelimiter: ';' });
await resetSettings();
expect(getSettings()).toEqual(DEFAULT_SETTINGS);
const stored = await fakeBrowser.storage.local.get('settings');
expect(stored.settings).toEqual(DEFAULT_SETTINGS);
});
it('reset cancels the pending debounced save rather than writing twice', async () => {
vi.useFakeTimers();
try {
const set = vi.spyOn(fakeBrowser.storage.local, 'set');
void updateSettings({ theme: 'dark' });
await resetSettings();
await vi.advanceTimersByTimeAsync(250);
// Exactly the reset's own write. Letting the debounce fire afterwards
// would persist the value the user just discarded.
expect(set).toHaveBeenCalledTimes(1);
const stored = await fakeBrowser.storage.local.get('settings');
expect(stored.settings).toEqual(DEFAULT_SETTINGS);
} finally {
vi.useRealTimers();
}
});
});