fix(i18n): plural forms, the count the retrofit missed, and error text that re-translates

Last batch from the Phase 4 adversarial review, including one the completeness
critic caught that none of the six lenses looked for.

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

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

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

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 committed 2026-07-26 13:37:31 +07:00
1 parent 2937f4edf0
commit 21fd11ce30
14 files changed
+260 -53

No files matched your search

+13
View File
@@ -24,3 +24,16 @@ export function getAppVersion(): string {
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;
}
+2 -2
View File
@@ -1,7 +1,7 @@
<script lang="ts">
import type { LiveNode } from '../browser/bookmarks';
import type { CheckState } from '../core/select';
import { t } from '../i18n/index.svelte';
import { num, t } from '../i18n/index.svelte';
import Self from './FolderPickNode.svelte';
interface Props {
@@ -53,7 +53,7 @@
onchange={(e) => ontoggle(node, (e.currentTarget as HTMLInputElement).checked)}
/>
<span class="title">{node.title}</span>
{#if bookmarks > 0}<span class="count">{bookmarks}</span>{/if}
{#if bookmarks > 0}<span class="count">{num(bookmarks)}</span>{/if}
</label>
</div>
+15 -6
View File
@@ -41,17 +41,26 @@
attestResolve = undefined;
}
function describeError(err: unknown): { message: string; detail: string | undefined } {
/**
* Map an error onto an i18n KEY plus a raw detail — never a resolved string.
* The session store outlives this component, and `t()` only re-runs where it
* is called, so a translated sentence stored here would never follow a
* language switch.
*/
function describeError(err: unknown): { messageKey: string; detail: string | undefined } {
if (err instanceof BmParseError) {
return { message: t(`errors.${err.code}`), detail: err.detail };
return { messageKey: `errors.${err.code}`, detail: err.detail };
}
if (err instanceof BmBackupError) {
return { message: t(`errors.${err.code}`), detail: err.message };
return { messageKey: `errors.${err.code}`, detail: err.message };
}
if (err instanceof BmBrowserError) {
return { message: t('errors.BROWSER'), detail: err.detail };
return { messageKey: 'errors.BROWSER', detail: err.detail };
}
return { message: t('errors.UNKNOWN'), detail: err instanceof Error ? err.message : undefined };
return {
messageKey: 'errors.UNKNOWN',
detail: err instanceof Error ? err.message : undefined,
};
}
async function onFile(file: File): Promise<void> {
@@ -209,7 +218,7 @@
onclick={resetImport}>{t('import.another')}</Button
>
{:else if session.kind === 'error'}
<Callout tone="danger">{session.message}</Callout>
<Callout tone="danger">{t(session.messageKey)}</Callout>
{#if session.detail !== undefined}
<pre class="detail">{session.detail}</pre>
{/if}
+3 -3
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { num, t } from '../i18n/index.svelte';
import { tPlural } from '../i18n/index.svelte';
import type { ParseWarning } from '../core/model';
interface Props {
@@ -11,10 +11,10 @@
{#if warnings.length > 0}
<details>
<summary>{t('import.warnings.title', { n: num(warnings.length) })}</summary>
<summary>{tPlural('import.warnings.title', warnings.length)}</summary>
<ul>
{#each warnings as warning (warning.code)}
<li>{t(`warnings.${warning.code}`, { n: num(warning.count) })}</li>
<li>{tPlural(`warnings.${warning.code}`, warning.count)}</li>
{/each}
</ul>
</details>
+2 -2
View File
@@ -7,7 +7,7 @@
* loses nothing).
*/
import { getAppVersion } from '../browser/app-info';
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';
@@ -117,7 +117,7 @@ function serialize(nodes: ReturnType<typeof toBookmarkNodes>, options: ExportOpt
return serializeNetscapeHtml(nodes);
case 'bm-json':
return serializeBmJson(nodes, {
version: getAppVersion(),
version: getGeneratorVersion(),
exportedAt: options.now.toISOString(),
});
case 'csv':
+21
View File
@@ -22,6 +22,27 @@ const TAGS: Record<Locale, LocaleTag> = {
// StatsCard alone formats four counts per paint — so cache per tag.
const numberFormats = new Map<LocaleTag, Intl.NumberFormat>();
const dateFormats = new Map<LocaleTag, Intl.DateTimeFormat>();
const pluralRules = new Map<LocaleTag, Intl.PluralRules>();
/** The two forms docs/07 §5 requires every plural key to carry. */
export type PluralForm = 'one' | 'other';
/**
* Pick a plural form for a count.
*
* Narrowed to `one`/`other` deliberately: `Intl.PluralRules` can return `zero`,
* `two`, `few` and `many` for other languages, but en yields only one/other and
* vi/ja only ever yield other — so the two-form dictionaries docs/07 §5
* specifies are sufficient for exactly the locales we ship.
*/
export function selectPluralForm(count: number, tag: LocaleTag): PluralForm {
let rules = pluralRules.get(tag);
if (rules === undefined) {
rules = new Intl.PluralRules(tag);
pluralRules.set(tag, rules);
}
return rules.select(count) === 'one' ? 'one' : 'other';
}
export function localeTag(locale: Locale): LocaleTag {
return TAGS[locale];
+28 -1
View File
@@ -1,4 +1,4 @@
import { formatCount, formatDateTime, localeTag } from './format';
import { formatCount, formatDateTime, localeTag, selectPluralForm } from './format';
import en from './locales/en';
import ja from './locales/ja';
import vi from './locales/vi';
@@ -48,6 +48,33 @@ export function dateTime(iso: string): string | undefined {
*/
export function t(path: string, params?: Record<string, string | number>): string {
const raw = lookup(dicts[locale], path) ?? lookup(dicts.en, path) ?? path;
return interpolate(raw, params);
}
/**
* Resolve a plural key — an object of `{ one, other }` per docs/07 §5.
*
* `{n}` is supplied automatically, already grouped for the locale, so callers
* pass the raw count and never have to format it themselves. VI and JA carry
* both forms with the same text (one grammatical form), which is what keeps the
* `satisfies Dict` shape check meaningful.
*/
export function tPlural(
path: string,
count: number,
params?: Record<string, string | number>,
): string {
const form = selectPluralForm(count, localeTag(locale));
const raw =
lookup(dicts[locale], `${path}.${form}`) ??
lookup(dicts[locale], `${path}.other`) ??
lookup(dicts.en, `${path}.${form}`) ??
lookup(dicts.en, `${path}.other`) ??
path;
return interpolate(raw, { n: num(count), ...params });
}
function interpolate(raw: string, params?: Record<string, string | number>): string {
if (params === undefined) return raw;
return raw.replace(/\{(\w+)\}/g, (match, token: string) =>
Object.hasOwn(params, token) ? String(params[token]) : match,
+36 -9
View File
@@ -72,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: {
@@ -200,15 +201,41 @@ const dict = {
'Your acceptance could not be saved, so nothing was recorded. Check that this browser allows extension storage, then try again.',
blocked: 'Accept the terms to use the Import, Export and Edit tabs.',
},
/**
* Every code is a plural key, including the two that interpolate no count —
* `ParseWarning` always carries one, so a uniform shape lets `WarningList`
* call `tPlural` unconditionally instead of maintaining a list of which
* codes count things.
*/
warnings: {
NO_BOOKMARKS: 'This file contains no bookmarks.',
DESCRIPTIONS_DROPPED:
'{n} description(s) were dropped — they have no place in the bookmark model.',
FAVICONS_IGNORED: '{n} favicon(s) ignored — the bookmarks API cannot set favicons.',
INVALID_DATE: '{n} unreadable date(s) were left blank.',
MISSING_URL: '{n} entries had no address and were skipped.',
NEWER_VERSION: 'This file was written by a newer version — reading it as best we can.',
EMPTY_TITLE: '{n} bookmark(s) had no title; their address is shown instead.',
NO_BOOKMARKS: {
one: 'This file contains no bookmarks.',
other: 'This file contains no bookmarks.',
},
DESCRIPTIONS_DROPPED: {
one: '{n} description was dropped — it has no place in the bookmark model.',
other: '{n} descriptions were dropped — they have no place in the bookmark model.',
},
FAVICONS_IGNORED: {
one: '{n} favicon ignored — the bookmarks API cannot set favicons.',
other: '{n} favicons ignored — the bookmarks API cannot set favicons.',
},
INVALID_DATE: {
one: '{n} unreadable date was left blank.',
other: '{n} unreadable dates were left blank.',
},
MISSING_URL: {
one: '{n} entry had no address and was skipped.',
other: '{n} entries had no address and were skipped.',
},
NEWER_VERSION: {
one: 'This file was written by a newer version — reading it as best we can.',
other: 'This file was written by a newer version — reading it as best we can.',
},
EMPTY_TITLE: {
one: '{n} bookmark had no title; its address is shown instead.',
other: '{n} bookmarks had no title; their address is shown instead.',
},
},
errors: {
NOT_NETSCAPE: 'This does not look like a bookmark HTML file.',
+31 -10
View File
@@ -65,7 +65,9 @@ export default {
replace: 'すべて置き換える',
},
warnings: {
title: '警告 {n} 件',
// 日本語は単複の区別がありませんが、docs/07 §5 に従い両方のキーを
// 保持します(`satisfies Dict` の形状チェックを成立させるため)。
title: { one: '警告 {n} 件', other: '警告 {n} 件' },
},
},
export: {
@@ -191,15 +193,34 @@ export default {
blocked: 'インポート・エクスポート・編集タブを使うには規約に同意してください。',
},
warnings: {
NO_BOOKMARKS: 'このファイルにブックマークは含まれていません。',
DESCRIPTIONS_DROPPED:
'説明 {n} 件を破棄しました。ブックマークのモデルに該当する項目がありません。',
FAVICONS_IGNORED:
'ファビコン {n} 件を無視しました。ブックマーク API はファビコンを設定できません。',
INVALID_DATE: '読み取れない日付 {n} 件を空欄にしました。',
MISSING_URL: 'アドレスのない項目 {n} 件をスキップしました。',
NEWER_VERSION: 'このファイルは新しいバージョンで作成されています。可能な範囲で読み込みます。',
EMPTY_TITLE: 'タイトルのないブックマークが {n} 件あり、代わりにアドレスを表示します。',
NO_BOOKMARKS: {
one: 'このファイルにブックマークは含まれていません。',
other: 'このファイルにブックマークは含まれていません。',
},
DESCRIPTIONS_DROPPED: {
one: '説明 {n} 件を破棄しました。ブックマークのモデルに該当する項目がありません。',
other: '説明 {n} 件を破棄しました。ブックマークのモデルに該当する項目がありません。',
},
FAVICONS_IGNORED: {
one: 'ファビコン {n} 件を無視しました。ブックマーク API はファビコンを設定できません。',
other: 'ファビコン {n} 件を無視しました。ブックマーク API はファビコンを設定できません。',
},
INVALID_DATE: {
one: '読み取れない日付 {n} 件を空欄にしました。',
other: '読み取れない日付 {n} 件を空欄にしました。',
},
MISSING_URL: {
one: 'アドレスのない項目 {n} 件をスキップしました。',
other: 'アドレスのない項目 {n} 件をスキップしました。',
},
NEWER_VERSION: {
one: 'このファイルは新しいバージョンで作成されています。可能な範囲で読み込みます。',
other: 'このファイルは新しいバージョンで作成されています。可能な範囲で読み込みます。',
},
EMPTY_TITLE: {
one: 'タイトルのないブックマークが {n} 件あり、代わりにアドレスを表示します。',
other: 'タイトルのないブックマークが {n} 件あり、代わりにアドレスを表示します。',
},
},
errors: {
NOT_NETSCAPE: 'ブックマークの HTML ファイルではないようです。',
+31 -8
View File
@@ -60,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: {
@@ -189,13 +191,34 @@ export default {
blocked: 'Hãy chấp nhận điều khoản để dùng các thẻ Nhập, Xuất và Chỉnh sửa.',
},
warnings: {
NO_BOOKMARKS: 'Tệp này không chứa bookmark nào.',
DESCRIPTIONS_DROPPED: 'Đã bỏ {n} phần mô tả — mô hình bookmark không có chỗ cho chúng.',
FAVICONS_IGNORED: 'Đã bỏ qua {n} favicon — API bookmark không thể đặt favicon.',
INVALID_DATE: 'Đã để trống {n} ngày không đọc được.',
MISSING_URL: 'Đã bỏ qua {n} mục không có địa chỉ.',
NEWER_VERSION: 'Tệp này được tạo bởi phiên bản mới hơn — đang đọc ở mức tốt nhất có thể.',
EMPTY_TITLE: '{n} bookmark không có tiêu đề; địa chỉ được hiển thị thay thế.',
NO_BOOKMARKS: {
one: 'Tệp này không chứa bookmark nào.',
other: 'Tệp này không chứa bookmark nào.',
},
DESCRIPTIONS_DROPPED: {
one: 'Đã bỏ {n} phần mô tả — mô hình bookmark không có chỗ cho chúng.',
other: 'Đã bỏ {n} phần mô tả — mô hình bookmark không có chỗ cho chúng.',
},
FAVICONS_IGNORED: {
one: 'Đã bỏ qua {n} favicon — API bookmark không thể đặt favicon.',
other: 'Đã bỏ qua {n} favicon — API bookmark không thể đặt favicon.',
},
INVALID_DATE: {
one: 'Đã để trống {n} ngày không đọc được.',
other: 'Đã để trống {n} ngày không đọc được.',
},
MISSING_URL: {
one: 'Đã bỏ qua {n} mục không có địa chỉ.',
other: 'Đã bỏ qua {n} mục không có địa chỉ.',
},
NEWER_VERSION: {
one: 'Tệp này được tạo bởi phiên bản mới hơn — đang đọc ở mức tốt nhất có thể.',
other: 'Tệp này được tạo bởi phiên bản mới hơn — đang đọc ở mức tốt nhất có thể.',
},
EMPTY_TITLE: {
one: '{n} bookmark không có tiêu đề; địa chỉ được hiển thị thay thế.',
other: '{n} bookmark không có tiêu đề; địa chỉ được hiển thị thay thế.',
},
},
errors: {
NOT_NETSCAPE: 'Đây có vẻ không phải tệp HTML bookmark.',
+2 -2
View File
@@ -8,7 +8,7 @@
* picker resolving, or by the user explicitly confirming the fallback
* download (docs/03 §1 step 6b).
*/
import { getAppVersion } from '../browser/app-info';
import { getGeneratorVersion } from '../browser/app-info';
import { clearRoots, getRootChildren, getRoots, toBookmarkNodes } from '../browser/bookmarks';
import {
isPickerAvailable,
@@ -160,7 +160,7 @@ export async function proveBackup(
let content: string;
try {
content = serializeBmJson(snapshot, {
version: getAppVersion(),
version: getGeneratorVersion(),
exportedAt: now.toISOString(),
});
} catch (cause) {
+9 -1
View File
@@ -32,7 +32,15 @@ export type ImportState =
| { kind: 'writing'; filename: string; progress: WriteProgress }
| { kind: 'done'; filename: string; created: number; plan: ImportPlan }
| { kind: 'cancelled'; filename: string; created: number }
| { kind: 'error'; filename: string; message: string; detail: string | undefined };
/**
* `messageKey` is a dotted i18n path, NOT a resolved string.
*
* `t()` is only reactive where it is called, and this state outlives the
* component; storing the translated sentence froze it in whatever language
* was active when the error happened, so switching language left the error
* message behind in the old one.
*/
| { kind: 'error'; filename: string; messageKey: string; detail: string | undefined };
let state = $state<ImportState>({ kind: 'idle' });
let options = $state<ImportOptionsState>({ mode: 'new-folder', dedupe: true });
+23 -7
View File
@@ -72,13 +72,29 @@ describe('dictionary completeness', () => {
expect(empty).toEqual([]);
});
it('has no plural keys yet, so no plural helper is owed', () => {
// docs/07 §5: a plural key is an object `{ one, other }` in EVERY locale and
// needs a selector helper. None exist today, and knip would fail an unused
// helper — so this fails loudly the day someone adds the first one.
const plurals = [...branches(en as Node)]
.filter(([, keys]) => keys.length === 2 && keys.includes('one') && keys.includes('other'))
it('carries every plural key as { one, other } in all three locales', () => {
// docs/07 §5. VI/JA have one grammatical form and repeat the same string,
// but they must still carry both keys or the `satisfies Dict` shape check
// §2 relies on for completeness stops proving anything.
const pluralPaths = [...branches(en as Node)]
.filter(([, keys]) => keys.includes('one') && keys.includes('other'))
.map(([path]) => path);
expect(plurals).toEqual([]);
expect(pluralPaths.length).toBeGreaterThan(0);
for (const [name, dict] of LOCALES) {
const leaves = flatten(dict);
for (const path of pluralPaths) {
expect(leaves.get(`${path}.one`), `${name}: ${path}.one`).toBeTypeOf('string');
expect(leaves.get(`${path}.other`), `${name}: ${path}.other`).toBeTypeOf('string');
}
}
});
it('gives every plural key exactly the two forms, and no stray siblings', () => {
const malformed = [...branches(en as Node)]
.filter(([, keys]) => keys.includes('one') || keys.includes('other'))
.filter(([, keys]) => keys.length !== 2)
.map(([path]) => path);
expect(malformed).toEqual([]);
});
});
+44 -2
View File
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it } from 'vitest';
import { formatCount, formatDateTime, localeTag } from '@/lib/i18n/format';
import { dateTime, getLocale, num, setLocale } from '@/lib/i18n/index.svelte';
import { formatCount, formatDateTime, localeTag, selectPluralForm } from '@/lib/i18n/format';
import { dateTime, getLocale, num, setLocale, tPlural } from '@/lib/i18n/index.svelte';
afterEach(() => {
setLocale('en');
@@ -63,6 +63,48 @@ describe('formatDateTime', () => {
});
});
describe('selectPluralForm', () => {
it('distinguishes one from other in English', () => {
expect(selectPluralForm(1, 'en-US')).toBe('one');
expect(selectPluralForm(0, 'en-US')).toBe('other');
expect(selectPluralForm(2, 'en-US')).toBe('other');
});
it('always returns other for vi and ja, which have one grammatical form', () => {
for (const count of [0, 1, 2, 100]) {
expect(selectPluralForm(count, 'vi-VN')).toBe('other');
expect(selectPluralForm(count, 'ja-JP')).toBe('other');
}
});
});
describe('tPlural', () => {
it('picks the singular form and supplies a formatted {n}', () => {
setLocale('en');
expect(tPlural('warnings.INVALID_DATE', 1)).toBe('1 unreadable date was left blank.');
});
it('picks the plural form and groups the count', () => {
setLocale('en');
expect(tPlural('warnings.INVALID_DATE', 1234)).toBe('1,234 unreadable dates were left blank.');
});
it('resolves in vi and ja without falling back to English', () => {
for (const locale of ['vi', 'ja'] as const) {
setLocale(locale);
const text = tPlural('warnings.INVALID_DATE', 3);
expect(text).not.toBe('warnings.INVALID_DATE');
expect(text).not.toContain('unreadable');
expect(text).toContain('3');
}
});
it('returns the path itself for an unknown key rather than throwing', () => {
setLocale('en');
expect(tPlural('warnings.NOT_A_REAL_CODE', 2)).toBe('warnings.NOT_A_REAL_CODE');
});
});
describe('reactive wrappers', () => {
it('getLocale() reports the resolved locale, not the stored preference', () => {
// The preference (getSettings().locale) also carries 'auto'; this never