feat(settings): the #settings tab, header controls, and a save path that tells the truth
Six rows per docs/06 §3.4 as amended -- the doc drew five, but Settings has carried markdownStyle since Phase 3 and #export was the only place to change it, so it never actually persisted. Plus the header language/theme controls from the docs/06 §3 layout, which have been missing since Phase 0. Three defects in the store had to be fixed for any of this to work, and none of them could fail before, because updateSettings and resetSettings had zero callers in src/: - writeSettings handed the Svelte $state proxy to chrome.storage.local.set, which structured-clones its argument. Proxies are not cloneable, so every save would have thrown DataCloneError in a real browser. fakeBrowser stores the reference without cloning, which is why 338 green tests never saw it; the new test clones explicitly to reproduce Chrome. - updateSettings replaced the settings object rather than mutating it, so any component capturing getSettings() into a local would silently stop updating. Four new components read this store. Now in-place, with an identity test. - resetSettings left the pending debounce running, so a reset within 200 ms of a change wrote twice -- the first write persisting values just discarded. updateSettings now returns a SaveOutcome that resolves when the write settles and never rejects, so the "Saved" toast reports what happened instead of assuming. flushSettings on visibilitychange shrinks the loss window from 200 ms to roughly nothing; the comment is explicit that it does not reach zero. Both entrypoints now await settings before mount() and drop the unguarded browser.i18n.getUILanguage() call at module scope, which could blank the page on a throw. Awaiting means the pre-load frame is an empty #app rather than content painted in the wrong locale and theme. Verified top-level await survives wxt build. Also gates the footer nav on isWriting(): navigating away during `attesting` unmounts ImportTab and strands its attestation resolver, deadlocking the import until reload. TabBar already guarded this; the footer was the way around it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
13 files changed
+853
-47
No files matched your search
@@ -3,15 +3,21 @@
|
||||
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 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 { 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());
|
||||
|
||||
onMount(() => {
|
||||
void loadSettings();
|
||||
const stopRouting = startRouting();
|
||||
|
||||
// Leaving mid-write would kill the queue with the tab (docs/03 §5).
|
||||
@@ -19,13 +25,31 @@
|
||||
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. */
|
||||
function save(patch: Parameters<typeof updateSettings>[0]): void {
|
||||
void updateSettings(patch).then((outcome) => {
|
||||
if (outcome.ok) pushToast(t('settings.saved'), 'success');
|
||||
else pushToast(outcome.detail ?? t('settings.saveFailed'), 'danger');
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<header>
|
||||
@@ -34,6 +58,10 @@
|
||||
<strong>{t('common.appName')}</strong>
|
||||
</div>
|
||||
<TabBar />
|
||||
<div class="controls">
|
||||
<LanguageSwitcher compact value={settings.locale} onchange={(locale) => save({ locale })} />
|
||||
<ThemeToggle compact value={settings.theme} onchange={(theme) => save({ theme })} />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
@@ -43,8 +71,10 @@
|
||||
<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. -->
|
||||
<!-- Phase 4's About tab lands in the next commit. -->
|
||||
<p class="placeholder">{t('common.comingSoon', { tab: t(`common.${getRoute()}`) })}</p>
|
||||
{/if}
|
||||
</main>
|
||||
@@ -52,8 +82,19 @@
|
||||
<footer>
|
||||
<span>v0.1.0 · GPL-3.0</span>
|
||||
<nav>
|
||||
<button onclick={() => navigate('settings')}>{t('common.settings')}</button>
|
||||
<button onclick={() => navigate('about')}>{t('common.about')}</button>
|
||||
<!-- Gated like TabBar's tabs: navigating away mid-write unmounts ImportTab
|
||||
and strands the attestation resolver, deadlocking the import
|
||||
(docs/03 §5). The footer used to be the one way around that. -->
|
||||
<button
|
||||
disabled={isWriting()}
|
||||
title={isWriting() ? t('common.busy') : undefined}
|
||||
onclick={() => navigate('settings')}>{t('common.settings')}</button
|
||||
>
|
||||
<button
|
||||
disabled={isWriting()}
|
||||
title={isWriting() ? t('common.busy') : undefined}
|
||||
onclick={() => navigate('about')}>{t('common.about')}</button
|
||||
>
|
||||
</nav>
|
||||
</footer>
|
||||
|
||||
@@ -89,6 +130,12 @@
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.mark {
|
||||
color: var(--accent);
|
||||
}
|
||||
@@ -118,7 +165,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,22 @@
|
||||
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;
|
||||
|
||||
// Settings are read 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. Awaiting means that frame
|
||||
// holds an empty #app instead: a blank moment rather than a visible EN->VI or
|
||||
// light->dark flip for exactly the users who bothered to change the setting.
|
||||
//
|
||||
// readSettings never throws (browser/storage.ts) and applyLocale guards the
|
||||
// i18n lookup, so this cannot leave the page unmounted. No timeout race:
|
||||
// storage.local.get always settles, and racing it would just re-introduce the
|
||||
// wrong-locale render this exists to prevent.
|
||||
await loadSettings();
|
||||
|
||||
export default mount(App, { target });
|
||||
@@ -3,12 +3,11 @@
|
||||
import { getRootChildren } from '@/lib/browser/bookmarks';
|
||||
import { openManager } from '@/lib/browser/open-manager';
|
||||
import { num, t } from '@/lib/i18n/index.svelte';
|
||||
import { loadSettings } from '@/lib/stores/settings.svelte';
|
||||
|
||||
let counts = $state<{ bookmarks: number; folders: number } | undefined>();
|
||||
|
||||
// Settings are loaded and awaited in main.ts, before this ever mounts.
|
||||
onMount(() => {
|
||||
void loadSettings();
|
||||
void countTree();
|
||||
});
|
||||
|
||||
|
||||
@@ -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 });
|
||||
@@ -7,6 +7,11 @@
|
||||
import type { MarkdownStyle } from '../core/serialize/markdown';
|
||||
import { countSelected, FORMAT_META, runExport } from '../export/run-export';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import {
|
||||
CSV_DELIMITER_CHOICES,
|
||||
MARKDOWN_STYLE_CHOICES,
|
||||
parseChoice,
|
||||
} from '../settings/options';
|
||||
import { getSettings } from '../stores/settings.svelte';
|
||||
import { pushToast } from '../stores/toast.svelte';
|
||||
import Button from './Button.svelte';
|
||||
@@ -85,10 +90,14 @@
|
||||
<span>{t('export.csvDelimiter')}</span>
|
||||
<select
|
||||
value={csvDelimiter}
|
||||
onchange={(e) => (csvDelimiter = (e.currentTarget as HTMLSelectElement).value as CsvDelimiter)}
|
||||
onchange={(e) => {
|
||||
const next = parseChoice(e.currentTarget.value, CSV_DELIMITER_CHOICES);
|
||||
if (next !== undefined) csvDelimiter = next;
|
||||
}}
|
||||
>
|
||||
<option value=",">{t('export.comma')}</option>
|
||||
<option value=";">{t('export.semicolon')}</option>
|
||||
{#each CSV_DELIMITER_CHOICES as choice (choice.value)}
|
||||
<option value={choice.value}>{t(choice.labelKey)}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
{/if}
|
||||
@@ -98,10 +107,14 @@
|
||||
<span>{t('export.markdownStyle')}</span>
|
||||
<select
|
||||
value={markdownStyle}
|
||||
onchange={(e) => (markdownStyle = (e.currentTarget as HTMLSelectElement).value as MarkdownStyle)}
|
||||
onchange={(e) => {
|
||||
const next = parseChoice(e.currentTarget.value, MARKDOWN_STYLE_CHOICES);
|
||||
if (next !== undefined) markdownStyle = next;
|
||||
}}
|
||||
>
|
||||
<option value="nested">{t('export.nested')}</option>
|
||||
<option value="flat">{t('export.flat')}</option>
|
||||
{#each MARKDOWN_STYLE_CHOICES as choice (choice.value)}
|
||||
<option value={choice.value}>{t(choice.labelKey)}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
{/if}
|
||||
|
||||
@@ -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,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,184 @@
|
||||
<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);
|
||||
|
||||
/**
|
||||
* 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');
|
||||
else pushToast(outcome.detail ?? t('settings.saveFailed'), 'danger');
|
||||
});
|
||||
}
|
||||
|
||||
/** 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');
|
||||
else pushToast(outcome.detail ?? t('settings.saveFailed'), 'danger');
|
||||
});
|
||||
}
|
||||
</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>
|
||||
|
||||
<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);
|
||||
}
|
||||
|
||||
footer {
|
||||
padding-top: var(--sp-4);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,79 @@
|
||||
<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: '☾',
|
||||
};
|
||||
</script>
|
||||
|
||||
<div class="group" class:compact role="radiogroup" aria-label={t('settings.theme')}>
|
||||
{#each THEME_CHOICES as choice (choice.value)}
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={value === choice.value}
|
||||
aria-label={compact ? t(choice.labelKey) : undefined}
|
||||
class:selected={value === choice.value}
|
||||
onclick={() => onchange(choice.value)}
|
||||
>
|
||||
{#if compact}
|
||||
<span aria-hidden="true">{GLYPH[choice.value]}</span>
|
||||
{:else}
|
||||
{t(choice.labelKey)}
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.group {
|
||||
display: inline-flex;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
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:last-child {
|
||||
border-right: none;
|
||||
}
|
||||
|
||||
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,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;
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -18,9 +22,17 @@ 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,32 +44,101 @@ 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 {
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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,86 @@ 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('still loads when the browser i18n lookup throws', async () => {
|
||||
vi.spyOn(fakeBrowser.i18n, 'getUILanguage').mockImplementation(() => {
|
||||
throw new Error('not implemented');
|
||||
@@ -78,10 +163,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();
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user