Skip to content

Commit c030c72

Browse files
committed
perf(i18n): assemble the whole English catalog from its slices, so no string ships twice
An app that mounts InternationalizationProvider or calls useTranslator() carries the whole catalog through the public context; with the components' slices beside it, each rendered component's strings were in the bundle twice. en.generated.ts is now the spread of the 78 slice modules, so a bundle that reaches both carries every string once. A pinned test checks the assembled catalog against the authored keys and messages. The changeset says which apps gain the saving and how a provider-mounting app moves. CONTRIBUTING, the CLI's i18n guide and the hardcoded-string lint messages now send core authors to useComponentTranslator(<slice>), which the catalog check requires, and name useTranslator() as the consumer-facing hook.
1 parent 34cf864 commit c030c72

7 files changed

Lines changed: 137 additions & 45 deletions

File tree

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
---
22
'@astryxdesign/core': patch
3+
'@astryxdesign/cli': patch
34
---
45

5-
[perf] A component carries only its own English strings. The shipped English catalog is now emitted one namespace at a time, and every core component renders with its own slice instead of the whole 408-key catalog, so an app bundles the strings of the components it renders: two rows of buttons and links drop about 5 KB (gzip) from their first load. `useTranslator()` and `InternationalizationContext` are unchanged and still resolve every `@astryx.*` key; an `InternationalizationProvider`'s `messages` and `overrides` still win over the slice; the slices themselves are not importable. One undocumented path moves: a value handed straight to `InternationalizationContext` without the provider no longer reaches core components or `useLocale`, `useDirection` and `useCollator`, which read the provider's runtime context; mount `InternationalizationProvider`.
6+
[perf] A component carries only its own English strings. The shipped English catalog is now emitted one namespace at a time, and every core component renders with its own slice instead of the whole 408-key catalog, so an app that renders components without mounting `InternationalizationProvider` or calling `useTranslator()` bundles only the strings of the components it renders: two rows of buttons and links drop about 5 KB (gzip) from their first load. An app that does mount the provider still carries the whole catalog, now assembled from the same slices so no string ships twice; it moves by under 1 KB either way (a few slice modules cost a little, many save a little). `useTranslator()` and `InternationalizationContext` are unchanged and still resolve every `@astryx.*` key; an `InternationalizationProvider`'s `messages` and `overrides` still win over the slice; the slices themselves are not importable. One undocumented path moves: a value handed straight to `InternationalizationContext` without the provider no longer reaches core components or `useLocale`, `useDirection` and `useCollator`, which read the provider's runtime context; mount `InternationalizationProvider`.
67

78
@vjeux

‎CONTRIBUTING.md‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -291,24 +291,35 @@ export * from './MyComponent';
291291
292292
### User-facing strings and text direction
293293

294-
Components read user-facing strings with `useTranslator()` rather than
295-
hardcoding them:
294+
Components read user-facing strings with `useComponentTranslator(<slice>)`
295+
rather than hardcoding them. The slice is the component's own namespace of the
296+
English catalog, generated under `src/i18n/generated-locales/en/`, so an app
297+
bundles only the strings of the components it renders:
296298

297299
```tsx
298-
import {useTranslator} from '@astryxdesign/core/i18n';
300+
import {useComponentTranslator} from '../i18n/useComponentTranslator';
301+
import saveButtonMessages from '../i18n/generated-locales/en/saveButton.generated';
299302

300303
function SaveButton() {
301-
const t = useTranslator();
302-
return <button>{t('@astryx.actions.save')}</button>;
304+
const t = useComponentTranslator(saveButtonMessages);
305+
return <button>{t('@astryx.saveButton.save')}</button>;
303306
}
304307
```
305308

