Translation files, step 0: typed text helper, checks and the baseline of the pages

Adds src/i18n (t, tList, tPlural over typed Dutch JSON, key and parameter
checks), the first text (back to top) as proof, a baseline tool for the
prerendered pages (pnpm baseline:save and baseline:check), a lint warning for
text typed straight into JSX, and docs/translations.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 17:34:18 +01:00
co-authored by Claude Sonnet 5.5
parent 107647f7a5
commit 246ebe5fd6
15 changed files with 834 additions and 2 deletions
+2 -1
View File
@@ -1,6 +1,7 @@
import { chakra } from '@chakra-ui/react';
import { Icon } from '@iconify/react/offline';
import upOutlined from '@iconify-icons/ant-design/up-outlined';
import { t } from '@/i18n';
import useScrolledPast from '@/hooks/useScrolledPast';
import { backToTopThreshold } from '@/lib/backToTopThreshold';
@@ -28,7 +29,7 @@ export default function BackToTop() {
<chakra.button
type="button"
onClick={scrollToTop}
aria-label="Terug naar boven"
aria-label={t('common.aria.backToTop')}
data-testid="back-to-top-button"
position="fixed"
bottom={EDGE}
+76
View File
@@ -0,0 +1,76 @@
// Checks of a language against the Dutch one, for the tests (and for anyone
// adding a language): the same keys, the same {parameters}, nothing empty.
export interface Problem {
key: string;
problem: string;
}
const PLACEHOLDER = /\{([A-Za-z][A-Za-z0-9]*)\}/g;
// The path of every text, with the text
export function leaves(tree: unknown, prefix = ''): Map<string, string> {
const found = new Map<string, string>();
if (typeof tree === 'string') {
found.set(prefix, tree);
} else if (Array.isArray(tree)) {
tree.forEach((item, index) => {
for (const [key, value] of leaves(
item,
join(prefix, String(index)),
)) {
found.set(key, value);
}
});
} else if (typeof tree === 'object' && tree !== null) {
for (const [name, child] of Object.entries(tree)) {
for (const [key, value] of leaves(child, join(prefix, name))) {
found.set(key, value);
}
}
}
return found;
}
const join = (prefix: string, name: string) =>
prefix === '' ? name : `${prefix}.${name}`;
export const placeholders = (text: string): string[] =>
[...text.matchAll(PLACEHOLDER)].map((match) => match[1]).sort();
// Problems of one tree on its own: empty texts, texts that still say TODO,
// braces that are not a valid {parameter}
export function checkFilled(tree: unknown): Problem[] {
const problems: Problem[] = [];
for (const [key, text] of leaves(tree)) {
if (text.trim() === '') problems.push({ key, problem: 'empty' });
if (/\bTODO\b/i.test(text)) problems.push({ key, problem: 'TODO' });
const open = (text.match(/\{/g) ?? []).length;
if (open !== placeholders(text).length) {
problems.push({ key, problem: 'invalid {parameter}' });
}
}
return problems;
}
// Problems of another language compared with the base: missing and extra
// keys, different {parameters}
export function compareMessages(base: unknown, other: unknown): Problem[] {
const problems: Problem[] = [];
const from = leaves(base);
const to = leaves(other);
for (const [key, text] of from) {
const translated = to.get(key);
if (translated === undefined) {
problems.push({ key, problem: 'missing' });
} else if (
placeholders(text).join() !== placeholders(translated).join()
) {
problems.push({ key, problem: 'different {parameters}' });
}
}
for (const key of to.keys()) {
if (!from.has(key)) problems.push({ key, problem: 'not in the base' });
}
return problems;
}
+142
View File
@@ -0,0 +1,142 @@
import { describe, expect, it } from 'vitest';
import { checkFilled, compareMessages, leaves, placeholders } from './compare';
import { fill, locale, locales, messages, nl, t, translator } from './index';
describe('t', () => {
it('gives the text of a key', () => {
expect(t('common.aria.backToTop')).toBe('Terug naar boven');
});
it('is the language of this build', () => {
expect(locale).toBe('nl');
expect(messages).toBe(nl);
});
it('fails for a key that does not exist, with the key in the message', () => {
expect(() => t('common.aria.bestaatNiet' as never)).toThrow(
'Missing text: common.aria.bestaatNiet',
);
expect(() => t('common.aria.backToTop.x' as never)).toThrow(
'Missing text',
);
expect(() => t('common' as never)).toThrow('Not a text: common');
});
});
// A tree of its own, to try parameters, plurals, lists and arrays
const tree = {
greeting: 'Hallo {name}, je hebt {count} berichten',
photos: { one: '{count} foto', other: '{count} foto’s' },
steps: ['Eerste', 'Tweede'],
faq: [{ question: 'Hoe?' }, { question: 'Waarom?' }],
mixed: ['Eerste', 3],
};
const own = translator(tree, 'nl');
describe('translator', () => {
it('fills {parameters}', () => {
expect(own.t('greeting', { name: 'Eva', count: 2 })).toBe(
'Hallo Eva, je hebt 2 berichten',
);
});
it('fails for a parameter that is not given', () => {
expect(() => own.t('greeting', { name: 'Eva' })).toThrow(
'Missing parameter {count}',
);
expect(() => own.t('greeting')).toThrow('Missing parameter {name}');
});
it('reaches texts inside lists by position', () => {
expect(own.t('faq.1.question')).toBe('Waarom?');
expect(own.t('steps.0')).toBe('Eerste');
});
it('gives a list of texts', () => {
expect(own.tList('steps')).toEqual(['Eerste', 'Tweede']);
expect(() => own.tList('mixed' as never)).toThrow(
'Not a list of texts',
);
expect(() => own.tList('greeting' as never)).toThrow(
'Not a list of texts',
);
});
it('chooses the singular or the plural form for the language', () => {
expect(own.tPlural('photos', 1)).toBe('1 foto');
expect(own.tPlural('photos', 0)).toBe('0 foto’s');
expect(own.tPlural('photos', 2)).toBe('2 foto’s');
expect(own.tPlural('photos', 21, { name: 'x' })).toBe('21 foto’s');
});
it('follows the plural rules of another language', () => {
// Polish: one, few and many forms; only "one" has its own text here
const pl = translator(tree, 'pl');
expect(pl.tPlural('photos', 1)).toBe('1 foto');
expect(pl.tPlural('photos', 5)).toBe('5 foto’s');
});
});
describe('fill', () => {
it('leaves a text without parameters as it is', () => {
expect(fill('Gewoon {{ tekst')).toBe('Gewoon {{ tekst');
});
});
describe('the texts of the site', () => {
it('are all filled, without TODO and with valid {parameters}', () => {
expect(checkFilled(nl)).toEqual([]);
expect(leaves(nl).size).toBeGreaterThan(0);
});
it.each(Object.keys(locales))(
'language %s has the same keys and parameters as Dutch',
(name) => {
expect(
compareMessages(nl, locales[name as keyof typeof locales]),
).toEqual([]);
},
);
});
describe('compareMessages and checkFilled', () => {
const base = { a: 'Hallo {name}', b: ['een', 'twee'], c: { d: 'x' } };
it('finds missing keys, extra keys and different parameters', () => {
const other = { a: 'Hello', b: ['one'], c: { d: 'x', e: 'extra' } };
expect(compareMessages(base, other)).toEqual([
{ key: 'a', problem: 'different {parameters}' },
{ key: 'b.1', problem: 'missing' },
{ key: 'c.e', problem: 'not in the base' },
]);
});
it('accepts parameters in another order', () => {
expect(
compareMessages({ a: '{x} en {y}' }, { a: '{y} and {x}' }),
).toEqual([]);
});
it('finds empty texts, TODO and broken braces', () => {
expect(
checkFilled({
a: ' ',
b: 'TODO vertalen',
c: 'kapot {naam',
d: 'ok',
}),
).toEqual([
{ key: 'a', problem: 'empty' },
{ key: 'b', problem: 'TODO' },
{ key: 'c', problem: 'invalid {parameter}' },
]);
});
it('lists the parameters of a text', () => {
expect(placeholders('{b} {a} {b}')).toEqual(['a', 'b', 'b']);
});
it('collects texts of numbers, booleans and null as nothing', () => {
expect(leaves({ a: 1, b: true, c: null, d: 'x' }).size).toBe(1);
});
});
+139
View File
@@ -0,0 +1,139 @@
import common from './nl/common.json';
// The texts of the site, per language, as JSON per area (src/i18n/<locale>/*.json).
// Only Dutch exists now. The types come from the Dutch files: a second language
// has to have exactly the same keys (see Messages and src/i18n/compare.ts), and
// a key that does not exist breaks the type check, so a missing text is found
// by the build and not by a visitor.
//
// No library: the files are imported as modules, so prerendering, hydrating
// and the host injection all see the same text without a loading step.
export const nl = { common };
export type Messages = typeof nl;
// Every language of the site; add one here (typed as Messages) to offer it
export const locales = { nl } satisfies Record<string, Messages>;
export type Locale = keyof typeof locales;
// The language of this build. A second language needs its own routes and a
// prerender per language; until then there is one.
export const locale: Locale = 'nl';
export const messages: Messages = locales[locale];
type Join<P extends string, K extends string> = P extends '' ? K : `${P}.${K}`;
// Dotted paths of every text (a string) in the messages; array positions are
// numbers (faq.0.question)
type StringPath<T, P extends string = ''> = T extends string
? P
: T extends readonly (infer U)[]
? StringPath<U, Join<P, `${number}`>>
: T extends object
? {
[K in keyof T & string]: StringPath<T[K], Join<P, K>>;
}[keyof T & string]
: never;
// Paths of lists of texts (an array of strings)
type ListPath<T, P extends string = ''> = T extends readonly string[]
? P
: T extends string
? never
: T extends readonly unknown[]
? never
: T extends object
? {
[K in keyof T & string]: ListPath<T[K], Join<P, K>>;
}[keyof T & string]
: never;
// A text with a singular and a plural form: { "one": "...", "other": "..." }
type PluralForms = { readonly one: string; readonly other: string };
type PluralPath<T, P extends string = ''> = T extends PluralForms
? P
: T extends string
? never
: T extends readonly unknown[]
? never
: T extends object
? {
[K in keyof T & string]: PluralPath<T[K], Join<P, K>>;
}[keyof T & string]
: never;
export type MessageKey = StringPath<Messages>;
export type ListKey = ListPath<Messages>;
export type PluralKey = PluralPath<Messages>;
export type Params = Readonly<Record<string, string | number>>;
function lookup(tree: unknown, key: string): unknown {
let node = tree;
for (const part of key.split('.')) {
if (typeof node !== 'object' || node === null || !(part in node)) {
throw new Error(`Missing text: ${key}`);
}
node = (node as Record<string, unknown>)[part];
}
return node;
}
// Replaces {name} by the parameter; a parameter that is not given is a bug in
// the caller, not something to show to a visitor
export function fill(text: string, params: Params = {}): string {
return text.replace(
/\{([A-Za-z][A-Za-z0-9]*)\}/g,
(_match, name: string) => {
if (!(name in params)) {
throw new Error(`Missing parameter {${name}} in: ${text}`);
}
return String(params[name]);
},
);
}
function text(tree: unknown, key: string, params?: Params): string {
const value = lookup(tree, key);
if (typeof value !== 'string') throw new Error(`Not a text: ${key}`);
return fill(value, params);
}
function list(tree: unknown, key: string): readonly string[] {
const value = lookup(tree, key);
if (
!Array.isArray(value) ||
value.some((item) => typeof item !== 'string')
) {
throw new Error(`Not a list of texts: ${key}`);
}
return value as readonly string[];
}
function plural(
tree: unknown,
forLocale: string,
key: string,
count: number,
params?: Params,
): string {
const forms = lookup(tree, key) as PluralForms;
const rule = new Intl.PluralRules(forLocale).select(count);
const form = rule === 'one' ? forms.one : forms.other;
return fill(form, { count, ...params });
}
// The functions for a language, over a tree of texts (the tests use their own)
export function translator<M extends object>(tree: M, forLocale: string) {
return {
t: (key: StringPath<M>, params?: Params) => text(tree, key, params),
tList: (key: ListPath<M>) => list(tree, key),
tPlural: (key: PluralPath<M>, count: number, params?: Params) =>
plural(tree, forLocale, key, count, params),
};
}
export const { t, tList, tPlural } = translator(messages, locale);
+5
View File
@@ -0,0 +1,5 @@
{
"aria": {
"backToTop": "Terug naar boven"
}
}