diff --git a/.changeset/i18n-cli-guide-caller-facing.md b/.changeset/i18n-cli-guide-caller-facing.md new file mode 100644 index 0000000000000..2a5ae61c49bdf --- /dev/null +++ b/.changeset/i18n-cli-guide-caller-facing.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/cli': patch +--- + +[docs] The i18n, RTL and testing guide keeps to what holds for a caller: `useTranslator()` resolves every `@astryx.*` key; how a core component reads its strings moves to the contributing guide. + +@vjeux diff --git a/.changeset/i18n-components-own-slices.md b/.changeset/i18n-components-own-slices.md new file mode 100644 index 0000000000000..fb695afed8740 --- /dev/null +++ b/.changeset/i18n-components-own-slices.md @@ -0,0 +1,8 @@ +--- +'@astryxdesign/core': patch +'@astryxdesign/cli': patch +--- + +[perf] A component carries only its own English strings. Every core component now renders with its own namespace slice of the English catalog instead of the whole catalog, so an app that renders components without mounting `InternationalizationProvider`, calling `useTranslator()` or importing `InternationalizationContext` (each of which carries the whole catalog), and that does not render `PowerSearch` (whose caller-supplied operator keys keep the whole catalog as their fallback), bundles only the strings of the components it renders: a page importing `Button`, `Dialog`, `DateInput` or `List` loads 6.2 to 6.8 KB (gzip) less JavaScript. An app that does mount the provider still carries the whole catalog, now assembled from the same slices so no string ships twice; such a page loads 1.2 to 1.9 KB (gzip) more, because the catalog spread over its slice modules compresses worse than one module (about 0.9 KB more when the provider is imported before the components). `useTranslator()` is unchanged. `astryx swizzle` points an ejected component's strings at the public `useTranslator()`: the internal translator import, the slice imports and a module-level merge of slices are rewritten, so the copy compiles in the app. + +@vjeux diff --git a/.changeset/i18n-context-codemod.md b/.changeset/i18n-context-codemod.md new file mode 100644 index 0000000000000..fe26b98d3bad2 --- /dev/null +++ b/.changeset/i18n-context-codemod.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/cli': patch +--- + +[feat] `astryx upgrade` runs `migrate-internationalization-context`, which rewrites `` (or its `.Provider`) to ``: a variable maps `locale`, `direction` (as `dir`) and `messages` — the fields every context value has — and its TODO names `overrides` and `translate`, which the variable's type may lack and the provider has no input for; an inline object literal maps key by key, `overrides` included, with a TODO for `translate` (a literal's `translate` key is kept beside it). Any other value — a call, a spread into a literal, a conditional — is left unchanged behind a TODO saying why. It rewrites JSX whose name resolves, unshadowed, to an Astryx import (named, aliased, or namespace), reuses the file's own provider import name, and leaves a reader of the context alone. + +@vjeux diff --git a/.changeset/i18n-en-namespace-slices.md b/.changeset/i18n-en-namespace-slices.md new file mode 100644 index 0000000000000..669609a722d2d --- /dev/null +++ b/.changeset/i18n-en-namespace-slices.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': minor +--- + +[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer configures Astryx: it drives neither `useLocale`, `useDirection` and `useCollator`, nor the components that read the locale or direction through them (the date, date-time, date-range and number inputs, Calendar, Chat, PowerSearch, Table sorting and filtering, Timestamp), nor any core component's strings — every component now renders with its own English slice through an internal translator, and `DateTimeInput`'s touch field reads `useLocale()`. One deliberate exception: a `PowerSearch` operator `i18nKey` from outside PowerSearch's own namespace (a key of another Astryx component, or of the app's catalog) still resolves through the public context's `translate`, since a caller may supply any key there; the shipped default operators are PowerSearch's own and read the slice like the rest of the component. Migration: mount `InternationalizationProvider`; its `locale`, `messages` and `overrides` take the value's fields of the same name, and its `dir` takes the value's `direction`. The provider has no `translate` input: an app that supplied its own `translate` expresses those strings as `messages` (a catalog per locale) or `overrides` (sparse, per locale) and the provider resolves them in the documented order. Run `astryx upgrade`: its `migrate-internationalization-context` transform rewrites a variable value to the provider's `locale`, `dir` and `messages` with a TODO for its `overrides` and `translate`, and an inline object literal key by key with a TODO for `translate`; any other value, and any element that spreads props, is left as written behind a TODO saying why. The provider now writes an internal runtime context that those hooks read. Reading the public context is unchanged, so a component that reads it with `useContext` and re-mounts `InternationalizationProvider` with a derived value keeps working: `locale`, `direction`, `messages`, `overrides` and `translate`, which still resolves every `@astryx.*` key against the whole shipped English catalog, with or without a provider; `useTranslator()` is unchanged. The English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` is what a core component renders with. The slices are not importable. + +@vjeux diff --git a/.changeset/vite-locale-alias-one-segment.md b/.changeset/vite-locale-alias-one-segment.md new file mode 100644 index 0000000000000..e9a415831e49f --- /dev/null +++ b/.changeset/vite-locale-alias-one-segment.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/build': patch +--- + +[fix] `astryxStylex()`'s alias for `@astryxdesign/core/locales/.generated.js` takes one path segment, so the per-namespace English slices under `locales/en/` — which the package's exports map keeps out of reach — no longer resolve through the source tree in a Vite app either. + +@vjeux diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 324c208e913a4..0e73522e22aa1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -292,24 +292,40 @@ export * from './MyComponent'; ### User-facing strings and text direction -Components read user-facing strings with `useTranslator()` rather than -hardcoding them: +Components read user-facing strings with `useComponentTranslator()` +rather than hardcoding them. The slice is the component's own namespace of the +English catalog, generated under `src/i18n/generated-locales/en/`, so an app +that neither mounts `InternationalizationProvider`, calls `useTranslator()` nor +imports `InternationalizationContext` (each carries the whole catalog), and does +not render `PowerSearch` (its caller-supplied operator keys keep the whole +catalog as their fallback, through the internal `useCatalogTranslator`), bundles +only the strings of the components it renders: ```tsx -import {useTranslator} from '@astryxdesign/core/i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import saveButtonMessages from '../i18n/generated-locales/en/saveButton.generated'; function SaveButton() { - const t = useTranslator(); - return ; + const t = useComponentTranslator(saveButtonMessages); + return ; } ``` -Astryx's own strings live in `packages/core/locales/en.json`. The -`@astryx/no-hardcoded-i18n-string` ESLint rule rejects a hardcoded one. For a -prop whose default is a translated string, alias the prop and resolve it in the -body: destructure `label: labelFromProps`, then +A file that reads several namespaces merges their slices once at module level +(`const messages = {...aMessages, ...bMessages}`) and passes that. Astryx's own +strings live in `packages/core/locales/en.json`, keyed +`@astryx..`; `pnpm generate:i18n-runtime` emits the slices, and +`pnpm check:i18n-catalog` fails a key read outside the file's slice, and any +import of `useTranslator` or `InternationalizationContext` inside core. The +`@astryx/no-hardcoded-i18n-string` ESLint rule rejects a hardcoded string. For +a prop whose default is a translated string, alias the prop and resolve it in +the body: destructure `label: labelFromProps`, then `const label = labelFromProps ?? t('@astryx..')`. +`useTranslator()` from `@astryxdesign/core/i18n` is the consumer-facing hook: +it carries the whole English catalog, so code inside `packages/core` does not +use it; packages that depend on core (`lab`, `richtext`) do. + A component that responds to text direction resolves it from the DOM, not from a render-time JavaScript read. Reach for the lightest tool that works, in this order: @@ -347,8 +363,8 @@ order: flip for free; don't pass them a direction flag. 4. **`useDirection()` context, as a last resort.** Use it only when you need the direction value during render and nothing above fits. It is SSR-safe - and returns `'ltr'` outside a provider (like `useTranslator`'s silent - fallback), but it is the one path that can mismatch on hydration when the + and returns `'ltr'` outside a provider (like a translator's silent + English fallback), but it is the one path that can mismatch on hydration when the provider's direction disagrees with ``. No Astryx component reads direction from context at render time. diff --git a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js index f0f27c2c06cf9..d576902546a5d 100644 --- a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js +++ b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js @@ -335,14 +335,14 @@ const rule = { type: 'problem', docs: { description: - 'Disallow hardcoded user-facing strings; route through useTranslator() instead', + 'Disallow hardcoded user-facing strings; route through a translator (useComponentTranslator() in core, useTranslator() elsewhere) instead', category: 'Best Practices', recommended: true, }, messages: { hardcodedString: 'Hardcoded user-facing string {{value}} in `{{name}}`. ' + - 'Route through `t(\'..\')` via `useTranslator()` so it can be localized.', + 'Route through `t(\'..\')` via `useComponentTranslator()` (in core; `useTranslator()` elsewhere) so it can be localized.', hardcodedDefault: 'Hardcoded default {{value}} for prop `{{name}}`. ' + 'Use the alias-and-resolve pattern: `{{name}}: {{name}}FromProps` in the destructure, then ' + @@ -352,7 +352,7 @@ const rule = { 'Use one catalog message via the provider-bound translator instead of constructing English text.', hardcodedCallArg: 'Hardcoded user-facing string {{value}} passed to `{{name}}()`. ' + - 'Route through `t(\'..\')` via `useTranslator()` so it can be localized.', + 'Route through `t(\'..\')` via `useComponentTranslator()` (in core; `useTranslator()` elsewhere) so it can be localized.', }, schema: [ { diff --git a/packages/build/src/vite.test.ts b/packages/build/src/vite.test.ts index 8f618832c8a34..1fcdc5b52ca46 100644 --- a/packages/build/src/vite.test.ts +++ b/packages/build/src/vite.test.ts @@ -176,6 +176,27 @@ describe('astryxStylex locale aliases', () => { path.join(corePackage, 'src/Button'), ); }); + + it('does not route a per-namespace English slice to its source file', () => { + // `locales/en/.generated.js` is the package's own: the exports + // map gives it a `null` target, and the alias for whole catalogs takes a + // single path segment, so the slice specifier never reaches + // `src/i18n/generated-locales/en/`. + const rootDir = path.join(tmpdir(), 'astryx-vite-alias'); + const aliases = getInjectedConfig(rootDir).resolve.alias; + const corePackage = path.join(rootDir, 'node_modules/@astryxdesign/core'); + const resolved = applyAlias( + aliases, + '@astryxdesign/core/locales/en/button.generated.js', + ); + expect(resolved).not.toContain('generated-locales'); + expect(resolved).not.toBe( + path.join( + corePackage, + 'src/i18n/generated-locales/en/button.generated.ts', + ), + ); + }); }); describe('astryxStylex optimizeDeps package discovery', () => { diff --git a/packages/build/src/vite.ts b/packages/build/src/vite.ts index 0581b58675edb..07f4a3d6c0b86 100644 --- a/packages/build/src/vite.ts +++ b/packages/build/src/vite.ts @@ -225,7 +225,12 @@ export function astryxStylex( resolve: { alias: [ { - find: /^@astryxdesign\/core\/locales\/(.+)\.generated\.js$/, + // A whole catalog, `locales/.generated.js`. The capture + // takes one path segment only: the per-namespace English slices + // under `locales/en/.generated.js` are the package's + // own (the exports map gives them a `null` target), and this + // alias must not reach them either. + find: /^@astryxdesign\/core\/locales\/([^/]+)\.generated\.js$/, replacement: path.join( coreSourceDir, 'i18n/generated-locales/$1.generated.ts', diff --git a/packages/cli/api/swizzle/copy/copy.mjs b/packages/cli/api/swizzle/copy/copy.mjs index a77bec1ba5065..d2c0a38121675 100644 --- a/packages/cli/api/swizzle/copy/copy.mjs +++ b/packages/cli/api/swizzle/copy/copy.mjs @@ -16,7 +16,11 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import {resolveComponentReplacement, resolveCore} from '../_adapter.mjs'; -import {assertWithin, sanitizeName, PathSafetyError} from '../../../foundation/fs/path-safety.mjs'; +import { + assertWithin, + sanitizeName, + PathSafetyError, +} from '../../../foundation/fs/path-safety.mjs'; import {checkGhCli} from '../_github.mjs'; import {Project} from '../../../foundation/config/project.mjs'; import { @@ -32,6 +36,81 @@ import {AstryxError, writeFailed} from '../../error.mjs'; /** Default issue tracker for maintainer feedback after swizzling. */ const DEFAULT_ISSUES_URL = 'https://github.com/facebook/astryx/issues/new'; +/** + * A core component reads its strings with the internal + * `useComponentTranslator()`; neither the hook nor the + * slices are public (the slices are `null` in the exports map). An ejected + * copy lives in the app, whose public translator is `useTranslator()` — it + * resolves every `@astryx.*` key against the whole English catalog — so the + * copy reads through that instead: the hook import becomes the public one, + * the slice imports and a module-level merge of slices go, and each call + * becomes `useTranslator()`. A type-only `TranslatorFn` import rides along. + * The internal `useCatalogTranslator` (caller-supplied keys) is the public + * `useTranslator` under another name, so its import becomes an alias of it. + * + * @param {string} content + * @param {string} ownerPackage + */ +export function rewriteComponentTranslator(content, ownerPackage) { + if ( + !content.includes('useComponentTranslator') && + !content.includes('useCatalogTranslator') + ) { + return content; + } + const i18n = `${ownerPackage}/i18n`; + return ( + content + // import {useCatalogTranslator} from '../i18n/useCatalogTranslator'; + // The internal whole-catalog translator for caller-supplied keys is the + // public `useTranslator` under another name; the alias keeps both call + // sites (`t` and `tCaller`) as written. + .replace( + /import\s*\{([^}]*)\}\s*from\s+['"](?:\.\.\/)+i18n\/useCatalogTranslator['"];?/g, + (_m, names) => { + const kept = names + .split(',') + .map((/** @type {string} */ n) => n.trim()) + .filter(Boolean) + .map((/** @type {string} */ n) => + n === 'useCatalogTranslator' + ? 'useTranslator as useCatalogTranslator' + : n, + ); + return `import {${kept.join(', ')}} from '${i18n}';`; + }, + ) + // import {useComponentTranslator[, type TranslatorFn]} from '../i18n/useComponentTranslator'; + .replace( + /import\s*\{([^}]*)\}\s*from\s+['"](?:\.\.\/)+i18n\/useComponentTranslator['"];?/g, + (_m, names) => { + const kept = names + .split(',') + .map((/** @type {string} */ n) => n.trim()) + .filter(Boolean) + .map((/** @type {string} */ n) => + n === 'useComponentTranslator' ? 'useTranslator' : n, + ); + return `import {${kept.join(', ')}} from '${i18n}';`; + }, + ) + // import xMessages from '../i18n/generated-locales/en/x.generated'; + .replace( + /^import\s+\w+\s+from\s+['"](?:\.\.\/)+i18n\/generated-locales\/[^'"]+['"];?\r?\n/gm, + '', + ) + // const messages = {...aMessages, ...bMessages}; + .replace( + /^const\s+\w+\s*=\s*\{(?:\s*\.\.\.\w+Messages\s*,?)+\s*\};?\r?\n/gm, + '', + ) + // useComponentTranslator(xMessages) -> useTranslator() + .replace(/\buseComponentTranslator\(\s*[\w.]+\s*\)/g, 'useTranslator()') + // The file header's `@input … i18n (useComponentTranslator)` note. + .replace(/\buseComponentTranslator\b/g, 'useTranslator') + ); +} + /** * Rewrite relative imports that point outside the component directory to use * the OWNER package's subpaths. Imports within the copied directory (./x) are @@ -58,6 +137,7 @@ const DEFAULT_ISSUES_URL = 'https://github.com/facebook/astryx/issues/new'; * @param {string} [ownerPackage] */ export function rewriteImports(content, ownerPackage = CORE_PACKAGE) { + content = rewriteComponentTranslator(content, ownerPackage); /** @param {string} importPath */ const mapTarget = importPath => { // Strip ALL leading `../` so a two-levels-up path never yields `/..`. @@ -270,14 +350,20 @@ export async function swizzleCopy(component, options = {}) { if (!owner) { throw new AstryxError( `Component "${dirName}" is not provided by package "${pkg}".`, - allOwners.map(o => ({name: o.package, reason: 'provides this component'})), + allOwners.map(o => ({ + name: o.package, + reason: 'provides this component', + })), ERROR_CODES.ERR_UNKNOWN_COMPONENT, ); } } else if (allOwners.length > 1) { throw new AstryxError( `Component "${dirName}" is provided by multiple packages. Re-run with --package to choose one.`, - allOwners.map(o => ({name: o.package, reason: 'provides this component'})), + allOwners.map(o => ({ + name: o.package, + reason: 'provides this component', + })), ERROR_CODES.ERR_AMBIGUOUS_COMPONENT, ); } else { diff --git a/packages/cli/api/swizzle/swizzle.test.mjs b/packages/cli/api/swizzle/swizzle.test.mjs index 045e46b2e1198..4511a725815c2 100644 --- a/packages/cli/api/swizzle/swizzle.test.mjs +++ b/packages/cli/api/swizzle/swizzle.test.mjs @@ -7,7 +7,10 @@ import {fileURLToPath} from 'node:url'; import {rewriteImports, swizzle} from './swizzle.mjs'; // api/swizzle/ -> up 3 = packages/cli, up 4 = repo root (has packages/core). -const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..'); +const REPO = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../..', +); describe('rewriteImports', () => { it('preserves the theme token subpath (StyleX module is a dedicated export)', () => { @@ -21,7 +24,9 @@ describe('rewriteImports', () => { it('rewrites ../utils/mergeProps to @astryxdesign/core/utils', () => { const input = `import { mergeProps } from '../utils/mergeProps';`; const result = rewriteImports(input); - expect(result).toBe(`import { mergeProps } from '@astryxdesign/core/utils';`); + expect(result).toBe( + `import { mergeProps } from '@astryxdesign/core/utils';`, + ); }); it('leaves same-level relative imports untouched', () => { @@ -115,26 +120,136 @@ describe('swizzle() API', () => { }); it('unknown component → AstryxError ERR_UNKNOWN_COMPONENT with suggestions', async () => { - await expect(swizzle('NotARealComponent99', {cwd: REPO})).rejects.toMatchObject({ + await expect( + swizzle('NotARealComponent99', {cwd: REPO}), + ).rejects.toMatchObject({ code: 'ERR_UNKNOWN_COMPONENT', }); }); }); +describe('rewriteImports — a component reading its own English slice', () => { + it('reads through the public useTranslator() in the ejected copy', () => { + const input = `import { + useComponentTranslator, + type TranslatorFn, +} from '../i18n/useComponentTranslator'; +import buttonMessages from '../i18n/generated-locales/en/button.generated'; +import fieldMessages from '../i18n/generated-locales/en/field.generated'; +const messages = { + ...buttonMessages, + ...fieldMessages, +}; +export function Button() { + const t = useComponentTranslator(messages); + return {t('@astryx.button.loading')}; +} +function helper(t: TranslatorFn) { + return t('@astryx.field.required'); +}`; + const out = rewriteImports(input); + expect(out).toContain( + "import {useTranslator, type TranslatorFn} from '@astryxdesign/core/i18n';", + ); + expect(out).toContain('const t = useTranslator();'); + expect(out).not.toContain('useComponentTranslator'); + expect(out).not.toContain('generated-locales'); + expect(out).not.toContain('Messages'); + expect(out).toContain('helper(t: TranslatorFn)'); + }); + + it('every core component, as swept, ejects with i18n imports the public barrel exports', () => { + // The barrel's exported names (the public name of an `X as Y` re-export). + const i18nIndex = fs.readFileSync( + path.join(REPO, 'packages/core/src/i18n/index.ts'), + 'utf-8', + ); + const exported = new Set( + [...i18nIndex.matchAll(/export (?:type )?\{([^}]+)\}/g)].flatMap(m => + m[1].split(',').map(n => + n + .trim() + .split(/\s+as\s+/) + .pop(), + ), + ), + ); + const srcDir = path.join(REPO, 'packages/core/src'); + const componentDirs = fs + .readdirSync(srcDir, {withFileTypes: true}) + .filter( + d => d.isDirectory() && d.name !== 'i18n' && !d.name.startsWith('_'), + ) + .map(d => d.name); + let sawTranslator = false; + let sawCallerKeyAlias = false; + for (const dir of componentDirs) { + const files = fs + .readdirSync(path.join(srcDir, dir)) + .filter( + f => + (f.endsWith('.ts') || f.endsWith('.tsx')) && + !f.includes('.test.') && + !f.includes('.doc.') && + !f.includes('.stories.'), + ); + for (const file of files) { + const rewritten = rewriteImports( + fs.readFileSync(path.join(srcDir, dir, file), 'utf-8'), + ); + const where = `${dir}/${file}`; + expect(rewritten, where).not.toContain('useComponentTranslator'); + expect(rewritten, where).not.toContain('generated-locales'); + expect(rewritten, where).not.toMatch(/i18n\/useCatalogTranslator/); + expect(rewritten, where).not.toMatch( + /import \w+ from ['"]@astryxdesign\/core\/i18n['"]/, + ); + const re = + /import\s*\{([^}]*)\}\s*from\s+['"]@astryxdesign\/core\/i18n['"]/g; + let m; + while ((m = re.exec(rewritten)) !== null) { + for (const raw of m[1].split(',')) { + // `X as Y` imports `X`; that is the name the barrel must export. + const name = raw + .trim() + .replace(/^type\s+/, '') + .split(/\s+as\s+/)[0]; + if (!name) continue; + expect( + exported.has(name), + `${where}: ${name} must be exported from the i18n barrel`, + ).toBe(true); + if (name === 'useTranslator') sawTranslator = true; + if (/useTranslator\s+as\s+useCatalogTranslator/.test(raw)) { + sawCallerKeyAlias = true; + } + } + } + } + } + expect(sawTranslator).toBe(true); + // PowerSearch reads caller-supplied keys through the internal + // whole-catalog translator; ejected, that is the public one under an alias. + expect(sawCallerKeyAlias).toBe(true); + }); +}); + describe('swizzle rewriteImports compiles for components with .stylex imports', () => { it('Button: every rewritten import resolves in the core exports map', async () => { const corePkg = JSON.parse( - fs.readFileSync( - path.join(REPO, 'packages/core/package.json'), - 'utf-8', - ), + fs.readFileSync(path.join(REPO, 'packages/core/package.json'), 'utf-8'), ); const exportKeys = new Set(Object.keys(corePkg.exports)); const buttonDir = path.join(REPO, 'packages/core/src/Button'); - const files = fs.readdirSync(buttonDir).filter( - f => (f.endsWith('.ts') || f.endsWith('.tsx')) && !f.includes('.test.') && !f.includes('.doc.'), - ); + const files = fs + .readdirSync(buttonDir) + .filter( + f => + (f.endsWith('.ts') || f.endsWith('.tsx')) && + !f.includes('.test.') && + !f.includes('.doc.'), + ); for (const file of files) { const content = fs.readFileSync(path.join(buttonDir, file), 'utf-8'); diff --git a/packages/cli/assets/codemods/transforms/next/__tests__/migrate-internationalization-context.test.mjs b/packages/cli/assets/codemods/transforms/next/__tests__/migrate-internationalization-context.test.mjs new file mode 100644 index 0000000000000..c5f5f9c8a7461 --- /dev/null +++ b/packages/cli/assets/codemods/transforms/next/__tests__/migrate-internationalization-context.test.mjs @@ -0,0 +1,517 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +import {execFileSync} from 'node:child_process'; +import {mkdtempSync, writeFileSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {describe, expect, it} from 'vitest'; +import jscodeshift from 'jscodeshift'; +import transform, {meta} from '../migrate-internationalization-context.mjs'; +import nextManifest from '../index.mjs'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repoRoot = path.resolve(here, '../../../../../../..'); + +const j = jscodeshift.withParser('tsx'); +const api = {jscodeshift: j, stats: () => {}, report: () => {}}; + +/** @param {string} source */ +function apply(source) { + return transform({source, path: 'test.tsx'}, api) ?? source; +} + +/** + * The printer wraps long attribute lists and places the TODO comment before + * the attribute it annotates; compare with whitespace folded and comments + * removed. + */ +const folded = (/** @type {string} */ text) => + text + .replace(/\/\*[\s\S]*?\*\//g, '') + .replace(/\s+/g, ' ') + .replace(/ >/g, '>'); + +const TRANSLATE_TODO = 'InternationalizationProvider has no `translate` input'; +const EXPRESSION_TODO = 'Not rewritten here: the value is an expression'; + +describe('migrate-internationalization-context', () => { + it('is staged in the next manifest, so astryx upgrade runs it', () => { + const entry = nextManifest.find( + t => t.name === 'migrate-internationalization-context', + ); + expect(entry).toBeDefined(); + expect(entry?.transform).toBe(transform); + expect(entry?.meta).toBe(meta); + }); + + it('rewrites a variable value to the provider, field by field, with a TODO for its translate', () => { + const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; +const app = ;`; + const output = apply(input); + expect(folded(output)).toContain( + 'locale={i18n.locale} dir={i18n.direction} messages={i18n.messages}>', + ); + expect(output).not.toContain('overrides='); + expect(output).toContain(TRANSLATE_TODO); + expect(output).toContain('pass the value’s `overrides`'); + expect(output).toContain( + "import {InternationalizationProvider} from '@astryxdesign/core/i18n';", + ); + expect(output).not.toContain('InternationalizationContext'); + }); + + it('maps an inline object key by key, keeping only the keys it has, and the .Provider form', () => { + const input = `import {InternationalizationContext} from '@astryxdesign/core'; +const app = ( + + + +);`; + const output = apply(input); + expect(folded(output)).toContain( + "", + ); + expect(output).toContain(''); + expect(output).toContain(TRANSLATE_TODO); + expect(output).not.toContain('overrides='); + }); + + it("keeps a literal's translate key beside the TODO rather than dropping it", () => { + const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; +const app = ;`; + const output = apply(input); + expect(output).toContain("locale={'en'}"); + expect(output).toContain(TRANSLATE_TODO); + expect(output).toContain('translate: myTranslate'); + }); + + it('leaves a call or a spread unchanged behind a TODO that says why', () => { + const input = `import {InternationalizationContext, InternationalizationProvider} from '@astryxdesign/core/i18n'; +import {useContext} from 'react'; +function Wrapped({children}) { + const ambient = useContext(InternationalizationContext); + return {children}; +} +const app = ;`; + const output = apply(input); + expect(folded(output)).toContain( + "", + ); + expect(folded(output)).toContain( + '', + ); + expect(output).not.toContain(' { + const input = `import * as i18n from '@astryxdesign/core/i18n'; +import {InternationalizationContext as Ctx, InternationalizationProvider as IP} from '@astryxdesign/core/i18n'; +const a = ; +const b = ;`; + const output = folded(apply(input)); + expect(output).toContain( + ''); + expect(output).not.toContain(' { + const input = `import {InternationalizationContext as Ctx} from '@astryxdesign/core/i18n'; +let out; +{ + const Ctx = MyOwnContext; + out = ; +} +function F({flag}) { + if (flag) { + const Ctx = Other; + return ; + } + for (const Ctx of contexts) { + out = ; + } + try { + run(); + } catch (Ctx) { + out = ; + } + return ; +}`; + const output = folded(apply(input)); + // The four shadowed uses (block, if block, loop head, catch) stay as written. + expect(output.match(//g)).toHaveLength(4); + expect(output).toContain('; }'); + // The one unshadowed use is rewritten. + expect(output).toContain( + '', + ); + // The context import stays: the file still names Ctx. + expect(output).toMatch( + /import \{ ?InternationalizationContext as Ctx, InternationalizationProvider ?\} from '@astryxdesign\/core\/i18n';/, + ); + }); + + it('counts a var anywhere in the function and a named class expression as shadows', () => { + const input = `import {InternationalizationContext as Ctx} from '@astryxdesign/core/i18n'; +function F({flag}) { + if (flag) { var Ctx = Other; } + return ; +} +function G(list) { + for (var Ctx of list) {} + return ; +} +const Shell = class Ctx { + render() { return ; } +}; +const ok = ;`; + const output = folded(apply(input)); + expect(output.match(//g)).toHaveLength(2); + expect(output).toContain(''); + expect(output).toContain( + '', + ); + }); + + it('imports the provider under a free alias when the module already binds that name', () => { + const wrapper = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; +function InternationalizationProvider({children}) { + return {children}; +}`; + const output = folded(apply(wrapper)); + expect(output).toContain( + "import {InternationalizationProvider as InternationalizationProvider2} from '@astryxdesign/core/i18n';", + ); + expect(output).toContain( + '{children}', + ); + expect(output).toContain( + 'function InternationalizationProvider({children})', + ); + const ownImport = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; +import {InternationalizationProvider} from './provider'; +const app = ;`; + const output2 = folded(apply(ownImport)); + expect(output2).toContain( + "import {InternationalizationProvider as InternationalizationProvider2} from '@astryxdesign/core/i18n';", + ); + expect(output2).toContain( + "import {InternationalizationProvider} from './provider';", + ); + expect(output2).toContain( + ' { + const input = `import {InternationalizationContext, type InternationalizationProvider} from '@astryxdesign/core/i18n'; +const app = ; +export type P = typeof InternationalizationProvider;`; + const output = folded(apply(input)); + expect(output).toContain( + ' { + const input = `import {InternationalizationContext, InternationalizationProvider} from '@astryxdesign/core/i18n'; +function Shadowing() { + const InternationalizationProvider = makeLocalProvider(); + return ; +} +const spread = ;`; + const output = folded(apply(input)); + expect(output).toContain( + '', + ); + expect(output).toContain( + '', + ); + expect(output.match(new RegExp(EXPRESSION_TODO, 'g'))).toBeNull(); + const raw = apply(input); + expect(raw).toContain( + 'a local named `InternationalizationProvider` shadows the provider import at this site', + ); + expect(raw.match(new RegExp(EXPRESSION_TODO, 'g'))).toHaveLength(1); + }); + + it('sees a private method parameter, a static block and a namespace body as scopes', () => { + const input = `import {InternationalizationContext as Ctx} from '@astryxdesign/core/i18n'; +class Shell { + #render(Ctx) { return ; } + static { const Ctx = Other; Shell.out = ; } + render() { return ; } +} +namespace Local { + const Ctx = Other; + export const out = ; +} +namespace Exported { + export const Ctx = Other; + export const out = ; +} +namespace Aliased { + import Ctx = Other.Context; + export const out = ; +} +namespace Declared { + declare function Ctx(props: {value: unknown}): null; + export const out = ; +} +namespace Nested { + namespace Ctx { export const Provider = Other; } + export const out = ; +} +export const ok = ;`; + const output = folded(apply(input)); + expect(output.match(//g)).toHaveLength(6); + expect(output).toContain(''); + expect(output).toContain( + '', + ); + expect(output).toContain( + '', + ); + }); + + it('sees a dotted namespace as binding its own name inside its body', () => { + const input = `import * as i18n from '@astryxdesign/core/i18n'; +import {InternationalizationContext as Ctx} from '@astryxdesign/core/i18n'; +namespace Outer.Ctx { + export const Provider = Other; + export const out = ; +} +namespace Outer.i18n { + export const InternationalizationContext = Other; + export const out = ; +} +export const ok = ;`; + const output = folded(apply(input)); + expect(output).toContain(''); + expect(output).toContain( + '', + ); + expect(output).toContain( + '', + ); + }); + + it('is not captured by a nested namespace named like the provider', () => { + const input = `import {InternationalizationContext as Ctx} from '@astryxdesign/core/i18n'; +namespace Captures { + namespace InternationalizationProvider { export const x = 1; } + export const out = ; +}`; + const output = folded(apply(input)); + // The module binds the provider's name, so the import takes a free alias + // and the element under that namespace renders the alias, not the namespace. + expect(output).toContain( + '', + ); + expect(output).toContain( + "import {InternationalizationProvider as InternationalizationProvider2} from '@astryxdesign/core/i18n';", + ); + }); + + it('leaves a shadowed name and a type-only import alone', () => { + const shadowed = `import {InternationalizationContext as Ctx} from '@astryxdesign/core/i18n'; +function Row({Ctx}) { + return ; +} +function Other() { + const Ctx = MyContext; + return ; +}`; + expect( + transform({source: shadowed, path: 'test.tsx'}, api), + ).toBeUndefined(); + const typeOnly = `import type {InternationalizationContextValue} from '@astryxdesign/core/i18n'; +import {type InternationalizationContext as CtxType} from '@astryxdesign/core/i18n'; +const InternationalizationContext = createContext(fallback); +const app = ; +export type Shape = typeof CtxType;`; + expect( + transform({source: typeOnly, path: 'test.tsx'}, api), + ).toBeUndefined(); + }); + + it('leaves a file alone that only reads the context, or names an unrelated context', () => { + const reader = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; +import {useContext} from 'react'; +const locale = () => useContext(InternationalizationContext).locale;`; + expect(transform({source: reader, path: 'test.tsx'}, api)).toBeUndefined(); + const unrelated = `import {InternationalizationContext} from './my-i18n'; +const app = ;`; + expect( + transform({source: unrelated, path: 'test.tsx'}, api), + ).toBeUndefined(); + }); + + it('rewrites a variable value into output that typechecks against the real i18n types', () => { + // The variable's inferred type has every required field and no `overrides`. + const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; +const i18n = { + locale: 'fr', + direction: 'ltr' as const, + messages: {}, + translate: (key: string) => key, +}; +export const app =
;`; + const output = apply(input); + const dir = mkdtempSync(path.join(tmpdir(), 'astryx-i18n-codemod-')); + const typecheck = (/** @type {string} */ source) => { + writeFileSync(path.join(dir, 'case.tsx'), source); + writeFileSync( + path.join(dir, 'tsconfig.json'), + JSON.stringify({ + compilerOptions: { + strict: true, + noEmit: true, + jsx: 'react-jsx', + module: 'esnext', + moduleResolution: 'bundler', + target: 'es2022', + skipLibCheck: true, + paths: { + '@astryxdesign/core/i18n': [ + path.join(repoRoot, 'packages/core/src/i18n/index.ts'), + ], + }, + typeRoots: [path.join(repoRoot, 'node_modules/@types')], + types: ['node', 'react'], + }, + files: ['case.tsx'], + }), + ); + try { + execFileSync( + process.execPath, + [path.join(repoRoot, 'node_modules/typescript/bin/tsc'), '-p', dir], + {encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']}, + ); + return ''; + } catch (error) { + return String(/** @type {any} */ (error).stdout ?? error); + } + }; + expect(typecheck(output)).toBe(''); + // The test bites: reading `overrides` off this variable is TS2339. + const naive = output.replace( + 'messages={i18n.messages}', + 'messages={i18n.messages} overrides={i18n.overrides}', + ); + expect(typecheck(naive)).toContain('TS2339'); + }, 60_000); + + it('leaves the consumer shape in the wild alone: read the ambient value, re-mount the provider', () => { + // Every use of the context outside Astryx that a code search found (two + // internal consumers, one public) has this shape; the transform over + // their files returned no change, and this fixture is that shape. + const input = `import {useContext, useMemo, type ReactNode} from 'react'; +import {InternationalizationContext, InternationalizationProvider} from '@astryxdesign/core/i18n'; +export function WithRowWording({children}: {children: ReactNode}) { + const i18n = useContext(InternationalizationContext); + const overrides = useMemo( + () => ({...i18n.overrides, en: {...ROW_WORDING, ...i18n.overrides?.en}}), + [i18n.overrides], + ); + return ( + + {children} + + ); +}`; + expect(transform({source: input, path: 'test.tsx'}, api)).toBeUndefined(); + }); + + it('leaves an empty literal behind the TODO on its value attribute, never as text', () => { + const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; +const app = ( +
+ + + +
+);`; + const output = apply(input); + expect(folded(output)).toContain( + '', + ); + expect(output).toContain(TRANSLATE_TODO); + expect(output).not.toContain(' { + const input = `'use client'; +// Copyright (c) Example. +import {InternationalizationContext} from '@astryxdesign/core'; +import {InternationalizationProvider} from '@astryxdesign/core/i18n'; +const app = ;`; + const output = apply(input); + expect(output).not.toContain("from '@astryxdesign/core';"); + expect(output).not.toMatch(/^import ['"]@astryxdesign\/core['"];/m); + expect(output).toContain( + "import {InternationalizationProvider} from '@astryxdesign/core/i18n';", + ); + expect(output).toContain('// Copyright (c) Example.'); + expect(output).toMatch(/^'use client';\n/); + expect(output).not.toContain(';;'); + expect(folded(output)).toContain( + ' { + // A spread AFTER `value` may carry its own `value` and win (JSX attributes + // apply in order). A spread BEFORE it is overridden as a context value, but + // the provider would read `dir`, `messages` or `overrides` out of it, which + // the context ignored — so the rewritten element would configure a + // different subtree. Neither is provable from source; both stay put. + const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; +const a =
; +const b = ; +const c = ;`; + const output = apply(input); + expect(folded(output)).toContain( + '', + ); + expect(folded(output)).toContain( + '', + ); + expect(folded(output)).toContain( + '', + ); + expect(output).not.toContain(' { + const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; +const a = ; +const b = ; +const c = ;`; + const once = apply(input); + expect(transform({source: once, path: 'test.tsx'}, api)).toBeUndefined(); + }); +}); diff --git a/packages/cli/assets/codemods/transforms/next/index.mjs b/packages/cli/assets/codemods/transforms/next/index.mjs index 45dead11115a2..8f85a6097b2f8 100644 --- a/packages/cli/assets/codemods/transforms/next/index.mjs +++ b/packages/cli/assets/codemods/transforms/next/index.mjs @@ -10,6 +10,9 @@ import migrateCodeBlockTokenizerToLanguage, { meta as migrateCodeBlockTokenizerToLanguageMeta, } from './migrate-codeblock-tokenizer-to-language.mjs'; +import migrateInternationalizationContext, { + meta as migrateInternationalizationContextMeta, +} from './migrate-internationalization-context.mjs'; export default [ { @@ -17,4 +20,9 @@ export default [ transform: migrateCodeBlockTokenizerToLanguage, meta: migrateCodeBlockTokenizerToLanguageMeta, }, + { + name: 'migrate-internationalization-context', + transform: migrateInternationalizationContext, + meta: migrateInternationalizationContextMeta, + }, ]; diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs new file mode 100644 index 0000000000000..aeca4034bbffb --- /dev/null +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -0,0 +1,666 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file Migrate a raw `InternationalizationContext` value to the provider. + * + * Rendering a value straight into `InternationalizationContext` no longer + * configures Astryx: `useLocale`, `useDirection`, `useCollator` — and each + * core component as it moves to its own English slice — read a runtime + * context that only `InternationalizationProvider` writes. The provider takes the same configuration under its own prop names, + * so the rewrite is mechanical where the value is plain: + * + * → locale={v.locale} + * dir={v.direction} + * messages={v.messages}> + * + * A variable maps the fields every context value has (`overrides` is + * optional, so a variable's type may lack it; the TODO names it); an inline + * object literal maps key by key and keeps only the keys it has. The provider has no `translate` input, and + * `translate` is a field of every context value, so every rewrite carries a + * TODO naming where those strings go (`messages` or `overrides`); a literal's + * `translate` key is kept beside it. A value that is any other expression + * (a call, a spread into a literal, a conditional) is left unchanged behind a + * TODO that says why: a call would run once per prop, and a spread of the + * ambient value would mount a provider without the app's catalogs. + * + * Only an element whose name resolves, unshadowed, to an Astryx import is + * rewritten (named, aliased, or namespace; a type-only import proves nothing; + * a same-named declaration in any block, `static {}` block, namespace body, + * function, loop head or catch clause between the element and the module + * shadows it, as does a parameter of any method including a private one, a + * `var` anywhere in the enclosing function and a named class expression's + * own name). The + * provider is imported under a free name when the module already binds + * `InternationalizationProvider` to something of its own, and the name + * written must itself reach that import at the edit site. An element that + * spreads props at all gets the TODO and no rewrite: a spread after `value` + * may override it, and a spread anywhere may carry `dir`, `messages` or + * `overrides`, which the context ignored but the provider would read. + * The import gains `InternationalizationProvider` under the file's existing + * local name for it when it has one, and loses the context import when + * nothing else reads it. A second run changes nothing. + */ + +const PACKAGE_PATTERN = /^@(astryxdesign|xds)\/core(\/i18n)?$/u; +const CONTEXT = 'InternationalizationContext'; +const PROVIDER = 'InternationalizationProvider'; + +/** Context value key → provider prop. */ +const PROP_FOR_KEY = new Map([ + ['locale', 'locale'], + ['direction', 'dir'], + ['messages', 'messages'], + ['overrides', 'overrides'], +]); + +/** + * The keys every context value has. A variable's inferred type may lack the + * optional `overrides`, and reading it would fail to typecheck, so a variable + * maps only these and the TODO names `overrides` beside `translate`. + */ +const REQUIRED_KEYS = ['locale', 'direction', 'messages']; + +const TODO_PREFIX = ' TODO(astryx upgrade): '; +const TODO_TRANSLATE = + `${TODO_PREFIX}InternationalizationProvider has no \`translate\` input; ` + + 'express those strings as `messages` (a catalog per locale) or `overrides`. '; +const TODO_VARIABLE = + `${TODO_PREFIX}InternationalizationProvider has no \`translate\` input; ` + + 'express those strings as `messages` (a catalog per locale) or `overrides`; ' + + 'pass the value\u2019s `overrides`, if it has any, as `overrides`. '; +const TODO_SPREAD = + `${TODO_PREFIX}a raw InternationalizationContext value no longer configures Astryx; ` + + 'mount InternationalizationProvider with this value\u2019s `locale`, `direction` (as `dir`), ' + + '`messages` and `overrides`. Not rewritten here: this element also spreads ' + + 'props. A spread after `value` may carry its own `value` and override this ' + + 'one; a spread anywhere may carry `dir`, `messages` or `overrides`, which ' + + 'the context ignored but the provider would read, so the configured subtree ' + + 'is not provable from here. '; +const TODO_EXPRESSION = + `${TODO_PREFIX}a raw InternationalizationContext value no longer configures Astryx; ` + + 'mount InternationalizationProvider with this value\u2019s `locale`, `direction` (as `dir`), ' + + '`messages` and `overrides`. Not rewritten here: the value is an expression, ' + + 'and a provider takes no catalogs from a parent, so a spread of the ambient ' + + 'value would lose them and a call would run once per prop. '; + +const todoShadowedProvider = (/** @type {string} */ name) => + `${TODO_PREFIX}a raw InternationalizationContext value no longer configures Astryx; ` + + `mount InternationalizationProvider with this value\u2019s \`locale\`, \`direction\` (as \`dir\`), ` + + `\`messages\` and \`overrides\`. Not rewritten here: a local named \`${name}\` shadows ` + + 'the provider import at this site. '; + +export const meta = { + title: + 'Migrate a raw InternationalizationContext value to InternationalizationProvider', + description: + 'Rewrites `` (or its `.Provider`) to `` (plus `overrides` from an inline literal), the only way to configure Astryx; `translate`, a variable’s `overrides`, and any other value are left behind a TODO.', + fileExtensions: ['.tsx', '.jsx', '.ts', '.js', '.mjs', '.cjs'], +}; + +/** + * @param {import('../../../../authoring/codemod/type').AstryxCodemodFile} file + * @param {import('../../../../authoring/codemod/type').CodemodTransformApi} api + * @returns {string | undefined} + */ +export default function migrateInternationalizationContext(file, api) { + if (!file.source.includes(CONTEXT)) return undefined; + + const j = api.jscodeshift; + const root = j(file.source); + + // Runtime bindings to the Astryx context (named/aliased), namespaces, and + // the file's local name for the provider if it already imports one. + /** @type {Set} */ + const contextNames = new Set(); + /** @type {Set} */ + const namespaceNames = new Set(); + /** @type {string | null} */ + let importedProviderName = null; + /** @type {any[]} */ + const astryxImports = []; + root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => { + const source = path.node.source.value; + if (path.node.importKind === 'type') return; + if (typeof source !== 'string' || !PACKAGE_PATTERN.test(source)) return; + astryxImports.push(path); + for (const specifier of path.node.specifiers ?? []) { + if (specifier.importKind === 'type') continue; + if (specifier.type === 'ImportSpecifier') { + if (specifier.imported?.name === CONTEXT) { + contextNames.add(specifier.local?.name ?? CONTEXT); + } else if (specifier.imported?.name === PROVIDER) { + importedProviderName = specifier.local?.name ?? PROVIDER; + } + } else if (specifier.type === 'ImportNamespaceSpecifier') { + namespaceNames.add(specifier.local.name); + } + } + }); + if (contextNames.size === 0 && namespaceNames.size === 0) return undefined; + + // Every identifier the module binds anywhere (declarations, imports, + // parameters, catch clauses, class and function names), so a provider + // import added here takes a name nothing else holds. + /** @type {Set} */ + const boundNames = new Set(); + root.find(j.Identifier).forEach((/** @type {any} */ p) => { + const parent = p.parent?.node; + if (!parent) return; + const binds = + (parent.type === 'VariableDeclarator' && parent.id === p.node) || + ((parent.type === 'FunctionDeclaration' || + parent.type === 'FunctionExpression' || + parent.type === 'ClassDeclaration' || + parent.type === 'ClassExpression' || + parent.type === 'TSDeclareFunction' || + parent.type === 'TSEnumDeclaration' || + parent.type === 'TSImportEqualsDeclaration' || + parent.type === 'TSModuleDeclaration') && + parent.id === p.node) || + parent.type === 'ImportSpecifier' || + parent.type === 'ImportDefaultSpecifier' || + parent.type === 'ImportNamespaceSpecifier' || + parent.type === 'CatchClause' || + parent.type === 'RestElement' || + parent.type === 'AssignmentPattern' || + parent.type === 'ArrayPattern' || + (parent.type === 'ObjectProperty' && + parent.value === p.node && + p.parent.parent?.node.type === 'ObjectPattern') || + (parent.type === 'Property' && + parent.value === p.node && + p.parent.parent?.node.type === 'ObjectPattern') || + ((parent.type === 'FunctionDeclaration' || + parent.type === 'FunctionExpression' || + parent.type === 'ArrowFunctionExpression' || + parent.type === 'ObjectMethod' || + parent.type === 'ClassMethod' || + parent.type === 'ClassPrivateMethod') && + parent.params.includes(p.node)); + if (binds) boundNames.add(p.node.name); + }); + // The name a named import of the provider takes: the file's own when it has + // one; otherwise `InternationalizationProvider`, or a free alias when the + // module already binds that name to something else (its own wrapper, say). + /** @type {string} */ + let providerLocalName = importedProviderName ?? PROVIDER; + if (importedProviderName === null) { + for (let n = 2; boundNames.has(providerLocalName); n += 1) { + providerLocalName = `${PROVIDER}${n}`; + } + } + // A `type` specifier of the provider proves nothing at runtime, so it does + // not count as an import either. + const providerNeedsImport = !astryxImports.some((/** @type {any} */ path) => + (path.node.specifiers ?? []).some( + (/** @type {any} */ s) => + s.type === 'ImportSpecifier' && + s.importKind !== 'type' && + s.imported?.name === PROVIDER, + ), + ); + + /** The identifiers a binding pattern declares. */ + const patternNames = ( + /** @type {any} */ node, + /** @type {string[]} */ out = [], + ) => { + if (!node) return out; + switch (node.type) { + case 'Identifier': + out.push(node.name); + break; + case 'ObjectPattern': + for (const property of node.properties) { + patternNames( + property.type === 'RestElement' + ? property.argument + : property.value, + out, + ); + } + break; + case 'ArrayPattern': + for (const element of node.elements) patternNames(element, out); + break; + case 'RestElement': + patternNames(node.argument, out); + break; + case 'AssignmentPattern': + patternNames(node.left, out); + break; + case 'TSParameterProperty': + patternNames(node.parameter, out); + break; + default: + break; + } + return out; + }; + + /** + * Whether a `var` named `name` is declared anywhere inside `node` without + * crossing into a nested function: a `var` hoists to its whole function. + */ + const declaresVar = (/** @type {any} */ node, /** @type {string} */ name) => { + let found = false; + const visit = (/** @type {any} */ n) => { + if (found || !n || typeof n !== 'object') return; + if (Array.isArray(n)) { + n.forEach(visit); + return; + } + if ( + n.type === 'FunctionDeclaration' || + n.type === 'FunctionExpression' || + n.type === 'ArrowFunctionExpression' || + n.type === 'ObjectMethod' || + n.type === 'ClassMethod' || + n.type === 'ClassPrivateMethod' || + n.type === 'StaticBlock' + ) { + return; + } + if ( + n.type === 'VariableDeclaration' && + n.kind === 'var' && + n.declarations.some((/** @type {any} */ d) => + patternNames(d.id).includes(name), + ) + ) { + found = true; + return; + } + for (const key of Object.keys(n)) { + if (key === 'loc' || key === 'comments' || key === 'type') continue; + visit(n[key]); + } + }; + visit(node); + return found; + }; + + /** Whether a statement list declares `name` (as a variable, function or class). */ + const bodyDeclares = ( + /** @type {any[]} */ statements, + /** @type {string} */ name, + ) => + statements.some((/** @type {any} */ wrapped) => { + // `export const …` / `export function …` inside a namespace body. + const statement = + wrapped.type === 'ExportNamedDeclaration' && wrapped.declaration + ? wrapped.declaration + : wrapped; + if (statement.type === 'VariableDeclaration') { + return statement.declarations.some((/** @type {any} */ d) => + patternNames(d.id).includes(name), + ); + } + if ( + statement.type === 'FunctionDeclaration' || + statement.type === 'ClassDeclaration' || + statement.type === 'TSDeclareFunction' || + statement.type === 'TSEnumDeclaration' || + statement.type === 'TSImportEqualsDeclaration' || + statement.type === 'TSModuleDeclaration' + ) { + // `declare function Ctx()`, `enum Ctx`, `import Ctx = Other.Thing`, + // `namespace Ctx {}`. + return statement.id?.name === name; + } + return false; + }); + + /** + * The name a `namespace A.B.C {}` declaration binds inside its own body: + * the last segment (`C`); for `namespace C {}`, `C`. A dotted name parses as + * nested declarations, so each level's own id is its last segment. + * @param {any} node a TSModuleDeclaration + */ + const namespaceOwnName = node => { + let id = node.id; + while (id?.type === 'TSQualifiedName') id = id.right; + return id?.type === 'Identifier' ? id.name : null; + }; + + /** + * The binding a JSX identifier resolves to is the module-level import: + * no block, function, catch clause or loop head between the element and + * the module declares the same name. Blocks get their own scope here + * (`let`/`const`/`class` are block-scoped), which the generic scope model + * does not give them. + * @param {any} path a JSXElement path + * @param {string} name + */ + const isImportBinding = (path, name) => { + for (let p = path.parent; p; p = p.parent) { + const node = p.node; + switch (node.type) { + case 'Program': + return ( + !bodyDeclares(node.body, name) && !declaresVar(node.body, name) + ); + case 'BlockStatement': + if (bodyDeclares(node.body, name)) return false; + break; + case 'SwitchStatement': + if ( + bodyDeclares( + node.cases.flatMap((/** @type {any} */ c) => c.consequent), + name, + ) + ) { + return false; + } + break; + case 'ForStatement': + if ( + node.init?.type === 'VariableDeclaration' && + bodyDeclares([node.init], name) + ) { + return false; + } + break; + case 'ForInStatement': + case 'ForOfStatement': + if ( + node.left?.type === 'VariableDeclaration' && + bodyDeclares([node.left], name) + ) { + return false; + } + break; + case 'StaticBlock': + case 'TSModuleBlock': + if (bodyDeclares(node.body, name) || declaresVar(node.body, name)) { + return false; + } + break; + case 'TSModuleDeclaration': + // `namespace Outer.Ctx {}` binds `Ctx` (its last segment) inside + // its own body; a plain `namespace Ctx {}` binds `Ctx` likewise. + if (namespaceOwnName(node) === name) return false; + break; + case 'FunctionDeclaration': + case 'FunctionExpression': + case 'ArrowFunctionExpression': + case 'ObjectMethod': + case 'ClassMethod': + case 'ClassPrivateMethod': + if ( + node.params.some((/** @type {any} */ param) => + patternNames(param).includes(name), + ) + ) { + return false; + } + if (node.type === 'FunctionExpression' && node.id?.name === name) { + return false; + } + if (declaresVar(node.body, name)) return false; + break; + case 'ClassExpression': + if (node.id?.name === name) return false; + break; + case 'CatchClause': + if (node.param && patternNames(node.param).includes(name)) + return false; + break; + default: + break; + } + } + return false; + }; + + /** + * How the element names the Astryx context: `''` for a named binding, the + * namespace's local name for `ns.Ctx`, or null when it is not the context + * (an unrelated name, or a shadowed one). Accepts a trailing `.Provider`. + * @param {any} path a JSXElement path + * @returns {string | null} + */ + const contextNamespaceOf = path => { + let name = path.node.openingElement.name; + if ( + name.type === 'JSXMemberExpression' && + name.property?.type === 'JSXIdentifier' && + name.property.name === 'Provider' + ) { + name = name.object; + } + if (name.type === 'JSXIdentifier') { + return contextNames.has(name.name) && isImportBinding(path, name.name) + ? '' + : null; + } + if ( + name.type === 'JSXMemberExpression' && + name.object?.type === 'JSXIdentifier' && + name.property?.type === 'JSXIdentifier' && + name.property.name === CONTEXT && + namespaceNames.has(name.object.name) && + isImportBinding(path, name.object.name) + ) { + return name.object.name; + } + return null; + }; + + const hasComment = (/** @type {any} */ node, /** @type {string} */ text) => + (node.comments ?? []).some((/** @type {any} */ c) => c.value === text); + const addComment = (/** @type {any} */ node, /** @type {string} */ text) => { + if (hasComment(node, text)) return false; + node.comments ??= []; + node.comments.push(j.commentBlock(text, true, false)); + return true; + }; + + let changed = false; + let needsNamedProvider = false; + root.find(j.JSXElement).forEach((/** @type {any} */ path) => { + const namespace = contextNamespaceOf(path); + if (namespace === null) return; + const opening = path.node.openingElement; + const valueAttribute = (opening.attributes ?? []).find( + (/** @type {any} */ a) => + a.type === 'JSXAttribute' && a.name?.name === 'value', + ); + if (!valueAttribute) { + // The value arrives through spread props: nothing to map, but the + // element still needs the upgrade's marker. + const spread = (opening.attributes ?? []).find( + (/** @type {any} */ a) => a.type === 'JSXSpreadAttribute', + ); + if (spread && addComment(spread, TODO_EXPRESSION)) changed = true; + return; + } + if (valueAttribute.value?.type !== 'JSXExpressionContainer') return; + // Any spread on the element makes the rewrite unprovable: one AFTER + // `value` may carry its own `value` and win (JSX attributes apply in + // order); one anywhere may carry `dir`, `messages` or `overrides`, which + // the raw context ignored but InternationalizationProvider would read, + // so the rewritten element would configure a different subtree. + const attributes = opening.attributes ?? []; + const valueIndex = attributes.indexOf(valueAttribute); + if ( + attributes.some((/** @type {any} */ a) => a.type === 'JSXSpreadAttribute') + ) { + if (addComment(valueAttribute, TODO_SPREAD)) changed = true; + return; + } + const value = valueAttribute.value.expression; + + /** @type {any[]} */ + const props = []; + /** @type {any[]} */ + const keptKeys = []; + if (value.type === 'Identifier') { + for (const key of REQUIRED_KEYS) { + const prop = /** @type {string} */ (PROP_FOR_KEY.get(key)); + props.push( + j.jsxAttribute( + j.jsxIdentifier(prop), + j.jsxExpressionContainer( + j.memberExpression(j.identifier(value.name), j.identifier(key)), + ), + ), + ); + } + } else if ( + value.type === 'ObjectExpression' && + value.properties.every( + (/** @type {any} */ p) => + (p.type === 'Property' || p.type === 'ObjectProperty') && + !p.computed && + (p.key.type === 'Identifier' || + p.key.type === 'StringLiteral' || + p.key.type === 'Literal'), + ) + ) { + for (const property of value.properties) { + const key = property.key.name ?? property.key.value; + const prop = PROP_FOR_KEY.get(key); + if (prop == null) { + keptKeys.push(property); + continue; + } + props.push( + j.jsxAttribute( + j.jsxIdentifier(prop), + j.jsxExpressionContainer(property.value), + ), + ); + } + } else { + // A call, a spread, a conditional: nothing mechanical is safe. + if (addComment(valueAttribute, TODO_EXPRESSION)) changed = true; + return; + } + if (props.length === 0) { + // Nothing to map (an empty literal, or one of unknown keys only): the + // TODO goes on the attribute, where it prints as a comment and not as + // text inside the element. + if (addComment(valueAttribute, TODO_TRANSLATE)) changed = true; + return; + } + + // The name written must reach the provider import from here: a local + // that shadows it at the edit site would capture the element. + if (namespace === '' && !isImportBinding(path, providerLocalName)) { + if (addComment(valueAttribute, todoShadowedProvider(providerLocalName))) { + changed = true; + } + return; + } + const providerName = + namespace === '' + ? j.jsxIdentifier(providerLocalName) + : j.jsxMemberExpression( + j.jsxIdentifier(namespace), + j.jsxIdentifier(PROVIDER), + ); + if (namespace === '' && providerNeedsImport) { + needsNamedProvider = true; + } + + // The mapped props take `value`'s slot among the element's attributes. + opening.name = providerName; + opening.attributes = [ + ...attributes.slice(0, valueIndex), + ...props, + ...attributes.slice(valueIndex + 1), + ]; + if (path.node.closingElement) { + path.node.closingElement.name = providerName; + } + // Every context value has a `translate`; the provider has no input for it. + const todo = props[props.length - 1] ?? opening; + if (keptKeys.length > 0) { + const kept = j.jsxAttribute( + j.jsxIdentifier('data-astryx-upgrade-translate'), + j.jsxExpressionContainer(j.objectExpression(keptKeys)), + ); + addComment(kept, TODO_TRANSLATE); + opening.attributes.push(kept); + } else { + addComment( + todo, + value.type === 'Identifier' ? TODO_VARIABLE : TODO_TRANSLATE, + ); + } + changed = true; + }); + + if (!changed) return undefined; + + if (needsNamedProvider) { + for (const path of astryxImports) { + const specifiers = path.node.specifiers ?? []; + if ( + !specifiers.some( + (/** @type {any} */ s) => + s.type === 'ImportSpecifier' && s.imported?.name === CONTEXT, + ) + ) { + continue; + } + specifiers.push( + j.importSpecifier( + j.identifier(PROVIDER), + j.identifier(providerLocalName), + ), + ); + break; + } + } + + // Drop the context import when the file no longer names it anywhere, and + // an import declaration that is left with no specifier. + for (const localName of contextNames) { + const stillNamed = + root + .find(j.Identifier, {name: localName}) + .filter( + (/** @type {any} */ p) => p.parent?.node.type !== 'ImportSpecifier', + ) + .size() > 0 || root.find(j.JSXIdentifier, {name: localName}).size() > 0; + if (stillNamed) continue; + for (const path of astryxImports) { + const before = (path.node.specifiers ?? []).length; + path.node.specifiers = (path.node.specifiers ?? []).filter( + (/** @type {any} */ s) => + !( + s.type === 'ImportSpecifier' && + s.imported?.name === CONTEXT && + (s.local?.name ?? CONTEXT) === localName + ), + ); + if (before > 0 && path.node.specifiers.length === 0) { + // Keep the comments that sat on the import (a license header, say) + // on whatever statement follows it. + const comments = path.node.comments ?? []; + const program = path.parent?.node; + if (program?.type === 'Program') { + const index = program.body.indexOf(path.node); + const next = program.body[index + 1]; + if (next && comments.length > 0) { + next.comments = [...comments, ...(next.comments ?? [])]; + } + program.body.splice(index, 1); + } else { + path.prune(); + } + } + } + } + + return ( + root + .toSource({quote: 'single', objectCurlySpacing: false}) + // Removing the statement after a directive leaves the printer's extra + // semicolon behind the directive. + .replace(/^(\s*(['"])use [\w-]+\2);;/m, '$1;') + ); +} diff --git a/packages/cli/assets/docs/tree/i18n-rtl-and-testing.doc.mjs b/packages/cli/assets/docs/tree/i18n-rtl-and-testing.doc.mjs index 7b55923254e5b..2cdcf64d039c3 100644 --- a/packages/cli/assets/docs/tree/i18n-rtl-and-testing.doc.mjs +++ b/packages/cli/assets/docs/tree/i18n-rtl-and-testing.doc.mjs @@ -11,7 +11,11 @@ export const docs = { type: 'generic', name: 'i18n-rtl-and-testing', title: 'RTL & Testing', - placement: {parent: 'namespace:internationalization', slot: 'guides', order: 30}, + placement: { + parent: 'namespace:internationalization', + slot: 'guides', + order: 30, + }, category: 'guide', description: 'Text direction (RTL), pseudo-locale testing, and contributor guidance for developers and translators.', @@ -122,7 +126,7 @@ import pseudo from '@astryxdesign/core/locales/pseudo.generated.js'; }, { type: 'prose', - text: 'Astryx component authors read strings with `useTranslator()` rather than hardcoding user-facing text.', + text: 'Astryx components read their own strings from the English catalog rather than hardcoding them. An app that neither mounts `InternationalizationProvider`, calls `useTranslator()` nor imports `InternationalizationContext`, and does not render `PowerSearch`, bundles only the strings of the components it renders; one that does any of those carries the whole catalog, each string once (`PowerSearch` keeps it as the fallback for the operator keys a caller supplies). Your own code reads any `@astryx.*` key with `useTranslator()`:', }, { type: 'code', @@ -137,7 +141,7 @@ function SaveButton() { }, { type: 'prose', - 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.", + text: "Astryx's own strings live in `packages/core/locales/en.json`, keyed `@astryx..`. The contributing guide covers how a core component reads its strings, the `@astryx/no-hardcoded-i18n-string` ESLint rule and the alias-and-resolve pattern used when adding new keys.", }, { type: 'prose', diff --git a/packages/cli/test/__golden__/no-icon-set/search-search.json b/packages/cli/test/__golden__/no-icon-set/search-search.json index 2573fa1bb2319..c3e974f29750d 100644 --- a/packages/cli/test/__golden__/no-icon-set/search-search.json +++ b/packages/cli/test/__golden__/no-icon-set/search-search.json @@ -3,7 +3,7 @@ "type": "search", "data": { "query": "search", - "matchCount": 113, + "matchCount": 114, "results": [ { "domain": "doc", diff --git a/packages/cli/test/__golden__/no-icon-set/search-search.txt b/packages/cli/test/__golden__/no-icon-set/search-search.txt index abe619e828b49..180a04f4d911d 100644 --- a/packages/cli/test/__golden__/no-icon-set/search-search.txt +++ b/packages/cli/test/__golden__/no-icon-set/search-search.txt @@ -1,4 +1,4 @@ -Results for "search" (20 of 113) +Results for "search" (20 of 114) name: cli/api/functions/search domain: doc package: @astryxdesign/cli diff --git a/packages/core/package.json b/packages/core/package.json index 295c3d98433c4..aaa5fc8133028 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -169,6 +169,7 @@ "types": "./dist/i18n/generated-locales/*.generated.d.ts", "default": "./dist/i18n/generated-locales/*.generated.js" }, + "./locales/en/*": null, "./AlertDialog": { "source": "./src/AlertDialog/index.ts", "types": "./dist/AlertDialog/index.d.ts", diff --git a/packages/core/src/AlertDialog/AlertDialog.tsx b/packages/core/src/AlertDialog/AlertDialog.tsx index 9553b3bc91f03..7a96fe4117293 100644 --- a/packages/core/src/AlertDialog/AlertDialog.tsx +++ b/packages/core/src/AlertDialog/AlertDialog.tsx @@ -29,7 +29,8 @@ import {Button, type ButtonVariant} from '../Button'; import type {BaseProps} from '../BaseProps'; import {mergeProps} from '../utils'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import alertDialogMessages from '../i18n/generated-locales/en/alertDialog.generated'; import {useMediaQuery} from '../hooks/useMediaQuery'; const SMALL_SCREEN_QUERY = '(max-width: 640px)'; @@ -157,7 +158,7 @@ export function AlertDialog({ 'data-testid': testId, ...rest }: AlertDialogProps) { - const t = useTranslator(); + const t = useComponentTranslator(alertDialogMessages); const cancelLabel = cancelLabelFromProps ?? t('@astryx.alertDialog.cancel'); const titleId = useId(); const descriptionId = useId(); diff --git a/packages/core/src/AppShell/AppShell.tsx b/packages/core/src/AppShell/AppShell.tsx index 04fbb2808ac3e..c3fcf3b03ead7 100644 --- a/packages/core/src/AppShell/AppShell.tsx +++ b/packages/core/src/AppShell/AppShell.tsx @@ -56,7 +56,8 @@ import {focusOutlineProps} from '../utils/focusOutline.stylex'; import {useMediaQuery} from '../hooks/useMediaQuery'; import {observeResize} from '../utils/sharedResizeObserver'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import appShellMessages from '../i18n/generated-locales/en/appShell.generated'; import {useThemeDefinition} from '../theme/useTheme'; import { DEFAULT_WIDTH_BREAKPOINTS, @@ -488,7 +489,7 @@ export function AppShell({ ref, ...rest }: AppShellProps) { - const t = useTranslator(); + const t = useComponentTranslator(appShellMessages); const activeTheme = useThemeDefinition(); // ========================================================================= // Parse mobileNav prop — normalize to config, custom element, or disabled diff --git a/packages/core/src/Avatar/Avatar.tsx b/packages/core/src/Avatar/Avatar.tsx index f7ac763c86476..0b3b336991fa4 100644 --- a/packages/core/src/Avatar/Avatar.tsx +++ b/packages/core/src/Avatar/Avatar.tsx @@ -5,7 +5,7 @@ /** * @file Avatar.tsx * @input Uses React, HTMLAttributes, ReactNode, useState, useRef; useTooltip - * (Tooltip hook) for the optional name-on-hover tooltip; useTranslator (i18n) + * (Tooltip hook) for the optional name-on-hover tooltip; useComponentTranslator (i18n) * @output Exports Avatar component, AvatarProps, AvatarSize types * @position Core implementation; consumed by index.ts * @@ -50,7 +50,9 @@ import {useTooltip} from '../Tooltip/useTooltip'; import {useDevWarning} from '../hooks/useDevWarning'; import {useLinkComponent} from '../Link/useLinkComponent'; import type {LinkComponentType} from '../Link/types'; -import {useTranslator, type TranslatorFn} from '../i18n'; +import type {TranslatorFn} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import avatarMessages from '../i18n/generated-locales/en/avatar.generated'; /** * The offset ratio for positioning elements on a circle's edge at 45°. @@ -599,7 +601,7 @@ export function Avatar({ // neither a name nor a labelled status, the avatar is decorative — expose // it as `presentation`/`aria-hidden` rather than announcing a meaningless // generic "Avatar" (obs-9). - const t = useTranslator(); + const t = useComponentTranslator(avatarMessages); const nameLabel = meaningfulAlt || meaningfulName; // This render can only see a label introspected off a directly-passed // element. A status inside a consumer's own wrapper reports through the ref diff --git a/packages/core/src/AvatarGroup/AvatarGroup.tsx b/packages/core/src/AvatarGroup/AvatarGroup.tsx index 45f2b852147ce..029c6cd9957fe 100644 --- a/packages/core/src/AvatarGroup/AvatarGroup.tsx +++ b/packages/core/src/AvatarGroup/AvatarGroup.tsx @@ -33,7 +33,8 @@ import {mergeProps} from '../utils'; import {composeEventHandlers} from '../utils/composeEventHandlers'; import {AvatarGroupContext} from './AvatarGroupContext'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import avatarGroupMessages from '../i18n/generated-locales/en/avatarGroup.generated'; import {useListFocus} from '../hooks/useListFocus'; import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import {VisuallyHidden} from '../VisuallyHidden'; @@ -123,7 +124,7 @@ export function AvatarGroup({ ref, ...props }: AvatarGroupProps): ReactNode { - const t = useTranslator(); + const t = useComponentTranslator(avatarGroupMessages); const ariaLabel = ariaLabelFromProps ?? t('@astryx.avatarGroup.label'); const numericSize = resolveSize(size); const overlap = Math.round(numericSize * OVERLAP_RATIO); diff --git a/packages/core/src/AvatarGroup/AvatarGroupOverflow.tsx b/packages/core/src/AvatarGroup/AvatarGroupOverflow.tsx index 0534fc8e3286f..65f48c35c1985 100644 --- a/packages/core/src/AvatarGroup/AvatarGroupOverflow.tsx +++ b/packages/core/src/AvatarGroup/AvatarGroupOverflow.tsx @@ -3,7 +3,7 @@ /** * @file AvatarGroupOverflow.tsx - * @input Uses React, StyleX, AvatarGroupContext, i18n (useTranslator) + * @input Uses React, StyleX, AvatarGroupContext, i18n (useComponentTranslator) * @output Exports AvatarGroupOverflow for overflow indicator * @position Slot component used inside AvatarGroup * @@ -32,7 +32,8 @@ import {themeProps} from '../utils/themeProps'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex'; import {usePressFeedback} from '../hooks/usePressFeedback'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import avatarGroupMessages from '../i18n/generated-locales/en/avatarGroup.generated'; const BORDER_WIDTH = 2; const OVERFLOW_FONT_RATIO = 0.35; @@ -160,7 +161,7 @@ export function AvatarGroupOverflow({ ...rest }: AvatarGroupOverflowProps): ReactNode { const pressable = usePressFeedback(); - const t = useTranslator(); + const t = useComponentTranslator(avatarGroupMessages); const group = useAvatarGroup(); const size = group?.size ?? 'md'; const shape = group?.shape ?? 'circle'; diff --git a/packages/core/src/Banner/Banner.tsx b/packages/core/src/Banner/Banner.tsx index 1802decf14df7..d840a8ffe27cb 100644 --- a/packages/core/src/Banner/Banner.tsx +++ b/packages/core/src/Banner/Banner.tsx @@ -73,7 +73,8 @@ import {composeEventHandlers, isRenderable, mergeProps} from '../utils'; import type {Elevation} from '../utils/types'; import {edgeCompSlot} from '../Layout/edgeCompensation.stylex'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import bannerMessages from '../i18n/generated-locales/en/banner.generated'; import type {BannerStatusMap, BannerContainerMap} from './index'; // ============================================================================= @@ -526,7 +527,7 @@ export function Banner({ onPointerDownCapture, ...rest }: BannerProps) { - const t = useTranslator(); + const t = useComponentTranslator(bannerMessages); const [isDismissed, setIsDismissed] = useState(false); // The disclosure state machine is the shared one — Banner owns no collapse // state of its own. `collapsible={false}` disables it, and that is what diff --git a/packages/core/src/Breadcrumbs/Breadcrumbs.tsx b/packages/core/src/Breadcrumbs/Breadcrumbs.tsx index 655cd4a22d0c5..a1635f90b1110 100644 --- a/packages/core/src/Breadcrumbs/Breadcrumbs.tsx +++ b/packages/core/src/Breadcrumbs/Breadcrumbs.tsx @@ -23,7 +23,8 @@ import {spacingVars} from '../theme/tokens.stylex'; import {mergeProps} from '../utils'; import type {BaseProps} from '../BaseProps'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import breadcrumbsMessages from '../i18n/generated-locales/en/breadcrumbs.generated'; import type {BreadcrumbsVariantMap} from './index'; // ============================================================================= @@ -139,7 +140,7 @@ export function Breadcrumbs({ ref, ...rest }: BreadcrumbsProps) { - const t = useTranslator(); + const t = useComponentTranslator(breadcrumbsMessages); const label = labelFromProps ?? t('@astryx.breadcrumbs.label'); const ctxValue = useMemo( () => ({variant, separator}), diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsx index 0d470d42b612b..f1db223a27da6 100644 --- a/packages/core/src/Button/Button.tsx +++ b/packages/core/src/Button/Button.tsx @@ -4,7 +4,7 @@ /** * @file Button.tsx - * @input Uses React, ButtonHTMLAttributes, ReactNode, i18n (useTranslator), group contexts + * @input Uses React, ButtonHTMLAttributes, ReactNode, i18n (useComponentTranslator), group contexts * @output Exports Button component, ButtonProps, ButtonVariant types * @position Core implementation; consumed by index.ts, tested by Button.test.tsx * @@ -65,7 +65,8 @@ import {themeProps} from '../utils/themeProps'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex'; import {usePressFeedback} from '../hooks/usePressFeedback'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import buttonMessages from '../i18n/generated-locales/en/button.generated'; import type {ButtonVariantMap} from './index'; /** @@ -598,7 +599,7 @@ export function Button({ ...props }: ButtonProps): ReactNode { const pressFeedback = usePressFeedback(); - const t = useTranslator(); + const t = useComponentTranslator(buttonMessages); const size = useSize(sizeProp, 'md'); const buttonGroup = useButtonGroup(); const inputGroup = useInputGroup(); diff --git a/packages/core/src/Calendar/Calendar.tsx b/packages/core/src/Calendar/Calendar.tsx index 79b92b41eee14..dbc25fdf1335c 100644 --- a/packages/core/src/Calendar/Calendar.tsx +++ b/packages/core/src/Calendar/Calendar.tsx @@ -94,7 +94,9 @@ import type { } from '../utils/dateTypes'; import {normalizeDayOfWeek} from '../utils/dateTypes'; import {themeProps} from '../utils/themeProps'; -import {useLocale, useTranslator} from '../i18n'; +import {useLocale} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import calendarMessages from '../i18n/generated-locales/en/calendar.generated'; import {VisuallyHidden} from '../VisuallyHidden'; /** How a month navigation moves the focused day: by its row offset in days, or by whole months. */ @@ -249,7 +251,7 @@ function firstEnabledDayOfMonth( * ``` */ export function Calendar({ref, ...props}: CalendarProps) { - const t = useTranslator(); + const t = useComponentTranslator(calendarMessages); const locale = useLocale(); const { handleRef, @@ -1252,7 +1254,7 @@ function DayCell({ onDayClick, onDayHover, }: DayCellProps) { - const t = useTranslator(); + const t = useComponentTranslator(calendarMessages); const locale = useLocale(); const pressable = usePressFeedback(); const {date, isOutside, dayNumber} = day; diff --git a/packages/core/src/Carousel/Carousel.tsx b/packages/core/src/Carousel/Carousel.tsx index f41bc90f0118e..84a50806682e3 100644 --- a/packages/core/src/Carousel/Carousel.tsx +++ b/packages/core/src/Carousel/Carousel.tsx @@ -49,7 +49,8 @@ import type {BaseProps} from '../BaseProps'; import {mergeProps, rtlStyles} from '../utils'; import type {SpacingStep} from '../utils/types'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import carouselMessages from '../i18n/generated-locales/en/carousel.generated'; import {useMergedRefs} from '../hooks/useMergedRefs'; /** @@ -338,7 +339,7 @@ export function Carousel({ 'data-testid': testId, ...htmlProps }: CarouselProps) { - const t = useTranslator(); + const t = useComponentTranslator(carouselMessages); const ariaLabel = ariaLabelFromProps ?? t('@astryx.carousel.label'); const scrollElRef = useRef(null); const startButtonRef = useRef(null); diff --git a/packages/core/src/Chat/ChatComposer.tsx b/packages/core/src/Chat/ChatComposer.tsx index bdff0dd2f4f75..256d6116c50cf 100644 --- a/packages/core/src/Chat/ChatComposer.tsx +++ b/packages/core/src/Chat/ChatComposer.tsx @@ -52,7 +52,8 @@ import {ChatComposerContext} from './ChatContext'; import type {ChatComposerInputControl} from './ChatContext'; import {ChatSendButton} from './ChatSendButton'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import chatMessages from '../i18n/generated-locales/en/chat.generated'; import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText'; import {focusOutlineStyles} from '../utils/focusOutline.stylex'; import { @@ -362,7 +363,7 @@ function isComposerEditor(target: EventTarget | null): target is HTMLElement { * ``` */ export function ChatComposer(props: ChatComposerProps) { - const t = useTranslator(); + const t = useComponentTranslator(chatMessages); const { ref, onSubmit, diff --git a/packages/core/src/Chat/ChatComposerDrawer.tsx b/packages/core/src/Chat/ChatComposerDrawer.tsx index 8df85ec892b60..be63c72d74c69 100644 --- a/packages/core/src/Chat/ChatComposerDrawer.tsx +++ b/packages/core/src/Chat/ChatComposerDrawer.tsx @@ -37,7 +37,12 @@ import {mergeProps} from '../utils'; import type {BaseProps} from '../BaseProps'; import {themeProps} from '../utils/themeProps'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import chatMessages from '../i18n/generated-locales/en/chat.generated'; +import chatComposerDrawerMessages from '../i18n/generated-locales/en/chatComposerDrawer.generated'; + +// The English strings this module reads: the namespaces its keys name. +const messages = {...chatMessages, ...chatComposerDrawerMessages}; export interface ChatComposerDrawerProps extends BaseProps { ref?: React.Ref; @@ -253,7 +258,7 @@ export function ChatComposerDrawer({ 'data-testid': testId, ...htmlProps }: ChatComposerDrawerProps): React.ReactElement { - const t = useTranslator(); + const t = useComponentTranslator(messages); const label = labelFromProps ?? t('@astryx.chat.composerDrawer.label'); const [internalCollapsed, setInternalCollapsed] = useState(defaultIsCollapsed); diff --git a/packages/core/src/Chat/ChatComposerInput.tsx b/packages/core/src/Chat/ChatComposerInput.tsx index 2ec516375ae0e..4814aa08520b4 100644 --- a/packages/core/src/Chat/ChatComposerInput.tsx +++ b/packages/core/src/Chat/ChatComposerInput.tsx @@ -68,7 +68,8 @@ import { import {Badge, type BadgeProps} from '../Badge'; import {useChatComposerContext} from './ChatContext'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import chatMessages from '../i18n/generated-locales/en/chat.generated'; // ============================================================================= // Types @@ -346,7 +347,7 @@ function serialize(node: Node): string { // ============================================================================= export function ChatComposerInput(props: ChatComposerInputProps) { - const t = useTranslator(); + const t = useComponentTranslator(chatMessages); const composerCtx = useChatComposerContext(); const hasControlledValueProp = props.value !== undefined; diff --git a/packages/core/src/Chat/ChatDictationButton.tsx b/packages/core/src/Chat/ChatDictationButton.tsx index 364247f542a94..c018784c4b8b8 100644 --- a/packages/core/src/Chat/ChatDictationButton.tsx +++ b/packages/core/src/Chat/ChatDictationButton.tsx @@ -28,7 +28,8 @@ import {Icon} from '../Icon'; import {mergeProps} from '../utils'; import type {BaseProps} from '../BaseProps'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import chatDictationButtonMessages from '../i18n/generated-locales/en/chatDictationButton.generated'; // ============================================================================= // Types @@ -113,7 +114,7 @@ export function ChatDictationButton({ style, ...rest }: ChatDictationButtonProps) { - const t = useTranslator(); + const t = useComponentTranslator(chatDictationButtonMessages); if (isHiddenWhenUnsupported && !dictation.isSupported) { return null; diff --git a/packages/core/src/Chat/ChatLayout.tsx b/packages/core/src/Chat/ChatLayout.tsx index 295825a914e15..d77f35241fab1 100644 --- a/packages/core/src/Chat/ChatLayout.tsx +++ b/packages/core/src/Chat/ChatLayout.tsx @@ -39,7 +39,8 @@ import {useChatNewMessages} from './useChatNewMessages'; import {ChatLayoutScrollButton} from './ChatLayoutScrollButton'; import {ChatLayoutContext} from './ChatContext'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import chatLayoutMessages from '../i18n/generated-locales/en/chatLayout.generated'; import {useMergedRefs} from '../hooks/useMergedRefs'; // ============================================================================= @@ -301,7 +302,7 @@ export function ChatLayout({ ref, ...rest }: ChatLayoutProps) { - const t = useTranslator(); + const t = useComponentTranslator(chatLayoutMessages); const rootRef = useRef(null); const scrollContainerRef = externalScrollRef ?? rootRef; diff --git a/packages/core/src/Chat/ChatLayoutScrollButton.tsx b/packages/core/src/Chat/ChatLayoutScrollButton.tsx index 70d7b9afd1c60..f406898d09951 100644 --- a/packages/core/src/Chat/ChatLayoutScrollButton.tsx +++ b/packages/core/src/Chat/ChatLayoutScrollButton.tsx @@ -32,7 +32,8 @@ import {Button} from '../Button'; import type {BaseProps} from '../BaseProps'; import {mergeProps} from '../utils'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import chatLayoutScrollButtonMessages from '../i18n/generated-locales/en/chatLayoutScrollButton.generated'; // ============================================================================= // Types @@ -138,7 +139,7 @@ export function ChatLayoutScrollButton({ style, ...rest }: ChatLayoutScrollButtonProps) { - const t = useTranslator(); + const t = useComponentTranslator(chatLayoutScrollButtonMessages); return ( // Two elements, two responsibilities. The outer one centres the pill and // holds the gap above the composer — spacing outside the pill's border diff --git a/packages/core/src/Chat/ChatMessage.tsx b/packages/core/src/Chat/ChatMessage.tsx index 35dea7d4aa1b1..d5f164ca7e4ae 100644 --- a/packages/core/src/Chat/ChatMessage.tsx +++ b/packages/core/src/Chat/ChatMessage.tsx @@ -37,7 +37,8 @@ import { import {isRenderable, mergeProps} from '../utils'; import type {BaseProps} from '../BaseProps'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import chatMessageMessages from '../i18n/generated-locales/en/chatMessage.generated'; export interface ChatMessageProps extends BaseProps { ref?: React.Ref; @@ -196,7 +197,7 @@ export function ChatMessage({ ref, ...rest }: ChatMessageProps) { - const t = useTranslator(); + const t = useComponentTranslator(chatMessageMessages); const listContext = useChatListContext(); const density = densityProp ?? listContext?.density ?? 'balanced'; diff --git a/packages/core/src/Chat/ChatMessageList.tsx b/packages/core/src/Chat/ChatMessageList.tsx index c11b51c3689ea..daa97ca3b8bab 100644 --- a/packages/core/src/Chat/ChatMessageList.tsx +++ b/packages/core/src/Chat/ChatMessageList.tsx @@ -37,7 +37,8 @@ import {Spinner} from '../Spinner'; import type {BaseProps} from '../BaseProps'; import type {SpacingStep} from '../utils/types'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import spinnerMessages from '../i18n/generated-locales/en/spinner.generated'; import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement'; export interface ChatMessageListProps extends BaseProps { @@ -240,7 +241,7 @@ export function ChatMessageList({ const sentinelRef = useRef(null); const innerRef = useRef(null); const [isLoadingTop, startTransition] = useTransition(); - const t = useTranslator(); + const t = useComponentTranslator(spinnerMessages); // The top loading Spinner sits inside the log and is silent; the list // announces its loading through the channel (spec:AST-086 FR4, FR8). useBusyAnnouncement(isLoadingTop, t('@astryx.spinner.loading'), innerRef); diff --git a/packages/core/src/Chat/ChatMessageMetadata.tsx b/packages/core/src/Chat/ChatMessageMetadata.tsx index 86ba588d8112f..3513963779b46 100644 --- a/packages/core/src/Chat/ChatMessageMetadata.tsx +++ b/packages/core/src/Chat/ChatMessageMetadata.tsx @@ -26,7 +26,8 @@ import type {IconName} from '../Icon/globalIconRegistry'; import {isRenderable, mergeProps} from '../utils'; import type {BaseProps} from '../BaseProps'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import chatMessages from '../i18n/generated-locales/en/chat.generated'; export type ChatMessageStatus = 'sending' | 'sent' | 'delivered' | 'read' | 'error'; @@ -118,7 +119,7 @@ export function ChatMessageMetadata({ style, ...rest }: ChatMessageMetadataProps) { - const t = useTranslator(); + const t = useComponentTranslator(chatMessages); const msgContext = useChatMessageContext(); const sender = msgContext?.sender ?? 'assistant'; diff --git a/packages/core/src/Chat/ChatPastedTextToken.tsx b/packages/core/src/Chat/ChatPastedTextToken.tsx index 2a5f2ecd479dc..e20f98a1e892b 100644 --- a/packages/core/src/Chat/ChatPastedTextToken.tsx +++ b/packages/core/src/Chat/ChatPastedTextToken.tsx @@ -25,7 +25,9 @@ import { import {Badge} from '../Badge'; import {Button} from '../Button'; import {HoverCard} from '../HoverCard'; -import {useTranslator, type TranslatorFn} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import chatMessages from '../i18n/generated-locales/en/chat.generated'; +import type {TranslatorFn} from '../i18n'; // ============================================================================= // Types @@ -90,7 +92,7 @@ export function ChatPastedTextToken({ text, onExpand, }: ChatPastedTextTokenProps) { - const t = useTranslator(); + const t = useComponentTranslator(chatMessages); const label = formatLabel(text, t); const cardContent = ( diff --git a/packages/core/src/Chat/ChatSendButton.tsx b/packages/core/src/Chat/ChatSendButton.tsx index 53a7705d1b04a..fca52e7d05339 100644 --- a/packages/core/src/Chat/ChatSendButton.tsx +++ b/packages/core/src/Chat/ChatSendButton.tsx @@ -27,7 +27,8 @@ import {useChatComposerContext} from './ChatContext'; import type {BaseProps} from '../BaseProps'; import {composeEventHandlers, mergeProps} from '../utils'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import chatSendButtonMessages from '../i18n/generated-locales/en/chatSendButton.generated'; // ============================================================================= // Types @@ -78,7 +79,7 @@ const styles = stylex.create({ * ``` */ export function ChatSendButton(props: ChatSendButtonProps): ReactNode { - const t = useTranslator(); + const t = useComponentTranslator(chatSendButtonMessages); const context = useChatComposerContext(); const { diff --git a/packages/core/src/Chat/ChatToolCalls.tsx b/packages/core/src/Chat/ChatToolCalls.tsx index b3be4fd84eb10..ae79c202706b1 100644 --- a/packages/core/src/Chat/ChatToolCalls.tsx +++ b/packages/core/src/Chat/ChatToolCalls.tsx @@ -39,7 +39,11 @@ import {Spinner} from '../Spinner'; import {VisuallyHidden} from '../VisuallyHidden'; import {themeProps} from '../utils/themeProps'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; -import {useTranslator} from '../i18n'; +import { + useComponentTranslator, + type TranslatorFn, +} from '../i18n/useComponentTranslator'; +import chatToolCallsMessages from '../i18n/generated-locales/en/chatToolCalls.generated'; // ============================================================================= // Types @@ -363,7 +367,7 @@ const STATUS_STYLES: Record< }; function getStatusAnnouncement( - t: ReturnType, + t: TranslatorFn, status: ChatToolCallStatus, errorMessage?: string, ): string { @@ -408,7 +412,7 @@ function CallRow({ call: ChatToolCallItem; hasClippedFocusRing?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(chatToolCallsMessages); const status = call.status ?? 'complete'; const hasDetail = call.resultDetail != null; const [isDetailOpen, setIsDetailOpen] = useState(false); @@ -544,7 +548,7 @@ function CallRow({ * ``` */ export function ChatToolCalls(props: ChatToolCallsProps) { - const t = useTranslator(); + const t = useComponentTranslator(chatToolCallsMessages); const { calls, label: customLabel, diff --git a/packages/core/src/Chat/useSpeechRecognition.ts b/packages/core/src/Chat/useSpeechRecognition.ts index 20c6e568e4845..402c4c8b9fa27 100644 --- a/packages/core/src/Chat/useSpeechRecognition.ts +++ b/packages/core/src/Chat/useSpeechRecognition.ts @@ -14,7 +14,9 @@ */ import {useState, useCallback, useEffect, useMemo, useRef} from 'react'; -import {useLocale, useTranslator} from '../i18n'; +import {useLocale} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import chatMessages from '../i18n/generated-locales/en/chat.generated'; // ============================================================================= // Types @@ -259,7 +261,7 @@ function getDefaultAudioContext(): AudioContext { export function useSpeechRecognition( options: UseSpeechRecognitionOptions = {}, ): UseSpeechRecognitionReturn { - const t = useTranslator(); + const t = useComponentTranslator(chatMessages); const providerLocale = useLocale(); const { lang, diff --git a/packages/core/src/Chat/useTriggerMenu.tsx b/packages/core/src/Chat/useTriggerMenu.tsx index 68ae119d320af..f4cf48152cd4f 100644 --- a/packages/core/src/Chat/useTriggerMenu.tsx +++ b/packages/core/src/Chat/useTriggerMenu.tsx @@ -44,7 +44,8 @@ import { import {mergeProps, groupItems, isImeKeyEvent} from '../utils'; import type {SearchableItem} from '../Typeahead/types'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import chatTriggerMenuMessages from '../i18n/generated-locales/en/chatTriggerMenu.generated'; import type {ChatComposerTrigger, ChatComposerToken} from './ChatComposerInput'; // ============================================================================= @@ -333,7 +334,7 @@ function deleteTriggerText( export function useTriggerMenu( options: UseTriggerMenuOptions, ): UseTriggerMenuReturn { - const t = useTranslator(); + const t = useComponentTranslator(chatTriggerMenuMessages); const { triggers, editableRef, diff --git a/packages/core/src/CheckboxInput/CheckboxInput.tsx b/packages/core/src/CheckboxInput/CheckboxInput.tsx index a3e9996370ccc..da3fc00d2414d 100644 --- a/packages/core/src/CheckboxInput/CheckboxInput.tsx +++ b/packages/core/src/CheckboxInput/CheckboxInput.tsx @@ -46,7 +46,8 @@ import {useTooltip} from '../Tooltip'; import {mergeProps, rtlStyles} from '../utils'; import {indicatorScope} from '../Indicator/indicator.markers.stylex'; import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import spinnerMessages from '../i18n/generated-locales/en/spinner.generated'; import {useIndicatorFocusRing} from '../hooks/useIndicatorFocusRing'; import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement'; import {usePressFeedback} from '../hooks/usePressFeedback'; @@ -373,7 +374,7 @@ export function CheckboxInput({ // `opacity: 0`, and only the indicator's own element can shape the outline // to match it. See useIndicatorFocusRing. const indicatorRef = useRef(null); - const t = useTranslator(); + const t = useComponentTranslator(spinnerMessages); // The busy Spinner sits in the decorative, aria-hidden indicator, so this // control announces its busy start itself (spec:AST-086 FR8). useBusyAnnouncement(isBusy, t('@astryx.spinner.loading'), indicatorRef); diff --git a/packages/core/src/CheckboxList/CheckboxListItem.tsx b/packages/core/src/CheckboxList/CheckboxListItem.tsx index 591bf799d9cd6..7ad8351f723fb 100644 --- a/packages/core/src/CheckboxList/CheckboxListItem.tsx +++ b/packages/core/src/CheckboxList/CheckboxListItem.tsx @@ -27,7 +27,8 @@ import type {CheckboxInputProps} from '../CheckboxInput/CheckboxInput'; import {ListItem} from '../List/ListItem'; import {ListContext} from '../List/ListContext'; import {CheckboxListContext} from './CheckboxListContext'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import checkboxListMessages from '../i18n/generated-locales/en/checkboxList.generated'; import {ItemDescriptionContext} from '../Item/ItemDescriptionContext'; import type {ItemAlign} from '../Item'; @@ -203,7 +204,7 @@ export function CheckboxListItem({ align, ...restProps }: CheckboxListItemProps) { - const t = useTranslator(); + const t = useComponentTranslator(checkboxListMessages); const ctx = use(CheckboxListContext); if (ctx && ctx.value !== undefined && value === undefined) { diff --git a/packages/core/src/Citation/Citation.tsx b/packages/core/src/Citation/Citation.tsx index 58ce033fcb924..4ab8cc26c6034 100644 --- a/packages/core/src/Citation/Citation.tsx +++ b/packages/core/src/Citation/Citation.tsx @@ -33,7 +33,8 @@ import {mergeProps} from '../utils'; import {isSafeUrl} from '../utils/safeUrl'; import type {BaseProps} from '../BaseProps'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import citationMessages from '../i18n/generated-locales/en/citation.generated'; import {renderIconSlot} from '../Icon'; export interface CitationSource { @@ -188,7 +189,7 @@ export function Citation({ 'data-testid': testId, ...rest }: CitationProps): React.ReactElement { - const t = useTranslator(); + const t = useComponentTranslator(citationMessages); const title = source.title ?? String(number); const href = source.url != null && isSafeUrl(source.url) ? source.url : undefined; diff --git a/packages/core/src/CodeBlock/CodeBlock.tsx b/packages/core/src/CodeBlock/CodeBlock.tsx index 96d665dad61e2..12767badb37d7 100644 --- a/packages/core/src/CodeBlock/CodeBlock.tsx +++ b/packages/core/src/CodeBlock/CodeBlock.tsx @@ -57,7 +57,8 @@ import {ensureHighlightStyles} from './highlightStyles'; import {applyHighlightRangesChunked} from './highlightRanges'; import {themeProps} from '../utils/themeProps'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import codeBlockMessages from '../i18n/generated-locales/en/codeBlock.generated'; import {SyntaxTheme, type SyntaxThemeDefinition} from '../theme/syntax'; // --------------------------------------------------------------------------- @@ -978,7 +979,7 @@ export function CodeBlock({ ref, ...props }: CodeBlockProps) { - const t = useTranslator(); + const t = useComponentTranslator(codeBlockMessages); // Owns the clipboard write, the transient copied flag, its reset timer, and // the polite copy announcement (a swapped aria-label alone is not reliably // announced) — shared with Timestamp via the same hook. diff --git a/packages/core/src/CommandPalette/CommandPalette.tsx b/packages/core/src/CommandPalette/CommandPalette.tsx index 02976a8262fdd..842029f4cc111 100644 --- a/packages/core/src/CommandPalette/CommandPalette.tsx +++ b/packages/core/src/CommandPalette/CommandPalette.tsx @@ -40,7 +40,8 @@ import {CommandPaletteEmpty} from './CommandPaletteEmpty'; import type {BaseProps} from '../BaseProps'; import {useAnnounce} from '../hooks/useAnnounce'; import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import commandPaletteMessages from '../i18n/generated-locales/en/commandPalette.generated'; export interface CommandPaletteProps< T extends SearchableItem = SearchableItem, @@ -297,7 +298,7 @@ export function CommandPalette({ maxHeight = 480, ...rest }: CommandPaletteProps) { - const t = useTranslator(); + const t = useComponentTranslator(commandPaletteMessages); const label = labelFromProps ?? t('@astryx.commandPalette.label'); const emptySearchText = emptySearchTextFromProps ?? t('@astryx.commandPalette.emptySearch'); diff --git a/packages/core/src/CommandPalette/CommandPaletteFooter.tsx b/packages/core/src/CommandPalette/CommandPaletteFooter.tsx index dce71a3b4f0b7..6cfda0d2201d5 100644 --- a/packages/core/src/CommandPalette/CommandPaletteFooter.tsx +++ b/packages/core/src/CommandPalette/CommandPaletteFooter.tsx @@ -24,7 +24,8 @@ import { } from '../theme/tokens.stylex'; import {Kbd} from '../Kbd'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import commandPaletteMessages from '../i18n/generated-locales/en/commandPalette.generated'; const styles = stylex.create({ footer: { @@ -90,7 +91,7 @@ export function CommandPaletteFooter({ style, ...props }: CommandPaletteFooterProps) { - const t = useTranslator(); + const t = useComponentTranslator(commandPaletteMessages); return (
({ controlClassName != null || controlStyle != null), ); - const t = useTranslator(); + const t = useComponentTranslator(messages); const pressable = usePressFeedback(); const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional}); const placeholder = placeholderFromProps ?? t('@astryx.selector.placeholder'); diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index 322a6c7c85059..2d47f3352a3b8 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -86,7 +86,9 @@ import {mergeProps, rtlStyles} from '../utils'; import type {BaseProps} from '../BaseProps'; import type {StyleXStyles} from '../theme/types'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import contextMenuMessages from '../i18n/generated-locales/en/contextMenu.generated'; +import dropdownMenuMessages from '../i18n/generated-locales/en/dropdownMenu.generated'; import type { DropdownMenuOption, DropdownMenuItemData, @@ -100,6 +102,9 @@ import { type AdaptivePresentation, } from '../hooks/useAdaptivePresentation'; +// The English strings this module reads: the namespaces its keys name. +const messages = {...contextMenuMessages, ...dropdownMenuMessages}; + const LazyMenuBottomSheet = lazy(async () => import('../DropdownMenu/MenuBottomSheet').then(module => ({ default: module.MenuBottomSheet, @@ -338,7 +343,7 @@ export function ContextMenu({ 'data-testid': testId, ...rest }: ContextMenuProps) { - const t = useTranslator(); + const t = useComponentTranslator(messages); const label = labelFromProps ?? t('@astryx.contextMenu.label'); const backLabel = t('@astryx.dropdownMenu.back'); const resolvedPresentation = useAdaptivePresentation(presentation); diff --git a/packages/core/src/DateInput/DateInput.tsx b/packages/core/src/DateInput/DateInput.tsx index e924f478c6c2c..3db4bce2b0e64 100644 --- a/packages/core/src/DateInput/DateInput.tsx +++ b/packages/core/src/DateInput/DateInput.tsx @@ -212,9 +212,15 @@ import { import type {SizeValue} from '../utils/types'; import {themeProps} from '../utils/themeProps'; import {focusOutlineStyles} from '../utils/focusOutline.stylex'; -import {useLocale, useTranslator} from '../i18n'; +import {useLocale} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import dateInputMessages from '../i18n/generated-locales/en/dateInput.generated'; +import spinnerMessages from '../i18n/generated-locales/en/spinner.generated'; import {useMergedRefs} from '../hooks/useMergedRefs'; + +// The English strings this module reads: the namespaces its keys name. +const messages = {...dateInputMessages, ...spinnerMessages}; export interface DateInputProps extends Omit< FieldInputBaseProps, 'onChange' | 'defaultValue' @@ -533,7 +539,7 @@ function PointerDateField({ onKeyDown: onKeyDownProp, ...controlProps } = rest; - const t = useTranslator(); + const t = useComponentTranslator(messages); const locale = useLocale(); const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional}); const placeholder = diff --git a/packages/core/src/DateInput/NativeDateField.tsx b/packages/core/src/DateInput/NativeDateField.tsx index 0f3f65bbecf77..683f513048123 100644 --- a/packages/core/src/DateInput/NativeDateField.tsx +++ b/packages/core/src/DateInput/NativeDateField.tsx @@ -52,7 +52,10 @@ import {useMediaQuery} from '../hooks/useMediaQuery'; import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement'; import {useResolvedRequired} from '../hooks/useResolvedRequired'; import {Icon} from '../Icon'; -import {useLocale, useTranslator} from '../i18n'; +import {useLocale} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import dateInputMessages from '../i18n/generated-locales/en/dateInput.generated'; +import spinnerMessages from '../i18n/generated-locales/en/spinner.generated'; import {useInputGroup} from '../InputGroup'; import {useFieldInputStyling} from '../Field/fieldParts'; import {joinAriaIDs} from '../utils/inputAria'; @@ -82,6 +85,9 @@ import { } from '../utils'; import {chainEventHandlers} from '../utils/chainEventHandlers'; +// The English strings this module reads: the namespaces its keys name. +const messages = {...dateInputMessages, ...spinnerMessages}; + const styles = stylex.create({ // Same as DateInput's: no hover ring while disabled or busy, and the // focus ring while the field's input holds focus. @@ -308,7 +314,7 @@ export function NativeDateField({ onBlur: onBlurProp, ...controlProps } = rest; - const t = useTranslator(); + const t = useComponentTranslator(messages); const locale = useLocale(); const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional}); const placeholder = diff --git a/packages/core/src/DateInput/TouchDateField.tsx b/packages/core/src/DateInput/TouchDateField.tsx index 372be82caf893..ece71a4d087e4 100644 --- a/packages/core/src/DateInput/TouchDateField.tsx +++ b/packages/core/src/DateInput/TouchDateField.tsx @@ -76,7 +76,11 @@ import {useResolvedRequired} from '../hooks/useResolvedRequired'; import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement'; import {Icon} from '../Icon'; import {IconButton} from '../IconButton'; -import {useLocale, useTranslator} from '../i18n'; +import {useLocale} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import calendarMessages from '../i18n/generated-locales/en/calendar.generated'; +import dateInputMessages from '../i18n/generated-locales/en/dateInput.generated'; +import spinnerMessages from '../i18n/generated-locales/en/spinner.generated'; import {useInputGroup} from '../InputGroup'; import {useFieldInputStyling} from '../Field/fieldParts'; import {joinAriaIDs} from '../utils/inputAria'; @@ -126,6 +130,13 @@ import { } from './monthGeometry'; import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex'; +// The English strings this module reads: the namespaces its keys name. +const messages = { + ...calendarMessages, + ...dateInputMessages, + ...spinnerMessages, +}; + /** * The comfortable minimum tap target on both iOS and Android, honoured by * every target inside the sheet. @@ -610,7 +621,7 @@ export function TouchDateField({ ...controlProps } = rest; const pressable = usePressFeedback(); - const t = useTranslator(); + const t = useComponentTranslator(messages); const locale = useLocale(); const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional}); const placeholder = diff --git a/packages/core/src/DateRangeInput/DateRangeInput.tsx b/packages/core/src/DateRangeInput/DateRangeInput.tsx index ee3bac7e414a4..74da3874aecd4 100644 --- a/packages/core/src/DateRangeInput/DateRangeInput.tsx +++ b/packages/core/src/DateRangeInput/DateRangeInput.tsx @@ -80,9 +80,22 @@ import {useMergedRefs} from '../hooks/useMergedRefs'; import {useResolvedRequired} from '../hooks/useResolvedRequired'; import {themeProps} from '../utils/themeProps'; import {focusOutlineStyles} from '../utils/focusOutline.stylex'; -import {useLocale, useTranslator} from '../i18n'; +import {useLocale} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import dateInputMessages from '../i18n/generated-locales/en/dateInput.generated'; +import dateRangeInputMessages from '../i18n/generated-locales/en/dateRangeInput.generated'; +import fieldMessages from '../i18n/generated-locales/en/field.generated'; +import spinnerMessages from '../i18n/generated-locales/en/spinner.generated'; import type {Locale} from '../i18n/types'; +// The English strings this module reads: the namespaces its keys name. +const messages = { + ...dateInputMessages, + ...dateRangeInputMessages, + ...fieldMessages, + ...spinnerMessages, +}; + export type {DateRange} from '../Calendar'; export interface DateRangePreset { @@ -541,7 +554,7 @@ export function DateRangeInput({ onClick: onClickProp, ...controlProps } = rest; - const t = useTranslator(); + const t = useComponentTranslator(messages); const locale = useLocale(); const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional}); const placeholder = diff --git a/packages/core/src/DateTimeInput/DateTimeInput.tsx b/packages/core/src/DateTimeInput/DateTimeInput.tsx index a5b5bc294bd75..ae12aca968fba 100644 --- a/packages/core/src/DateTimeInput/DateTimeInput.tsx +++ b/packages/core/src/DateTimeInput/DateTimeInput.tsx @@ -101,7 +101,12 @@ import {useResolvedRequired} from '../hooks/useResolvedRequired'; import {useSize} from '../SizeContext/SizeContext'; import {themeProps} from '../utils/themeProps'; import {focusOutlineStyles} from '../utils/focusOutline.stylex'; -import {useLocale, useTranslator} from '../i18n'; +import {useLocale} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import dateInputMessages from '../i18n/generated-locales/en/dateInput.generated'; +import dateTimeInputMessages from '../i18n/generated-locales/en/dateTimeInput.generated'; +import timeInputMessages from '../i18n/generated-locales/en/timeInput.generated'; +import spinnerMessages from '../i18n/generated-locales/en/spinner.generated'; import {useMergedRefs} from '../hooks/useMergedRefs'; import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll'; @@ -114,6 +119,14 @@ import { type PickerPresentation, } from '../utils/inputPresentation'; import {useDevWarning} from '../hooks/useDevWarning'; + +// The English strings this module reads: the namespaces its keys name. +const messages = { + ...dateInputMessages, + ...dateTimeInputMessages, + ...timeInputMessages, + ...spinnerMessages, +}; export type ISODateTimeString = string & { readonly __brand: 'ISODateTimeString'; }; @@ -663,7 +676,7 @@ function PointerDateTimeField({ onKeyDown: onKeyDownProp, ...controlProps } = rest; - const t = useTranslator(); + const t = useComponentTranslator(messages); const locale = useLocale(); const usesNativePicker = nativeMode !== 'off'; // `forced` (`presentation="native"`, FR2): no Astryx fallback. `adaptive` diff --git a/packages/core/src/DateTimeInput/NativeDateSegment.tsx b/packages/core/src/DateTimeInput/NativeDateSegment.tsx index bee10c4879e7b..054f66af84549 100644 --- a/packages/core/src/DateTimeInput/NativeDateSegment.tsx +++ b/packages/core/src/DateTimeInput/NativeDateSegment.tsx @@ -33,7 +33,9 @@ import {hasEditableDateSegments} from '../DateInput/nativeDateSegments'; import {useMediaQuery} from '../hooks/useMediaQuery'; import {useMergedRefs} from '../hooks/useMergedRefs'; import {Icon} from '../Icon'; -import {useLocale, useTranslator} from '../i18n'; +import {useLocale} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import dateInputMessages from '../i18n/generated-locales/en/dateInput.generated'; import {VisuallyHidden} from '../VisuallyHidden'; import { focusOutlineStyles, @@ -100,7 +102,7 @@ export function NativeDateSegment({ onBlur: onBlurProp, ...inputProps } = controlProps ?? {}; - const t = useTranslator(); + const t = useComponentTranslator(dateInputMessages); const locale = useLocale(); const isTouchPointer = useMediaQuery('(pointer: coarse)'); const internalInputRef = useRef(null); diff --git a/packages/core/src/DateTimeInput/NativeTimeSegment.tsx b/packages/core/src/DateTimeInput/NativeTimeSegment.tsx index 303ca5ab51a1a..8ebe9772c7a3b 100644 --- a/packages/core/src/DateTimeInput/NativeTimeSegment.tsx +++ b/packages/core/src/DateTimeInput/NativeTimeSegment.tsx @@ -34,7 +34,8 @@ import type {InputStatusType} from '../Field'; import {useMediaQuery} from '../hooks/useMediaQuery'; import {useMergedRefs} from '../hooks/useMergedRefs'; import {Icon} from '../Icon'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import timeInputMessages from '../i18n/generated-locales/en/timeInput.generated'; import type {ThemeProps} from '../utils/themeProps'; import {VisuallyHidden} from '../VisuallyHidden'; import { @@ -125,7 +126,7 @@ export function NativeTimeSegment({ onBlur: onBlurProp, ...inputProps } = controlProps ?? {}; - const t = useTranslator(); + const t = useComponentTranslator(timeInputMessages); const isTouchPointer = useMediaQuery('(pointer: coarse)'); const internalInputRef = useRef(null); const mergedInputRef = useMergedRefs(inputRef, internalInputRef); diff --git a/packages/core/src/DateTimeInput/TouchDateTimeField.tsx b/packages/core/src/DateTimeInput/TouchDateTimeField.tsx index 654dcecdd2323..d9b4c400189f7 100644 --- a/packages/core/src/DateTimeInput/TouchDateTimeField.tsx +++ b/packages/core/src/DateTimeInput/TouchDateTimeField.tsx @@ -23,7 +23,6 @@ */ import { - use, useCallback, useEffect, useId, @@ -50,7 +49,12 @@ import {useResolvedRequired} from '../hooks/useResolvedRequired'; import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement'; import {Icon} from '../Icon'; import {IconButton} from '../IconButton'; -import {useTranslator, InternationalizationContext} from '../i18n'; +import {useLocale} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import calendarMessages from '../i18n/generated-locales/en/calendar.generated'; +import dateInputMessages from '../i18n/generated-locales/en/dateInput.generated'; +import dateTimeInputMessages from '../i18n/generated-locales/en/dateTimeInput.generated'; +import spinnerMessages from '../i18n/generated-locales/en/spinner.generated'; import {SegmentedControl, SegmentedControlItem} from '../SegmentedControl'; import {useSize} from '../SizeContext/SizeContext'; import {Spinner} from '../Spinner'; @@ -110,6 +114,14 @@ import { } from '../DateInput/monthGeometry'; import type {DateTimeInputProps, ISODateTimeString} from './DateTimeInput'; +// The English strings this module reads: the namespaces its keys name. +const messages = { + ...calendarMessages, + ...dateInputMessages, + ...dateTimeInputMessages, + ...spinnerMessages, +}; + function splitDateTime(dt: ISODateTimeString | undefined): { date: ISODateString | undefined; time: ISOTimeString | undefined; @@ -504,9 +516,9 @@ export function TouchDateTimeField({ onKeyDown: onKeyDownProp, ...controlProps } = rest; - const t = useTranslator(); + const t = useComponentTranslator(messages); const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional}); - const {locale} = use(InternationalizationContext); + const locale = useLocale(); const placeholder = placeholderFromProps ?? t('@astryx.dateTimeInput.placeholder'); const timePlaceholder = diff --git a/packages/core/src/Dialog/DialogHeader.tsx b/packages/core/src/Dialog/DialogHeader.tsx index 303fb414f1893..bd4e4c44c4ac0 100644 --- a/packages/core/src/Dialog/DialogHeader.tsx +++ b/packages/core/src/Dialog/DialogHeader.tsx @@ -28,7 +28,8 @@ import type {BaseProps} from '../BaseProps'; import {isRenderable, mergeProps} from '../utils'; import {themeProps} from '../utils/themeProps'; import {useDialogContext} from './DialogContext'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import dialogMessages from '../i18n/generated-locales/en/dialog.generated'; const styles = stylex.create({ container: { @@ -159,7 +160,7 @@ export function DialogHeader({ ref, ...rest }: DialogHeaderProps) { - const t = useTranslator(); + const t = useComponentTranslator(dialogMessages); const titleRef = useRef(null); const dialogContext = useDialogContext(); const shouldAutoFocus = dialogContext?.isInline !== true; diff --git a/packages/core/src/Drawer/DrawerHeader.tsx b/packages/core/src/Drawer/DrawerHeader.tsx index 4c8e2c8435310..aee347b3a5d82 100644 --- a/packages/core/src/Drawer/DrawerHeader.tsx +++ b/packages/core/src/Drawer/DrawerHeader.tsx @@ -34,7 +34,8 @@ import {Heading} from '../Heading'; import {Icon} from '../Icon'; import {LayoutHeader} from '../Layout'; import {Text} from '../Text'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import dialogMessages from '../i18n/generated-locales/en/dialog.generated'; import {isRenderable, mergeProps, themeProps} from '../utils'; const styles = stylex.create({ @@ -147,7 +148,7 @@ export function DrawerHeader({ ref, ...rest }: DrawerHeaderProps) { - const t = useTranslator(); + const t = useComponentTranslator(dialogMessages); const hasSubtitle = isRenderable(subtitle); const hasStartContent = isRenderable(startContent); const hasEndContent = isRenderable(endContent); diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx index 55c9ed01649f5..68aa4d5fe182e 100644 --- a/packages/core/src/DropdownMenu/DropdownMenu.tsx +++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx @@ -107,7 +107,8 @@ import { getInteractionModality, useInteractionModalityTracking, } from '../utils/interactionModality'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import dropdownMenuMessages from '../i18n/generated-locales/en/dropdownMenu.generated'; import {focusOutlineStyles} from '../utils/focusOutline.stylex'; // The menu's own lower cap on the placement axis; the viewport cap underneath @@ -628,7 +629,7 @@ function DropdownMenuBottomSheet({ 'data-testid': testId, ...rest }: DropdownMenuDataProps & {presentation: 'bottom-sheet'}) { - const t = useTranslator(); + const t = useComponentTranslator(dropdownMenuMessages); const button = buttonFromProps ?? {label: t(DEFAULT_BUTTON_I18N_KEY)}; const backLabel = t('@astryx.dropdownMenu.back'); const buttonRef = useRef(null); @@ -921,7 +922,7 @@ function DropdownMenuPopover({ 'data-testid': testId, ...props }: DropdownMenuProps) { - const t = useTranslator(); + const t = useComponentTranslator(dropdownMenuMessages); const button = buttonFromProps ?? {label: t(DEFAULT_BUTTON_I18N_KEY)}; const items = ('items' in props ? props.items : undefined) ?? []; diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx index ba205437fc827..aa860d2b20a2a 100644 --- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx +++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx @@ -119,7 +119,12 @@ import { } from './DropdownMenuContext'; import {focusMenuItemOnHover} from './menuItemHover'; import {DropdownMenuItem} from './DropdownMenuItem'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import dropdownMenuMessages from '../i18n/generated-locales/en/dropdownMenu.generated'; +import spinnerMessages from '../i18n/generated-locales/en/spinner.generated'; + +// The English strings this module reads: the namespaces its keys name. +const messages = {...dropdownMenuMessages, ...spinnerMessages}; // The flyout's own lower cap on the placement axis; the viewport cap under // it and the inline gutter beside it are the layer runtime's (spec:AST-059). @@ -502,7 +507,7 @@ export function DropdownMenuSubMenu( ...rest } = props; - const t = useTranslator(); + const t = useComponentTranslator(messages); const menuCtx = useDropdownMenuContext(); const rootSurface = use(DropdownMenuSurfaceContext); const rootHasRegions = use(MenuRegionsContext); diff --git a/packages/core/src/Field/FieldLabel.tsx b/packages/core/src/Field/FieldLabel.tsx index 6cac00136f664..b97423a20829a 100644 --- a/packages/core/src/Field/FieldLabel.tsx +++ b/packages/core/src/Field/FieldLabel.tsx @@ -4,7 +4,7 @@ /** * @file FieldLabel.tsx - * @input Uses React, Icon, IconType, useTranslator, FormLayoutContext + * @input Uses React, Icon, IconType, useComponentTranslator, FormLayoutContext * @output Exports FieldLabel component, FieldLabelProps * @position Core label implementation; used by Field, CheckboxInput, Switch * @@ -30,7 +30,8 @@ import { } from '../theme/tokens.stylex'; import {Icon, renderIconSlot, type IconType} from '../Icon'; import {Tooltip} from '../Tooltip'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import fieldMessages from '../i18n/generated-locales/en/field.generated'; import {themeProps} from '../utils/themeProps'; import {useInputContainer} from '../hooks/useInputContainer'; import {FormLayoutContext} from '../FormLayout/FormLayoutContext'; @@ -211,7 +212,7 @@ export function FieldLabel({ ref, ...rest }: FieldLabelProps) { - const t = useTranslator(); + const t = useComponentTranslator(fieldMessages); const {defaultOptionality} = use(FormLayoutContext); // A form-level `defaultOptionality` means "only the exception is marked": a diff --git a/packages/core/src/Field/InputClearButton.tsx b/packages/core/src/Field/InputClearButton.tsx index a9e154f0954a1..5fba303cd6a4b 100644 --- a/packages/core/src/Field/InputClearButton.tsx +++ b/packages/core/src/Field/InputClearButton.tsx @@ -20,7 +20,8 @@ import type {ReactNode} from 'react'; import * as stylex from '@stylexjs/stylex'; import {Button} from '../Button'; import {Icon} from '../Icon'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import inputClearButtonMessages from '../i18n/generated-locales/en/inputClearButton.generated'; import {themeProps} from '../utils/themeProps'; const styles = stylex.create({ @@ -138,7 +139,7 @@ function renderInputClearButton({ } export function InputClearButton(props: InputClearButtonProps): ReactNode { - const t = useTranslator(); + const t = useComponentTranslator(inputClearButtonMessages); return renderInputClearButton({ ...props, tooltip: t('@astryx.inputClearButton.tooltip'), @@ -149,7 +150,7 @@ export function InputClearButton(props: InputClearButtonProps): ReactNode { export function InternalInputClearButton( props: InternalInputClearButtonProps, ): ReactNode { - const t = useTranslator(); + const t = useComponentTranslator(inputClearButtonMessages); return renderInputClearButton({ ...props, tooltip: t('@astryx.inputClearButton.tooltip'), diff --git a/packages/core/src/FileInput/FileInput.tsx b/packages/core/src/FileInput/FileInput.tsx index 1ece331f284b8..8aaebb926c23e 100644 --- a/packages/core/src/FileInput/FileInput.tsx +++ b/packages/core/src/FileInput/FileInput.tsx @@ -64,10 +64,15 @@ import { } from '../Field/fieldParts'; import type {SizeValue} from '../utils/types'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import fileInputMessages from '../i18n/generated-locales/en/fileInput.generated'; +import spinnerMessages from '../i18n/generated-locales/en/spinner.generated'; import type {TranslatorFn} from '../i18n'; import {useMergedRefs} from '../hooks/useMergedRefs'; + +// The English strings this module reads: the namespaces its keys name. +const messages = {...fileInputMessages, ...spinnerMessages}; function formatFileSize(bytes: number, t: TranslatorFn): string { if (bytes < 1024) { return t('@astryx.fileInput.fileSize.bytes', {size: bytes}); @@ -480,7 +485,7 @@ export function FileInput({ containerClassName, containerStyle, }); - const t = useTranslator(); + const t = useComponentTranslator(messages); const generatedID = useId(); const id = idProp ?? generatedID; const descriptionID = useId(); diff --git a/packages/core/src/Kbd/Kbd.tsx b/packages/core/src/Kbd/Kbd.tsx index 6340505199e73..68dc9bf26fb88 100644 --- a/packages/core/src/Kbd/Kbd.tsx +++ b/packages/core/src/Kbd/Kbd.tsx @@ -19,7 +19,9 @@ import {mergeProps} from '../utils'; import {isApplePlatform} from '../utils/isApplePlatform'; import type {BaseProps} from '../BaseProps'; import {themeProps} from '../utils/themeProps'; -import {useTranslator, type TranslatorFn} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import kbdMessages from '../i18n/generated-locales/en/kbd.generated'; +import type {TranslatorFn} from '../i18n'; import { colorVars, spacingVars, @@ -166,7 +168,7 @@ export interface KbdProps extends BaseProps { * ``` */ export function Kbd({keys, ref, xstyle, className, style, ...rest}: KbdProps) { - const t = useTranslator(); + const t = useComponentTranslator(kbdMessages); const isMac = useSyncExternalStore( subscribeToPlatformChanges, isApplePlatform, diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsx index 476487c352650..1c0325379b830 100644 --- a/packages/core/src/Lightbox/Lightbox.tsx +++ b/packages/core/src/Lightbox/Lightbox.tsx @@ -45,7 +45,8 @@ import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider'; import {overlayPaddingReset} from '../Layout/padding.stylex'; import {LayerDepthProvider} from '../Layer/LayerDepthContext'; import {useLayerDismissal} from '../Layer/useLayerDismissal'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import lightboxMessages from '../i18n/generated-locales/en/lightbox.generated'; import {useMergedRefs} from '../hooks/useMergedRefs'; import {isRtlElement} from '../hooks/isRtlElement'; @@ -329,7 +330,7 @@ export function Lightbox({ onKeyDown: onKeyDownProp, ...props }: LightboxProps) { - const t = useTranslator(); + const t = useComponentTranslator(lightboxMessages); const dialogRef = useRef(null); const mergedDialogRef = useMergedRefs(ref, dialogRef); const containerRef = useRef(null); diff --git a/packages/core/src/Link/Link.tsx b/packages/core/src/Link/Link.tsx index 963910ec09537..355ce9bbbefed 100644 --- a/packages/core/src/Link/Link.tsx +++ b/packages/core/src/Link/Link.tsx @@ -47,7 +47,8 @@ import {themeProps} from '../utils/themeProps'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex'; import {usePressFeedback} from '../hooks/usePressFeedback'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import linkMessages from '../i18n/generated-locales/en/link.generated'; import {disabledInteractionProps} from '../utils/disabledInteraction'; /** @@ -312,7 +313,7 @@ export function Link({ // document controller once, so the link's output stays a pure function of // its props. const pressable = usePressFeedback(); - const t = useTranslator(); + const t = useComponentTranslator(linkMessages); const newTabLabel = newTabLabelFromProps ?? t('@astryx.link.newTab'); const LinkComponent = useLinkComponent(as); const role = useInteractiveRole({href, onClick, isDisabled}); diff --git a/packages/core/src/Markdown/Markdown.tsx b/packages/core/src/Markdown/Markdown.tsx index e33a355583934..724bc364c8e0f 100644 --- a/packages/core/src/Markdown/Markdown.tsx +++ b/packages/core/src/Markdown/Markdown.tsx @@ -94,7 +94,9 @@ import { headingLinksHeadingStyle, } from './plugins/HeadingLinksRenderer'; import {themeProps} from '../utils/themeProps'; -import {useTranslator, type TranslatorFn} from '../i18n'; +import type {TranslatorFn} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import markdownMessages from '../i18n/generated-locales/en/markdown.generated'; type SyncReactNode = Exclude>; type RenderExtensionNode = MarkdownExtensionNode; @@ -2142,7 +2144,7 @@ export function Markdown< 'data-testid': testId, ...props }: MarkdownProps): React.ReactElement { - const t = useTranslator(); + const t = useComponentTranslator(markdownMessages); // Keep one list while it names the same values, so an inline // `codeLanguages={[…]}` does not re-render every block on each parent // render (adjusting state during render, not in an Effect). diff --git a/packages/core/src/Markdown/plugins/HeadingLinksRenderer.tsx b/packages/core/src/Markdown/plugins/HeadingLinksRenderer.tsx index 96d6ecb854f13..437611ea70fe6 100644 --- a/packages/core/src/Markdown/plugins/HeadingLinksRenderer.tsx +++ b/packages/core/src/Markdown/plugins/HeadingLinksRenderer.tsx @@ -17,7 +17,8 @@ import {Button} from '../../Button/Button'; import {Icon} from '../../Icon'; import {useClipboard} from '../../hooks/useClipboard'; import {useContainerReveal} from '../../hooks/useContainerReveal'; -import {useTranslator} from '../../i18n'; +import {useComponentTranslator} from '../../i18n/useComponentTranslator'; +import markdownHeadingLinksMessages from '../../i18n/generated-locales/en/markdownHeadingLinks.generated'; import {colorVars, sizeVars, spacingVars} from '../../theme/tokens.stylex'; import {mergeProps, rtlStyles} from '../../utils'; @@ -132,7 +133,7 @@ export function HeadingLinksRenderer({ headingTextStyle, blockSpacingStyle, }: HeadingLinksRendererProps): ReactElement { - const t = useTranslator(); + const t = useComponentTranslator(markdownHeadingLinksMessages); const copiedLabel = t('@astryx.markdownHeadingLinks.copied'); const copyLabel = t('@astryx.markdownHeadingLinks.copy', { heading: headingLabel || headingId, diff --git a/packages/core/src/MetadataList/MetadataList.tsx b/packages/core/src/MetadataList/MetadataList.tsx index bf84783da8f9c..af6d15adc10b1 100644 --- a/packages/core/src/MetadataList/MetadataList.tsx +++ b/packages/core/src/MetadataList/MetadataList.tsx @@ -4,7 +4,7 @@ /** * @file MetadataList.tsx - * @input Uses React, ReactNode, StyleXStyles, theme tokens, MetadataListContext, i18n (useTranslator) + * @input Uses React, ReactNode, StyleXStyles, theme tokens, MetadataListContext, i18n (useComponentTranslator) * @output Exports MetadataList component, MetadataListProps, MetadataListColumns types * @position Core implementation; consumed by index.ts, tested by MetadataList.test.tsx * @@ -31,7 +31,8 @@ import { import type {BaseProps} from '../BaseProps'; import {mergeProps} from '../utils'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import metadataListMessages from '../i18n/generated-locales/en/metadataList.generated'; // ============================================================================= // Types @@ -216,7 +217,7 @@ export function MetadataList({ ); const [isShowAll, setIsShowAll] = useState(false); const contentId = useId(); - const t = useTranslator(); + const t = useComponentTranslator(metadataListMessages); const contextValue = useMemo( () => ({ diff --git a/packages/core/src/MobileNav/MobileNav.tsx b/packages/core/src/MobileNav/MobileNav.tsx index 0da8e0abd7446..0db2ea5d90025 100644 --- a/packages/core/src/MobileNav/MobileNav.tsx +++ b/packages/core/src/MobileNav/MobileNav.tsx @@ -76,7 +76,8 @@ import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider'; import {useLayerDismissal} from '../Layer/useLayerDismissal'; import type {BaseProps} from '../BaseProps'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import mobileNavMessages from '../i18n/generated-locales/en/mobileNav.generated'; import {useMergedRefs} from '../hooks/useMergedRefs'; // ============================================================================= @@ -474,7 +475,7 @@ export function MobileNav({ ref, ...rest }: MobileNavProps) { - const t = useTranslator(); + const t = useComponentTranslator(mobileNavMessages); // Read from AppShell context as fallback const appShellMobile = useAppShellMobile(); const isOpen = isOpenProp ?? appShellMobile.isMobileNavOpen; diff --git a/packages/core/src/MobileNav/MobileNavToggle.tsx b/packages/core/src/MobileNav/MobileNavToggle.tsx index 2a567ca1fcddf..c157d3386f9ef 100644 --- a/packages/core/src/MobileNav/MobileNavToggle.tsx +++ b/packages/core/src/MobileNav/MobileNavToggle.tsx @@ -18,7 +18,8 @@ import {Button} from '../Button'; import {Icon} from '../Icon'; import {useAppShellMobile} from '../AppShell/AppShellMobileContext'; import type {BaseProps} from '../BaseProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import mobileNavMessages from '../i18n/generated-locales/en/mobileNav.generated'; export interface MobileNavToggleProps extends Pick< BaseProps, @@ -67,7 +68,7 @@ export function MobileNavToggle({ className, style, }: MobileNavToggleProps) { - const t = useTranslator(); + const t = useComponentTranslator(mobileNavMessages); const label = labelFromProps ?? t('@astryx.mobileNav.toggle.open'); const { isMobile, diff --git a/packages/core/src/MoreMenu/MoreMenu.tsx b/packages/core/src/MoreMenu/MoreMenu.tsx index 5d56b05c47d57..1a37af3824f91 100644 --- a/packages/core/src/MoreMenu/MoreMenu.tsx +++ b/packages/core/src/MoreMenu/MoreMenu.tsx @@ -30,7 +30,8 @@ import type {LayerAlignment, LayerPlacement} from '../Layer'; import type {ButtonVariant, ButtonSize} from '../Button'; import type {BaseProps} from '../BaseProps'; import {stableClassName} from '../naming'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import moreMenuMessages from '../i18n/generated-locales/en/moreMenu.generated'; export interface MoreMenuProps extends Pick< BaseProps, @@ -144,7 +145,7 @@ export function MoreMenu({ 'data-testid': testId, ref, }: MoreMenuProps) { - const t = useTranslator(); + const t = useComponentTranslator(moreMenuMessages); const label = labelFromProps ?? t('@astryx.moreMenu.label'); const size = useSize(sizeProp, 'md'); const moreIcon = useIcon('moreHorizontal'); diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx index 192d85440ed37..6d6b28efae5e0 100644 --- a/packages/core/src/MultiSelector/MultiSelector.tsx +++ b/packages/core/src/MultiSelector/MultiSelector.tsx @@ -105,12 +105,24 @@ import {groupStyles, inputGroupItemProps} from '../InputGroup/groupStyles'; import {useInputGroup} from '../InputGroup/InputGroupContext'; import {InputGroupInternalContext} from '../InputGroup/InputGroupInternalContext'; import {VisuallyHidden} from '../VisuallyHidden'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import inputMessages from '../i18n/generated-locales/en/input.generated'; +import multiSelectorMessages from '../i18n/generated-locales/en/multiSelector.generated'; +import textInputMessages from '../i18n/generated-locales/en/textInput.generated'; +import spinnerMessages from '../i18n/generated-locales/en/spinner.generated'; import type {AdaptivePresentation} from '../hooks/useAdaptivePresentation'; import {SelectorBottomSheet} from '../Selector/SelectorBottomSheet'; import {useSelectorPresentation} from '../Selector/useSelectorPresentation'; import {selectorPresentationStyles} from '../Selector/selectorPresentation.stylex'; +// The English strings this module reads: the namespaces its keys name. +const messages = { + ...inputMessages, + ...multiSelectorMessages, + ...spinnerMessages, + ...textInputMessages, +}; + // Sentinel value for the select-all item in keyboard navigation const SELECT_ALL_VALUE = '__xds_select_all__'; @@ -1159,7 +1171,7 @@ export function MultiSelector({ controlClassName != null || controlStyle != null), ); - const t = useTranslator(); + const t = useComponentTranslator(messages); const pressable = usePressFeedback(); const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional}); const placeholder = diff --git a/packages/core/src/NumberInput/NumberInput.tsx b/packages/core/src/NumberInput/NumberInput.tsx index ee285dab0c6dc..0c449e8efde3e 100644 --- a/packages/core/src/NumberInput/NumberInput.tsx +++ b/packages/core/src/NumberInput/NumberInput.tsx @@ -223,7 +223,9 @@ import { } from '../Field/fieldParts'; import type {SizeValue} from '../utils/types'; import {themeProps} from '../utils/themeProps'; -import {useTranslator, useLocale} from '../i18n'; +import {useLocale} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import numberInputMessages from '../i18n/generated-locales/en/numberInput.generated'; import {formatEditableNumber} from './numberParser'; import {parseNumberInput, resolveNumberInputCommit} from './numberInputCommit'; @@ -587,7 +589,7 @@ export function NumberInput({ containerStyle, }); const pressable = usePressFeedback(); - const t = useTranslator(); + const t = useComponentTranslator(numberInputMessages); const locale = useLocale(); const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional}); const size = useSize(sizeProp, 'md'); diff --git a/packages/core/src/Outline/Outline.tsx b/packages/core/src/Outline/Outline.tsx index c6e6333c1313a..77fbce6ff258b 100644 --- a/packages/core/src/Outline/Outline.tsx +++ b/packages/core/src/Outline/Outline.tsx @@ -45,7 +45,8 @@ import {themeProps} from '../utils/themeProps'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex'; import {usePressFeedback} from '../hooks/usePressFeedback'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import outlineMessages from '../i18n/generated-locales/en/outline.generated'; import {useMergedRefs} from '../hooks/useMergedRefs'; export type {OutlineItem} from './types'; @@ -325,7 +326,7 @@ export function Outline({ ...props }: OutlineProps) { const pressable = usePressFeedback(); - const t = useTranslator(); + const t = useComponentTranslator(outlineMessages); const label = labelFromProps ?? t('@astryx.outline.label'); const rootRef = useRef(null); const LinkComponent = useLinkComponent(); diff --git a/packages/core/src/Pagination/Pagination.tsx b/packages/core/src/Pagination/Pagination.tsx index 3e161fc2d8b64..08ce957431c65 100644 --- a/packages/core/src/Pagination/Pagination.tsx +++ b/packages/core/src/Pagination/Pagination.tsx @@ -45,7 +45,8 @@ import {mergeProps, rtlStyles} from '../utils'; import type {BaseProps} from '../BaseProps'; import {themeProps} from '../utils/themeProps'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; -import {useTranslator} from '../i18n/useTranslator'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import paginationMessages from '../i18n/generated-locales/en/pagination.generated'; import type {PaginationVariantMap} from './index'; // ============================================================================= @@ -395,7 +396,7 @@ export function Pagination({ const [, startTransition] = useTransition(); // Resolve system strings once per render. Prop overrides win. - const t = useTranslator(); + const t = useComponentTranslator(paginationMessages); const label = labelFromProps ?? t('@astryx.pagination.label'); const firstLabel = t('@astryx.pagination.first'); const lastLabel = t('@astryx.pagination.last'); diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsx index 8788ac2f633c4..017cddb0ff638 100644 --- a/packages/core/src/Popover/Popover.tsx +++ b/packages/core/src/Popover/Popover.tsx @@ -64,7 +64,8 @@ import { preloadPopoverBottomSheet, } from './lazyPopoverBottomSheet'; import {Button} from '../Button'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import popoverMessages from '../i18n/generated-locales/en/popover.generated'; // ============================================================================= // Helpers @@ -510,7 +511,7 @@ export function Popover({ style, 'data-testid': testId, }: PopoverProps): ReactElement { - const t = useTranslator(); + const t = useComponentTranslator(popoverMessages); const wrapperRef = useRef(null); const measurementFrameRef = useRef(null); const [hasOverflow, setHasOverflow] = useState(false); diff --git a/packages/core/src/Popover/usePopover.tsx b/packages/core/src/Popover/usePopover.tsx index 42c9519d0ec56..e63d79d797f21 100644 --- a/packages/core/src/Popover/usePopover.tsx +++ b/packages/core/src/Popover/usePopover.tsx @@ -30,7 +30,8 @@ import { import {Button} from '../Button'; import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector'; import {rtlStyles} from '../utils'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import popoverMessages from '../i18n/generated-locales/en/popover.generated'; import {useDevWarning} from '../hooks/useDevWarning'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; import {mergeProps} from '../utils/mergeProps'; @@ -402,7 +403,7 @@ function usePopoverImplementation( isModal = true, } = options; - const t = useTranslator(); + const t = useComponentTranslator(popoverMessages); const closeButtonLabel = closeButtonLabelFromProps ?? t('@astryx.popover.close'); diff --git a/packages/core/src/PowerSearch/PowerSearch.test.tsx b/packages/core/src/PowerSearch/PowerSearch.test.tsx index 113c03e88fbaf..e1b5323ea9159 100644 --- a/packages/core/src/PowerSearch/PowerSearch.test.tsx +++ b/packages/core/src/PowerSearch/PowerSearch.test.tsx @@ -21,6 +21,13 @@ import { } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import {PowerSearch} from './PowerSearch'; +import { + InternationalizationContext, + translateWithCatalog, + type InternationalizationContextValue, +} from '../i18n/InternationalizationContext'; +import {getResolve} from '../i18n/resolve'; +import frFR from '../i18n/generated-locales/fr-FR.generated'; import {__resetLiveRegionsForTest} from '../hooks/useAnnounce'; import type {PowerSearchConfig, PowerSearchFilter} from './types'; import {TestIcon} from '../__tests__/TestIcon'; @@ -165,6 +172,123 @@ describe('PowerSearch', () => { expect(screen.getByRole('combobox')).toHaveFocus(); }); + it('resolves a caller-supplied operator i18nKey from any shipped namespace along the search, token and editor paths', async () => { + // `operator.i18nKey` is public and unrestricted; this one names a key + // outside PowerSearch's own namespace. No provider is mounted, so the + // whole shipped catalog is the only source — the fallback a caller had + // before components read their own slices. + const user = userEvent.setup(); + const callerKeyConfig: PowerSearchConfig = { + name: 'TestSearch', + fields: [ + { + key: 'status', + label: 'Status', + defaultOperator: 'apply', + operators: [ + { + key: 'apply', + i18nKey: '@astryx.table.filter.apply', + value: { + type: 'enum', + values: [{value: 'open', label: 'Open'}], + }, + }, + ], + }, + ], + }; + render(); + const input = screen.getByRole('combobox', {name: 'Search'}); + await user.type(input, 'status open'); + // Search suggestions. + await user.click( + await screen.findByRole('option', { + name: 'Status Apply Open', + hidden: true, + }), + ); + // The token. + const token = screen.getByText('Status: Apply'); + expect(token).toBeInTheDocument(); + // The edit popover's operator list. + await user.click(token); + expect( + await screen.findByRole('option', {name: 'Apply', hidden: true}), + ).toBeInTheDocument(); + }); + + it('under a raw context value, shipped operators read the same source as every other PowerSearch string; a caller key reads the context', async () => { + // A value rendered straight into the public context configures nothing a + // component reads (that path retires; InternationalizationProvider is the + // way to configure Astryx). So PowerSearch's own strings — the search box + // and the shipped `is` operator alike — stay English from the slice, one + // configuration for the whole component; a key the caller supplies from + // another namespace still follows the context's `translate`, as it did. + const user = userEvent.setup(); + const runtimeMessages = {'fr-FR': frFR}; + const value: InternationalizationContextValue = { + locale: 'fr-FR', + direction: 'ltr', + // The public value's `messages` is the authoring shape; the resolver + // takes the runtime one. Only `translate` is read by this test. + messages: Object.fromEntries( + Object.entries(runtimeMessages).map(([locale, catalog]) => [ + locale, + Object.fromEntries( + Object.entries(catalog).map(([key, defaultMessage]) => [ + key, + {defaultMessage}, + ]), + ), + ]), + ), + translate: translateWithCatalog(getResolve('fr-FR', runtimeMessages)), + }; + const mixedConfig: PowerSearchConfig = { + name: 'TestSearch', + fields: [ + { + key: 'status', + label: 'Status', + defaultOperator: 'is', + operators: [ + { + key: 'is', + i18nKey: '@astryx.powersearch.operator.is', + value: {type: 'enum', values: [{value: 'open', label: 'Open'}]}, + }, + { + key: 'apply', + i18nKey: '@astryx.table.filter.apply', + value: {type: 'enum', values: [{value: 'open', label: 'Open'}]}, + }, + ], + }, + ], + }; + render( + + + , + ); + // The search box: PowerSearch's own string, English from the slice. + const input = screen.getByRole('combobox', {name: 'Search'}); + await user.type(input, 'status open'); + // Shipped default operator: PowerSearch's own namespace, also English. + expect( + await screen.findByRole('option', {name: 'Status is Open', hidden: true}), + ).toBeInTheDocument(); + // Caller-supplied key from another namespace: the context's translate. + expect( + await screen.findByRole('option', { + name: 'Status Appliquer Open', + hidden: true, + }), + ).toBeInTheDocument(); + expect(screen.queryByRole('option', {name: /Status est Open/})).toBeNull(); + }); + it('clears all added filters when the clear button is clicked', async () => { const user = userEvent.setup(); render(); diff --git a/packages/core/src/PowerSearch/PowerSearch.tsx b/packages/core/src/PowerSearch/PowerSearch.tsx index 50f5154aac8fd..9926e7bc62ca3 100644 --- a/packages/core/src/PowerSearch/PowerSearch.tsx +++ b/packages/core/src/PowerSearch/PowerSearch.tsx @@ -58,7 +58,9 @@ import {PowerSearchEditPopover} from './PowerSearchEditPopover'; import {resolveOperatorLabel} from './resolveOperatorLabel'; import {themeProps} from '../utils/themeProps'; import {truncateCharacters} from '../utils/characters'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import {useCatalogTranslator} from '../i18n/useCatalogTranslator'; +import powersearchMessages from '../i18n/generated-locales/en/powersearch.generated'; import {useLocale} from '../i18n/useLocale'; import type {Locale} from '../i18n/types'; import type { @@ -585,7 +587,10 @@ export function PowerSearch({ const size = useSize(sizeProp, 'md'); const config = useInternalConfig(configProp); const searchSource = usePowerSearchSource(config, maxSearchResults); - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); + // A caller's own operator `i18nKey` reads the whole catalog; shipped + // defaults (`@astryx.powersearch.*`) read the slice like every fixed string. + const tCaller = useCatalogTranslator(); const locale = useLocale(); const label = labelFromProps ?? t('@astryx.powersearch.label'); const placeholder = @@ -647,7 +652,9 @@ export function PowerSearch({ return filters.map((filter, index) => { const field = config.getField(filter.field); const operator = config.getOperator(filter.field, filter.operator); - const resolvedOp = operator ? resolveOperatorLabel(operator, t) : ''; + const resolvedOp = operator + ? resolveOperatorLabel(operator, t, tCaller) + : ''; const operatorLabel = resolvedOp ? `: ${resolvedOp}` : ''; const valueStr = operator ? formatFilterValue( @@ -676,7 +683,7 @@ export function PowerSearch({ }, }; }); - }, [filters, config, maxTokenLength, timezoneID, t, locale]); + }, [filters, config, maxTokenLength, timezoneID, t, tCaller, locale]); // Handle tokenizer onChange (field selected from typeahead) const handleTokenizerChange = useCallback( @@ -866,7 +873,9 @@ export function PowerSearch({ // Default token rendering const fieldLabel = field?.label ?? ''; - const operatorLabel = operator ? resolveOperatorLabel(operator, t) : ''; + const operatorLabel = operator + ? resolveOperatorLabel(operator, t, tCaller) + : ''; const tokenLabel = `${fieldLabel}: ${operatorLabel}`.trim(); const adjustedMaxLength = Math.max( maxTokenLength - fieldLabel.length - operatorLabel.length, @@ -934,6 +943,7 @@ export function PowerSearch({ handleTokenClick, componentOverrides, t, + tCaller, ], ); diff --git a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx index 156e7a87fd279..65bc4ebf1a85f 100644 --- a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx +++ b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx @@ -19,7 +19,9 @@ import {Selector} from '../Selector'; import {HStack, VStack} from '../Stack'; import {Icon} from '../Icon'; import {TreeList, type TreeListItemData} from '../TreeList'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import {useCatalogTranslator} from '../i18n/useCatalogTranslator'; +import powersearchMessages from '../i18n/generated-locales/en/powersearch.generated'; import {isImeKeyEvent} from '../utils/ime'; import {spacingVars, typeScaleVars} from '../theme/tokens.stylex'; import { @@ -264,7 +266,10 @@ function NestedSubFilterRow({ maxMenuItems, isReadOnly, }: NestedSubFilterRowProps) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); + // A caller's own operator `i18nKey` reads the whole catalog; shipped + // defaults (`@astryx.powersearch.*`) read the slice like every fixed string. + const tCaller = useCatalogTranslator(); const fieldOptions = useMemo( () => config.getVisibleFields().map(field => ({ @@ -278,9 +283,9 @@ function NestedSubFilterRow({ const operators = config.getVisibleOperators(subFilter.field); return operators.map(op => ({ value: op.key, - label: resolveOperatorLabel(op, t), + label: resolveOperatorLabel(op, t, tCaller), })); - }, [config, subFilter.field, t]); + }, [config, subFilter.field, t, tCaller]); const currentOperator = subFilter.operator ? config.getOperator(subFilter.field, subFilter.operator) @@ -397,7 +402,7 @@ function NestedEditor({ maxMenuItems, isReadOnly, }: NestedEditorProps) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const [subFilters, setSubFilters] = useState(() => { if (partialFilter.value && partialFilter.value.type === 'nested') { return partialFilter.value.value.map(f => initEditableFilter(config, f)); @@ -661,7 +666,10 @@ export function PowerSearchEditPopover({ maxMenuItems, isReadOnly = false, }: PowerSearchEditPopoverProps) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); + // A caller's own operator `i18nKey` reads the whole catalog; shipped + // defaults (`@astryx.powersearch.*`) read the slice like every fixed string. + const tCaller = useCatalogTranslator(); const saveButtonLabel = saveButtonLabelFromProps ?? t('@astryx.powersearch.editor.apply'); const [partialFilter, setPartialFilter] = @@ -686,9 +694,9 @@ export function PowerSearchEditPopover({ const operators = config.getVisibleOperators(partialFilter.field); return operators.map(op => ({ value: op.key, - label: resolveOperatorLabel(op, t), + label: resolveOperatorLabel(op, t, tCaller), })); - }, [config, partialFilter.field, t]); + }, [config, partialFilter.field, t, tCaller]); // An "empty" operator takes no value, so choosing one completes the filter: // save it from the choice itself, once, rather than reacting to the state. diff --git a/packages/core/src/PowerSearch/PowerSearchToken.test.tsx b/packages/core/src/PowerSearch/PowerSearchToken.test.tsx index d1ab8527f7f3a..23db52fd169db 100644 --- a/packages/core/src/PowerSearch/PowerSearchToken.test.tsx +++ b/packages/core/src/PowerSearch/PowerSearchToken.test.tsx @@ -101,6 +101,20 @@ describe('PowerSearchToken', () => { expect(screen.getByText('Status: contains')).toBeInTheDocument(); }); + it('resolves a caller-supplied i18nKey from any shipped namespace, with no provider mounted', () => { + // `operator.i18nKey` is public and unrestricted: a caller may name any + // `@astryx.*` key, not only PowerSearch's own. The whole catalog stays + // the fallback for it even though the token's fixed strings read a slice. + renderToken({ + operator: { + key: 'apply', + i18nKey: '@astryx.table.filter.apply', + value: {type: 'string'}, + }, + }); + expect(screen.getByText('Status: Apply')).toBeInTheDocument(); + }); + it('renders the formatted value in its own element beside the label', () => { const {container} = renderToken({value: {type: 'string', value: 'open'}}); const label = screen.getByText('Status: is'); diff --git a/packages/core/src/PowerSearch/PowerSearchToken.tsx b/packages/core/src/PowerSearch/PowerSearchToken.tsx index cd55ba5a800e6..974c741c539f6 100644 --- a/packages/core/src/PowerSearch/PowerSearchToken.tsx +++ b/packages/core/src/PowerSearch/PowerSearchToken.tsx @@ -12,7 +12,9 @@ import React from 'react'; import * as stylex from '@stylexjs/stylex'; import {Token} from '../Token'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import {useCatalogTranslator} from '../i18n/useCatalogTranslator'; +import powersearchMessages from '../i18n/generated-locales/en/powersearch.generated'; import {useLocale} from '../i18n/useLocale'; import {fontWeightVars} from '../theme/tokens.stylex'; import {formatFilterValue} from './formatFilterValue'; @@ -44,11 +46,14 @@ export function PowerSearchToken({ isDisabled, }: PowerSearchTokenProps) { const config = useInternalConfig(configProp); - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); + // A caller's own operator `i18nKey` reads the whole catalog; shipped + // defaults (`@astryx.powersearch.*`) read the slice like every fixed string. + const tCaller = useCatalogTranslator(); const locale = useLocale(); const fieldLabel = field.label; - const resolvedOperatorLabel = resolveOperatorLabel(operator, t); + const resolvedOperatorLabel = resolveOperatorLabel(operator, t, tCaller); const operatorLabel = resolvedOperatorLabel ? `: ${resolvedOperatorLabel}` : ''; diff --git a/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx b/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx index 894c9ac7138ef..71534cff15091 100644 --- a/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx +++ b/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx @@ -45,7 +45,9 @@ import {TimeInput} from '../TimeInput'; import {Selector} from '../Selector'; import {Tokenizer} from '../Tokenizer'; import {Typeahead} from '../Typeahead'; -import {useLocale, useTranslator} from '../i18n'; +import {useLocale} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import powersearchMessages from '../i18n/generated-locales/en/powersearch.generated'; export interface PowerSearchValueEditorProps { operatorValue: OperatorValue; @@ -114,7 +116,7 @@ function StringEditor({ maxMenuItems?: number; isDisabled?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const currentValue = filterValue?.type === 'string' ? filterValue.value : ''; // When a searchSource is provided, render a typeahead instead of a plain @@ -172,7 +174,7 @@ function StringListEditor({ maxMenuItems?: number; isDisabled?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const currentValue: SearchableItem[] = useMemo(() => { if (filterValue?.type !== 'string_list') { return []; @@ -293,7 +295,7 @@ function IntegerEditor({ onEnter?: () => void; isDisabled?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const currentValue = filterValue?.type === 'integer' ? filterValue.value : undefined; const handlers = useNumberEditorHandlers({ @@ -338,7 +340,7 @@ function FloatEditor({ onEnter?: () => void; isDisabled?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const currentValue = filterValue?.type === 'float' ? filterValue.value : undefined; const handlers = useNumberEditorHandlers({ @@ -380,7 +382,7 @@ function TimeEditor({ onChange: (value: FilterValue) => void; isDisabled?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const currentValue = filterValue?.type === 'time' ? (filterValue.value as ISOTimeString) @@ -413,7 +415,7 @@ function DateAbsoluteEditor({ onChange: (value: FilterValue) => void; isDisabled?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); // Convert unixSeconds to ISO date string for the date input const currentValue = useMemo(() => { if (filterValue?.type !== 'date_absolute') { @@ -450,7 +452,7 @@ function DateRelativeEditor({ onChange: (value: FilterValue, shouldSave?: boolean) => void; isDisabled?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const currentValue = filterValue?.type === 'date_relative' ? filterValue.value : undefined; @@ -510,7 +512,7 @@ function DateRangeEditor({ onChange: (value: FilterValue) => void; isDisabled?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const currentValue = useMemo(() => { if (filterValue?.type !== 'date_range') { return null; @@ -578,7 +580,7 @@ function EnumEditor({ onChange: (value: FilterValue, shouldSave?: boolean) => void; isDisabled?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const currentValue = filterValue?.type === 'enum' ? filterValue.value : undefined; @@ -616,7 +618,7 @@ function EnumListEditor({ onChange: (value: FilterValue) => void; isDisabled?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const items = useMemo( () => enumItemsToSearchableItems(operatorValue.values), [operatorValue.values], @@ -671,7 +673,7 @@ function EntityListEditor({ maxMenuItems?: number; isDisabled?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const source = useMemo>(() => { if (operatorValue.searchSource) { return operatorValue.searchSource; @@ -734,7 +736,7 @@ function CustomEditor({ onChange: (value: FilterValue) => void; isDisabled?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const currentValue = filterValue?.type === 'custom' ? filterValue.value : null; const EditorComponent = operatorValue.Editor; diff --git a/packages/core/src/PowerSearch/resolveOperatorLabel.ts b/packages/core/src/PowerSearch/resolveOperatorLabel.ts index 957b34412064a..3d3770dcb36ab 100644 --- a/packages/core/src/PowerSearch/resolveOperatorLabel.ts +++ b/packages/core/src/PowerSearch/resolveOperatorLabel.ts @@ -15,6 +15,13 @@ * Astryx's shipped default operators use the i18nKey variant; consumers * writing custom operators typically use the label variant. * + * Two translators serve the i18nKey variant. A key in PowerSearch's own + * namespace (`@astryx.powersearch.*`, every shipped default) resolves through + * the component translator, exactly like PowerSearch's other fixed strings, + * so the whole component reads one configuration. Any other key — a caller + * naming another Astryx namespace, or its own catalog — resolves through the + * whole-catalog translator, which keeps the shipped fallback the caller had. + * * SYNC: When modified, update: * - /packages/core/src/PowerSearch/types.ts (PowerSearchOperator type) * - /packages/core/src/PowerSearch/index.ts (re-export) @@ -23,12 +30,18 @@ import type {TranslatorFn} from '../i18n'; import type {PowerSearchOperator} from './types'; +/** The namespace of PowerSearch's own strings, shipped defaults included. */ +const OWN_NAMESPACE = '@astryx.powersearch.'; + export function resolveOperatorLabel( operator: PowerSearchOperator, t: TranslatorFn, + tCaller: TranslatorFn = t, ): string { if ('label' in operator && operator.label !== undefined) { return operator.label; } - return t(operator.i18nKey); + return operator.i18nKey.startsWith(OWN_NAMESPACE) + ? t(operator.i18nKey) + : tCaller(operator.i18nKey); } diff --git a/packages/core/src/PowerSearch/usePowerSearchSource.ts b/packages/core/src/PowerSearch/usePowerSearchSource.ts index df6b0d6d6de6c..22bdd9a12ae40 100644 --- a/packages/core/src/PowerSearch/usePowerSearchSource.ts +++ b/packages/core/src/PowerSearch/usePowerSearchSource.ts @@ -15,7 +15,9 @@ import {useMemo} from 'react'; import type {SearchSource} from '../Typeahead/types'; import {groupItems} from '../utils'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import {useCatalogTranslator} from '../i18n/useCatalogTranslator'; +import powersearchMessages from '../i18n/generated-locales/en/powersearch.generated'; import {resolveOperatorLabel} from './resolveOperatorLabel'; import type {InternalConfig} from './useInternalConfig'; import type {PowerSearchItem, PowerSearchOperator, FilterValue} from './types'; @@ -29,14 +31,17 @@ export function usePowerSearchSource( config: InternalConfig, maxTypedResults: number, ): SearchSource { - const t = useTranslator(); + // Shipped default operators (`@astryx.powersearch.*`) read the slice like + // every fixed string; a caller's own `i18nKey` reads the whole catalog. + const t = useComponentTranslator(powersearchMessages); + const tCaller = useCatalogTranslator(); return useMemo(() => { const allItems = buildFieldItems(config); // Resolver stays inline — `t()` internally memoizes both catalog // lookups and parsed IntlMessageFormat instances, so calling it // per keystroke is already O(1). const opLabel = (op: PowerSearchOperator): string => - resolveOperatorLabel(op, t); + resolveOperatorLabel(op, t, tCaller); return { search(query: string): PowerSearchItem[] { @@ -212,7 +217,7 @@ export function usePowerSearchSource( return allItems; }, }; - }, [config, t, maxTypedResults]); + }, [config, t, tCaller, maxTypedResults]); } interface ValueMatch { diff --git a/packages/core/src/Resizable/ResizeHandle.tsx b/packages/core/src/Resizable/ResizeHandle.tsx index 248e97df20020..b7e02323b3491 100644 --- a/packages/core/src/Resizable/ResizeHandle.tsx +++ b/packages/core/src/Resizable/ResizeHandle.tsx @@ -52,7 +52,8 @@ import { type ResizableProps, } from './useResizable'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import resizableMessages from '../i18n/generated-locales/en/resizable.generated'; import {useMergedRefs} from '../hooks/useMergedRefs'; const KEYBOARD_STEP = 10; @@ -450,7 +451,7 @@ export function ResizeHandle({ ref, ...props }: ResizeHandleProps) { - const t = useTranslator(); + const t = useComponentTranslator(resizableMessages); const label = labelFromProps ?? t('@astryx.resizable.handle.label'); const handleRef = useRef(null); // The pointer that owns the in-flight drag, plus the values its deltas are diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx index 77adf71c6ea98..7e1e263445cb7 100644 --- a/packages/core/src/Selector/Selector.tsx +++ b/packages/core/src/Selector/Selector.tsx @@ -99,12 +99,24 @@ import {groupStyles, inputGroupItemProps} from '../InputGroup/groupStyles'; import {useInputGroup} from '../InputGroup/InputGroupContext'; import {InputGroupInternalContext} from '../InputGroup/InputGroupInternalContext'; import {VisuallyHidden} from '../VisuallyHidden'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import inputMessages from '../i18n/generated-locales/en/input.generated'; +import selectorMessages from '../i18n/generated-locales/en/selector.generated'; +import textInputMessages from '../i18n/generated-locales/en/textInput.generated'; +import spinnerMessages from '../i18n/generated-locales/en/spinner.generated'; import type {AdaptivePresentation} from '../hooks/useAdaptivePresentation'; import {SelectorBottomSheet} from './SelectorBottomSheet'; import {useSelectorPresentation} from './useSelectorPresentation'; import {selectorPresentationStyles} from './selectorPresentation.stylex'; +// The English strings this module reads: the namespaces its keys name. +const messages = { + ...inputMessages, + ...selectorMessages, + ...spinnerMessages, + ...textInputMessages, +}; + const styles = stylex.create({ // Trigger container — the enhanced click target wrapping the combobox button and clear button as siblings triggerContainer: { @@ -946,7 +958,7 @@ function filterOptionsByQuery( export function Selector( props: SelectorProps, ) { - const t = useTranslator(); + const t = useComponentTranslator(messages); const pressable = usePressFeedback(); const { label, diff --git a/packages/core/src/SideNav/SideNav.tsx b/packages/core/src/SideNav/SideNav.tsx index 8a0dd84998ccb..4b5a85f3afde9 100644 --- a/packages/core/src/SideNav/SideNav.tsx +++ b/packages/core/src/SideNav/SideNav.tsx @@ -49,7 +49,8 @@ import {ResizeHandle} from '../Resizable/ResizeHandle'; import {themeProps} from '../utils/themeProps'; import {SizeProvider} from '../SizeContext/SizeContext'; import {useDevWarning} from '../hooks/useDevWarning'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import sideNavMessages from '../i18n/generated-locales/en/sideNav.generated'; import {useMergedRefs} from '../hooks/useMergedRefs'; // ============================================================================= @@ -427,7 +428,7 @@ export function SideNav({ handleRef, ...props }: SideNavProps) { - const t = useTranslator(); + const t = useComponentTranslator(sideNavMessages); // Parse collapsible prop const collapsibleConfig = typeof collapsible === 'object' ? collapsible : {}; const hasCollapseButton = collapsibleConfig.hasButton ?? true; diff --git a/packages/core/src/SideNav/SideNavCollapseButton.tsx b/packages/core/src/SideNav/SideNavCollapseButton.tsx index 01612794a7bd8..947c2efc65bb0 100644 --- a/packages/core/src/SideNav/SideNavCollapseButton.tsx +++ b/packages/core/src/SideNav/SideNavCollapseButton.tsx @@ -31,7 +31,8 @@ import { type SideNavImperativeCollapseHandle, } from './SideNavCollapseContext'; import {useAppShellMobile} from '../AppShell/AppShellMobileContext'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import sideNavCollapseButtonMessages from '../i18n/generated-locales/en/sideNavCollapseButton.generated'; import type {ElementSize} from '../SizeContext/SizeContext'; // ============================================================================= @@ -138,7 +139,7 @@ export function SideNavCollapseButton({ onClick: onClickProp, ...props }: SideNavCollapseButtonProps) { - const t = useTranslator(); + const t = useComponentTranslator(sideNavCollapseButtonMessages); const {isCollapsed, toggle, isCollapsible} = useSideNavCollapseState( collapsible, handleRef, diff --git a/packages/core/src/SideNav/SideNavHeading.tsx b/packages/core/src/SideNav/SideNavHeading.tsx index e38e2140f64bf..f2b9111e72253 100644 --- a/packages/core/src/SideNav/SideNavHeading.tsx +++ b/packages/core/src/SideNav/SideNavHeading.tsx @@ -49,7 +49,8 @@ import type {BaseProps} from '../BaseProps'; import {useMenuHover} from '../hooks/useMenuHover'; import {NavHeadingCloseContext} from '../NavMenu/NavMenuContext'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import sideNavMessages from '../i18n/generated-locales/en/sideNav.generated'; // ============================================================================= // Styles @@ -382,7 +383,7 @@ export function SideNavHeading({ ...props }: SideNavHeadingProps) { const pressable = usePressFeedback(); - const t = useTranslator(); + const t = useComponentTranslator(sideNavMessages); const LinkComponent = useLinkComponent(as); const {isCollapsed} = useSideNavCollapse(); const rootRef = useRef(null); diff --git a/packages/core/src/SideNav/SideNavItem.tsx b/packages/core/src/SideNav/SideNavItem.tsx index 02ee513331fca..76dae83a0c89a 100644 --- a/packages/core/src/SideNav/SideNavItem.tsx +++ b/packages/core/src/SideNav/SideNavItem.tsx @@ -74,7 +74,8 @@ import { import {useSideNavRenderMode} from './SideNavRenderContext'; import {useAppShellMobile} from '../AppShell/AppShellMobileContext'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import sideNavItemMessages from '../i18n/generated-locales/en/sideNavItem.generated'; import {useMergedRefs} from '../hooks/useMergedRefs'; // ============================================================================= @@ -513,7 +514,7 @@ export function SideNavItem({ // The row (or, collapsed, the trigger/link/button) is the pressable; the // expand toggle inside it is its own. const pressable = usePressFeedback(); - const t = useTranslator(); + const t = useComponentTranslator(sideNavItemMessages); const {isCollapsed} = useSideNavCollapse(); const renderMode = useSideNavRenderMode(); const {closeMobileNav} = useAppShellMobile(); diff --git a/packages/core/src/Spinner/Spinner.tsx b/packages/core/src/Spinner/Spinner.tsx index 7f7deddc90b6c..0e588d332e4ab 100644 --- a/packages/core/src/Spinner/Spinner.tsx +++ b/packages/core/src/Spinner/Spinner.tsx @@ -4,7 +4,7 @@ /** * @file Spinner.tsx - * @input Uses React, i18n (useTranslator), StyleX, SVG rendering + * @input Uses React, i18n (useComponentTranslator), StyleX, SVG rendering * @output Exports Spinner component, SpinnerProps, SpinnerSize, SpinnerShade types * @position Core implementation of spinner loading indicator * @@ -22,7 +22,8 @@ import {colorVars, durationVars, spacingVars} from '../theme/tokens.stylex'; import type {BaseProps} from '../BaseProps'; import {Text} from '../Text/Text'; import {mergeProps} from '../utils'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import spinnerMessages from '../i18n/generated-locales/en/spinner.generated'; import {themeProps} from '../utils/themeProps'; // ============================================================================= @@ -509,7 +510,7 @@ export function Spinner({ const arcLength = circumference * ARC_FRACTION; const hasLabel = label != null; const labelId = useId(); - const t = useTranslator(); + const t = useComponentTranslator(spinnerMessages); // When a visible string label renders (and no explicit aria-label is set), // name the status element from the visible Text via aria-labelledby instead diff --git a/packages/core/src/Stepper/Step.tsx b/packages/core/src/Stepper/Step.tsx index 30a239d56c250..2101cc981ee10 100644 --- a/packages/core/src/Stepper/Step.tsx +++ b/packages/core/src/Stepper/Step.tsx @@ -63,7 +63,8 @@ import {usePressFeedback} from '../hooks/usePressFeedback'; import type {BaseProps} from '../BaseProps'; import {Icon} from '../Icon'; import {VisuallyHidden} from '../VisuallyHidden'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import stepMessages from '../i18n/generated-locales/en/step.generated'; import {useStepperInternalContext} from './StepperContext'; import {stepMarker} from './stepper.stylex'; import type {StepStatus} from './StepStatus'; @@ -1012,7 +1013,7 @@ export function Step({ ...rest }: StepProps) { const pressable = usePressFeedback(); - const t = useTranslator(); + const t = useComponentTranslator(stepMessages); const ctx = useStepperInternalContext(); const { activeStep, diff --git a/packages/core/src/Stepper/Stepper.tsx b/packages/core/src/Stepper/Stepper.tsx index e11aad483d384..6e342b7d2ab41 100644 --- a/packages/core/src/Stepper/Stepper.tsx +++ b/packages/core/src/Stepper/Stepper.tsx @@ -41,7 +41,8 @@ import type {BaseProps} from '../BaseProps'; import {themeProps} from '../utils'; import {Icon} from '../Icon'; import {IconButton} from '../IconButton'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import stepperMessages from '../i18n/generated-locales/en/stepper.generated'; import { StepperContext, StepperInternalContext, @@ -246,7 +247,7 @@ export function Stepper({ ref, ...rest }: StepperProps) { - const t = useTranslator(); + const t = useComponentTranslator(stepperMessages); const label = labelFromProps ?? t('@astryx.stepper.label'); const minimumStepWidth = horizontalOptions?.minimumStepWidth ?? DEFAULT_MIN_STEP_WIDTH; diff --git a/packages/core/src/Switch/Switch.tsx b/packages/core/src/Switch/Switch.tsx index d3249eb9b3fb7..1e3059db19a43 100644 --- a/packages/core/src/Switch/Switch.tsx +++ b/packages/core/src/Switch/Switch.tsx @@ -4,7 +4,7 @@ /** * @file Switch.tsx - * @input Uses React, useId, ChangeEvent, FieldLabel, FieldStatus, IconType, InputStatus, useTooltip, i18n (useTranslator) + * @input Uses React, useId, ChangeEvent, FieldLabel, FieldStatus, IconType, InputStatus, useTooltip, i18n (useComponentTranslator) * @output Exports Switch component, SwitchProps, SwitchLabelPosition, SwitchLabelSpacing * @position Core implementation; consumed by index.ts, tested by Switch.test.tsx * @@ -51,7 +51,8 @@ import type {SizeValue} from '../utils/types'; import {themeProps} from '../utils/themeProps'; import {useAnnounce} from '../hooks/useAnnounce'; import {useResolvedRequired} from '../hooks/useResolvedRequired'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import switchMessages from '../i18n/generated-locales/en/switch.generated'; import {useMergedRefs} from '../hooks/useMergedRefs'; import {usePressFeedback} from '../hooks/usePressFeedback'; @@ -573,7 +574,7 @@ export function Switch({ 'aria-labelledby': ariaLabelledByProp, ...rest }: SwitchProps) { - const t = useTranslator(); + const t = useComponentTranslator(switchMessages); const id = useId(); // The row is the pressable: the input, the track and the label all sit // inside it, and the pressed arms above read the row's scope marker. diff --git a/packages/core/src/TabList/TabList.tsx b/packages/core/src/TabList/TabList.tsx index 65b8c12086ab5..5e9d7e5501a00 100644 --- a/packages/core/src/TabList/TabList.tsx +++ b/packages/core/src/TabList/TabList.tsx @@ -56,7 +56,8 @@ import {themeProps} from '../utils/themeProps'; import {observeResize} from '../utils/sharedResizeObserver'; import {devWarn} from '../utils/devWarning'; import {focusOutlineProps} from '../utils/focusOutline.stylex'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import tabListMessages from '../i18n/generated-locales/en/tabList.generated'; import {useMergedRefs} from '../hooks/useMergedRefs'; /** @@ -413,7 +414,7 @@ export function TabList({ [EDGE_COMP_ATTR]: _edgeCompAttr, ...restProps }: TabListProps) { - const t = useTranslator(); + const t = useComponentTranslator(tabListMessages); const ariaLabel = ariaLabelFromProps ?? t('@astryx.tabList.label'); const size = useSize(sizeProp, 'md'); const hasScroll = overflow !== 'visible'; diff --git a/packages/core/src/Table/BaseTable.tsx b/packages/core/src/Table/BaseTable.tsx index 92ce3b827cab3..6c45cf2a0dfc1 100644 --- a/packages/core/src/Table/BaseTable.tsx +++ b/packages/core/src/Table/BaseTable.tsx @@ -47,7 +47,8 @@ import {devError} from '../utils/devWarning'; import {EmptyState} from '../EmptyState'; import {Text} from '../Text'; import {themeProps} from '../utils/themeProps'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import tableMessages from '../i18n/generated-locales/en/table.generated'; const styles = stylex.create({ table: { @@ -357,7 +358,7 @@ function BaseTableInner>({ ref, ...rest }: BaseTableProps & {ref?: Ref}): ReactElement { - const t = useTranslator(); + const t = useComponentTranslator(tableMessages); // Use stable empty array when no plugins provided const plugins = pluginsProp ?? (EMPTY_PLUGINS as TablePlugin[]); diff --git a/packages/core/src/Table/Table.tsx b/packages/core/src/Table/Table.tsx index 14cb8ef8bb150..a596720171bd7 100644 --- a/packages/core/src/Table/Table.tsx +++ b/packages/core/src/Table/Table.tsx @@ -33,7 +33,8 @@ import type { TableRenderProps, } from './types'; import type {StyleXStyles} from '../theme/types'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import tableMessages from '../i18n/generated-locales/en/table.generated'; // ============================================================================= // Table Types @@ -150,7 +151,7 @@ function TableScrollWrapper({ beforeTable?: React.ReactNode; afterTable?: React.ReactNode; }) { - const t = useTranslator(); + const t = useComponentTranslator(tableMessages); const label = t('@astryx.table.label'); const {getViewportProps, getContentProps, state} = useScrollableArea({ axis: 'inline', diff --git a/packages/core/src/Table/TableSelectionToolbar.tsx b/packages/core/src/Table/TableSelectionToolbar.tsx index f884beb859da3..32d73d7c505e9 100644 --- a/packages/core/src/Table/TableSelectionToolbar.tsx +++ b/packages/core/src/Table/TableSelectionToolbar.tsx @@ -13,7 +13,8 @@ import type {ReactNode} from 'react'; import {Button} from '../Button'; import {Toolbar} from '../Toolbar'; import type {ToolbarProps} from '../Toolbar'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import tableMessages from '../i18n/generated-locales/en/table.generated'; import type {TableSelectionState} from './plugins/selection/useTableSelectionState'; export interface TableSelectionToolbarProps extends Omit< @@ -45,7 +46,7 @@ export function TableSelectionToolbar({ variant = 'muted', ...toolbarProps }: TableSelectionToolbarProps): ReactNode { - const t = useTranslator(); + const t = useComponentTranslator(tableMessages); const label = labelFromProps ?? t('@astryx.table.selection.bulkActionsLabel'); const clearLabel = clearLabelFromProps ?? t('@astryx.table.selection.clearAll'); diff --git a/packages/core/src/Table/plugins/filtering/useTableFiltering.tsx b/packages/core/src/Table/plugins/filtering/useTableFiltering.tsx index 92b652f9b8842..43d69283012fe 100644 --- a/packages/core/src/Table/plugins/filtering/useTableFiltering.tsx +++ b/packages/core/src/Table/plugins/filtering/useTableFiltering.tsx @@ -49,7 +49,10 @@ import type { HeaderCellRenderProps, } from '../../types'; import {proportional} from '../../columnUtils'; -import {useLocale, useTranslator} from '../../../i18n'; +import {useLocale} from '../../../i18n'; +import {useComponentTranslator} from '../../../i18n/useComponentTranslator'; +import tableMessages from '../../../i18n/generated-locales/en/table.generated'; +import tableFilteringMessages from '../../../i18n/generated-locales/en/tableFiltering.generated'; import type { PowerSearchConfig, PowerSearchField, @@ -65,6 +68,9 @@ import type { EntityListOperatorValue, } from '../../../PowerSearch/types'; +// The English strings this module reads: the namespaces its keys name. +const messages = {...tableMessages, ...tableFilteringMessages}; + // ============================================================================= // Filter Value Types // ============================================================================= @@ -430,7 +436,7 @@ function TextFilterControl({ size: 'sm' | 'md'; hasClear?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(messages); const store = useFilterStore(); const config = store.getConfig(); const value = config.filters[columnKey]; @@ -540,7 +546,7 @@ function NumberFilterControl({ size: 'sm' | 'md'; hasClear?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(messages); const store = useFilterStore(); const config = store.getConfig(); const value = config.filters[columnKey]; @@ -615,7 +621,7 @@ function SelectorFilterControl({ size: 'sm' | 'md'; hasClear?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(messages); const store = useFilterStore(); const config = store.getConfig(); const value = config.filters[columnKey]; @@ -679,7 +685,7 @@ function MultiSelectorFilterControl({ size: 'sm' | 'md'; hasClear?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(messages); const store = useFilterStore(); const config = store.getConfig(); const value = config.filters[columnKey]; @@ -721,7 +727,7 @@ function DateFilterControl({ size: 'sm' | 'md'; hasClear?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(messages); const store = useFilterStore(); const value = store.getConfig().filters[columnKey] as string | undefined; @@ -750,7 +756,7 @@ function TimeFilterControl({ size: 'sm' | 'md'; hasClear?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(messages); const store = useFilterStore(); const value = store.getConfig().filters[columnKey] as string | undefined; @@ -781,7 +787,7 @@ function StringListFilterControl({ size: 'sm' | 'md'; hasClear?: boolean; }) { - const t = useTranslator(); + const t = useComponentTranslator(messages); const store = useFilterStore(); const value = (store.getConfig().filters[columnKey] as string[] | undefined) ?? []; @@ -923,7 +929,7 @@ function PopoverFilterTrigger({ header: string; operatorValue: OperatorValue; }) { - const t = useTranslator(); + const t = useComponentTranslator(messages); const store = useFilterStore(); const config = store.getConfig(); const value = config.filters[columnKey]; diff --git a/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx index 0d96ccfa429de..6cce4b63bc633 100644 --- a/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx +++ b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx @@ -21,7 +21,8 @@ import { } from '../../../theme/tokens.stylex'; import {Icon} from '../../../Icon'; import type {TablePlugin} from '../../types'; -import {useTranslator} from '../../../i18n'; +import {useComponentTranslator} from '../../../i18n/useComponentTranslator'; +import tableGroupedRowsMessages from '../../../i18n/generated-locales/en/tableGroupedRows.generated'; // A synthetic group-header row injected into the flattened data. Real rows // never carry this marker. @@ -272,7 +273,7 @@ const styles = stylex.create({ export function useTableGroupedRows>( config: UseTableGroupedRowsConfig, ): UseTableGroupedRowsResult { - const t = useTranslator(); + const t = useComponentTranslator(tableGroupedRowsMessages); const { data, groupBy, diff --git a/packages/core/src/Table/plugins/pagination/useTablePagination.tsx b/packages/core/src/Table/plugins/pagination/useTablePagination.tsx index fcc2994043da6..f031de75847f9 100644 --- a/packages/core/src/Table/plugins/pagination/useTablePagination.tsx +++ b/packages/core/src/Table/plugins/pagination/useTablePagination.tsx @@ -22,7 +22,8 @@ import {spacingVars} from '../../../theme/tokens.stylex'; import {Pagination} from '../../../Pagination'; import type {PaginationProps} from '../../../Pagination'; import type {TablePlugin} from '../../types'; -import {useTranslator} from '../../../i18n'; +import {useComponentTranslator} from '../../../i18n/useComponentTranslator'; +import tableMessages from '../../../i18n/generated-locales/en/table.generated'; // ============================================================================= // Styles @@ -197,7 +198,7 @@ export interface UseTablePaginationConfig { export function useTablePagination>( config: UseTablePaginationConfig, ): TablePlugin { - const t = useTranslator(); + const t = useComponentTranslator(tableMessages); const { page, onPageChange, diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx index 095a49fae8b73..ca84a793e6f97 100644 --- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx +++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx @@ -5,7 +5,7 @@ /** * @file useTableRowExpansion.tsx * @input React, StyleX, Icon, Table types, table context (density), i18n - * (useTranslator) + * (useComponentTranslator) * @output Exports useTableRowExpansion hook + config type * @position Row-expansion plugin (detail panel); consumed by Table via plugins prop * @@ -41,7 +41,8 @@ import {Icon} from '../../../Icon'; import {VisuallyHidden} from '../../../VisuallyHidden'; import {resolveContextActions} from '../../tableContextMenu'; import {useTableContext} from '../../useTableCellStyles'; -import {useTranslator} from '../../../i18n'; +import {useComponentTranslator} from '../../../i18n/useComponentTranslator'; +import tableRowExpansionMessages from '../../../i18n/generated-locales/en/tableRowExpansion.generated'; import {rtlStyles} from '../../../utils'; import { hasInteractiveAncestor, @@ -314,7 +315,7 @@ function ExpansionChevron({ isExpanded: boolean; onToggle: () => void; }) { - const t = useTranslator(); + const t = useComponentTranslator(tableRowExpansionMessages); const ctx = useTableContext(); return (