306-
Astryx's own strings live in `packages/core/locales/en.json`. The
307-
`@astryx/no-hardcoded-i18n-string` ESLint rule rejects a hardcoded one. For a
308-
prop whose default is a translated string, alias the prop and resolve it in the
309-
body: destructure `label: labelFromProps`, then
309+
A file that reads several namespaces merges their slices once at module level
310+
(`const messages = {...aMessages, ...bMessages}`) and passes that. Astryx's own
311+
strings live in `packages/core/locales/en.json`, keyed
312+
`@astryx.<namespace>.<name>`; `pnpm generate:i18n-runtime` emits the slices, and
313+
`pnpm check:i18n-catalog` fails a key read outside the file's slice. The
314+
`@astryx/no-hardcoded-i18n-string` ESLint rule rejects a hardcoded string. For
315+
a prop whose default is a translated string, alias the prop and resolve it in
316+
the body: destructure `label: labelFromProps`, then
310317
`const label = labelFromProps ?? t('@astryx.<component>.<key>')`.
311318

319+
`useTranslator()` from `@astryxdesign/core/i18n` is the consumer-facing hook:
320+
it carries the whole English catalog, so code inside `packages/core` does not
321+
use it; packages that depend on core (`lab`, `richtext`) do.
322+
312323
A component that responds to text direction resolves it from the DOM, not from
313324
a render-time JavaScript read. Reach for the lightest tool that works, in this
314325
order:
@@ -346,8 +357,8 @@ order:
346357
flip for free; don't pass them a direction flag.
347358
4. **`useDirection()` context, as a last resort.** Use it only when you need
348359
the direction value during render and nothing above fits. It is SSR-safe
349-
and returns `'ltr'` outside a provider (like `useTranslator`'s silent
350-
fallback), but it is the one path that can mismatch on hydration when the
360+
and returns `'ltr'` outside a provider (like a translator's silent
361+
English fallback), but it is the one path that can mismatch on hydration when the
351362
provider's direction disagrees with `<html dir>`. No Astryx component reads
352363
direction from context at render time.
353364

‎internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js‎

