Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4cb075820f | ||
|
|
3c25eaf8cf | ||
|
|
21fd11ce30 | ||
|
|
2937f4edf0 | ||
|
|
16bbba371d | ||
|
|
0a14fb4257 | ||
|
|
c44c813aec | ||
|
|
372741142e | ||
|
|
2c2d8347ae | ||
|
|
f897a711bd | ||
|
|
93cf6b87fe | ||
|
|
85f134c6e8 | ||
|
|
06b499205d |
No files matched your search
@@ -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
|
||||
|
||||
@@ -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").
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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>
|
||||
@@ -1,16 +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).
|
||||
@@ -18,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>
|
||||
@@ -32,30 +78,65 @@
|
||||
<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>
|
||||
|
||||
<!-- Mounted once, outside <main>, so the route chain below cannot unmount it
|
||||
mid-dismiss and strand a timer (docs/06 §4). -->
|
||||
<Toast />
|
||||
|
||||
<style>
|
||||
header,
|
||||
footer {
|
||||
@@ -84,6 +165,12 @@
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.mark {
|
||||
color: var(--accent);
|
||||
}
|
||||
@@ -95,10 +182,6 @@
|
||||
min-height: 60vh;
|
||||
}
|
||||
|
||||
.placeholder {
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
footer nav {
|
||||
display: flex;
|
||||
gap: var(--sp-3);
|
||||
@@ -113,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>
|
||||
@@ -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 });
|
||||
@@ -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 { t } from '@/lib/i18n/index.svelte';
|
||||
import { loadSettings } from '@/lib/stores/settings.svelte';
|
||||
import { num, t } from '@/lib/i18n/index.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: counts.bookmarks, folders: 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>
|
||||
@@ -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 });
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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>
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import type { DuplicateGroup } from '../core/dedupe';
|
||||
import type { EditNode } from '../edit/patch-tree';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import Button from './Button.svelte';
|
||||
|
||||
interface Props {
|
||||
@@ -18,14 +18,14 @@
|
||||
|
||||
<aside aria-label={t('edit.duplicates')}>
|
||||
<header>
|
||||
<strong>{t('edit.duplicatesFound', { groups: groups.length, extra })}</strong>
|
||||
<strong>{t('edit.duplicatesFound', { groups: num(groups.length), extra: num(extra) })}</strong>
|
||||
<button class="close" aria-label={t('common.cancel')} onclick={onclose}>✕</button>
|
||||
</header>
|
||||
|
||||
{#if groups.length === 0}
|
||||
<p class="muted">{t('edit.noDuplicates')}</p>
|
||||
{:else}
|
||||
<Button variant="danger" onclick={onkeepFirst}>{t('edit.keepFirst', { n: extra })}</Button>
|
||||
<Button variant="danger" onclick={onkeepFirst}>{t('edit.keepFirst', { n: num(extra) })}</Button>
|
||||
|
||||
<ul>
|
||||
{#each groups as group (group.key)}
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
} from '../edit/patch-tree';
|
||||
import { canMoveInto, moveTargets } from '../edit/move-target';
|
||||
import { resolveKey, visibleRows } from '../edit/tree-keyboard';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import Button from './Button.svelte';
|
||||
import Callout from './Callout.svelte';
|
||||
import ConfirmDialog from './ConfirmDialog.svelte';
|
||||
@@ -443,7 +443,7 @@
|
||||
danger
|
||||
title={t('edit.deleteTitle')}
|
||||
body={descendantCount > 0
|
||||
? t('edit.deleteFolderBody', { title: pendingDelete?.title ?? '', n: descendantCount })
|
||||
? t('edit.deleteFolderBody', { title: pendingDelete?.title ?? '', n: num(descendantCount) })
|
||||
: t('edit.deleteBody', { title: pendingDelete?.title ?? '' })}
|
||||
confirmLabel={t('edit.delete')}
|
||||
cancelLabel={t('common.cancel')}
|
||||
@@ -456,7 +456,7 @@
|
||||
danger
|
||||
title={t('edit.keepFirstTitle')}
|
||||
body={t('edit.keepFirstBody', {
|
||||
n: duplicateGroups.reduce((n, g) => n + g.nodes.length - 1, 0),
|
||||
n: num(duplicateGroups.reduce((n, g) => n + g.nodes.length - 1, 0)),
|
||||
})}
|
||||
confirmLabel={t('edit.delete')}
|
||||
cancelLabel={t('common.cancel')}
|
||||
|
||||
@@ -6,8 +6,14 @@
|
||||
import type { CsvDelimiter } from '../core/serialize/csv';
|
||||
import type { MarkdownStyle } from '../core/serialize/markdown';
|
||||
import { countSelected, FORMAT_META, runExport } from '../export/run-export';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
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';
|
||||
import Callout from './Callout.svelte';
|
||||
import FolderPickTree from './FolderPickTree.svelte';
|
||||
@@ -17,7 +23,6 @@
|
||||
let selection = $state<ReadonlySet<string> | undefined>(undefined);
|
||||
let format = $state<ExportFormat>('netscape-html');
|
||||
let loadError = $state<string | undefined>();
|
||||
let toast = $state<string | undefined>();
|
||||
let csvDelimiter = $state<CsvDelimiter>(',');
|
||||
let markdownStyle = $state<MarkdownStyle>('nested');
|
||||
|
||||
@@ -55,9 +60,11 @@
|
||||
markdownStyle,
|
||||
now: new Date(),
|
||||
});
|
||||
toast = t('export.saved', { name: result.filename });
|
||||
pushToast(t('export.saved', { name: result.filename }), 'success');
|
||||
} catch (err) {
|
||||
toast = err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN');
|
||||
// Tone matters: this used to share a variable with the success message
|
||||
// and rendered failures in success-green.
|
||||
pushToast(err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN'), 'danger');
|
||||
}
|
||||
})();
|
||||
}
|
||||
@@ -83,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}
|
||||
@@ -96,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}
|
||||
@@ -109,12 +124,9 @@
|
||||
disabled={bookmarkCount === 0}
|
||||
onclick={download}
|
||||
>
|
||||
{t('export.start', { n: bookmarkCount })}
|
||||
{t('export.start', { n: num(bookmarkCount) })}
|
||||
</Button>
|
||||
|
||||
{#if toast !== undefined}
|
||||
<p class="toast" role="status">{toast}</p>
|
||||
{/if}
|
||||
</section>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -155,10 +167,4 @@
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
.toast {
|
||||
margin: 0;
|
||||
font-size: var(--fs-1);
|
||||
color: var(--success);
|
||||
}
|
||||
</style>
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { ImportMode } from '../browser/storage';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import Callout from './Callout.svelte';
|
||||
|
||||
interface Props {
|
||||
@@ -46,7 +46,7 @@
|
||||
disabled={mode === 'replace'}
|
||||
onchange={(e) => onchange({ dedupe: (e.currentTarget as HTMLInputElement).checked })}
|
||||
/>
|
||||
<span>{t('import.dedupe', { n: duplicates })}</span>
|
||||
<span>{t('import.dedupe', { n: num(duplicates) })}</span>
|
||||
</label>
|
||||
|
||||
{#if mode === 'replace'}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { timestampSuffix } from '../browser/download';
|
||||
import { BmAborted, BmBackupError, BmBrowserError } from '../browser/errors';
|
||||
import { BmParseError } from '../core/model';
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import { prepareImport, runImport } from '../import/run-import';
|
||||
import { getSettings } from '../stores/settings.svelte';
|
||||
import {
|
||||
@@ -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> {
|
||||
@@ -122,7 +131,14 @@
|
||||
}
|
||||
}
|
||||
|
||||
/** ISO date + local time, matching the `import.folderName` key (docs/07 §3). */
|
||||
/**
|
||||
* ISO date + local time, matching the `import.folderName` key (docs/07 §3).
|
||||
*
|
||||
* Deliberately NOT run through Intl, unlike every count in this file: docs/07
|
||||
* §3 pins the folder name to the localized *word* plus an ISO date
|
||||
* (`Đã nhập 2026-07-03`). Localizing it here would change the names of
|
||||
* bookmark folders this extension creates in the user's browser.
|
||||
*/
|
||||
function formatFolderDate(now: Date): string {
|
||||
const pad = (n: number): string => String(n).padStart(2, '0');
|
||||
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
|
||||
@@ -136,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">
|
||||
@@ -152,7 +168,7 @@
|
||||
variant={options.mode === 'replace' ? 'danger' : 'primary'}
|
||||
onclick={() => void start(session.filename)}
|
||||
>
|
||||
{t('import.start', { n: session.result.stats.bookmarks })}
|
||||
{t('import.start', { n: num(session.result.stats.bookmarks) })}
|
||||
</Button>
|
||||
</section>
|
||||
</div>
|
||||
@@ -176,18 +192,18 @@
|
||||
label={t('common.import')}
|
||||
/>
|
||||
<p class="muted">
|
||||
{t('import.progress', { done: session.progress.done, total: session.progress.total })}
|
||||
{t('import.progress', { done: num(session.progress.done), total: num(session.progress.total) })}
|
||||
{#if session.progress.currentPath !== ''}<span class="path">{session.progress.currentPath}</span>{/if}
|
||||
</p>
|
||||
<Callout tone="warn">{t('import.keepTabOpen')}</Callout>
|
||||
<Button onclick={cancelWrite}>{t('common.cancel')}</Button>
|
||||
</div>
|
||||
{:else if session.kind === 'done'}
|
||||
<Callout tone="success">{t('import.doneSummary', { created: session.created })}</Callout>
|
||||
<Callout tone="success">{t('import.doneSummary', { created: num(session.created) })}</Callout>
|
||||
<p class="muted">
|
||||
{t('import.skipped', {
|
||||
existing: session.plan.stats.skippedExisting,
|
||||
inFile: session.plan.stats.skippedInFile,
|
||||
existing: num(session.plan.stats.skippedExisting),
|
||||
inFile: num(session.plan.stats.skippedInFile),
|
||||
})}
|
||||
</p>
|
||||
<div class="actions">
|
||||
@@ -197,12 +213,12 @@
|
||||
>
|
||||
</div>
|
||||
{:else if session.kind === 'cancelled'}
|
||||
<Callout tone="warn">{t('import.cancelledSummary', { created: session.created })}</Callout>
|
||||
<Callout tone="warn">{t('import.cancelledSummary', { created: num(session.created) })}</Callout>
|
||||
<Button
|
||||
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>
|
||||
@@ -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>
|
||||
@@ -10,6 +10,9 @@
|
||||
const percent = $derived(total === 0 ? 0 : Math.round((done / total) * 100));
|
||||
// Announce every 10% rather than on every tick — docs/06 §5.
|
||||
const announced = $derived(Math.floor(percent / 10) * 10);
|
||||
// Not run through Intl (unlike counts elsewhere): this is 0–100, and none of
|
||||
// en-US/vi-VN/ja-JP groups a two-digit number — so it would cost a formatter
|
||||
// lookup on the hottest render path in the app and change nothing.
|
||||
</script>
|
||||
|
||||
<div class="wrap">
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import type { TreeStats } from '../core/model';
|
||||
|
||||
interface Props {
|
||||
@@ -11,10 +11,10 @@
|
||||
</script>
|
||||
|
||||
<dl>
|
||||
<div><dt>{t('import.stats.bookmarks')}</dt><dd>{stats.bookmarks}</dd></div>
|
||||
<div><dt>{t('import.stats.folders')}</dt><dd>{stats.folders}</dd></div>
|
||||
<div><dt>{t('import.stats.depth')}</dt><dd>{stats.maxDepth}</dd></div>
|
||||
<div><dt>{t('import.stats.duplicates')}</dt><dd>{duplicates}</dd></div>
|
||||
<div><dt>{t('import.stats.bookmarks')}</dt><dd>{num(stats.bookmarks)}</dd></div>
|
||||
<div><dt>{t('import.stats.folders')}</dt><dd>{num(stats.folders)}</dd></div>
|
||||
<div><dt>{t('import.stats.depth')}</dt><dd>{num(stats.maxDepth)}</dd></div>
|
||||
<div><dt>{t('import.stats.duplicates')}</dt><dd>{num(duplicates)}</dd></div>
|
||||
</dl>
|
||||
|
||||
<style>
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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>
|
||||
@@ -0,0 +1,85 @@
|
||||
<script lang="ts">
|
||||
import { t } from '../i18n/index.svelte';
|
||||
import { dismissToast, getVisibleToast } from '../stores/toast.svelte';
|
||||
|
||||
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}
|
||||
<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);
|
||||
bottom: var(--sp-4);
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
max-width: 44ch;
|
||||
padding: var(--sp-2) var(--sp-3);
|
||||
border: 1px solid var(--border);
|
||||
border-left: 3px solid var(--fg-muted);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-raised);
|
||||
color: var(--fg);
|
||||
font-size: var(--fs-1);
|
||||
box-shadow: 0 4px 16px rgb(0 0 0 / 0.18);
|
||||
}
|
||||
|
||||
.success {
|
||||
border-left-color: var(--success);
|
||||
}
|
||||
|
||||
.danger {
|
||||
border-left-color: var(--danger);
|
||||
}
|
||||
|
||||
button {
|
||||
font: inherit;
|
||||
flex-shrink: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--fg-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
</style>
|
||||
@@ -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}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { 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: warnings.length })}</summary>
|
||||
<summary>{tPlural('import.warnings.title', warnings.length)}</summary>
|
||||
<ul>
|
||||
{#each warnings as warning (warning.code)}
|
||||
<li>{t(`warnings.${warning.code}`, { n: warning.count })}</li>
|
||||
<li>{tPlural(`warnings.${warning.code}`, warning.count)}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
@@ -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 }
|
||||
@@ -44,7 +44,12 @@ export interface ExportPreview {
|
||||
bookmarks: number;
|
||||
}
|
||||
|
||||
/** ISO date for the Markdown heading — locale-independent by design (docs/07 §3). */
|
||||
/**
|
||||
* ISO date for the Markdown heading — locale-independent by design (docs/07 §3).
|
||||
*
|
||||
* Deliberately not `Intl`: file names and file *contents* stay locale-neutral so
|
||||
* an exported file means the same thing whoever opens it.
|
||||
*/
|
||||
function isoDate(now: Date): string {
|
||||
const pad = (n: number): string => String(n).padStart(2, '0');
|
||||
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
|
||||
@@ -112,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':
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Locale-aware number and date formatting — docs/07 §3.
|
||||
*
|
||||
* Purpose: the single place `Intl` is constructed, so every rendered count and
|
||||
* timestamp follows the UI language rather than the browser's.
|
||||
* Inputs: a resolved `Locale`, plus raw numbers / ISO 8601 strings.
|
||||
* Guarantees: pure (no Svelte, no `chrome.*`), never throws — an unparseable
|
||||
* date returns `undefined` rather than blowing up mid-render.
|
||||
*/
|
||||
import type { Locale } from './resolve-locale';
|
||||
|
||||
/** BCP 47 tags docs/07 §3 pins per locale. */
|
||||
export type LocaleTag = 'en-US' | 'vi-VN' | 'ja-JP';
|
||||
|
||||
const TAGS: Record<Locale, LocaleTag> = {
|
||||
en: 'en-US',
|
||||
vi: 'vi-VN',
|
||||
ja: 'ja-JP',
|
||||
};
|
||||
|
||||
// Constructing an Intl formatter is expensive relative to a render, and
|
||||
// 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];
|
||||
}
|
||||
|
||||
/** Group a count for display — VI uses `.` thousands, EN `,`, JA `,`. */
|
||||
export function formatCount(value: number, tag: LocaleTag): string {
|
||||
let format = numberFormats.get(tag);
|
||||
if (format === undefined) {
|
||||
format = new Intl.NumberFormat(tag);
|
||||
numberFormats.set(tag, format);
|
||||
}
|
||||
return format.format(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format an ISO 8601 instant for display.
|
||||
*
|
||||
* Returns `undefined` — not a fallback string — when the input is unparseable.
|
||||
* That is load-bearing: `readLegal` deliberately coerces a missing `acceptedAt`
|
||||
* to `''` (browser/storage.ts), and `Intl.format(new Date(''))` throws a
|
||||
* RangeError *inside a render*, which would blank the whole About tab. Forcing
|
||||
* the caller to branch is the point.
|
||||
*/
|
||||
export function formatDateTime(iso: string, tag: LocaleTag): string | undefined {
|
||||
const date = new Date(iso);
|
||||
if (Number.isNaN(date.getTime())) return undefined;
|
||||
|
||||
let format = dateFormats.get(tag);
|
||||
if (format === undefined) {
|
||||
format = new Intl.DateTimeFormat(tag, { dateStyle: 'medium', timeStyle: 'short' });
|
||||
dateFormats.set(tag, format);
|
||||
}
|
||||
return format.format(date);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { formatCount, formatDateTime, localeTag, selectPluralForm } from './format';
|
||||
import en from './locales/en';
|
||||
import ja from './locales/ja';
|
||||
import vi from './locales/vi';
|
||||
@@ -19,6 +20,27 @@ export function setLocale(next: Locale): void {
|
||||
locale = next;
|
||||
}
|
||||
|
||||
/**
|
||||
* The *resolved* locale (`en|vi|ja`).
|
||||
*
|
||||
* Not to be confused with `getSettings().locale`, the *preference*, which also
|
||||
* carries `'auto'`. Language controls must bind to the preference — binding to
|
||||
* this makes choosing "Automatic" instantly snap the control to "English".
|
||||
*/
|
||||
export function getLocale(): Locale {
|
||||
return locale;
|
||||
}
|
||||
|
||||
/** Group a count for the current locale (docs/07 §3). Reactive. */
|
||||
export function num(value: number): string {
|
||||
return formatCount(value, localeTag(locale));
|
||||
}
|
||||
|
||||
/** Format an ISO instant for the current locale, or `undefined` if unparseable. */
|
||||
export function dateTime(iso: string): string | undefined {
|
||||
return formatDateTime(iso, localeTag(locale));
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a dotted key path, falling back to English, then to the key itself.
|
||||
* Interpolation is `{token}` replacement only — never concatenate sentence
|
||||
@@ -26,6 +48,33 @@ export function setLocale(next: Locale): void {
|
||||
*/
|
||||
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,
|
||||
|
||||
+114
-10
@@ -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: {
|
||||
@@ -123,15 +128,114 @@ const dict = {
|
||||
keepFirstBody:
|
||||
'Keep the first copy of each link and delete the other {n}? This cannot be undone.',
|
||||
},
|
||||
settings: {
|
||||
autosave: 'Changes are saved as you make them.',
|
||||
language: 'Language',
|
||||
languageNote: 'Applies to this extension only, not to the browser.',
|
||||
localeAuto: 'Automatic (follow the browser)',
|
||||
lang: {
|
||||
// Endonyms, deliberately identical in all three dictionaries: a Japanese
|
||||
// user hunting for Vietnamese looks for "Tiếng Việt", not "ベトナム語".
|
||||
en: 'English',
|
||||
vi: 'Tiếng Việt',
|
||||
ja: '日本語',
|
||||
},
|
||||
theme: 'Theme',
|
||||
themes: {
|
||||
system: 'System',
|
||||
light: 'Light',
|
||||
dark: 'Dark',
|
||||
},
|
||||
defaultExportFormat: 'Default export format',
|
||||
defaultExportFormatNote: 'Pre-selected when you open the Export tab.',
|
||||
defaultImportMode: 'Default import mode',
|
||||
defaultImportModeNote: 'Pre-selected when you open the Import tab.',
|
||||
csvDelimiter: 'CSV delimiter',
|
||||
csvDelimiterNote: 'Use semicolons if your spreadsheet expects them.',
|
||||
markdownStyle: 'Markdown layout',
|
||||
markdownStyleNote: 'How exported Markdown arranges your folders.',
|
||||
saved: 'Settings saved',
|
||||
saveFailed: 'Your settings could not be saved.',
|
||||
reset: 'Reset to defaults',
|
||||
resetTitle: 'Reset all settings?',
|
||||
resetBody:
|
||||
'Language, theme and every default choice go back to how they started. Your bookmarks are not touched.',
|
||||
resetConfirm: 'Reset',
|
||||
resetDone: 'Settings reset to defaults',
|
||||
},
|
||||
about: {
|
||||
tagline:
|
||||
'Import, export and edit bookmarks between browsers — offline, no account, no cloud. Your data never leaves your device.',
|
||||
version: 'Version {version}',
|
||||
links: 'Links',
|
||||
repo: 'GitHub repository',
|
||||
issues: 'Report an issue',
|
||||
changelog: 'Releases and changelog',
|
||||
thirdParty: 'Third-party dependencies: None',
|
||||
thirdPartyNote: 'BookmarkMagic ships no runtime libraries at all.',
|
||||
donate: 'Support development',
|
||||
donateNote: 'Entirely optional — BookmarkMagic is free software either way.',
|
||||
legal: 'Legal',
|
||||
accepted: 'Legal terms accepted on {date} · version {version}',
|
||||
acceptedUndated: 'Legal terms accepted · version {version}',
|
||||
notAccepted: 'You have not accepted the legal terms yet.',
|
||||
},
|
||||
legal: {
|
||||
title: 'Before you start',
|
||||
summary:
|
||||
'BookmarkMagic runs entirely on your device. It has no servers, makes no network requests, and collects nothing — your bookmarks and settings never leave this browser. It is free software under the GPL-3.0 licence and comes with no warranty of any kind. Bookmark operations change your browser data, and the "Replace everything" mode deletes your current bookmarks, so keep your own backups of anything you care about.',
|
||||
updatedTitle: 'The terms have been updated',
|
||||
updatedBody:
|
||||
'These documents changed since you accepted them. Please read them again to continue.',
|
||||
documents: 'Documents',
|
||||
eula: 'End User License Agreement',
|
||||
license: 'License (GPL-3.0)',
|
||||
disclaimer: 'Disclaimer',
|
||||
privacy: 'Privacy Policy',
|
||||
englishNote: 'The legally binding documents are in English.',
|
||||
accept: 'I have read and accept the terms above',
|
||||
continue: 'Accept & continue',
|
||||
close: 'Close tab',
|
||||
closeManually: 'You can close this tab now.',
|
||||
saveFailed:
|
||||
'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.',
|
||||
|
||||
+106
-11
@@ -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: {
|
||||
@@ -116,16 +120,107 @@ export default {
|
||||
keepFirstTitle: '重複したコピーを削除しますか?',
|
||||
keepFirstBody: '各リンクの最初のコピーを残し、他の {n} 件を削除しますか?元に戻せません。',
|
||||
},
|
||||
settings: {
|
||||
autosave: '変更は自動的に保存されます。',
|
||||
language: '言語',
|
||||
languageNote: 'この拡張機能だけに適用され、ブラウザの言語は変わりません。',
|
||||
localeAuto: '自動(ブラウザに合わせる)',
|
||||
lang: {
|
||||
// 自称表記。三つの辞書で意図的に同一にしています。
|
||||
en: 'English',
|
||||
vi: 'Tiếng Việt',
|
||||
ja: '日本語',
|
||||
},
|
||||
theme: 'テーマ',
|
||||
themes: {
|
||||
system: 'システム',
|
||||
light: 'ライト',
|
||||
dark: 'ダーク',
|
||||
},
|
||||
defaultExportFormat: '既定のエクスポート形式',
|
||||
defaultExportFormatNote: 'エクスポートタブを開いたときに選択されます。',
|
||||
defaultImportMode: '既定のインポート方法',
|
||||
defaultImportModeNote: 'インポートタブを開いたときに選択されます。',
|
||||
csvDelimiter: 'CSV の区切り文字',
|
||||
csvDelimiterNote: '表計算ソフトが必要とする場合はセミコロンを選んでください。',
|
||||
markdownStyle: 'Markdown のレイアウト',
|
||||
markdownStyleNote: 'エクスポートした Markdown でフォルダを並べる方法です。',
|
||||
saved: '設定を保存しました',
|
||||
saveFailed: '設定を保存できませんでした。',
|
||||
reset: '既定値に戻す',
|
||||
resetTitle: 'すべての設定を戻しますか?',
|
||||
resetBody:
|
||||
'言語・テーマ・すべての既定の選択が初期状態に戻ります。ブックマークには影響しません。',
|
||||
resetConfirm: '戻す',
|
||||
resetDone: '設定を既定値に戻しました',
|
||||
},
|
||||
about: {
|
||||
tagline:
|
||||
'ブラウザ間でブックマークをインポート・エクスポート・編集 — オフライン、アカウント不要、クラウド不要。データが端末から出ることはありません。',
|
||||
version: 'バージョン {version}',
|
||||
links: 'リンク',
|
||||
repo: 'GitHub リポジトリ',
|
||||
issues: '問題を報告',
|
||||
changelog: 'リリースと変更履歴',
|
||||
thirdParty: 'サードパーティ依存: なし',
|
||||
thirdPartyNote: 'BookmarkMagic は実行時ライブラリを一切同梱していません。',
|
||||
donate: '開発を支援する',
|
||||
donateNote: '完全に任意です — BookmarkMagic はどちらにせよ自由ソフトウェアです。',
|
||||
legal: '法的事項',
|
||||
accepted: '{date} に規約に同意済み · バージョン {version}',
|
||||
acceptedUndated: '規約に同意済み · バージョン {version}',
|
||||
notAccepted: 'まだ法的規約に同意していません。',
|
||||
},
|
||||
legal: {
|
||||
title: 'ご利用の前に',
|
||||
summary:
|
||||
'BookmarkMagic は完全にお使いの端末上で動作します。サーバーを持たず、ネットワーク通信を行わず、何も収集しません — ブックマークと設定がこのブラウザから出ることはありません。GPL-3.0 ライセンスの自由ソフトウェアであり、いかなる保証もありません。ブックマーク操作はブラウザのデータを変更し、「すべて置き換える」方法では現在のブックマークが削除されますので、大切なものはご自身でバックアップを保管してください。',
|
||||
updatedTitle: '規約が更新されました',
|
||||
updatedBody:
|
||||
'ご同意いただいた後にこれらの文書が変更されました。続けるにはもう一度お読みください。',
|
||||
documents: '文書',
|
||||
eula: 'エンドユーザーライセンス契約',
|
||||
license: 'ライセンス(GPL-3.0)',
|
||||
disclaimer: '免責事項',
|
||||
privacy: 'プライバシーポリシー',
|
||||
englishNote: '法的効力を持つ文書は英語で書かれています。',
|
||||
accept: '上記の規約を読み、同意します',
|
||||
continue: '同意して続ける',
|
||||
close: 'タブを閉じる',
|
||||
closeManually: 'このタブを閉じていただいて構いません。',
|
||||
saveFailed:
|
||||
'同意を保存できなかったため、何も記録されていません。このブラウザで拡張機能のストレージが許可されているか確認してから、もう一度お試しください。',
|
||||
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 ファイルではないようです。',
|
||||
|
||||
+105
-9
@@ -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: {
|
||||
@@ -115,14 +119,106 @@ export default {
|
||||
keepFirstTitle: 'Xóa các bản trùng?',
|
||||
keepFirstBody: 'Giữ bản đầu tiên của mỗi liên kết và xóa {n} bản còn lại? Không thể hoàn tác.',
|
||||
},
|
||||
settings: {
|
||||
autosave: 'Thay đổi được lưu ngay khi bạn chỉnh.',
|
||||
language: 'Ngôn ngữ',
|
||||
languageNote: 'Chỉ áp dụng cho tiện ích này, không đổi ngôn ngữ trình duyệt.',
|
||||
localeAuto: 'Tự động (theo trình duyệt)',
|
||||
lang: {
|
||||
// Tên bản ngữ, cố ý giữ giống hệt nhau ở cả ba từ điển.
|
||||
en: 'English',
|
||||
vi: 'Tiếng Việt',
|
||||
ja: '日本語',
|
||||
},
|
||||
theme: 'Giao diện',
|
||||
themes: {
|
||||
system: 'Theo hệ thống',
|
||||
light: 'Sáng',
|
||||
dark: 'Tối',
|
||||
},
|
||||
defaultExportFormat: 'Định dạng xuất mặc định',
|
||||
defaultExportFormatNote: 'Được chọn sẵn khi bạn mở thẻ Xuất.',
|
||||
defaultImportMode: 'Chế độ nhập mặc định',
|
||||
defaultImportModeNote: 'Được chọn sẵn khi bạn mở thẻ Nhập.',
|
||||
csvDelimiter: 'Ký tự phân cách CSV',
|
||||
csvDelimiterNote: 'Dùng dấu chấm phẩy nếu bảng tính của bạn cần.',
|
||||
markdownStyle: 'Bố cục Markdown',
|
||||
markdownStyleNote: 'Cách sắp xếp thư mục trong tệp Markdown xuất ra.',
|
||||
saved: 'Đã lưu cài đặt',
|
||||
saveFailed: 'Không thể lưu cài đặt của bạn.',
|
||||
reset: 'Khôi phục mặc định',
|
||||
resetTitle: 'Khôi phục toàn bộ cài đặt?',
|
||||
resetBody:
|
||||
'Ngôn ngữ, giao diện và mọi lựa chọn mặc định sẽ trở về ban đầu. Bookmark của bạn không bị đụng tới.',
|
||||
resetConfirm: 'Khôi phục',
|
||||
resetDone: 'Đã khôi phục cài đặt mặc định',
|
||||
},
|
||||
about: {
|
||||
tagline:
|
||||
'Nhập, xuất và chỉnh sửa bookmark giữa các trình duyệt — ngoại tuyến, không tài khoản, không đám mây. Dữ liệu của bạn không bao giờ rời khỏi máy.',
|
||||
version: 'Phiên bản {version}',
|
||||
links: 'Liên kết',
|
||||
repo: 'Kho mã trên GitHub',
|
||||
issues: 'Báo lỗi',
|
||||
changelog: 'Bản phát hành và nhật ký thay đổi',
|
||||
thirdParty: 'Thư viện bên thứ ba: Không có',
|
||||
thirdPartyNote: 'BookmarkMagic không đi kèm bất kỳ thư viện chạy nào.',
|
||||
donate: 'Ủng hộ dự án',
|
||||
donateNote: 'Hoàn toàn tự nguyện — BookmarkMagic vẫn là phần mềm tự do.',
|
||||
legal: 'Pháp lý',
|
||||
accepted: 'Đã chấp nhận điều khoản ngày {date} · phiên bản {version}',
|
||||
acceptedUndated: 'Đã chấp nhận điều khoản · phiên bản {version}',
|
||||
notAccepted: 'Bạn chưa chấp nhận các điều khoản pháp lý.',
|
||||
},
|
||||
legal: {
|
||||
title: 'Trước khi bắt đầu',
|
||||
summary:
|
||||
'BookmarkMagic chạy hoàn toàn trên máy của bạn. Tiện ích không có máy chủ, không gửi yêu cầu mạng và không thu thập gì cả — bookmark và cài đặt của bạn không bao giờ rời khỏi trình duyệt này. Đây là phần mềm tự do theo giấy phép GPL-3.0 và không kèm bảo hành dưới bất kỳ hình thức nào. Các thao tác bookmark sẽ thay đổi dữ liệu trình duyệt, và chế độ "Thay thế toàn bộ" sẽ xóa bookmark hiện tại, nên hãy tự giữ bản sao lưu cho những gì bạn cần.',
|
||||
updatedTitle: 'Các điều khoản đã được cập nhật',
|
||||
updatedBody: 'Những tài liệu này đã thay đổi kể từ lần bạn chấp nhận. Hãy đọc lại để tiếp tục.',
|
||||
documents: 'Tài liệu',
|
||||
eula: 'Thỏa thuận cấp phép người dùng cuối',
|
||||
license: 'Giấy phép (GPL-3.0)',
|
||||
disclaimer: 'Tuyên bố miễn trừ',
|
||||
privacy: 'Chính sách quyền riêng tư',
|
||||
englishNote: 'Các tài liệu có hiệu lực pháp lý được viết bằng tiếng Anh.',
|
||||
accept: 'Tôi đã đọc và chấp nhận các điều khoản trên',
|
||||
continue: 'Chấp nhận & tiếp tục',
|
||||
close: 'Đóng thẻ',
|
||||
closeManually: 'Bạn có thể đóng thẻ này ngay bây giờ.',
|
||||
saveFailed:
|
||||
'Không thể lưu việc chấp nhận của bạn, nên chưa có gì được ghi lại. Hãy kiểm tra xem trình duyệt có cho phép tiện ích lưu trữ hay không, rồi thử lại.',
|
||||
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.',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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' },
|
||||
];
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 });
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Transient status messages — docs/06 §4 (queue, auto-dismiss 4 s, ARIA status).
|
||||
*
|
||||
* Purpose: one place that owns toast state AND its timers.
|
||||
* Inputs: `pushToast` calls from anywhere in the Manager.
|
||||
* Guarantees: exactly one toast is visible at a time; a timer can only ever
|
||||
* dismiss the item that started it; nothing here touches the DOM, so a fired
|
||||
* timer is harmless even when no `<Toast>` is rendered.
|
||||
*
|
||||
* The store owns the timers rather than the component because `<Toast>` mounts
|
||||
* once at the App root while the route chain below it unmounts on every
|
||||
* navigation. Component-owned timers would leak by construction; this way there
|
||||
* is nothing to clean up.
|
||||
*/
|
||||
|
||||
export type ToastTone = 'success' | 'danger' | 'info';
|
||||
|
||||
export interface ToastItem {
|
||||
id: string;
|
||||
message: string;
|
||||
tone: ToastTone;
|
||||
}
|
||||
|
||||
const AUTO_DISMISS_MS = 4000;
|
||||
/** Overflow drops the oldest *pending* item — never the one on screen. */
|
||||
const MAX_QUEUED = 3;
|
||||
|
||||
let queue = $state<ToastItem[]>([]);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let nextId = 0;
|
||||
|
||||
export function getVisibleToast(): ToastItem | undefined {
|
||||
return queue[0];
|
||||
}
|
||||
|
||||
export function pushToast(message: string, tone: ToastTone = 'info'): void {
|
||||
const visible = queue[0];
|
||||
|
||||
// A repeat of what is already on screen restarts its timer instead of
|
||||
// queueing a twin. One debounced settings save resolves one promise that may
|
||||
// have several subscribers, and without this the user gets three identical
|
||||
// "Settings saved" toasts in a row.
|
||||
if (visible !== undefined && visible.message === message && visible.tone === tone) {
|
||||
startTimer(visible.id);
|
||||
return;
|
||||
}
|
||||
|
||||
nextId += 1;
|
||||
const item: ToastItem = { id: `toast-${nextId}`, message, tone };
|
||||
|
||||
if (queue.length >= MAX_QUEUED) queue = [...queue.slice(0, 1), ...queue.slice(2), item];
|
||||
else queue = [...queue, item];
|
||||
|
||||
if (queue.length === 1) startTimer(item.id);
|
||||
}
|
||||
|
||||
export function dismissToast(id: string): void {
|
||||
if (queue[0]?.id !== id) return;
|
||||
shift();
|
||||
}
|
||||
|
||||
/** Test teardown — module state outlives a single `it()`. */
|
||||
export function clearToasts(): void {
|
||||
clearTimer();
|
||||
queue = [];
|
||||
nextId = 0;
|
||||
}
|
||||
|
||||
function shift(): void {
|
||||
clearTimer();
|
||||
queue = queue.slice(1);
|
||||
const next = queue[0];
|
||||
if (next !== undefined) startTimer(next.id);
|
||||
}
|
||||
|
||||
function startTimer(id: string): void {
|
||||
clearTimer();
|
||||
timer = setTimeout(() => {
|
||||
timer = undefined;
|
||||
// The identity check is what stops a user dismiss racing this timeout from
|
||||
// shifting twice and flashing the next toast for a single frame.
|
||||
if (queue[0]?.id !== id) return;
|
||||
shift();
|
||||
}, AUTO_DISMISS_MS);
|
||||
}
|
||||
|
||||
function clearTimer(): void {
|
||||
if (timer === undefined) return;
|
||||
clearTimeout(timer);
|
||||
timer = undefined;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import en from '@/lib/i18n/locales/en';
|
||||
import ja from '@/lib/i18n/locales/ja';
|
||||
import vi from '@/lib/i18n/locales/vi';
|
||||
|
||||
/**
|
||||
* Runtime companions to the `satisfies Dict` compile check (docs/07 §2).
|
||||
*
|
||||
* The compile check proves the *shape* matches. It is blind to what these
|
||||
* assert: interpolation tokens drifting between locales, empty leaves, and the
|
||||
* check itself being silently disabled by someone changing `satisfies` to `as`.
|
||||
*/
|
||||
|
||||
type Node = { [key: string]: Node | string };
|
||||
|
||||
const LOCALES: [name: string, dict: Node][] = [
|
||||
['vi', vi as Node],
|
||||
['ja', ja as Node],
|
||||
];
|
||||
|
||||
/** Every leaf as a dotted path → value. */
|
||||
function flatten(node: Node, prefix = ''): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
for (const [key, value] of Object.entries(node)) {
|
||||
const path = prefix === '' ? key : `${prefix}.${key}`;
|
||||
if (typeof value === 'string') out.set(path, value);
|
||||
else for (const [inner, text] of flatten(value, path)) out.set(inner, text);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `{token}` names, sorted, so two orderings of the same set compare equal. */
|
||||
function tokens(text: string): string[] {
|
||||
return [...text.matchAll(/\{(\w+)\}/gu)].map((match) => match[1] ?? '').sort();
|
||||
}
|
||||
|
||||
/** Every branch node as a dotted path → its own key names. */
|
||||
function branches(node: Node, prefix = ''): Map<string, string[]> {
|
||||
const out = new Map<string, string[]>();
|
||||
for (const [key, value] of Object.entries(node)) {
|
||||
if (typeof value === 'string') continue;
|
||||
const path = prefix === '' ? key : `${prefix}.${key}`;
|
||||
out.set(path, Object.keys(value));
|
||||
for (const [inner, keys] of branches(value, path)) out.set(inner, keys);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const english = flatten(en as Node);
|
||||
|
||||
describe('dictionary completeness', () => {
|
||||
it.each(LOCALES)('%s has exactly the same key paths as en', (_name, dict) => {
|
||||
expect([...flatten(dict).keys()].sort()).toEqual([...english.keys()].sort());
|
||||
});
|
||||
|
||||
it.each(LOCALES)('%s uses the same interpolation tokens as en in every string', (_name, dict) => {
|
||||
// `satisfies Dict` cannot see this: a translation that drops {total} from
|
||||
// 'Importing… {done} / {total}' type-checks and renders a broken sentence.
|
||||
const drift: string[] = [];
|
||||
for (const [path, text] of flatten(dict)) {
|
||||
const expected = tokens(english.get(path) ?? '');
|
||||
const actual = tokens(text);
|
||||
if (actual.join('|') !== expected.join('|')) {
|
||||
drift.push(`${path}: expected {${expected.join('}, {')}}, got {${actual.join('}, {')}}`);
|
||||
}
|
||||
}
|
||||
expect(drift).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([['en', en as Node], ...LOCALES])('%s has no empty leaves', (_name, dict) => {
|
||||
const empty = [...flatten(dict)].filter(([, text]) => text.trim() === '').map(([path]) => path);
|
||||
expect(empty).toEqual([]);
|
||||
});
|
||||
|
||||
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(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([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { formatCount, formatDateTime, localeTag, selectPluralForm } from '@/lib/i18n/format';
|
||||
import { dateTime, getLocale, num, setLocale, tPlural } from '@/lib/i18n/index.svelte';
|
||||
|
||||
afterEach(() => {
|
||||
setLocale('en');
|
||||
});
|
||||
|
||||
describe('localeTag', () => {
|
||||
it('maps each locale onto the BCP 47 tag docs/07 §3 pins', () => {
|
||||
expect(localeTag('en')).toBe('en-US');
|
||||
expect(localeTag('vi')).toBe('vi-VN');
|
||||
expect(localeTag('ja')).toBe('ja-JP');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatCount', () => {
|
||||
it('groups thousands for English', () => {
|
||||
expect(formatCount(1_234_567, 'en-US')).toBe('1,234,567');
|
||||
});
|
||||
|
||||
it('groups thousands for vi/ja with a locale-appropriate separator', () => {
|
||||
// Asserted structurally rather than glyph-for-glyph: ICU separator data can
|
||||
// shift between Node releases, and a brittle assertion here would block an
|
||||
// unrelated Node bump for no real gain.
|
||||
expect(formatCount(1_234_567, 'vi-VN')).toMatch(/^1\D234\D567$/u);
|
||||
expect(formatCount(1_234_567, 'ja-JP')).toMatch(/^1\D234\D567$/u);
|
||||
expect(formatCount(1_234_567, 'vi-VN')).not.toBe(formatCount(1_234_567, 'en-US'));
|
||||
});
|
||||
|
||||
it('keeps the cache keyed by tag — interleaved calls do not bleed', () => {
|
||||
const en = formatCount(1_000, 'en-US');
|
||||
const vi = formatCount(1_000, 'vi-VN');
|
||||
expect(formatCount(1_000, 'en-US')).toBe(en);
|
||||
expect(formatCount(1_000, 'vi-VN')).toBe(vi);
|
||||
expect(en).not.toBe(vi);
|
||||
});
|
||||
|
||||
it('leaves small numbers alone in every locale', () => {
|
||||
expect(formatCount(0, 'en-US')).toBe('0');
|
||||
expect(formatCount(42, 'ja-JP')).toBe('42');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatDateTime', () => {
|
||||
it('renders a valid instant, differently per locale', () => {
|
||||
const en = formatDateTime('2026-07-25T10:00:00.000Z', 'en-US');
|
||||
const ja = formatDateTime('2026-07-25T10:00:00.000Z', 'ja-JP');
|
||||
// Not an exact string: output is timezone-dependent and the suite does not
|
||||
// pin TZ (doing so would change every existing date test's environment).
|
||||
expect(en).toContain('2026');
|
||||
expect(ja).toContain('2026');
|
||||
expect(en).not.toBe(ja);
|
||||
});
|
||||
|
||||
it('returns undefined instead of throwing on an unparseable date', () => {
|
||||
// readLegal coerces a missing acceptedAt to '' (browser/storage.ts), and
|
||||
// Intl.format(new Date('')) throws RangeError *inside a render*, which
|
||||
// would blank the About tab. This is the guard against that.
|
||||
expect(formatDateTime('', 'en-US')).toBeUndefined();
|
||||
expect(formatDateTime('not-a-date', 'en-US')).toBeUndefined();
|
||||
expect(() => formatDateTime('', 'ja-JP')).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
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
|
||||
// does. Language controls must bind to the preference, not to this.
|
||||
setLocale('ja');
|
||||
expect(getLocale()).toBe('ja');
|
||||
});
|
||||
|
||||
it('num() follows setLocale', () => {
|
||||
setLocale('vi');
|
||||
expect(num(1_234_567)).toBe(formatCount(1_234_567, 'vi-VN'));
|
||||
setLocale('en');
|
||||
expect(num(1_234_567)).toBe('1,234,567');
|
||||
});
|
||||
|
||||
it('dateTime() follows setLocale and propagates the undefined guard', () => {
|
||||
setLocale('ja');
|
||||
expect(dateTime('2026-07-25T10:00:00.000Z')).toBe(
|
||||
formatDateTime('2026-07-25T10:00:00.000Z', 'ja-JP'),
|
||||
);
|
||||
expect(dateTime('')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { clearToasts, dismissToast, getVisibleToast, pushToast } from '@/lib/stores/toast.svelte';
|
||||
|
||||
beforeEach(() => {
|
||||
clearToasts();
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
clearToasts();
|
||||
});
|
||||
|
||||
describe('toast queue', () => {
|
||||
it('shows a pushed message and dismisses it after 4 s', () => {
|
||||
pushToast('Saved', 'success');
|
||||
expect(getVisibleToast()?.message).toBe('Saved');
|
||||
|
||||
vi.advanceTimersByTime(3999);
|
||||
expect(getVisibleToast()).toBeDefined();
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(getVisibleToast()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('is a queue, not a stack — the second waits for the first', () => {
|
||||
pushToast('first');
|
||||
pushToast('second');
|
||||
expect(getVisibleToast()?.message).toBe('first');
|
||||
|
||||
vi.advanceTimersByTime(4000);
|
||||
expect(getVisibleToast()?.message).toBe('second');
|
||||
|
||||
vi.advanceTimersByTime(4000);
|
||||
expect(getVisibleToast()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('restarts the timer for a repeat of the visible message instead of queueing a twin', () => {
|
||||
// One debounced settings save resolves one promise with several
|
||||
// subscribers; without this the user gets three identical "Saved" toasts.
|
||||
pushToast('Settings saved', 'success');
|
||||
vi.advanceTimersByTime(3000);
|
||||
pushToast('Settings saved', 'success');
|
||||
|
||||
vi.advanceTimersByTime(3000);
|
||||
expect(getVisibleToast()?.message).toBe('Settings saved');
|
||||
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(getVisibleToast()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('treats the same text with a different tone as a distinct toast', () => {
|
||||
pushToast('Done', 'success');
|
||||
pushToast('Done', 'danger');
|
||||
vi.advanceTimersByTime(4000);
|
||||
expect(getVisibleToast()?.tone).toBe('danger');
|
||||
});
|
||||
|
||||
it('does not let a stale timer shift the next item early after a manual dismiss', () => {
|
||||
pushToast('first');
|
||||
const first = getVisibleToast();
|
||||
pushToast('second');
|
||||
|
||||
vi.advanceTimersByTime(1000);
|
||||
dismissToast(first?.id ?? '');
|
||||
expect(getVisibleToast()?.message).toBe('second');
|
||||
|
||||
// The first item's original 4 s deadline passes here. Without the id check
|
||||
// in the timeout it would shift again and flash "second" away instantly.
|
||||
vi.advanceTimersByTime(3000);
|
||||
expect(getVisibleToast()?.message).toBe('second');
|
||||
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(getVisibleToast()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores a dismiss for an item that is not on screen', () => {
|
||||
pushToast('first');
|
||||
pushToast('second');
|
||||
const queuedId = 'toast-2';
|
||||
|
||||
dismissToast(queuedId);
|
||||
expect(getVisibleToast()?.message).toBe('first');
|
||||
});
|
||||
|
||||
it('caps the queue by dropping the oldest pending item, never the visible one', () => {
|
||||
pushToast('visible');
|
||||
pushToast('pending-a');
|
||||
pushToast('pending-b');
|
||||
pushToast('pending-c');
|
||||
|
||||
expect(getVisibleToast()?.message).toBe('visible');
|
||||
vi.advanceTimersByTime(4000);
|
||||
// 'pending-a' was the oldest queued item when the cap was hit.
|
||||
expect(getVisibleToast()?.message).toBe('pending-b');
|
||||
vi.advanceTimersByTime(4000);
|
||||
expect(getVisibleToast()?.message).toBe('pending-c');
|
||||
vi.advanceTimersByTime(4000);
|
||||
expect(getVisibleToast()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('defaults to the info tone', () => {
|
||||
pushToast('plain');
|
||||
expect(getVisibleToast()?.tone).toBe('info');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user