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:
@@ -5,4 +5,4 @@ This file is the entry point for AI coding agents working in this repository. Pr
|
||||
## Index
|
||||
|
||||
- [.ai/layout-conventions.md](.ai/layout-conventions.md) — how to build and update the Mermaid diagrams in [LAYOUT.md](LAYOUT.md).
|
||||
- [README.md](README.md) and [docs/](docs/) — set-up and commands, [CMS integration](docs/cms-integration.md), [deploy and CI](docs/deploy-and-ci.md) and the [go-live checklist](docs/go-live-checklist.md). Update them in the same change when you alter the packages or banners, the use of the CMS API, the workflow (inputs, jobs, triggers), the server config or the go-live conditions. Work that is not built through AI-DLC is documented there, not only in a commit message.
|
||||
- [README.md](README.md) and [docs/](docs/) — set-up and commands, [CMS integration](docs/cms-integration.md), [deploy and CI](docs/deploy-and-ci.md) and the [go-live checklist](docs/go-live-checklist.md), [translations](docs/translations.md) and the [assets and licences](docs/assets-and-licenses.md). New texts of the site go in `web/src/i18n/nl/*.json`, not in the components. Update them in the same change when you alter the packages or banners, the use of the CMS API, the workflow (inputs, jobs, triggers), the server config or the go-live conditions. Work that is not built through AI-DLC is documented there, not only in a commit message.
|
||||
|
||||
@@ -31,5 +31,6 @@ Lay-out of the website and its pages can be found in a separate document [LAYOUT
|
||||
- [docs/cms-integration.md](docs/cms-integration.md): packages and banners from the CMS, the API, the build step, live refresh and the reverse proxy.
|
||||
- [docs/deploy-and-ci.md](docs/deploy-and-ci.md): the pipeline, the workflow inputs, deploying to test, the nightly build and the TEST ONLY commit.
|
||||
- [docs/assets-and-licenses.md](docs/assets-and-licenses.md): where the images, icons and fonts come from and what is still to confirm about their licence.
|
||||
- [docs/translations.md](docs/translations.md): where the texts of the site live (language files), how keys work and how a language is added.
|
||||
- [docs/go-live-checklist.md](docs/go-live-checklist.md): what must be true before the CMS features and the contact form go to production.
|
||||
- [aidlc-docs/](aidlc-docs/): the AI-DLC records per feature (requirements, design, decisions, audit). [aidlc-docs/active-features.md](aidlc-docs/active-features.md) lists them.
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# Texts and translations
|
||||
|
||||
The texts of the site live in language files, not in the components. Dutch is the only language now; the structure allows a second one without a redesign.
|
||||
|
||||
## Where things are
|
||||
|
||||
- `web/src/i18n/nl/*.json`: the Dutch texts, one file per area (`common`, `site`, `home`, `about`, `contact`, `shoots`, `portfolio`, `instagram`, `testimonials`, `seo`). The files are the source of the types.
|
||||
- `web/src/i18n/index.ts`: `t(key, params?)` for a text, `tList(key)` for a list of texts, `tPlural(key, count, params?)` for a text with a singular and a plural form, `locales`, `locale` and `Messages`.
|
||||
- `web/src/i18n/compare.ts`: the checks the tests use (same keys and parameters, nothing empty).
|
||||
- The typed content modules in `web/src/content` keep their structure, images and paths; the words come from the language files.
|
||||
|
||||
Not in the language files: the hero (becomes a CMS module), the privacy statement (separate feature), and everything that comes from the CMS (packages, banners, later the gallery).
|
||||
|
||||
## Keys
|
||||
|
||||
Dotted paths: the file name, then the page or section, then the element: `home.pricing.title`, `shoots.newborn.faq.0.question`, `common.aria.backToTop`, `common.form.errors.required`, `seo.pages.contact.title`. A list is an array in the JSON and keeps the order of the page; a position is a number in the path. Parameters are written `{name}`; a text with a plural has the forms `one` and `other` (`photos.one`, `photos.other`) and `{count}` is filled in by `tPlural`. No HTML in the texts: a text with a link or emphasis is a structured list of parts, as the content modules already have.
|
||||
|
||||
## How a missing text is found
|
||||
|
||||
- `t('...')` only accepts keys that exist in the Dutch files; a typo or a missing key stops `tsc` and the build.
|
||||
- A second language is typed as `Messages`, so a missing key is a compile error there too.
|
||||
- A test checks that every language has the same keys and `{parameters}` as Dutch, and that no text is empty or says TODO.
|
||||
- ESLint (`react/jsx-no-literals`) warns about a text typed straight into JSX, so a new hardcoded text is noticed in review and in CI.
|
||||
|
||||
## Adding a language (later)
|
||||
|
||||
1. Copy `web/src/i18n/nl` to `web/src/i18n/<code>` and translate the values (keys and `{parameters}` stay).
|
||||
2. Add it to `locales` in `web/src/i18n/index.ts`; the tests then compare it with Dutch.
|
||||
3. The site needs routes per language (`/en/...`) and a prerender per language, and `<html lang>` from the language. That is a separate piece of work; the texts do not stand in its way.
|
||||
|
||||
## Moving the texts over: the check that nothing changed
|
||||
|
||||
While the texts were moved into the language files, the prerendered pages had to stay word for word the same. `pnpm baseline:save` (after `pnpm build`) saves the text, links, labels, meta tags and structured data of every page in `web/.baseline` (not in git), and `pnpm baseline:check` compares a new build with it; styling, scripts and file hashes are ignored. A step is only done when the check says the pages are equal.
|
||||
@@ -33,3 +33,6 @@ lighthouse-reports
|
||||
|
||||
# Written by config/fetchOfferings.ts before every build
|
||||
src/content/offerings.generated.json
|
||||
|
||||
# Saved text of the prerendered pages (pnpm baseline:save), a local safety net
|
||||
.baseline
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { firstDifferences, normalizeHtml } from './htmlBaseline.ts';
|
||||
|
||||
describe('normalizeHtml', () => {
|
||||
it('keeps text, links, labels, meta and structured data', () => {
|
||||
const html =
|
||||
'<html><head><title>Titel</title><meta name="description" content="Tekst"/>' +
|
||||
'<link rel="canonical" href="https://a.nl/"/></head><body>' +
|
||||
'<a href="/over-mij" aria-label="Naar over mij">Over mij</a>' +
|
||||
'<script type="application/ld+json">{"a":1}</script></body></html>';
|
||||
const out = normalizeHtml(html);
|
||||
for (const part of [
|
||||
'<title>Titel</title>',
|
||||
'content="Tekst"',
|
||||
'rel="canonical"',
|
||||
'aria-label="Naar over mij"',
|
||||
'Over mij',
|
||||
'{"a":1}',
|
||||
]) {
|
||||
expect(out).toContain(part);
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves out look and build details', () => {
|
||||
const html =
|
||||
'<style data-emotion="css">.a{}</style><script src="/assets/x-AbCd1234.js"></script>' +
|
||||
'<link rel="stylesheet" href="/assets/y-AbCd1234.css"/><!-- opmerking -->' +
|
||||
'<div class="css-1abc" style="color:red" data-reveal="hidden" id="x">tekst</div>' +
|
||||
'<img src="/assets/foto-AbCd1234.jpg"/><noscript><style>.b{}</style></noscript>';
|
||||
const out = normalizeHtml(html);
|
||||
expect(out).not.toMatch(
|
||||
/css-1abc|color:red|data-reveal|opmerking|\.a\{|stylesheet|AbCd1234.js/,
|
||||
);
|
||||
expect(out).toContain('<div id="x">');
|
||||
expect(out).toContain('/assets/foto.jpg');
|
||||
expect(out).toContain(
|
||||
'<noscript>' + String.fromCharCode(10) + '</noscript>',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the CMS markers and the data block', () => {
|
||||
const html =
|
||||
'<!--CMS:DATA--><script type="application/json" id="cms-data">{"x":1}</script>' +
|
||||
'<!--CMS:OFFERINGS-HTML-->a<!--/CMS:OFFERINGS-HTML-->';
|
||||
const out = normalizeHtml(html);
|
||||
expect(out).toContain('<!--CMS:DATA-->');
|
||||
expect(out).toContain('{"x":1}');
|
||||
expect(out).toContain('<!--/CMS:OFFERINGS-HTML-->');
|
||||
});
|
||||
|
||||
it('notices a changed word', () => {
|
||||
expect(normalizeHtml('<p>een</p>')).not.toBe(
|
||||
normalizeHtml('<p>twee</p>'),
|
||||
);
|
||||
});
|
||||
|
||||
it('puts one tag per line and ends with a newline', () => {
|
||||
expect(normalizeHtml('<ul> <li>a</li> <li>b</li> </ul>')).toBe(
|
||||
'<ul>\n<li>a</li>\n<li>b</li>\n</ul>\n',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('firstDifferences', () => {
|
||||
it('shows the lines that differ, at most a few', () => {
|
||||
const out = firstDifferences('a\nb\nc', 'a\nB\nc\nd');
|
||||
expect(out.join('\n')).toContain('regel 2');
|
||||
expect(out.join('\n')).toContain('basislijn: b');
|
||||
expect(out.join('\n')).toContain('nu: B');
|
||||
expect(out.join('\n')).toContain('(geen)');
|
||||
expect(firstDifferences('a', 'a')).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
// Safety net for moving texts into the language files: saves what the
|
||||
// prerendered pages say (their text, links, labels, meta tags and structured
|
||||
// data) and later checks that a new build says exactly the same. Styling,
|
||||
// scripts, asset hashes and generated class names are left out, so only a
|
||||
// change of wording or content shows up.
|
||||
//
|
||||
// Usage (after `pnpm build`):
|
||||
// node config/htmlBaseline.ts save writes .baseline/<page>.html (ignored by git)
|
||||
// node config/htmlBaseline.ts check compares dist/client with .baseline
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
|
||||
const DIST = 'dist/client';
|
||||
const BASELINE = '.baseline';
|
||||
|
||||
// What stays: text, links, labels, meta, structured data and the data block
|
||||
const KEEP_SCRIPT = /type="application\/(?:ld\+json|json)"/;
|
||||
|
||||
export function normalizeHtml(html: string): string {
|
||||
return (
|
||||
html
|
||||
.replace(/<!--(?!\/?CMS:)[\s\S]*?-->/g, '')
|
||||
.replace(/<style[\s\S]*?<\/style>/g, '')
|
||||
.replace(
|
||||
/<script\b([^>]*)>([\s\S]*?)<\/script>/g,
|
||||
(all, attrs: string) => (KEEP_SCRIPT.test(attrs) ? all : ''),
|
||||
)
|
||||
.replace(/<noscript>[\s\S]*?<\/noscript>/g, '<noscript></noscript>')
|
||||
// Only the canonical link is content; the others point to hashed files
|
||||
.replace(/<link\b[^>]*>/g, (tag) =>
|
||||
/rel="canonical"/.test(tag) ? tag : '',
|
||||
)
|
||||
// Look, not content
|
||||
.replace(/\s(?:class|style|data-emotion|data-reveal)="[^"]*"/g, '')
|
||||
.replace(/\s(?:hidden|inert)=""/g, ' $&')
|
||||
// The hash in /assets/name-Hash.ext
|
||||
.replace(
|
||||
/(\/assets\/[\w.-]*?)-[A-Za-z0-9_-]{8}(\.[a-z0-9]+)/g,
|
||||
'$1$2',
|
||||
)
|
||||
.replace(/>\s+</g, '><')
|
||||
// One tag per line, so a difference is readable
|
||||
.replace(/></g, '>\n<')
|
||||
.trim() + '\n'
|
||||
);
|
||||
}
|
||||
|
||||
function pages(dir: string): string[] {
|
||||
return readdirSync(dir, { recursive: true, withFileTypes: true })
|
||||
.filter((entry) => entry.isFile() && entry.name.endsWith('.html'))
|
||||
.map((entry) => relative(dir, join(entry.parentPath, entry.name)))
|
||||
.sort();
|
||||
}
|
||||
|
||||
// The first lines that differ, for the message
|
||||
export function firstDifferences(a: string, b: string, max = 6): string[] {
|
||||
const left = a.split('\n');
|
||||
const right = b.split('\n');
|
||||
const out: string[] = [];
|
||||
for (
|
||||
let i = 0;
|
||||
i < Math.max(left.length, right.length) && out.length < max;
|
||||
i++
|
||||
) {
|
||||
if (left[i] !== right[i]) {
|
||||
out.push(
|
||||
` regel ${i + 1}:`,
|
||||
` basislijn: ${left[i] ?? '(geen)'}`,
|
||||
` nu: ${right[i] ?? '(geen)'}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function save() {
|
||||
mkdirSync(BASELINE, { recursive: true });
|
||||
for (const page of pages(DIST)) {
|
||||
const target = join(BASELINE, page.replace(/[\\/]/g, '__'));
|
||||
writeFileSync(
|
||||
target,
|
||||
normalizeHtml(readFileSync(join(DIST, page), 'utf8')),
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
`Basislijn opgeslagen: ${pages(DIST).length} pagina's in ${BASELINE}`,
|
||||
);
|
||||
}
|
||||
|
||||
function check(): boolean {
|
||||
if (!existsSync(BASELINE)) {
|
||||
console.error('Geen basislijn; draai eerst `save`.');
|
||||
return false;
|
||||
}
|
||||
let ok = true;
|
||||
const names = pages(DIST);
|
||||
for (const page of names) {
|
||||
const file = join(BASELINE, page.replace(/[\\/]/g, '__'));
|
||||
if (!existsSync(file)) {
|
||||
console.error(`${page}: niet in de basislijn`);
|
||||
ok = false;
|
||||
continue;
|
||||
}
|
||||
const now = normalizeHtml(readFileSync(join(DIST, page), 'utf8'));
|
||||
const was = readFileSync(file, 'utf8');
|
||||
if (now !== was) {
|
||||
ok = false;
|
||||
console.error(`${page}: tekst verschilt van de basislijn`);
|
||||
console.error(firstDifferences(was, now).join('\n'));
|
||||
}
|
||||
}
|
||||
if (ok) console.log(`Gelijk aan de basislijn: ${names.length} pagina's`);
|
||||
return ok;
|
||||
}
|
||||
|
||||
if (process.argv[1]?.endsWith('htmlBaseline.ts')) {
|
||||
const command = process.argv[2];
|
||||
if (command === 'save') save();
|
||||
else if (command === 'check') process.exitCode = check() ? 0 : 1;
|
||||
else {
|
||||
console.error('Gebruik: node config/htmlBaseline.ts save|check');
|
||||
process.exitCode = 2;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import jsxA11y from 'eslint-plugin-jsx-a11y';
|
||||
import react from 'eslint-plugin-react';
|
||||
|
||||
// Alleen regels die fouten vinden; opmaak is aan Prettier
|
||||
export default tseslint.config(
|
||||
@@ -31,6 +32,43 @@ export default tseslint.config(
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
{
|
||||
// Texts of the site live in the language files (src/i18n), not in the
|
||||
// JSX. Warning for now while the pages are moved over, an error when
|
||||
// that is done. Left out: the hero (becomes a CMS module), tests and
|
||||
// the build-only helpers.
|
||||
files: ['src/components/**/*.tsx', 'src/routes/**/*.tsx'],
|
||||
ignores: [
|
||||
'src/components/Hero/**',
|
||||
// The privacy statement is its own feature, not moved yet
|
||||
'src/routes/privacyverklaring.tsx',
|
||||
'**/*.test.tsx',
|
||||
'src/routeTree.gen.ts',
|
||||
],
|
||||
plugins: { react },
|
||||
rules: {
|
||||
'react/jsx-no-literals': [
|
||||
'warn',
|
||||
{
|
||||
noStrings: false,
|
||||
ignoreProps: true,
|
||||
// Technical signs that are not words
|
||||
allowedStrings: [
|
||||
'/',
|
||||
'|',
|
||||
'·',
|
||||
'–',
|
||||
'—',
|
||||
'×',
|
||||
'+',
|
||||
'-',
|
||||
':',
|
||||
'…',
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
// The copied cms-client package stays headless: it may only import
|
||||
// react and its own files (also enforced by its boundary test)
|
||||
|
||||
@@ -20,6 +20,8 @@
|
||||
"audit:dev": "pnpm audit || echo Meldingen in ontwikkeltools blokkeren niet, zie NFR-SEC-05",
|
||||
"lighthouse": "lhci autorun && lhci autorun --config=lighthouserc.desktop.cjs",
|
||||
"server-config": "node config/writeServerConfig.ts",
|
||||
"baseline:save": "node config/htmlBaseline.ts save",
|
||||
"baseline:check": "node config/htmlBaseline.ts check",
|
||||
"check": "pnpm lint && pnpm format:check && pnpm test && pnpm build && pnpm e2e && pnpm audit:deps && pnpm audit:dev && pnpm lighthouse"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -40,6 +42,7 @@
|
||||
"axe-core": "^4.14.0",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-plugin-jsx-a11y": "^6.10.2",
|
||||
"eslint-plugin-react": "^7.37.5",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"fast-check": "^4.10.2",
|
||||
"globals": "^17.13.0",
|
||||
|
||||
Generated
+187
@@ -260,6 +260,9 @@ importers:
|
||||
eslint-plugin-jsx-a11y:
|
||||
specifier: ^6.10.2
|
||||
version: 6.10.2(eslint@9.39.5(jiti@2.7.0)(supports-color@5.5.0))
|
||||
eslint-plugin-react:
|
||||
specifier: ^7.37.5
|
||||
version: 7.37.5(eslint@9.39.5(jiti@2.7.0)(supports-color@5.5.0))
|
||||
eslint-plugin-react-hooks:
|
||||
specifier: ^7.1.1
|
||||
version: 7.1.1(eslint@9.39.5(jiti@2.7.0)(supports-color@5.5.0))(supports-color@5.5.0)
|
||||
@@ -1728,6 +1731,10 @@ packages:
|
||||
resolution: {integrity: sha512-VXY5eFRarnXcYxwBjJzPmEhH55+rmP79/+ueDhi0F+TuqfHCItagIHqxeUZrmgrOPa31QTh9H85DjX3FfJ0FTg==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
array.prototype.findlast@1.2.5:
|
||||
resolution: {integrity: sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
array.prototype.flat@1.3.3:
|
||||
resolution: {integrity: sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -1736,6 +1743,10 @@ packages:
|
||||
resolution: {integrity: sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
array.prototype.tosorted@1.1.4:
|
||||
resolution: {integrity: sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
arraybuffer.prototype.slice@1.0.4:
|
||||
resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -2126,6 +2137,10 @@ packages:
|
||||
resolution: {integrity: sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==}
|
||||
engines: {node: '>=0.3.1'}
|
||||
|
||||
doctrine@2.1.0:
|
||||
resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
dom-accessibility-api@0.5.16:
|
||||
resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
|
||||
|
||||
@@ -2190,6 +2205,10 @@ packages:
|
||||
resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
es-iterator-helpers@1.4.0:
|
||||
resolution: {integrity: sha512-c/A0P0oxkACDc+cKWw8evLXK83oBKgn0qPOqCYT4x9uolpCIJAcYvJC9QYKNDRPsTeGyCrQ326jrvgZWdCdK5Q==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
es-module-lexer@2.3.2:
|
||||
resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==}
|
||||
|
||||
@@ -2246,6 +2265,12 @@ packages:
|
||||
peerDependencies:
|
||||
eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0
|
||||
|
||||
eslint-plugin-react@7.37.5:
|
||||
resolution: {integrity: sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==}
|
||||
engines: {node: '>=4'}
|
||||
peerDependencies:
|
||||
eslint: ^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7
|
||||
|
||||
eslint-scope@8.4.0:
|
||||
resolution: {integrity: sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
@@ -2781,6 +2806,10 @@ packages:
|
||||
isomorphic-fetch@3.0.0:
|
||||
resolution: {integrity: sha512-qvUtwJ3j6qwsF3jLxkZ72qCgjMysPzDfeV240JHiGZsANBYd+EEuu35v7dfrJ9Up0Ak07D7GGSkGhCHTqg/5wA==}
|
||||
|
||||
iterator.prototype@1.1.5:
|
||||
resolution: {integrity: sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
jiti@2.7.0:
|
||||
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
|
||||
hasBin: true
|
||||
@@ -2978,6 +3007,10 @@ packages:
|
||||
lookup-closest-locale@6.2.0:
|
||||
resolution: {integrity: sha512-/c2kL+Vnp1jnV6K6RpDTHK3dgg0Tu2VVp+elEiJpjfS1UyY7AjOYHohRug6wT0OpoX2qFgNORndE9RqesfVxWQ==}
|
||||
|
||||
loose-envify@1.4.0:
|
||||
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
|
||||
hasBin: true
|
||||
|
||||
lru-cache@11.5.3:
|
||||
resolution: {integrity: sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==}
|
||||
engines: {node: 20 || >=22}
|
||||
@@ -3109,6 +3142,10 @@ packages:
|
||||
resolution: {integrity: sha512-eonl3sLUha+S1GzTPxychyhnUzKyeQkZ7jLjKrBagJgPla13F+uQ71HgpFefyHgqrjEbCPkDArxYsjY8/+gLKA==}
|
||||
engines: {node: '>= 0.4.0'}
|
||||
|
||||
node-exports-info@1.6.2:
|
||||
resolution: {integrity: sha512-kXs9Go0cah0qHVV2v389IXQLdLCeE1xfFtjOAF+iobu0OIoG1pje8At2vMHyaPMiPMnG/LWP50twML21eMcAag==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
node-fetch@2.7.0:
|
||||
resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==}
|
||||
engines: {node: 4.x || >=6.0.0}
|
||||
@@ -3122,6 +3159,10 @@ packages:
|
||||
resolution: {integrity: sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
object-assign@4.1.1:
|
||||
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
object-inspect@1.13.4:
|
||||
resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -3134,6 +3175,10 @@ packages:
|
||||
resolution: {integrity: sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
object.entries@1.1.9:
|
||||
resolution: {integrity: sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
object.fromentries@2.0.8:
|
||||
resolution: {integrity: sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -3307,6 +3352,9 @@ packages:
|
||||
resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==}
|
||||
engines: {node: '>=0.4.0'}
|
||||
|
||||
prop-types@15.8.1:
|
||||
resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}
|
||||
|
||||
proxy-addr@2.0.8:
|
||||
resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==}
|
||||
engines: {node: '>= 0.10'}
|
||||
@@ -3411,6 +3459,11 @@ packages:
|
||||
engines: {node: '>= 0.4'}
|
||||
hasBin: true
|
||||
|
||||
resolve@2.0.0-next.7:
|
||||
resolution: {integrity: sha512-tqt+NBWwyaMgw3zDsnygx4CByWjQEJHOPMdslYhppaQSJUtL/D4JO9CcBBlhPoI8lz9oJIDXkwXfhF4aWqP8xQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
hasBin: true
|
||||
|
||||
restore-cursor@2.0.0:
|
||||
resolution: {integrity: sha512-6IzJLuGi4+R14vwagDHX+JrXmPVtPpn4mffDJ1UdR7/Edm87fl6yi8mMBIVvFtJaNTUvjughmW4hwLhRG7gC1Q==}
|
||||
engines: {node: '>=4'}
|
||||
@@ -3626,6 +3679,13 @@ packages:
|
||||
resolution: {integrity: sha512-o7+c9bW6zpAdJHTtujeePODAhkuicdAryFsfVKwA+wGw89wJ4GTY484WTucM9hLtDEOpOvI+aHnzqnC5lHp4Rg==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
string.prototype.matchall@4.1.0:
|
||||
resolution: {integrity: sha512-tHNHTxInrYLCga9O9YGxWA3G9/nnzQw8UGAyqGx3Ar1pSTTzIuM4woFSq4SowkXCjJIwq5sIiQvEfRI9tCH1qQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
string.prototype.repeat@1.0.0:
|
||||
resolution: {integrity: sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==}
|
||||
|
||||
string.prototype.trim@1.2.11:
|
||||
resolution: {integrity: sha512-PwvK7BU+CMTJGYQCTZb5RWXIML92lftJLhQz1tBzgKiqGxJaMlBAa48POXaNAC2s4y8jr3EFqrkF9+44neS46w==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -6136,6 +6196,15 @@ snapshots:
|
||||
is-string: 1.1.1
|
||||
math-intrinsics: 1.1.0
|
||||
|
||||
array.prototype.findlast@1.2.5:
|
||||
dependencies:
|
||||
call-bind: 1.0.9
|
||||
define-properties: 1.2.1
|
||||
es-abstract: 1.24.2
|
||||
es-errors: 1.3.0
|
||||
es-object-atoms: 1.1.2
|
||||
es-shim-unscopables: 1.1.0
|
||||
|
||||
array.prototype.flat@1.3.3:
|
||||
dependencies:
|
||||
call-bind: 1.0.9
|
||||
@@ -6150,6 +6219,14 @@ snapshots:
|
||||
es-abstract: 1.24.2
|
||||
es-shim-unscopables: 1.1.0
|
||||
|
||||
array.prototype.tosorted@1.1.4:
|
||||
dependencies:
|
||||
call-bind: 1.0.9
|
||||
define-properties: 1.2.1
|
||||
es-abstract: 1.24.2
|
||||
es-errors: 1.3.0
|
||||
es-shim-unscopables: 1.1.0
|
||||
|
||||
arraybuffer.prototype.slice@1.0.4:
|
||||
dependencies:
|
||||
array-buffer-byte-length: 1.0.2
|
||||
@@ -6548,6 +6625,10 @@ snapshots:
|
||||
|
||||
diff@9.0.0: {}
|
||||
|
||||
doctrine@2.1.0:
|
||||
dependencies:
|
||||
esutils: 2.0.3
|
||||
|
||||
dom-accessibility-api@0.5.16: {}
|
||||
|
||||
dom-accessibility-api@0.6.3: {}
|
||||
@@ -6657,6 +6738,25 @@ snapshots:
|
||||
|
||||
es-errors@1.3.0: {}
|
||||
|
||||
es-iterator-helpers@1.4.0:
|
||||
dependencies:
|
||||
call-bind: 1.0.9
|
||||
call-bound: 1.0.4
|
||||
define-properties: 1.2.1
|
||||
es-abstract: 1.24.2
|
||||
es-errors: 1.3.0
|
||||
es-set-tostringtag: 2.1.0
|
||||
function-bind: 1.1.2
|
||||
get-intrinsic: 1.3.0
|
||||
globalthis: 1.0.4
|
||||
gopd: 1.2.0
|
||||
has-property-descriptors: 1.0.2
|
||||
has-proto: 1.2.0
|
||||
has-symbols: 1.1.0
|
||||
internal-slot: 1.1.0
|
||||
iterator.prototype: 1.1.5
|
||||
math-intrinsics: 1.1.0
|
||||
|
||||
es-module-lexer@2.3.2: {}
|
||||
|
||||
es-object-atoms@1.1.2:
|
||||
@@ -6758,6 +6858,28 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
eslint-plugin-react@7.37.5(eslint@9.39.5(jiti@2.7.0)(supports-color@5.5.0)):
|
||||
dependencies:
|
||||
array-includes: 3.2.0
|
||||
array.prototype.findlast: 1.2.5
|
||||
array.prototype.flatmap: 1.3.3
|
||||
array.prototype.tosorted: 1.1.4
|
||||
doctrine: 2.1.0
|
||||
es-iterator-helpers: 1.4.0
|
||||
eslint: 9.39.5(jiti@2.7.0)(supports-color@5.5.0)
|
||||
estraverse: 5.3.0
|
||||
hasown: 2.0.4
|
||||
jsx-ast-utils: 3.3.5
|
||||
minimatch: 3.1.5
|
||||
object.entries: 1.1.9
|
||||
object.fromentries: 2.0.8
|
||||
object.values: 1.2.1
|
||||
prop-types: 15.8.1
|
||||
resolve: 2.0.0-next.7
|
||||
semver: 6.3.1
|
||||
string.prototype.matchall: 4.1.0
|
||||
string.prototype.repeat: 1.0.0
|
||||
|
||||
eslint-scope@8.4.0:
|
||||
dependencies:
|
||||
esrecurse: 4.3.0
|
||||
@@ -7373,6 +7495,15 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- encoding
|
||||
|
||||
iterator.prototype@1.1.5:
|
||||
dependencies:
|
||||
define-data-property: 1.1.4
|
||||
es-object-atoms: 1.1.2
|
||||
get-intrinsic: 1.3.0
|
||||
get-proto: 1.0.1
|
||||
has-symbols: 1.1.0
|
||||
set-function-name: 2.0.2
|
||||
|
||||
jiti@2.7.0: {}
|
||||
|
||||
jpeg-js@0.4.4: {}
|
||||
@@ -7584,6 +7715,10 @@ snapshots:
|
||||
|
||||
lookup-closest-locale@6.2.0: {}
|
||||
|
||||
loose-envify@1.4.0:
|
||||
dependencies:
|
||||
js-tokens: 4.0.0
|
||||
|
||||
lru-cache@11.5.3: {}
|
||||
|
||||
lru-cache@5.1.1:
|
||||
@@ -7679,12 +7814,21 @@ snapshots:
|
||||
|
||||
netmask@2.1.1: {}
|
||||
|
||||
node-exports-info@1.6.2:
|
||||
dependencies:
|
||||
array.prototype.flatmap: 1.3.3
|
||||
es-errors: 1.3.0
|
||||
object.entries: 1.1.9
|
||||
semver: 6.3.1
|
||||
|
||||
node-fetch@2.7.0:
|
||||
dependencies:
|
||||
whatwg-url: 5.0.0
|
||||
|
||||
node-releases@2.0.57: {}
|
||||
|
||||
object-assign@4.1.1: {}
|
||||
|
||||
object-inspect@1.13.4: {}
|
||||
|
||||
object-keys@1.1.1: {}
|
||||
@@ -7698,6 +7842,13 @@ snapshots:
|
||||
has-symbols: 1.1.0
|
||||
object-keys: 1.1.1
|
||||
|
||||
object.entries@1.1.9:
|
||||
dependencies:
|
||||
call-bind: 1.0.9
|
||||
call-bound: 1.0.4
|
||||
define-properties: 1.2.1
|
||||
es-object-atoms: 1.1.2
|
||||
|
||||
object.fromentries@2.0.8:
|
||||
dependencies:
|
||||
call-bind: 1.0.9
|
||||
@@ -7862,6 +8013,12 @@ snapshots:
|
||||
|
||||
progress@2.0.3: {}
|
||||
|
||||
prop-types@15.8.1:
|
||||
dependencies:
|
||||
loose-envify: 1.4.0
|
||||
object-assign: 4.1.1
|
||||
react-is: 16.13.1
|
||||
|
||||
proxy-addr@2.0.8:
|
||||
dependencies:
|
||||
forwarded: 0.2.0
|
||||
@@ -7993,6 +8150,15 @@ snapshots:
|
||||
path-parse: 1.0.7
|
||||
supports-preserve-symlinks-flag: 1.0.0
|
||||
|
||||
resolve@2.0.0-next.7:
|
||||
dependencies:
|
||||
es-errors: 1.3.0
|
||||
is-core-module: 2.17.0
|
||||
node-exports-info: 1.6.2
|
||||
object-keys: 1.1.1
|
||||
path-parse: 1.0.7
|
||||
supports-preserve-symlinks-flag: 1.0.0
|
||||
|
||||
restore-cursor@2.0.0:
|
||||
dependencies:
|
||||
onetime: 2.0.1
|
||||
@@ -8245,6 +8411,27 @@ snapshots:
|
||||
define-properties: 1.2.1
|
||||
es-abstract: 1.24.2
|
||||
|
||||
string.prototype.matchall@4.1.0:
|
||||
dependencies:
|
||||
call-bind: 1.0.9
|
||||
call-bound: 1.0.4
|
||||
define-properties: 1.2.1
|
||||
es-abstract: 1.24.2
|
||||
es-errors: 1.3.0
|
||||
es-object-atoms: 1.1.2
|
||||
get-intrinsic: 1.3.0
|
||||
gopd: 1.2.0
|
||||
has-symbols: 1.1.0
|
||||
internal-slot: 1.1.0
|
||||
regexp.prototype.flags: 1.5.4
|
||||
set-function-name: 2.0.2
|
||||
side-channel: 1.1.1
|
||||
|
||||
string.prototype.repeat@1.0.0:
|
||||
dependencies:
|
||||
define-properties: 1.2.1
|
||||
es-abstract: 1.24.2
|
||||
|
||||
string.prototype.trim@1.2.11:
|
||||
dependencies:
|
||||
call-bind: 1.0.9
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"aria": {
|
||||
"backToTop": "Terug naar boven"
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,7 @@ export default defineConfig(({ mode }) => ({
|
||||
exclude: ['src/routeTree.gen.ts', 'src/test/**', '**/*.test.*'],
|
||||
thresholds: {
|
||||
'src/lib/**': fullCoverage,
|
||||
'src/i18n/**': fullCoverage,
|
||||
'src/seo.ts': fullCoverage,
|
||||
'src/sitemap.ts': fullCoverage,
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user