Lines changed: 37 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -111,15 +111,15 @@ const ARIA_TEXT_ATTRS = new Set([
111111
* one of these is flagged.
112112
*/
113113
const SUFFIX_PATTERNS = [
114-
/Label$/, // saveButtonLabel, cancelLabel, previousLabel, ...
115-
/Text$/, // emptySearchText, helperText, errorText, ...
116-
/Placeholder$/,// searchPlaceholder, timePlaceholder, ...
117-
/Title$/, // dialogTitle, ...
118-
/Message$/, // disabledMessage, errorMessage, ...
119-
/Tooltip$/, // ...
120-
/Hint$/, // ...
121-
/Description$/,// ...
122-
/Summary$/, // ...
114+
/Label$/, // saveButtonLabel, cancelLabel, previousLabel, ...
115+
/Text$/, // emptySearchText, helperText, errorText, ...
116+
/Placeholder$/, // searchPlaceholder, timePlaceholder, ...
117+
/Title$/, // dialogTitle, ...
118+
/Message$/, // disabledMessage, errorMessage, ...
119+
/Tooltip$/, // ...
120+
/Hint$/, // ...
121+
/Description$/, // ...
122+
/Summary$/, // ...
123123
];
124124

125125
function isUserFacingName(name) {
@@ -154,7 +154,11 @@ function looksUserFacing(value) {
154154
return false;
155155
}
156156
// All-caps enum constant like `IS_ANY_OF`
157-
if (value === value.toUpperCase() && /[A-Z_]/.test(value) && !/\s/.test(value)) {
157+
if (
158+
value === value.toUpperCase() &&
159+
/[A-Z_]/.test(value) &&
160+
!/\s/.test(value)
161+
) {
158162
return false;
159163
}
160164
// Single lowercase word (identifier-shaped: `contains`, `email`, `foo123`)
@@ -227,8 +231,20 @@ function reportUserFacingLiteralsIn(expr, name, context, isDefault, opts = {}) {
227231
}
228232
return;
229233
case 'ConditionalExpression':
230-
reportUserFacingLiteralsIn(expr.consequent, name, context, isDefault, opts);
231-
reportUserFacingLiteralsIn(expr.alternate, name, context, isDefault, opts);
234+
reportUserFacingLiteralsIn(
235+
expr.consequent,
236+
name,
237+
context,
238+
isDefault,
239+
opts,
240+
);
241+
reportUserFacingLiteralsIn(
242+
expr.alternate,
243+
name,
244+
context,
245+
isDefault,
246+
opts,
247+
);
232248
return;
233249
case 'LogicalExpression':
234250
// Only the right side can be a fallback/default string; the left is a
@@ -247,21 +263,21 @@ const rule = {
247263
type: 'problem',
248264
docs: {
249265
description:
250-
'Disallow hardcoded user-facing strings; route through useTranslator() instead',
266+
'Disallow hardcoded user-facing strings; route through a translator (useComponentTranslator(<slice>) in core, useTranslator() elsewhere) instead',
251267
category: 'Best Practices',
252268
recommended: true,
253269
},
254270
messages: {
255271
hardcodedString:
256272
'Hardcoded user-facing string {{value}} in `{{name}}`. ' +
257-
'Route through `t(\'<namespace>.<component>.<key>\')` via `useTranslator()` so it can be localized.',
273+
"Route through `t('<namespace>.<component>.<key>')` via `useComponentTranslator(<slice>)` (in core; `useTranslator()` elsewhere) so it can be localized.",
258274
hardcodedDefault:
259275
'Hardcoded default {{value}} for prop `{{name}}`. ' +
260276
'Use the alias-and-resolve pattern: `{{name}}: {{name}}FromProps` in the destructure, then ' +
261-
'`const {{name}} = {{name}}FromProps ?? t(\'<namespace>.<component>.<key>\');` inside the body.',
277+
"`const {{name}} = {{name}}FromProps ?? t('<namespace>.<component>.<key>');` inside the body.",
262278
hardcodedCallArg:
263279
'Hardcoded user-facing string {{value}} passed to `{{name}}()`. ' +
264-
'Route through `t(\'<namespace>.<component>.<key>\')` via `useTranslator()` so it can be localized.',
280+
"Route through `t('<namespace>.<component>.<key>')` via `useComponentTranslator(<slice>)` (in core; `useTranslator()` elsewhere) so it can be localized.",
265281
},
266282
schema: [
267283
{
@@ -292,10 +308,7 @@ const rule = {
292308
// 1. JSX attribute string literals: <X label="Cancel">
293309
JSXAttribute(node) {
294310
if (!node.name || node.name.type === 'JSXNamespacedName') return;
295-
const name =
296-
node.name.type === 'JSXIdentifier'
297-
? node.name.name
298-
: null;
311+
const name = node.name.type === 'JSXIdentifier' ? node.name.name : null;
299312
if (!isUserFacingName(name)) return;
300313

301314
// 1. Bare string-literal attribute: <X label="Cancel">
@@ -334,8 +347,8 @@ const rule = {
334347
node.key.type === 'Identifier'
335348
? node.key.name
336349
: node.key.type === 'Literal'
337-
? node.key.value
338-
: null;
350+
? node.key.value
351+
: null;
339352
if (!isUserFacingName(name)) return;
340353
if (
341354
node.value.type !== 'Literal' ||
@@ -366,8 +379,8 @@ const rule = {
366379
property.key.type === 'Identifier'
367380
? property.key.name
368381
: property.key.type === 'Literal'
369-
? property.key.value
370-
: null;
382+
? property.key.value
383+
: null;
371384
if (!isUserFacingName(name)) return;
372385
reportUserFacingLiteralsIn(
373386
node.right,

‎packages/cli/assets/docs/tree/i18n-rtl-and-testing.doc.mjs‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,11 @@ export const docs = {
1111
type: 'generic',
1212
name: 'i18n-rtl-and-testing',
1313
title: 'RTL & Testing',
14-
placement: {parent: 'namespace:internationalization', slot: 'guides', order: 30},
14+
placement: {
15+
parent: 'namespace:internationalization',
16+
slot: 'guides',
17+
order: 30,
18+
},
1519
category: 'guide',
1620
description:
1721
'Text direction (RTL), pseudo-locale testing, and contributor guidance for developers and translators.',
@@ -122,22 +126,23 @@ import pseudo from '@astryxdesign/core/locales/pseudo.generated.js';
122126
},
123127
{
124128
type: 'prose',
125-
text: 'Astryx component authors read strings with `useTranslator()` rather than hardcoding user-facing text.',
129+
text: "Astryx component authors read strings with `useComponentTranslator(<slice>)` rather than hardcoding user-facing text. The slice is the component's own namespace of the English catalog, so an app bundles only the strings of the components it renders.",
126130
},
127131
{
128132
type: 'code',
129133
lang: 'tsx',
130134
label: 'Read an astryx string',
131-
code: `import {useTranslator} from '@astryxdesign/core/i18n';
135+
code: `import {useComponentTranslator} from '../i18n/useComponentTranslator';
136+
import saveButtonMessages from '../i18n/generated-locales/en/saveButton.generated';
132137
133138
function SaveButton() {
134-
const t = useTranslator();
135-
return <button>{t('@astryx.actions.save')}</button>;
139+
const t = useComponentTranslator(saveButtonMessages);
140+
return <button>{t('@astryx.saveButton.save')}</button>;
136141
}`,
137142
},
138143
{
139144
type: 'prose',
140-
text: "Astryx's own strings live in `packages/core/locales/en.json`. New user-facing strings must go through `useTranslator`; this is enforced by the `@astryx/no-hardcoded-i18n-string` ESLint rule. See the AI contribution guide for the alias-and-resolve pattern used when adding new keys.",
145+
text: "Astryx's own strings live in `packages/core/locales/en.json`, keyed `@astryx.<namespace>.<name>`. New user-facing strings must go through the translator; the `@astryx/no-hardcoded-i18n-string` ESLint rule enforces that, and `pnpm check:i18n-catalog` fails a key read outside the file's slice. `useTranslator()` from `@astryxdesign/core/i18n` is the consumer-facing hook and carries the whole catalog. See the AI contribution guide for the alias-and-resolve pattern used when adding new keys.",
141146
},
142147
{
143148
type: 'prose',

‎packages/core/src/i18n/useComponentTranslator.test.tsx‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,10 @@ import {useTranslator} from './useTranslator';
1919
import {InternationalizationContext} from './InternationalizationContext';
2020
import {InternationalizationProvider} from './InternationalizationProvider';
2121
import {__resetForTests} from './resolve';
22+
import enCatalog from './generated-locales/en.generated';
2223
import buttonMessages from './generated-locales/en/button.generated';
2324
import paginationMessages from './generated-locales/en/pagination.generated';
25+
import enSource from '../../locales/en.json';
2426
import type {MessagesByLocale, Overrides} from './types';
2527

2628
const FR_MESSAGES: MessagesByLocale = {
@@ -100,6 +102,22 @@ describe('useComponentTranslator', () => {
100102
});
101103
});
102104

105+
describe('the whole English catalog', () => {
106+
it('is the spread of the namespace slices and carries every authored key once', () => {
107+
const authored = Object.keys(enSource).sort();
108+
expect(Object.keys(enCatalog).sort()).toEqual(authored);
109+
for (const key of authored) {
110+
expect(enCatalog[key]).toBe(
111+
(enSource as Record<string, {defaultMessage: string}>)[key]
112+
.defaultMessage,
113+
);
114+
}
115+
expect(enCatalog['@astryx.button.loading']).toBe(
116+
buttonMessages['@astryx.button.loading'],
117+
);
118+
});
119+
});
120+
103121
describe('the public InternationalizationContext boundary', () => {
104122
it('its translate falls back to the whole shipped English catalog with no provider, as it always has', () => {
105123
const {result} = renderHook(() => use(InternationalizationContext));

‎scripts/generate-i18n-runtime.mjs‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,13 @@
88
* translator descriptions. Each generated module exports only the
99
* key-to-defaultMessage map used at runtime.
1010
*
11-
* The English catalog is also emitted one namespace at a time, under
11+
* The English catalog is emitted one namespace at a time, under
1212
* `generated-locales/en/<namespace>.generated.ts`: a component carries its own
1313
* slice through `useComponentTranslator`, so an app bundles the strings of the
14-
* components it renders rather than the whole library's.
14+
* components it renders rather than the whole library's. The whole English
15+
* catalog, `en.generated.ts`, is the spread of those slices rather than a
16+
* second copy of the strings, so an app that also mounts the provider or calls
17+
* `useTranslator()` ships each string once.
1518
*/
1619

1720
import {spawn} from 'node:child_process';
@@ -147,6 +150,29 @@ export async function renderRuntimeCatalogModule(runtimeCatalog, sourceFile) {
147150
);
148151
}
149152

153+
/**
154+
* The whole English catalog as the spread of its namespace slices. Each
155+
* string lives in one module; a bundle that reaches both a component's slice
156+
* and the whole catalog carries it once.
157+
*/
158+
export async function renderEnglishCatalogModule(namespaces) {
159+
const {format, resolveConfig} = await import('prettier');
160+
const outputFile = getGeneratedModulePath(EN_FILE);
161+
const identifier = namespace => `${namespace}Messages`;
162+
const imports = namespaces
163+
.map(
164+
namespace =>
165+
`import ${identifier(namespace)} from './${EN_SLICES_DIR}/${namespace}.generated';`,
166+
)
167+
.join('\n');
168+
const spreads = namespaces
169+
.map(namespace => `...${identifier(namespace)},`)
170+
.join('\n');
171+
const source = `// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n/**\n * @generated by scripts/generate-i18n-runtime.mjs from packages/core/locales/${EN_FILE}.\n * The whole English catalog: the spread of its namespace slices under ./${EN_SLICES_DIR}/,\n * so each string ships once however it is reached.\n * Translator descriptions remain in the authored JSON catalogs and must not be copied here.\n * Do not edit by hand. Run \`pnpm generate:i18n-runtime\` instead.\n */\n\n${imports}\n\nconst runtimeCatalog: Readonly<Record<string, string>> = {\n${spreads}\n};\n\nexport default runtimeCatalog;\n`;
172+
const prettierConfig = await resolveConfig(outputFile);
173+
return format(source, {...prettierConfig, filepath: outputFile});
174+
}
175+
150176
export async function renderNamespaceSliceModule(slice, namespace) {
151177
return renderCatalogModule(
152178
slice,
@@ -227,7 +253,10 @@ export async function generateRuntimeCatalogs({check = false} = {}) {
227253
removeStaleModules(slicesDir, expectedSliceFiles);
228254
let changed = 0;
229255
for (const [file, catalog] of Object.entries(runtimeCatalogs)) {
230-
const output = await renderRuntimeCatalogModule(catalog, file);
256+
const output =
257+
file === EN_FILE
258+
? await renderEnglishCatalogModule(Object.keys(slices))
259+
: await renderRuntimeCatalogModule(catalog, file);
231260
if (writeIfChanged(getGeneratedModulePath(file), output)) changed += 1;
232261
}
233262
for (const [namespace, slice] of Object.entries(slices)) {

‎scripts/generate-i18n-runtime.test.mjs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
getSliceModuleName,
1717
isSourceLocaleFile,
1818
namespaceOf,
19+
renderEnglishCatalogModule,
1920
renderNamespaceSliceModule,
2021
renderRuntimeCatalogModule,
2122
} from './generate-i18n-runtime.mjs';
@@ -167,6 +168,20 @@ describe('English namespace slices', () => {
167168
);
168169
expect(output).toContain('export default runtimeCatalog;');
169170
});
171+
172+
it('renders the whole English catalog as the spread of its slices, so each string ships once', async () => {
173+
const output = await renderEnglishCatalogModule(['button', 'pagination']);
174+
expect(output).toContain(
175+
"import buttonMessages from './en/button.generated';",
176+
);
177+
expect(output).toContain(
178+
"import paginationMessages from './en/pagination.generated';",
179+
);
180+
expect(output).toContain('...buttonMessages,');
181+
expect(output).toContain('...paginationMessages,');
182+
expect(output).not.toMatch(/'@astryx\./);
183+
expect(output).toContain('export default runtimeCatalog;');
184+
});
170185
});
171186

172187
describe('generated module names', () => {

0 commit comments

Comments
 (0)