From 5e4c993e729e4e83c05ee1fba6bcd2594fbaa5e5 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 11 Oct 2026 16:36:48 -0700 Subject: [PATCH 01/36] perf(i18n): let a component carry only its own English strings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit resolve.ts imported the whole shipped English catalog (408 keys, 78 component namespaces, 22.6 KB raw / 6 KB gzip) as the fallback of every translation, so any app rendering one component that calls t() bundled the strings of the other hundred. This is the runtime half, with no change for an app yet; the components move to it in a follow-up. The generator also emits generated-locales/en/.generated.ts, one per key namespace, and the exports map gives ./locales/en/* a null target so the slices stay the package's own while every whole catalog stays importable. resolve.ts imports no catalog: the English fallback is the caller's, passed per call. useComponentTranslator(slice) is the hook a core component renders with; it, useLocale, useDirection and useCollator read a new internal TranslationRuntimeContext that carries the resolver and no catalog. The public InternationalizationContext keeps its shape and its `translate` bound to the whole catalog, the provider writes both, and useTranslator() reads the public one as before, so a consumer's direct `translate(key)` and `useTranslator()` behave exactly as today; the provider's messages and overrides still win over the fallback. check:i18n-catalog gains the slice-coverage rule: every @astryx..* key a slice-rendering file reads must belong to a namespace its slice carries, and a file handed `t` is covered by its component directory's slices. Tests pin the resolver, the hook, the public context boundary (a direct `translate` of a core key with no provider → the English string), the compiled import graph of the runtime, the export surface through Node's package resolution, the generator split and the coverage rule. CONTRIBUTING and the hardcoded-string lint messages describe the component pattern; the CLI's i18n guide keeps to what a caller can use. --- .changeset/i18n-en-namespace-slices.md | 8 + CONTRIBUTING.md | 34 ++- .../no-hardcoded-i18n-string.js | 61 +++-- .../docs/tree/i18n-rtl-and-testing.doc.mjs | 4 +- packages/core/package.json | 1 + .../src/i18n/InternationalizationContext.ts | 43 ++-- .../src/i18n/InternationalizationProvider.tsx | 32 ++- .../src/i18n/TranslationRuntimeContext.ts | 46 ++++ .../i18n/__tests__/i18n.source-build.test.mjs | 71 ++++++ .../i18n/__tests__/locale-exports.test.mjs | 74 ++++++ .../core/src/i18n/__tests__/resolve.test.ts | 58 ++++- packages/core/src/i18n/resolve.ts | 26 +- packages/core/src/i18n/useCollator.ts | 8 +- .../src/i18n/useComponentTranslator.test.tsx | 147 +++++++++++ .../core/src/i18n/useComponentTranslator.ts | 56 +++++ packages/core/src/i18n/useDirection.ts | 8 +- packages/core/src/i18n/useLocale.ts | 8 +- packages/core/src/i18n/useTranslator.ts | 16 +- scripts/check-i18n-catalog.mjs | 231 +++++++++++++++++- scripts/check-i18n-catalog.test.mjs | 145 +++++++++++ scripts/generate-i18n-runtime.mjs | 99 +++++++- scripts/generate-i18n-runtime.test.mjs | 47 ++++ scripts/sync-exports.js | 6 + 23 files changed, 1120 insertions(+), 109 deletions(-) create mode 100644 .changeset/i18n-en-namespace-slices.md create mode 100644 packages/core/src/i18n/TranslationRuntimeContext.ts create mode 100644 packages/core/src/i18n/__tests__/i18n.source-build.test.mjs create mode 100644 packages/core/src/i18n/__tests__/locale-exports.test.mjs create mode 100644 packages/core/src/i18n/useComponentTranslator.test.tsx create mode 100644 packages/core/src/i18n/useComponentTranslator.ts diff --git a/.changeset/i18n-en-namespace-slices.md b/.changeset/i18n-en-namespace-slices.md new file mode 100644 index 0000000000000..4c1873055bf12 --- /dev/null +++ b/.changeset/i18n-en-namespace-slices.md @@ -0,0 +1,8 @@ +--- +'@astryxdesign/core': patch +'@astryxdesign/cli': patch +--- + +[chore] The i18n runtime can hand a component its own English strings. The English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice; the components themselves move to it in a follow-up, so nothing changes for an app yet. `useTranslator()` and `InternationalizationContext` are unchanged and still resolve every `@astryx.*` key; an `InternationalizationProvider`'s `messages` and `overrides` still win; the slices themselves are not importable. One undocumented path moves: a value handed straight to `InternationalizationContext` without the provider no longer reaches `useLocale`, `useDirection` and `useCollator`, which read the provider's runtime context; mount `InternationalizationProvider`. + +@vjeux diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 70749bdd90594..cdaebd90b9c51 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -291,24 +291,36 @@ 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 +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. 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 a component inside `packages/core` +renders with its slice instead; packages that depend on core (`lab`, +`richtext`) use `useTranslator()`. + 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: @@ -346,8 +358,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 3df9f81b8b208..cfdb10f06ebf4 100644 --- a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js +++ b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js @@ -111,15 +111,15 @@ const ARIA_TEXT_ATTRS = new Set([ * one of these is flagged. */ const SUFFIX_PATTERNS = [ - /Label$/, // saveButtonLabel, cancelLabel, previousLabel, ... - /Text$/, // emptySearchText, helperText, errorText, ... - /Placeholder$/,// searchPlaceholder, timePlaceholder, ... - /Title$/, // dialogTitle, ... - /Message$/, // disabledMessage, errorMessage, ... - /Tooltip$/, // ... - /Hint$/, // ... - /Description$/,// ... - /Summary$/, // ... + /Label$/, // saveButtonLabel, cancelLabel, previousLabel, ... + /Text$/, // emptySearchText, helperText, errorText, ... + /Placeholder$/, // searchPlaceholder, timePlaceholder, ... + /Title$/, // dialogTitle, ... + /Message$/, // disabledMessage, errorMessage, ... + /Tooltip$/, // ... + /Hint$/, // ... + /Description$/, // ... + /Summary$/, // ... ]; function isUserFacingName(name) { @@ -154,7 +154,11 @@ function looksUserFacing(value) { return false; } // All-caps enum constant like `IS_ANY_OF` - if (value === value.toUpperCase() && /[A-Z_]/.test(value) && !/\s/.test(value)) { + if ( + value === value.toUpperCase() && + /[A-Z_]/.test(value) && + !/\s/.test(value) + ) { return false; } // Single lowercase word (identifier-shaped: `contains`, `email`, `foo123`) @@ -227,8 +231,20 @@ function reportUserFacingLiteralsIn(expr, name, context, isDefault, opts = {}) { } return; case 'ConditionalExpression': - reportUserFacingLiteralsIn(expr.consequent, name, context, isDefault, opts); - reportUserFacingLiteralsIn(expr.alternate, name, context, isDefault, opts); + reportUserFacingLiteralsIn( + expr.consequent, + name, + context, + isDefault, + opts, + ); + reportUserFacingLiteralsIn( + expr.alternate, + name, + context, + isDefault, + opts, + ); return; case 'LogicalExpression': // Only the right side can be a fallback/default string; the left is a @@ -247,21 +263,21 @@ 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 ' + - '`const {{name}} = {{name}}FromProps ?? t(\'..\');` inside the body.', + "`const {{name}} = {{name}}FromProps ?? t('..');` inside the body.", 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: [ { @@ -292,10 +308,7 @@ const rule = { // 1. JSX attribute string literals: JSXAttribute(node) { if (!node.name || node.name.type === 'JSXNamespacedName') return; - const name = - node.name.type === 'JSXIdentifier' - ? node.name.name - : null; + const name = node.name.type === 'JSXIdentifier' ? node.name.name : null; if (!isUserFacingName(name)) return; // 1. Bare string-literal attribute: @@ -334,8 +347,8 @@ const rule = { node.key.type === 'Identifier' ? node.key.name : node.key.type === 'Literal' - ? node.key.value - : null; + ? node.key.value + : null; if (!isUserFacingName(name)) return; if ( node.value.type !== 'Literal' || @@ -366,8 +379,8 @@ const rule = { property.key.type === 'Identifier' ? property.key.name : property.key.type === 'Literal' - ? property.key.value - : null; + ? property.key.value + : null; if (!isUserFacingName(name)) return; reportUserFacingLiteralsIn( node.right, 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..b39536b0856e0 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 @@ -122,7 +122,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, so an app bundles only the strings of the components it renders. Your own code reads any `@astryx.*` key with `useTranslator()`:", }, { type: 'code', @@ -137,7 +137,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/core/package.json b/packages/core/package.json index 8f02333465c35..76e4d83136b43 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/i18n/InternationalizationContext.ts b/packages/core/src/i18n/InternationalizationContext.ts index 80ebf11dc5ebe..bb681bb2f0306 100644 --- a/packages/core/src/i18n/InternationalizationContext.ts +++ b/packages/core/src/i18n/InternationalizationContext.ts @@ -4,9 +4,13 @@ /** * @file InternationalizationContext.ts - * @input React createContext, i18n types + * @input React createContext, i18n types, the whole shipped English catalog * @output Exports InternationalizationContext and InternationalizationContextValue - * @position Context definition for client-side locale + messages + * @position Context definition for client-side locale + messages: the public + * context a consumer reads. Its `translate` resolves every `@astryx.*` key, + * falling back to the shipped English catalog, so this module carries that + * catalog; the components inside this package read + * TranslationRuntimeContext instead and carry only their own slices. * * Separated from InternationalizationProvider.tsx so components can consume * the context without pulling in the full provider implementation. @@ -14,35 +18,44 @@ * * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/i18n/InternationalizationProvider.tsx - * - /packages/core/src/i18n/t.client.ts - * - /packages/core/src/i18n/useDirection.ts - * - /packages/core/src/i18n/useLocale.ts - * - /packages/core/src/i18n/useCollator.ts - * - /packages/core/src/i18n/getLocaleDirection.ts - * - /packages/core/src/i18n/index.ts + * - /packages/core/src/i18n/TranslationRuntimeContext.ts + * - /packages/core/src/i18n/useTranslator.ts */ import {createContext} from 'react'; -import {getResolve} from './resolve'; +import enCatalog from './generated-locales/en.generated'; import type {Locale, MessagesByLocale, Overrides} from './types'; +import type {MessageResolver} from './TranslationRuntimeContext'; +import {getResolve} from './resolve'; + +/** A translator over the whole shipped catalog: `translate(key, values?)`. */ +export type Translate = ( + key: string, + values?: Record, +) => string; export interface InternationalizationContextValue { locale: Locale; direction: 'ltr' | 'rtl'; messages: MessagesByLocale; overrides?: Overrides; - translate: ReturnType; + /** + * Resolves a key against the provider's catalogs and overrides, then the + * whole shipped English catalog. + */ + translate: Translate; +} + +/** Bind the whole English catalog as a resolver's fallback. */ +export function translateWithCatalog(resolve: MessageResolver): Translate { + return (key, values) => resolve(key, values, enCatalog); } -/** - * Default value falls through to the shipped en catalog in resolve(). - * A consumer that doesn't render a provider still gets English defaults. - */ export const InternationalizationContext = createContext({ locale: 'en', direction: 'ltr', messages: {}, - translate: getResolve('en', {}), + translate: translateWithCatalog(getResolve('en', {})), }); InternationalizationContext.displayName = 'InternationalizationContext'; diff --git a/packages/core/src/i18n/InternationalizationProvider.tsx b/packages/core/src/i18n/InternationalizationProvider.tsx index 84f2f91fc9f91..9fb78ed4a32fa 100644 --- a/packages/core/src/i18n/InternationalizationProvider.tsx +++ b/packages/core/src/i18n/InternationalizationProvider.tsx @@ -4,7 +4,7 @@ /** * @file InternationalizationProvider.tsx - * @input React, InternationalizationContext, i18n types + * @input React, InternationalizationContext, TranslationRuntimeContext, i18n types * @output Exports InternationalizationProvider component and props type * @position Provider component for astryx i18n locale + messages * @@ -20,7 +20,11 @@ */ import {useMemo, type ReactNode} from 'react'; -import {InternationalizationContext} from './InternationalizationContext'; +import { + InternationalizationContext, + translateWithCatalog, +} from './InternationalizationContext'; +import {TranslationRuntimeContext} from './TranslationRuntimeContext'; import {getLocaleDirection} from './getLocaleDirection'; import type { Locale, @@ -115,20 +119,34 @@ export function InternationalizationProvider({ children, }: InternationalizationProviderProps) { const direction = dir ?? getLocaleDirection(locale); - const value = useMemo(() => { + // One resolver, two readers: the components inside this package pass their + // own English slice to it; the public context binds the whole catalog. + const runtime = useMemo(() => { const providedMessages = messages ?? {}; return { locale, direction, messages: normalizeMessages(providedMessages), overrides, - translate: getResolve(locale, providedMessages, overrides), + resolve: getResolve(locale, providedMessages, overrides), }; }, [locale, direction, messages, overrides]); + const value = useMemo( + () => ({ + locale: runtime.locale, + direction: runtime.direction, + messages: runtime.messages, + overrides: runtime.overrides, + translate: translateWithCatalog(runtime.resolve), + }), + [runtime], + ); return ( - - {children} - + + + {children} + + ); } diff --git a/packages/core/src/i18n/TranslationRuntimeContext.ts b/packages/core/src/i18n/TranslationRuntimeContext.ts new file mode 100644 index 0000000000000..615b8721dee3c --- /dev/null +++ b/packages/core/src/i18n/TranslationRuntimeContext.ts @@ -0,0 +1,46 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file TranslationRuntimeContext.ts + * @input React createContext; getResolve + * @output Exports TranslationRuntimeContext — the locale, direction, catalogs + * and the message resolver that the components inside this package read — + * and its value type + * @position Internal to the i18n runtime. The public InternationalizationContext + * is this value plus a `translate` bound to the whole English catalog; the + * provider writes both. This module imports no catalog, so a component that + * reads it (useComponentTranslator, useLocale, useDirection, useCollator) + * bundles none; the whole catalog rides only with the public context, the + * provider and useTranslator. + * + * SYNC: When modified, update these files to stay in sync: + * - /packages/core/src/i18n/InternationalizationContext.ts + * - /packages/core/src/i18n/InternationalizationProvider.tsx + * - /packages/core/src/i18n/useComponentTranslator.ts + */ + +import {createContext} from 'react'; +import {getResolve} from './resolve'; +import type {Locale, MessagesByLocale, Overrides} from './types'; + +/** Resolves a key against the provider's catalogs, then the caller's English. */ +export type MessageResolver = ReturnType; + +export interface TranslationRuntimeContextValue { + locale: Locale; + direction: 'ltr' | 'rtl'; + messages: MessagesByLocale; + overrides?: Overrides; + resolve: MessageResolver; +} + +export const TranslationRuntimeContext = + createContext({ + locale: 'en', + direction: 'ltr', + messages: {}, + resolve: getResolve('en', {}), + }); +TranslationRuntimeContext.displayName = 'TranslationRuntimeContext'; diff --git a/packages/core/src/i18n/__tests__/i18n.source-build.test.mjs b/packages/core/src/i18n/__tests__/i18n.source-build.test.mjs new file mode 100644 index 0000000000000..bdef983f62212 --- /dev/null +++ b/packages/core/src/i18n/__tests__/i18n.source-build.test.mjs @@ -0,0 +1,71 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file i18n.source-build.test.mjs + * @input Uses Babel, the core build config, and the i18n runtime and a + * component source + * @output Verifies the shipped i18n runtime the components read imports no + * English catalog: the whole catalog rides only with the public context, + * the provider and useTranslator, and a component carries its own slice + * @position Regression test for the import graph of the shipped i18n modules + */ + +import fs from 'node:fs/promises'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {parseAsync, transformAsync} from '@babel/core'; +import {describe, expect, it} from 'vitest'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const CORE_ROOT = path.resolve(__dirname, '../../..'); +const SRC_ROOT = path.join(CORE_ROOT, 'src'); + +/** The relative specifiers a compiled module imports statically. */ +async function compiledStaticImportsOf(relativeFile) { + const file = path.join(SRC_ROOT, relativeFile); + const source = await fs.readFile(file, 'utf8'); + const result = await transformAsync(source, { + babelrc: false, + configFile: path.join(CORE_ROOT, 'babel.config.json'), + filename: file, + }); + const ast = await parseAsync(result.code, { + babelrc: false, + configFile: false, + filename: `${file}.js`, + sourceType: 'module', + }); + return ast.program.body + .filter(node => node.type === 'ImportDeclaration') + .map(node => node.source.value); +} + +const WHOLE_CATALOG = /generated-locales\/en\.generated\.js$/; + +describe('the shipped i18n runtime and the English catalog', () => { + it('the runtime a component reads imports no catalog', async () => { + for (const file of [ + 'i18n/resolve.ts', + 'i18n/TranslationRuntimeContext.ts', + 'i18n/useComponentTranslator.ts', + 'i18n/useLocale.ts', + 'i18n/useDirection.ts', + 'i18n/useCollator.ts', + ]) { + const imports = await compiledStaticImportsOf(file); + expect(imports, file).not.toContainEqual( + expect.stringMatching(/generated-locales/), + ); + expect(imports, file).not.toContain('./InternationalizationContext.js'); + } + }); + + it('the public context carries the whole catalog, and useTranslator reads it', async () => { + expect( + await compiledStaticImportsOf('i18n/InternationalizationContext.ts'), + ).toContainEqual(expect.stringMatching(WHOLE_CATALOG)); + expect(await compiledStaticImportsOf('i18n/useTranslator.ts')).toContain( + './InternationalizationContext.js', + ); + }); +}); diff --git a/packages/core/src/i18n/__tests__/locale-exports.test.mjs b/packages/core/src/i18n/__tests__/locale-exports.test.mjs new file mode 100644 index 0000000000000..f8217b91b4781 --- /dev/null +++ b/packages/core/src/i18n/__tests__/locale-exports.test.mjs @@ -0,0 +1,74 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file locale-exports.test.mjs + * @input The package's exports map, read through Node's own package + * resolution from a workspace app that depends on the package + * @output Verifies the public locale surface: every whole catalog under + * `@astryxdesign/core/locales/.generated.js` resolves, and the + * per-namespace English slices under `locales/en/` do not — they are the + * package's own, rendered through the internal useComponentTranslator + * @position Regression test for the `./locales/en/*` null export + */ + +import {spawnSync} from 'node:child_process'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {describe, expect, it} from 'vitest'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const REPO_ROOT = path.resolve(__dirname, '../../../../..'); + +/** + * Resolve a specifier the way a consumer's bundler or Node would: through + * the package's exports map, from a module inside a workspace app that + * depends on the package. `import.meta.resolve` consults the map only and + * never reads the target, so a built `dist/` is not needed: a matching + * pattern yields its target path, and a `null` target or no match is + * ERR_PACKAGE_PATH_NOT_EXPORTED. Run in a fresh process so the test's own + * module loader plays no part. + */ +function resolveFromConsumer(specifier) { + const script = ` + try { + console.log(JSON.stringify({ok: import.meta.resolve(${JSON.stringify(specifier)})})); + } catch (error) { + console.log(JSON.stringify({code: error.code})); + } + `; + const result = spawnSync( + process.execPath, + ['--input-type=module', '--eval', script], + { + cwd: path.join(REPO_ROOT, 'apps/sandbox'), + encoding: 'utf8', + }, + ); + if (result.status !== 0) { + throw new Error( + `node exited ${result.status} (${result.signal ?? 'no signal'}): ${result.stderr}`, + ); + } + return JSON.parse(result.stdout.trim()); +} + +describe('the public locale surface of @astryxdesign/core', () => { + it('resolves a whole catalog by locale', () => { + expect( + resolveFromConsumer('@astryxdesign/core/locales/en.generated.js').ok, + ).toMatch(/\/dist\/i18n\/generated-locales\/en\.generated\.js$/); + expect( + resolveFromConsumer('@astryxdesign/core/locales/fr-FR.generated.js').ok, + ).toMatch(/\/dist\/i18n\/generated-locales\/fr-FR\.generated\.js$/); + }); + + it('does not resolve a per-namespace English slice', () => { + for (const namespace of ['button', 'pagination']) { + expect( + resolveFromConsumer( + `@astryxdesign/core/locales/en/${namespace}.generated.js`, + ), + ).toEqual({code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'}); + } + }); +}); diff --git a/packages/core/src/i18n/__tests__/resolve.test.ts b/packages/core/src/i18n/__tests__/resolve.test.ts index 88b0e7efb9682..43a700fa9ee37 100644 --- a/packages/core/src/i18n/__tests__/resolve.test.ts +++ b/packages/core/src/i18n/__tests__/resolve.test.ts @@ -10,19 +10,27 @@ import {describe, expect, test, beforeEach, vi} from 'vitest'; import {__resetForTests, getResolve, resolveLocaleChain} from '../resolve'; +import enCatalog from '../generated-locales/en.generated'; +import paginationMessages from '../generated-locales/en/pagination.generated'; import type { Catalog, MessagesByLocale, Overrides, ProviderMessagesByLocale, + RuntimeCatalog, } from '../types'; +// The English fallback is the caller's (a component's slice, or the whole +// catalog through useTranslator); these cases resolve against the whole +// catalog, as useTranslator does, unless a case passes its own. const resolve = ( - ...[key, values, locale, messages, overrides]: [ - ...Parameters>, - ...Parameters, - ] -) => getResolve(locale, messages, overrides)(key, values); + key: string, + values: Record | undefined, + locale: Parameters[0], + messages: Parameters[1], + overrides: Parameters[2], + fallback: RuntimeCatalog | undefined = enCatalog, +) => getResolve(locale, messages, overrides)(key, values, fallback); // Reset caches between tests so warn-once and formatter cache don't bleed. beforeEach(() => { @@ -61,9 +69,7 @@ describe('resolveLocaleChain', () => { }); describe('resolve — basic lookup', () => { - test('falls back to shipped en catalog when locale is en and no messages passed', () => { - // The compact shipped English catalog is loaded at module initialization; - // Pagination keys should resolve. This asserts the module wiring end-to-end. + test('falls back to the shipped en catalog when locale is en and no messages passed', () => { const out = resolve( '@astryx.pagination.next', undefined, @@ -74,6 +80,42 @@ describe('resolve — basic lookup', () => { expect(out).toBe('Go to next page'); }); + test("resolves from a component's own namespace slice, and no further", () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + expect( + resolve( + '@astryx.pagination.next', + undefined, + 'en', + {}, + undefined, + paginationMessages, + ), + ).toBe('Go to next page'); + // A key of another namespace is not in the slice: the key comes back and + // the one-time warning fires, which is what check:i18n-catalog prevents. + expect( + resolve( + '@astryx.button.loading', + undefined, + 'en', + {}, + undefined, + paginationMessages, + ), + ).toBe('@astryx.button.loading'); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('missing key')); + warn.mockRestore(); + }); + + test('carries no English catalog of its own: with no fallback the key comes back', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + expect(getResolve('en', {})('@astryx.pagination.next', undefined)).toBe( + '@astryx.pagination.next', + ); + warn.mockRestore(); + }); + test('returns the key itself and warns for unknown key', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); const out = resolve( diff --git a/packages/core/src/i18n/resolve.ts b/packages/core/src/i18n/resolve.ts index 120551ef7d198..6d488afd7cba5 100644 --- a/packages/core/src/i18n/resolve.ts +++ b/packages/core/src/i18n/resolve.ts @@ -11,17 +11,25 @@ * 2. Per-locale override for a parent locale (pt-BR → pt) * 3. Shipped catalog entry for the exact locale * 4. Shipped catalog entry for a parent locale (pt-BR → pt) - * 5. Shipped en catalog (the source of truth, always present) + * 5. The caller's English fallback (the source of truth): a component's own + * namespace slice through useComponentTranslator, or the whole shipped en + * catalog through useTranslator. This module imports no catalog itself, + * so a bundle carries only the slices of the components it renders. * 6. The key itself (dev-visible fallback, warns once) * * SYNC: When modified, update these files to stay in sync: + * - /packages/core/src/i18n/useComponentTranslator.ts * - /packages/core/src/i18n/useTranslator.ts * - /packages/core/src/i18n/__tests__/resolve.test.ts */ import IntlMessageFormat from 'intl-messageformat'; -import type {Locale, Overrides, ProviderMessagesByLocale} from './types'; -import enCatalog from './generated-locales/en.generated'; +import type { + Locale, + Overrides, + ProviderMessagesByLocale, + RuntimeCatalog, +} from './types'; import {warnOnce, __resetDevWarnings} from '../utils/devWarning'; /** @@ -112,11 +120,17 @@ export function getResolve( ) { const lookup = getLookup(locale, messages, overrides); - return (key: string, values: Record | undefined) => { - const result = lookup[key] ?? enCatalog[key]; + return ( + key: string, + values: Record | undefined, + fallback?: RuntimeCatalog, + ) => { + const result = lookup[key] ?? fallback?.[key]; if (result === undefined) { // Fires ONLY when a key is missing from every source including the - // shipped `en` catalog — a real bug (typo, stale catalog, deleted key). + // caller's English fallback — a real bug (typo, stale catalog, deleted + // key, or a component reading a key outside its own namespace slice; + // `check:i18n-catalog` catches the last one before it ships). // Fallback to `en` from a non-en locale is expected and stays silent, // matching the FormatJS / i18next default. warnOnce( diff --git a/packages/core/src/i18n/useCollator.ts b/packages/core/src/i18n/useCollator.ts index 57cfbbe5de6c1..149c777a06728 100644 --- a/packages/core/src/i18n/useCollator.ts +++ b/packages/core/src/i18n/useCollator.ts @@ -4,7 +4,7 @@ /** * @file useCollator.ts - * @input InternationalizationContext (via use()), optional Intl.CollatorOptions + * @input TranslationRuntimeContext (via use()), optional Intl.CollatorOptions * @output A memoized Intl.Collator bound to the active locale * @position Public provider-aware string-comparison hook. Exported from the * i18n barrel for components, sibling packages, and consumers that need @@ -15,7 +15,7 @@ * useTranslator/useDirection/useLocale fallback. * * SYNC: When modified, update: - * - /packages/core/src/i18n/InternationalizationContext.ts + * - /packages/core/src/i18n/TranslationRuntimeContext.ts * - /packages/core/src/i18n/useLocale.ts * - /packages/core/src/i18n/useCollator.doc.mjs * - /packages/core/src/i18n/index.ts @@ -23,7 +23,7 @@ */ import {use, useMemo} from 'react'; -import {InternationalizationContext} from './InternationalizationContext'; +import {TranslationRuntimeContext} from './TranslationRuntimeContext'; /** * Returns an `Intl.Collator` for the active provider locale, memoized across @@ -36,7 +36,7 @@ import {InternationalizationContext} from './InternationalizationContext'; * ``` */ export function useCollator(options?: Intl.CollatorOptions): Intl.Collator { - const ctx = use(InternationalizationContext); + const ctx = use(TranslationRuntimeContext); return useMemo( () => new Intl.Collator(ctx.locale, options), [ctx.locale, options], diff --git a/packages/core/src/i18n/useComponentTranslator.test.tsx b/packages/core/src/i18n/useComponentTranslator.test.tsx new file mode 100644 index 0000000000000..2ab8b2db4cdd1 --- /dev/null +++ b/packages/core/src/i18n/useComponentTranslator.test.tsx @@ -0,0 +1,147 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file useComponentTranslator.test.tsx + * @input Uses vitest, @testing-library/react, useComponentTranslator, the + * i18n provider and two English namespace slices + * @output Verifies a component's translator resolves its own slice, the + * provider's catalog and overrides ahead of it, nothing outside it, and + * stays stable across renders + * @position Testing; validates useComponentTranslator.ts. Resolution order + * itself is covered by resolve.test.ts. + */ + +import {use} from 'react'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {renderHook} from '@testing-library/react'; +import {useComponentTranslator} from './useComponentTranslator'; +import {useTranslator} from './useTranslator'; +import {InternationalizationContext} from './InternationalizationContext'; +import {InternationalizationProvider} from './InternationalizationProvider'; +import {__resetForTests} from './resolve'; +import enCatalog from './generated-locales/en.generated'; +import buttonMessages from './generated-locales/en/button.generated'; +import paginationMessages from './generated-locales/en/pagination.generated'; +import enSource from '../../locales/en.json'; +import type {MessagesByLocale, Overrides} from './types'; + +const FR_MESSAGES: MessagesByLocale = { + fr: {'@astryx.button.loading': {defaultMessage: 'Chargement'}}, +}; +const FR_OVERRIDES: Overrides = { + fr: {'@astryx.button.loading': 'Patientez'}, +}; + +beforeEach(() => { + __resetForTests(); +}); + +describe('useComponentTranslator', () => { + it("resolves the component's own keys from its slice with no provider", () => { + const {result} = renderHook(() => useComponentTranslator(buttonMessages)); + expect(result.current('@astryx.button.loading')).toBe('Loading'); + }); + + it('formats ICU values from the slice', () => { + const {result} = renderHook(() => + useComponentTranslator(paginationMessages), + ); + expect( + result.current('@astryx.pagination.pageAnnounce', {current: 3}), + ).toContain('3'); + }); + + it("returns a key outside the slice as the key, and warns once: the slice is the component's whole English", () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const {result} = renderHook(() => useComponentTranslator(buttonMessages)); + expect(result.current('@astryx.pagination.next')).toBe( + '@astryx.pagination.next', + ); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('missing key')); + warn.mockRestore(); + }); + + it("lets the provider's catalog beat the slice", () => { + const {result} = renderHook(() => useComponentTranslator(buttonMessages), { + wrapper: ({children}) => ( + + {children} + + ), + }); + expect(result.current('@astryx.button.loading')).toBe('Chargement'); + }); + + it("lets a provider override beat the provider's catalog and the slice", () => { + const {result} = renderHook(() => useComponentTranslator(buttonMessages), { + wrapper: ({children}) => ( + + {children} + + ), + }); + expect(result.current('@astryx.button.loading')).toBe('Patientez'); + }); + + it('hands back the same function across renders while the slice and provider hold', () => { + const {result, rerender} = renderHook(() => + useComponentTranslator(buttonMessages), + ); + const first = result.current; + rerender(); + expect(result.current).toBe(first); + }); + + it('useTranslator with no argument still resolves every shipped key', () => { + const {result} = renderHook(() => useTranslator()); + expect(result.current('@astryx.button.loading')).toBe('Loading'); + expect(result.current('@astryx.pagination.next')).toBe('Go to next page'); + }); +}); + +describe('the whole English catalog', () => { + it('carries every authored key and message, and agrees with the slices', () => { + const authored = Object.keys(enSource).sort(); + expect(Object.keys(enCatalog).sort()).toEqual(authored); + for (const key of authored) { + expect(enCatalog[key]).toBe( + (enSource as Record)[key] + .defaultMessage, + ); + } + expect(enCatalog['@astryx.button.loading']).toBe( + buttonMessages['@astryx.button.loading'], + ); + }); +}); + +describe('the public InternationalizationContext boundary', () => { + it('its translate falls back to the whole shipped English catalog with no provider, as it always has', () => { + const {result} = renderHook(() => use(InternationalizationContext)); + expect(result.current.locale).toBe('en'); + expect(result.current.translate('@astryx.pagination.next', undefined)).toBe( + 'Go to next page', + ); + expect(result.current.translate('@astryx.button.loading')).toBe('Loading'); + }); + + it('its translate falls back to English under a provider whose catalog lacks the key', () => { + const {result} = renderHook(() => use(InternationalizationContext), { + wrapper: ({children}) => ( + + {children} + + ), + }); + expect(result.current.locale).toBe('fr'); + expect(result.current.translate('@astryx.button.loading')).toBe( + 'Chargement', + ); + expect(result.current.translate('@astryx.pagination.next')).toBe( + 'Go to next page', + ); + }); +}); diff --git a/packages/core/src/i18n/useComponentTranslator.ts b/packages/core/src/i18n/useComponentTranslator.ts new file mode 100644 index 0000000000000..3fe36726498f6 --- /dev/null +++ b/packages/core/src/i18n/useComponentTranslator.ts @@ -0,0 +1,56 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useComponentTranslator.ts + * @input TranslationRuntimeContext (via use()); the component's own English + * namespace slice from ./generated-locales/en/.generated + * @output Exports useComponentTranslator — the translator a core component + * renders with — and the TranslatorFn type + * @position The i18n hook for components inside this package. A component + * passes the slice of the English catalog that holds its own keys, so a + * bundle carries the strings of the components it renders and nothing of + * the other hundred. Consumers use useTranslator, which carries the whole + * catalog; this hook imports none. + * + * SYNC: When modified, update these files to stay in sync: + * - /packages/core/src/i18n/useTranslator.ts + * - /packages/core/src/i18n/resolve.ts + * - /scripts/check-i18n-catalog.mjs (the slice-coverage rule) + */ + +import {use, useMemo} from 'react'; +import {TranslationRuntimeContext} from './TranslationRuntimeContext'; +import type {RuntimeCatalog} from './types'; + +export type TranslatorFn = ( + key: string, + values?: Record, +) => string; + +/** + * Returns a translator bound to the current provider's locale whose English + * fallback is `messages`: the component's own namespace slice, or a + * module-level merge of the slices it reads. Stable while the provider and + * the slice are, so it is safe in memo dependencies, event handlers and + * effects. + * + * @example + * ``` + * import buttonMessages from '../i18n/generated-locales/en/button.generated'; + * + * function Button() { + * const t = useComponentTranslator(buttonMessages); + * return {t('@astryx.button.loading')}; + * } + * ``` + */ +export function useComponentTranslator(messages: RuntimeCatalog): TranslatorFn { + const {resolve: resolveMessage} = use(TranslationRuntimeContext); + return useMemo( + () => (key: string, values?: Record) => + resolveMessage(key, values, messages), + [messages, resolveMessage], + ); +} diff --git a/packages/core/src/i18n/useDirection.ts b/packages/core/src/i18n/useDirection.ts index a8184b98ed49b..bc4177740b341 100644 --- a/packages/core/src/i18n/useDirection.ts +++ b/packages/core/src/i18n/useDirection.ts @@ -4,7 +4,7 @@ /** * @file useDirection.ts - * @input InternationalizationContext (via use()) + * @input TranslationRuntimeContext (via use()) * @output 'ltr' | 'rtl' * @position Client hook for reading the ambient text direction. Returns 'ltr' * when called outside a provider (matches the silent-en-fallback pattern of @@ -18,15 +18,15 @@ * the provider's direction disagrees with the actual ``. * * SYNC: When modified, update these files to stay in sync: - * - /packages/core/src/i18n/InternationalizationContext.ts + * - /packages/core/src/i18n/TranslationRuntimeContext.ts * - /packages/core/src/i18n/getLocaleDirection.ts (server-safe counterpart) * - /packages/core/src/i18n/index.ts */ import {use} from 'react'; -import {InternationalizationContext} from './InternationalizationContext'; +import {TranslationRuntimeContext} from './TranslationRuntimeContext'; export function useDirection(): 'ltr' | 'rtl' { - const ctx = use(InternationalizationContext); + const ctx = use(TranslationRuntimeContext); return ctx.direction; } diff --git a/packages/core/src/i18n/useLocale.ts b/packages/core/src/i18n/useLocale.ts index a5dda8a01c880..07f91a211262e 100644 --- a/packages/core/src/i18n/useLocale.ts +++ b/packages/core/src/i18n/useLocale.ts @@ -4,7 +4,7 @@ /** * @file useLocale.ts - * @input InternationalizationContext (via use()) + * @input TranslationRuntimeContext (via use()) * @output The active BCP 47 locale tag * @position Public provider-aware locale accessor. Exported from the i18n * barrel for components, sibling packages, and consumers that must thread @@ -18,17 +18,17 @@ * provider-backed contract. * * SYNC: When modified, update: - * - /packages/core/src/i18n/InternationalizationContext.ts + * - /packages/core/src/i18n/TranslationRuntimeContext.ts * - /packages/core/src/i18n/useLocale.doc.mjs * - /packages/core/src/i18n/index.ts * - /packages/core/src/i18n/__tests__/useLocale.test.tsx */ import {use} from 'react'; -import {InternationalizationContext} from './InternationalizationContext'; +import {TranslationRuntimeContext} from './TranslationRuntimeContext'; import type {Locale} from './types'; export function useLocale(): Locale { - const ctx = use(InternationalizationContext); + const ctx = use(TranslationRuntimeContext); return ctx.locale; } diff --git a/packages/core/src/i18n/useTranslator.ts b/packages/core/src/i18n/useTranslator.ts index c7abd5dc450a6..e3948b7005596 100644 --- a/packages/core/src/i18n/useTranslator.ts +++ b/packages/core/src/i18n/useTranslator.ts @@ -8,7 +8,10 @@ * @output Exports useTranslator hook returning a stable translator function * @position Client-side hook for translating outside of render (event handlers, * effects, non-component code) while still resolving against the current - * provider's locale. + * provider's locale. The consumer-facing translator: it resolves every + * `@astryx.*` key, so it carries the whole English catalog. A component + * inside this package uses useComponentTranslator with its own slice + * instead, so an app bundles only the strings of the components it renders. * * Prefer `t()` for translations at the callsite during render. When you need * to translate inside an event handler or effect, capture a translator during @@ -16,20 +19,19 @@ * * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/i18n/index.ts - * - /packages/core/src/i18n/t.client.ts + * - /packages/core/src/i18n/useComponentTranslator.ts */ import {use} from 'react'; import {InternationalizationContext} from './InternationalizationContext'; +import type {TranslatorFn} from './useComponentTranslator'; -export type TranslatorFn = ( - key: string, - values?: Record, -) => string; +export type {TranslatorFn}; /** * Returns a translator function bound to the current provider's locale. - * Safe to call from event handlers and effects. + * Safe to call from event handlers and effects. Its English fallback is the + * whole shipped catalog, so any `@astryx.*` key resolves. * * @example * ``` diff --git a/scripts/check-i18n-catalog.mjs b/scripts/check-i18n-catalog.mjs index 0ad65b71c9f54..ae39a9526f550 100644 --- a/scripts/check-i18n-catalog.mjs +++ b/scripts/check-i18n-catalog.mjs @@ -31,6 +31,15 @@ * gate and that lint rule cannot disagree about what a key reference is. A * reference whose key is not statically knowable is reported as unverifiable * rather than passed or failed silently. + * + * 4. Slice coverage. A component in packages/core/src renders with + * `useComponentTranslator()`, where the slice is the English + * catalog of one namespace (`generated-locales/en/.generated`) + * or a module-level spread of several. Every `@astryx..*` key + * the file reads must belong to a namespace its slice carries, or the + * component would show the key at runtime. A file that reads keys but + * calls no translator hook (it is handed `t`) is covered by the slices + * of the hook callers in its component directory. */ import fs from 'node:fs'; @@ -67,6 +76,15 @@ const LOCALE_MISSING_KEYS_ARE_FATAL = false; * exclusions the crowdin-download workflow applies to this directory. */ const NOT_A_SHIPPED_LOCALE = new Set(['en.json', 'pseudo.json']); +/** The package whose components carry their own English slices (rule 4). */ +const SLICED_SRC_DIR = 'packages/core/src'; +const COMPONENT_HOOK = 'useComponentTranslator'; +const CONSUMER_HOOK = 'useTranslator'; +/** The public context, which binds the whole catalog to its `translate`. */ +const CONSUMER_CONTEXT = 'InternationalizationContext'; +const SLICE_MODULE_RE = + /\/i18n\/generated-locales\/en\/([A-Za-z0-9]+)\.generated$/; + /** Translator call targets, per the i18n-key-format lint rule. */ const TRANSLATOR_CALL_NAMES = new Set(['t', 'translator', 'translate']); @@ -579,6 +597,187 @@ function extractKeyRefs(source, fileName) { return {refs, unresolved}; } +/** + * The namespace of an astryx key: `@astryx.button.loading` → `button`. + */ +function namespaceOf(key) { + return key.slice(KEY_PREFIX.length).split('.')[0]; +} + +/** + * Rule 4's view of one source file: which translator hooks it calls and the + * namespaces of the slices it passes them. + * + * A slice argument is an identifier that is either the default import of a + * `generated-locales/en/.generated` module, or a module-level + * `const` whose initializer spreads such imports. Anything else is reported + * as an unresolvable slice. + * + * @param {string} source file contents + * @param {string} fileName display name (drives .tsx parsing) + * @returns {{hookCalls: {line: number, namespaces: string[] | null}[], + * consumerHookImports: {line: number, name: string}[]}} + */ +function extractSliceUsage(source, fileName) { + const sourceFile = ts.createSourceFile( + fileName, + source, + ts.ScriptTarget.Latest, + true, + fileName.endsWith('.tsx') || fileName.endsWith('.jsx') + ? ts.ScriptKind.TSX + : ts.ScriptKind.TS, + ); + const lineOf = node => + sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + + 1; + + // Default imports of slice modules, by local name → namespace; and the + // lines where the consumer hook is imported from an i18n module. + const sliceImports = new Map(); + const consumerHookImports = []; + for (const statement of sourceFile.statements) { + if (!ts.isImportDeclaration(statement)) continue; + if (!ts.isStringLiteral(statement.moduleSpecifier)) continue; + const specifier = statement.moduleSpecifier.text; + const clause = statement.importClause; + if (!clause) continue; + const sliceMatch = specifier.match(SLICE_MODULE_RE); + if (sliceMatch && clause.name) { + sliceImports.set(clause.name.text, sliceMatch[1]); + } + if ( + /(^|\/)i18n(\/[^/]+)?$/.test(specifier) && + clause.namedBindings && + ts.isNamedImports(clause.namedBindings) + ) { + for (const element of clause.namedBindings.elements) { + const imported = (element.propertyName ?? element.name).text; + if ( + (imported === CONSUMER_HOOK || imported === CONSUMER_CONTEXT) && + !element.isTypeOnly + ) { + consumerHookImports.push({line: lineOf(element), name: imported}); + } + } + } + } + + // Module-level `const x = {...a, ...b}` over slice imports. + const merged = new Map(); + for (const statement of sourceFile.statements) { + if (!ts.isVariableStatement(statement)) continue; + for (const decl of statement.declarationList.declarations) { + if (!ts.isIdentifier(decl.name) || !decl.initializer) continue; + const init = unwrap(decl.initializer); + if (!ts.isObjectLiteralExpression(init)) continue; + const namespaces = []; + let resolvable = true; + for (const prop of init.properties) { + if ( + ts.isSpreadAssignment(prop) && + ts.isIdentifier(prop.expression) && + sliceImports.has(prop.expression.text) + ) { + namespaces.push(sliceImports.get(prop.expression.text)); + } else { + resolvable = false; + } + } + if (resolvable && namespaces.length > 0) { + merged.set(decl.name.text, namespaces); + } + } + } + + const resolveSlice = node => { + const n = unwrap(node); + if (!n || !ts.isIdentifier(n)) return null; + if (sliceImports.has(n.text)) return [sliceImports.get(n.text)]; + if (merged.has(n.text)) return merged.get(n.text); + return null; + }; + + const hookCalls = []; + const visit = node => { + if ( + ts.isCallExpression(node) && + ts.isIdentifier(node.expression) && + node.expression.text === COMPONENT_HOOK + ) { + const arg = node.arguments[0]; + hookCalls.push({ + line: lineOf(node), + namespaces: arg ? resolveSlice(arg) : null, + }); + } + ts.forEachChild(node, visit); + }; + visit(sourceFile); + + return {hookCalls, consumerHookImports}; +} + +/** + * Rule 4 over the sliced package: every key a file reads is carried by the + * slices it (or, for a file handed `t`, its component directory) renders + * with. Pure over the per-file facts, so it is unit-testable. + * + * @param {Map} files keyed by + * path relative to the sliced source dir + * @returns {string[]} human-readable problems (empty = covered) + */ +function checkSliceCoverage(files) { + const problems = []; + const coveredByDir = new Map(); + for (const [rel, {hookCalls}] of files) { + const dir = rel.split('/')[0]; + const set = coveredByDir.get(dir) ?? new Set(); + for (const call of hookCalls) { + for (const ns of call.namespaces ?? []) set.add(ns); + } + coveredByDir.set(dir, set); + } + for (const [rel, {refs, hookCalls}] of files) { + for (const call of hookCalls) { + if (call.namespaces === null) { + problems.push( + `${rel}:${call.line} ${COMPONENT_HOOK}: the slice is not a default import of ` + + `generated-locales/en/.generated, or a module-level spread of such imports`, + ); + } + } + // A file that calls no component hook reads its keys through the + // consumer hook or a `t` it was handed; only a slice-rendering file, or a + // file in a directory that has one, is held to its slices. + const dirCovered = coveredByDir.get(rel.split('/')[0]); + if ( + refs.length === 0 || + (hookCalls.length === 0 && (dirCovered == null || dirCovered.size === 0)) + ) { + continue; + } + const own = new Set(); + for (const call of hookCalls) { + for (const ns of call.namespaces ?? []) own.add(ns); + } + const covering = + hookCalls.length > 0 ? own : (coveredByDir.get(rel.split('/')[0]) ?? own); + const where = hookCalls.length > 0 ? 'its slice' : "its directory's slices"; + for (const {line, key} of refs) { + const ns = namespaceOf(key); + if (!covering.has(ns)) { + problems.push( + `${rel}:${line} ${key} is outside ${where} (${[...covering].sort().join(', ') || 'none'})`, + ); + } + } + } + return problems; +} + /** * Validate the shape of the source catalog: every entry needs a usable * `defaultMessage` and a non-empty `description`. @@ -691,16 +890,21 @@ function main() { const unverifiable = []; let refCount = 0; const seen = new Set(); + const slicedFiles = new Map(); for (const dir of SRC_DIRS) { const abs = path.join(ROOT, dir); if (!fs.existsSync(abs)) continue; for (const file of walk(abs)) { const rel = path.relative(ROOT, file); - const {refs, unresolved} = extractKeyRefs( - fs.readFileSync(file, 'utf8'), - file, - ); + const source = fs.readFileSync(file, 'utf8'); + const {refs, unresolved} = extractKeyRefs(source, file); + if (dir === SLICED_SRC_DIR && !rel.includes('/i18n/')) { + slicedFiles.set(path.relative(abs, file), { + refs, + ...extractSliceUsage(source, file), + }); + } refCount += refs.length; for (const {line, key} of refs) { seen.add(key); @@ -720,6 +924,18 @@ function main() { }); } + // 4. Slice coverage + const sliceProblems = checkSliceCoverage(slicedFiles); + if (sliceProblems.length > 0) { + errors.push({ + title: `${sliceProblems.length} slice coverage problem(s) in ${SLICED_SRC_DIR}`, + lines: sliceProblems, + hint: + `Render with ${COMPONENT_HOOK}() where the slice imports ` + + `generated-locales/en/.generated for every namespace the file reads.`, + }); + } + // 2. Locale parity const localeFiles = fs .readdirSync(path.join(ROOT, LOCALES_DIR)) @@ -812,8 +1028,13 @@ function main() { process.exit(1); } + const slicedHookCalls = [...slicedFiles.values()].reduce( + (n, f) => n + f.hookCalls.length, + 0, + ); console.log( `✓ check:i18n-catalog — ${seen.size} key(s) over ${refCount} reference(s) resolve; ` + + `${slicedHookCalls} ${COMPONENT_HOOK} call(s) carry the namespaces their files read; ` + `${enKeys.size} en and ${translatedMessageCount} translated message(s) parsed and contract-checked; ` + `plural categories evaluated with runtime CLDR ${process.versions.cldr}; ` + `${localeFiles.length} locale(s) consistent`, @@ -828,6 +1049,8 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) { export { extractKeyRefs, + extractSliceUsage, + checkSliceCoverage, validateSourceCatalog, compareLocale, parseIcuMessage, diff --git a/scripts/check-i18n-catalog.test.mjs b/scripts/check-i18n-catalog.test.mjs index b3495d2d81884..f62b19be5032d 100644 --- a/scripts/check-i18n-catalog.test.mjs +++ b/scripts/check-i18n-catalog.test.mjs @@ -13,6 +13,8 @@ import {describe, it, expect} from 'vitest'; import { extractKeyRefs, + extractSliceUsage, + checkSliceCoverage, validateSourceCatalog, compareLocale, parseIcuMessage, @@ -481,3 +483,146 @@ describe('ICU plural categories', () => { ]); }); }); + +describe('extractSliceUsage — the slices a component renders with', () => { + const usage = source => extractSliceUsage(source, 'Test.tsx'); + + it('resolves a slice import passed to the component hook', () => { + const {hookCalls, consumerHookImports} = usage(` + import {useComponentTranslator} from '../i18n/useComponentTranslator'; + import buttonMessages from '../i18n/generated-locales/en/button.generated'; + function Button() { const t = useComponentTranslator(buttonMessages); return t('@astryx.button.loading'); } + `); + expect(hookCalls).toEqual([{line: 4, namespaces: ['button']}]); + expect(consumerHookImports).toEqual([]); + }); + + it('resolves a module-level spread of several slices', () => { + const {hookCalls} = usage(` + import {useComponentTranslator} from '../i18n/useComponentTranslator'; + import dateInputMessages from '../i18n/generated-locales/en/dateInput.generated'; + import timeInputMessages from '../i18n/generated-locales/en/timeInput.generated'; + const messages = {...dateInputMessages, ...timeInputMessages}; + function Field() { const t = useComponentTranslator(messages); return t('@astryx.dateInput.open'); } + `); + expect(hookCalls).toEqual([ + {line: 6, namespaces: ['dateInput', 'timeInput']}, + ]); + }); + + it('declares an argument it cannot trace to slice imports unresolvable', () => { + const {hookCalls} = usage(` + import {useComponentTranslator} from '../i18n/useComponentTranslator'; + const messages = {'@astryx.button.loading': 'Loading'}; + function Button() { const t = useComponentTranslator(messages); return t('@astryx.button.loading'); } + `); + expect(hookCalls).toEqual([{line: 4, namespaces: null}]); + }); + + it('reports a value import of the consumer hook or the public context, and not a type import', () => { + expect( + usage(`import {useLocale, useTranslator} from '../i18n';`) + .consumerHookImports, + ).toEqual([{line: 1, name: 'useTranslator'}]); + expect( + usage(`import {useTranslator} from '../../../i18n/useTranslator';`) + .consumerHookImports, + ).toEqual([{line: 1, name: 'useTranslator'}]); + expect( + usage(`import {InternationalizationContext} from '../i18n';`) + .consumerHookImports, + ).toEqual([{line: 1, name: 'InternationalizationContext'}]); + expect( + usage( + `import {useLocale, type TranslatorFn, type InternationalizationContextValue} from '../i18n';`, + ).consumerHookImports, + ).toEqual([]); + }); +}); + +describe('checkSliceCoverage — every key a file reads is in a slice it renders with', () => { + const file = (refs, hookCalls, consumerHookImports = []) => ({ + refs: refs.map((key, i) => ({line: i + 1, key})), + hookCalls, + consumerHookImports, + }); + + it('passes a file whose keys are all in its slices', () => { + expect( + checkSliceCoverage( + new Map([ + [ + 'DateInput/DateInput.tsx', + file( + ['@astryx.dateInput.open', '@astryx.calendar.today'], + [{line: 9, namespaces: ['dateInput', 'calendar']}], + ), + ], + ]), + ), + ).toEqual([]); + }); + + it('names the key, the line and the slices when a key is outside them', () => { + expect( + checkSliceCoverage( + new Map([ + [ + 'Button/Button.tsx', + file( + ['@astryx.button.loading'], + [{line: 9, namespaces: ['pagination']}], + ), + ], + ]), + ), + ).toEqual([ + 'Button/Button.tsx:1 @astryx.button.loading is outside its slice (pagination)', + ]); + }); + + it('covers a file handed `t` by the hook callers of its component directory', () => { + const files = new Map([ + [ + 'PowerSearch/PowerSearchToken.tsx', + file([], [{line: 3, namespaces: ['powersearch']}]), + ], + [ + 'PowerSearch/formatFilterValue.ts', + file(['@astryx.powersearch.between'], []), + ], + ['Table/helper.ts', file(['@astryx.powersearch.between'], [])], + [ + 'Table/Table.tsx', + file(['@astryx.table.sort'], [{line: 3, namespaces: ['table']}]), + ], + ]); + expect(checkSliceCoverage(files)).toEqual([ + "Table/helper.ts:1 @astryx.powersearch.between is outside its directory's slices (table)", + ]); + }); + + it('leaves a file that renders with no component hook, in a directory with none, alone', () => { + expect( + checkSliceCoverage( + new Map([['Legacy/Legacy.tsx', file(['@astryx.legacy.label'], [])]]), + ), + ).toEqual([]); + }); + + it('reports an unresolvable slice', () => { + expect( + checkSliceCoverage( + new Map([ + [ + 'Spinner/Spinner.tsx', + file(['@astryx.spinner.loading'], [{line: 9, namespaces: null}]), + ], + ]), + ), + ).toEqual([ + 'Spinner/Spinner.tsx:9 useComponentTranslator: the slice is not a default import of generated-locales/en/.generated, or a module-level spread of such imports', + 'Spinner/Spinner.tsx:1 @astryx.spinner.loading is outside its slice (none)', + ]); + }); +}); diff --git a/scripts/generate-i18n-runtime.mjs b/scripts/generate-i18n-runtime.mjs index 11727db9635f6..477e9577568eb 100644 --- a/scripts/generate-i18n-runtime.mjs +++ b/scripts/generate-i18n-runtime.mjs @@ -7,6 +7,11 @@ * packages/core/locales/*.json remain the canonical Crowdin sources and keep * translator descriptions. Each generated module exports only the * key-to-defaultMessage map used at runtime. + * + * The English catalog is emitted one namespace at a time, under + * `generated-locales/en/.generated.ts`: a component carries its own + * slice through `useComponentTranslator`, so an app bundles the strings of the + * components it renders rather than the whole library's. */ import {spawn} from 'node:child_process'; @@ -28,6 +33,13 @@ const GENERATED_LOCALES_DIR = path.join( ); const EN_FILE = 'en.json'; const PSEUDO_FILE = 'pseudo.json'; +/** + * Where the per-namespace English slices live, under GENERATED_LOCALES_DIR. + * The package's exports map gives `./locales/en/*` a `null` target, so the + * slices are the package's own and never a consumer import path. + */ +const EN_SLICES_DIR = 'en'; +const KEY_PREFIX = '@astryx.'; function readJson(file) { return JSON.parse(fs.readFileSync(file, 'utf8')); @@ -69,6 +81,42 @@ export function createRuntimeCatalogs(sourceCatalogs) { return runtimeCatalogs; } +/** + * The namespace of a catalog key: `@astryx.button.loading` belongs to + * `button`. Every key names one, which is also the slice module's name. + */ +export function namespaceOf(key) { + const [namespace, ...rest] = key.slice(KEY_PREFIX.length).split('.'); + if (!key.startsWith(KEY_PREFIX) || !namespace || rest.length === 0) { + throw new Error( + `${key}: a catalog key is "${KEY_PREFIX}."`, + ); + } + return namespace; +} + +/** Split a runtime catalog into one map per namespace, keys in source order. */ +export function createNamespaceSlices(runtimeCatalog) { + const slices = {}; + for (const [key, message] of Object.entries(runtimeCatalog)) { + const namespace = namespaceOf(key); + (slices[namespace] ??= {})[key] = message; + } + return slices; +} + +export function getSliceModuleName(namespace) { + return `${namespace}.generated.ts`; +} + +function getSliceModulePath(namespace) { + return path.join( + GENERATED_LOCALES_DIR, + EN_SLICES_DIR, + getSliceModuleName(namespace), + ); +} + export function getGeneratedModuleName(sourceFile) { if (!sourceFile.endsWith('.json')) { throw new Error(`Expected a JSON locale filename: ${sourceFile}`); @@ -80,16 +128,31 @@ function getGeneratedModulePath(sourceFile) { return path.join(GENERATED_LOCALES_DIR, getGeneratedModuleName(sourceFile)); } -export async function renderRuntimeCatalogModule(runtimeCatalog, sourceFile) { +async function renderCatalogModule(runtimeCatalog, outputFile, description) { const {format, resolveConfig} = await import('prettier'); - const outputFile = getGeneratedModulePath(sourceFile); + const source = `// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n/**\n * @generated by scripts/generate-i18n-runtime.mjs from ${description}.\n * Translator descriptions remain in the authored JSON catalogs and must not be copied here.\n * Do not edit by hand. Run \`pnpm generate:i18n-runtime\` instead.\n */\n\nconst runtimeCatalog: Readonly> = ${JSON.stringify(runtimeCatalog)};\n\nexport default runtimeCatalog;\n`; + const prettierConfig = await resolveConfig(outputFile); + return format(source, {...prettierConfig, filepath: outputFile}); +} + +export async function renderRuntimeCatalogModule(runtimeCatalog, sourceFile) { const sourceDescription = sourceFile === PSEUDO_FILE ? 'the pseudo-localization projection of packages/core/locales/en.json' : `packages/core/locales/${sourceFile}`; - const source = `// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n/**\n * @generated by scripts/generate-i18n-runtime.mjs from ${sourceDescription}.\n * Translator descriptions remain in the authored JSON catalogs and must not be copied here.\n * Do not edit by hand. Run \`pnpm generate:i18n-runtime\` instead.\n */\n\nconst runtimeCatalog: Readonly> = ${JSON.stringify(runtimeCatalog)};\n\nexport default runtimeCatalog;\n`; - const prettierConfig = await resolveConfig(outputFile); - return format(source, {...prettierConfig, filepath: outputFile}); + return renderCatalogModule( + runtimeCatalog, + getGeneratedModulePath(sourceFile), + sourceDescription, + ); +} + +export async function renderNamespaceSliceModule(slice, namespace) { + return renderCatalogModule( + slice, + getSliceModulePath(namespace), + `the \`${namespace}\` keys of packages/core/locales/${EN_FILE}`, + ); } function readSourceCatalogs() { @@ -118,18 +181,16 @@ function writeIfChanged(file, content) { return true; } -function removeStaleModules(expectedFiles) { - if (!fs.existsSync(GENERATED_LOCALES_DIR)) return 0; +function removeStaleModules(directory, expectedFiles) { + if (!fs.existsSync(directory)) return 0; let removed = 0; - for (const entry of fs.readdirSync(GENERATED_LOCALES_DIR, { - withFileTypes: true, - })) { + for (const entry of fs.readdirSync(directory, {withFileTypes: true})) { if ( entry.isFile() && entry.name.endsWith('.generated.ts') && !expectedFiles.has(entry.name) ) { - fs.rmSync(path.join(GENERATED_LOCALES_DIR, entry.name)); + fs.rmSync(path.join(directory, entry.name)); removed += 1; } } @@ -152,19 +213,31 @@ export async function generateRuntimeCatalogs({check = false} = {}) { return; } - fs.mkdirSync(GENERATED_LOCALES_DIR, {recursive: true}); + const slicesDir = path.join(GENERATED_LOCALES_DIR, EN_SLICES_DIR); + fs.mkdirSync(slicesDir, {recursive: true}); const expectedFiles = new Set( Object.keys(runtimeCatalogs).map(getGeneratedModuleName), ); - const removed = removeStaleModules(expectedFiles); + const slices = createNamespaceSlices(runtimeCatalogs[EN_FILE]); + const expectedSliceFiles = new Set( + Object.keys(slices).map(getSliceModuleName), + ); + const removed = + removeStaleModules(GENERATED_LOCALES_DIR, expectedFiles) + + removeStaleModules(slicesDir, expectedSliceFiles); let changed = 0; for (const [file, catalog] of Object.entries(runtimeCatalogs)) { const output = await renderRuntimeCatalogModule(catalog, file); if (writeIfChanged(getGeneratedModulePath(file), output)) changed += 1; } + for (const [namespace, slice] of Object.entries(slices)) { + const output = await renderNamespaceSliceModule(slice, namespace); + if (writeIfChanged(getSliceModulePath(namespace), output)) changed += 1; + } console.log( `Generated ${Object.keys(runtimeCatalogs).length} runtime locale modules ` + + `and ${Object.keys(slices).length} English namespace slices ` + `(${changed} changed, ${removed} stale removed)`, ); } diff --git a/scripts/generate-i18n-runtime.test.mjs b/scripts/generate-i18n-runtime.test.mjs index 97756420f922d..e6b576e6d66e2 100644 --- a/scripts/generate-i18n-runtime.test.mjs +++ b/scripts/generate-i18n-runtime.test.mjs @@ -8,11 +8,15 @@ import path from 'node:path'; import {fileURLToPath} from 'node:url'; import {describe, expect, it} from 'vitest'; import { + createNamespaceSlices, createRuntimeCatalog, createRuntimeCatalogs, createSpawnInvocation, getGeneratedModuleName, + getSliceModuleName, isSourceLocaleFile, + namespaceOf, + renderNamespaceSliceModule, renderRuntimeCatalogModule, } from './generate-i18n-runtime.mjs'; @@ -122,6 +126,49 @@ describe('createRuntimeCatalogs', () => { }); }); +describe('English namespace slices', () => { + it('names the namespace of a key', () => { + expect(namespaceOf('@astryx.button.loading')).toBe('button'); + expect(namespaceOf('@astryx.dateTimeInput.time.hour')).toBe( + 'dateTimeInput', + ); + }); + + it('rejects a key that names no namespace', () => { + expect(() => namespaceOf('@astryx.loading')).toThrow('.'); + expect(() => namespaceOf('loading')).toThrow('.'); + }); + + it('splits a runtime catalog into one map per namespace, every key kept once', () => { + const slices = createNamespaceSlices({ + '@astryx.button.loading': 'Loading', + '@astryx.pagination.next': 'Go to next page', + '@astryx.pagination.previous': 'Go to previous page', + }); + expect(slices).toEqual({ + button: {'@astryx.button.loading': 'Loading'}, + pagination: { + '@astryx.pagination.next': 'Go to next page', + '@astryx.pagination.previous': 'Go to previous page', + }, + }); + expect(Object.values(slices).flatMap(Object.keys)).toHaveLength(3); + }); + + it('renders a slice as the same string-map module shape, named after the namespace', async () => { + expect(getSliceModuleName('button')).toBe('button.generated.ts'); + const output = await renderNamespaceSliceModule( + {'@astryx.button.loading': 'Loading'}, + 'button', + ); + expect(output).toContain('from the `button` keys of'); + expect(output).toContain( + "const runtimeCatalog: Readonly> = {\n '@astryx.button.loading': 'Loading',\n};", + ); + expect(output).toContain('export default runtimeCatalog;'); + }); +}); + describe('generated module names', () => { it('places generated modules beside the i18n runtime with an explicit suffix', () => { expect(getGeneratedModuleName('fr-FR.json')).toBe('fr-FR.generated.ts'); diff --git a/scripts/sync-exports.js b/scripts/sync-exports.js index ddc98d5f035c4..90412cff6883e 100644 --- a/scripts/sync-exports.js +++ b/scripts/sync-exports.js @@ -188,6 +188,12 @@ const STATIC_EXPORTS = { types: './dist/i18n/generated-locales/*.generated.d.ts', default: './dist/i18n/generated-locales/*.generated.js', }, + // The per-namespace English slices under generated-locales/en/ are the + // package's own: a core component renders with its slice through the + // internal useComponentTranslator. The longer pattern wins the match, so + // this keeps them off the public surface while `./locales/en.generated.js` + // and the other whole catalogs stay importable. + './locales/en/*': null, }; /** From dcb9666507d46e058876674e2848e99ac31b0282 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 11 Oct 2026 17:22:18 -0700 Subject: [PATCH 02/36] chore(i18n): declare the raw-context path's retirement A value rendered straight into the public InternationalizationContext, without InternationalizationProvider, drove useLocale, useDirection, useCollator and every component's strings in the last release; with the hooks reading the provider's runtime context it reaches none of them. The changeset says so at the breaking tier, with the migration (mount the provider), and the context module's header says which readers each context reaches. The shipped i18n guide qualifies which apps the slicing saves bytes for, and carries its own docs changeset. --- .changeset/i18n-cli-guide-caller-facing.md | 7 +++++++ .changeset/i18n-en-namespace-slices.md | 5 ++--- packages/cli/assets/docs/tree/i18n-rtl-and-testing.doc.mjs | 2 +- packages/core/src/i18n/InternationalizationContext.ts | 5 ++++- 4 files changed, 14 insertions(+), 5 deletions(-) create mode 100644 .changeset/i18n-cli-guide-caller-facing.md 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-en-namespace-slices.md b/.changeset/i18n-en-namespace-slices.md index 4c1873055bf12..ba55d7949255d 100644 --- a/.changeset/i18n-en-namespace-slices.md +++ b/.changeset/i18n-en-namespace-slices.md @@ -1,8 +1,7 @@ --- -'@astryxdesign/core': patch -'@astryxdesign/cli': patch +'@astryxdesign/core': minor --- -[chore] The i18n runtime can hand a component its own English strings. The English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice; the components themselves move to it in a follow-up, so nothing changes for an app yet. `useTranslator()` and `InternationalizationContext` are unchanged and still resolve every `@astryx.*` key; an `InternationalizationProvider`'s `messages` and `overrides` still win; the slices themselves are not importable. One undocumented path moves: a value handed straight to `InternationalizationContext` without the provider no longer reaches `useLocale`, `useDirection` and `useCollator`, which read the provider's runtime context; mount `InternationalizationProvider`. +[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives core components' strings or `useLocale`, `useDirection` and `useCollator`. Migration: mount `InternationalizationProvider`; it takes the same `locale`, `messages`, `overrides` and `dir`. The provider now writes an internal runtime context that those hooks and every core component 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. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice; the components themselves move to it in a follow-up, so bundles do not change yet. The slices are not importable. @vjeux 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 b39536b0856e0..711d0a0950c8c 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 @@ -122,7 +122,7 @@ import pseudo from '@astryxdesign/core/locales/pseudo.generated.js'; }, { type: 'prose', - text: "Astryx components read their own strings from the English catalog rather than hardcoding them, so an app bundles only the strings of the components it renders. Your own code reads any `@astryx.*` key with `useTranslator()`:", + text: "Astryx components read their strings from the English catalog rather than hardcoding them. Your own code reads any `@astryx.*` key with `useTranslator()`:", }, { type: 'code', diff --git a/packages/core/src/i18n/InternationalizationContext.ts b/packages/core/src/i18n/InternationalizationContext.ts index bb681bb2f0306..6e1ff984454aa 100644 --- a/packages/core/src/i18n/InternationalizationContext.ts +++ b/packages/core/src/i18n/InternationalizationContext.ts @@ -10,7 +10,10 @@ * context a consumer reads. Its `translate` resolves every `@astryx.*` key, * falling back to the shipped English catalog, so this module carries that * catalog; the components inside this package read - * TranslationRuntimeContext instead and carry only their own slices. + * TranslationRuntimeContext instead and carry only their own slices. Both + * are written by InternationalizationProvider, which is how an app + * configures Astryx: a value rendered straight into this context reaches + * consumers of this context and nothing inside the package. * * Separated from InternationalizationProvider.tsx so components can consume * the context without pulling in the full provider implementation. From 3a4142ea41ddc3622a9493072200cdc1c3057c19 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 11 Oct 2026 18:16:36 -0700 Subject: [PATCH 03/36] feat(cli): migrate a raw InternationalizationContext value to the provider MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `astryx upgrade` runs migrate-internationalization-context: a (or .Provider) becomes ; an inline object maps key by key and a `translate` key, which has no provider input, stays behind a TODO. Only JSX bound to an Astryx import is rewritten; a file that only reads the context is left alone. The breaking changeset now carries the full migration: direction → dir, an own `translate` → messages/overrides, and the codemod. --- .changeset/i18n-context-codemod.md | 7 + .changeset/i18n-en-namespace-slices.md | 2 +- ...rate-internationalization-context.test.mjs | 100 +++++++ .../assets/codemods/transforms/next/index.mjs | 12 +- .../migrate-internationalization-context.mjs | 252 ++++++++++++++++++ 5 files changed, 371 insertions(+), 2 deletions(-) create mode 100644 .changeset/i18n-context-codemod.md create mode 100644 packages/cli/assets/codemods/transforms/next/__tests__/migrate-internationalization-context.test.mjs create mode 100644 packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs diff --git a/.changeset/i18n-context-codemod.md b/.changeset/i18n-context-codemod.md new file mode 100644 index 0000000000000..93b490adc6de1 --- /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 field by field, an inline object key by key, and a `translate` key, which has no provider input, stays behind a TODO. It rewrites JSX bound to an Astryx import (named, aliased, or namespace) and adds the provider import; a file that only reads the context is left alone. + +@vjeux diff --git a/.changeset/i18n-en-namespace-slices.md b/.changeset/i18n-en-namespace-slices.md index ba55d7949255d..27c5645117631 100644 --- a/.changeset/i18n-en-namespace-slices.md +++ b/.changeset/i18n-en-namespace-slices.md @@ -2,6 +2,6 @@ '@astryxdesign/core': minor --- -[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives core components' strings or `useLocale`, `useDirection` and `useCollator`. Migration: mount `InternationalizationProvider`; it takes the same `locale`, `messages`, `overrides` and `dir`. The provider now writes an internal runtime context that those hooks and every core component 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. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice; the components themselves move to it in a follow-up, so bundles do not change yet. The slices are not importable. +[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives core components' strings or `useLocale`, `useDirection` and `useCollator`. 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. `astryx upgrade` runs `migrate-internationalization-context`, which performs the rewrite and leaves a `translate` key behind a TODO. The provider now writes an internal runtime context that those hooks and every core component 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. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice. The slices are not importable. @vjeux 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..d6d08deb18d2b --- /dev/null +++ b/packages/cli/assets/codemods/transforms/next/__tests__/migrate-internationalization-context.test.mjs @@ -0,0 +1,100 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +import {describe, expect, it} from 'vitest'; +import jscodeshift from 'jscodeshift'; +import transform from '../migrate-internationalization-context.mjs'; + +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; compare with whitespace folded. */ +const folded = (/** @type {string} */ text) => text.replace(/\s+/g, ' '); + +describe('migrate-internationalization-context', () => { + it('rewrites a context value from a variable to the provider, prop by prop', () => { + const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; +const app = ;`; + const output = apply(input); + expect(folded(output)).toContain( + '', + ); + 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(output).toContain( + "", + ); + expect(output).toContain(''); + expect(output).not.toContain('overrides='); + }); + + it('leaves a translate key behind a 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( + 'TODO(astryx upgrade): InternationalizationProvider has no `translate` input', + ); + expect(output).toContain('translate: myTranslate'); + }); + + it('keeps the context import when the file still reads the context', () => { + const input = `import {InternationalizationContext, InternationalizationProvider} from '@astryxdesign/core/i18n'; +import {useContext} from 'react'; +function Wrapped({children}) { + const ambient = useContext(InternationalizationContext); + return {children}; +}`; + const output = apply(input); + expect(output).toContain('useContext(InternationalizationContext)'); + expect(output).toMatch( + /import \{InternationalizationContext, InternationalizationProvider\} from '@astryxdesign\/core\/i18n';/, + ); + // A spread cannot be mapped to props; it stays behind the TODO. + expect(output).toContain("locale={'de'}"); + expect(output).toContain('...ambient'); + }); + + it('handles a namespace import and an alias', () => { + const input = `import * as i18n from '@astryxdesign/core/i18n'; +import {InternationalizationContext as Ctx} from '@astryxdesign/core/i18n'; +const a = ; +const b = ;`; + const output = folded(apply(input)); + expect(output).toContain( + '', + ); + expect(output).toContain( + '', + ); + }); + + 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(); + }); +}); diff --git a/packages/cli/assets/codemods/transforms/next/index.mjs b/packages/cli/assets/codemods/transforms/next/index.mjs index 2af3bdfcf09ad..c6aa776a0e725 100644 --- a/packages/cli/assets/codemods/transforms/next/index.mjs +++ b/packages/cli/assets/codemods/transforms/next/index.mjs @@ -7,4 +7,14 @@ * this file into the resolved version folder. */ -export default []; +import migrateInternationalizationContext, { + meta as migrateInternationalizationContextMeta, +} from './migrate-internationalization-context.mjs'; + +export default [ + { + 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..e956956934bfa --- /dev/null +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -0,0 +1,252 @@ +// 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 every + * core component read a runtime context that only `InternationalizationProvider` + * writes. The provider takes the same configuration under its own prop names, + * so the rewrite is mechanical: + * + * → locale={v.locale} + * dir={v.direction} + * messages={v.messages} + * overrides={v.overrides}> + * + * An inline object literal maps key by key and keeps only the keys it has. A + * `translate` key has no provider input — the provider resolves from + * `messages` and `overrides` — so it is left behind a TODO rather than + * dropped. Only elements bound to an Astryx import are rewritten (named, + * aliased, or namespace); the import gains `InternationalizationProvider` + * when the file does not already have it, and loses the context import when + * nothing else reads it. + */ + +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'], +]); + +const TODO = + ' TODO(astryx upgrade): InternationalizationProvider has no `translate` input; ' + + 'express these strings as `messages` (per locale) or `overrides`. '; + +export const meta = { + title: + 'Migrate a raw InternationalizationContext value to InternationalizationProvider', + description: + 'Rewrites `` (or its `.Provider`) to ``, the only way to configure Astryx.', + 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); + + // Local names bound to the Astryx context (named/aliased) and namespaces. + /** @type {Set} */ + const contextNames = new Set(); + /** @type {Set} */ + const namespaceNames = new Set(); + /** @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' && + specifier.imported?.name === CONTEXT + ) { + contextNames.add(specifier.local?.name ?? CONTEXT); + } else if (specifier.type === 'ImportNamespaceSpecifier') { + namespaceNames.add(specifier.local.name); + } + } + }); + if (contextNames.size === 0 && namespaceNames.size === 0) return undefined; + + /** + * The namespace a JSX name renders the context through, or `''` for a + * named binding, or null when the element is not the Astryx context. + * Accepts `Ctx`, `Ctx.Provider`, `ns.Ctx` and `ns.Ctx.Provider`. + * @param {any} name a JSXOpeningElement name + * @returns {string | null} + */ + const contextNamespaceOf = name => { + // Peel a trailing `.Provider`. + if ( + name.type === 'JSXMemberExpression' && + name.property?.type === 'JSXIdentifier' && + name.property.name === 'Provider' + ) { + name = name.object; + } + if (name.type === 'JSXIdentifier') { + return contextNames.has(name.name) ? '' : null; + } + if ( + name.type === 'JSXMemberExpression' && + name.object?.type === 'JSXIdentifier' && + name.property?.type === 'JSXIdentifier' && + name.property.name === CONTEXT && + namespaceNames.has(name.object.name) + ) { + return name.object.name; + } + return null; + }; + + let changed = false; + let needsNamedProvider = false; + root.find(j.JSXElement).forEach((/** @type {any} */ path) => { + const opening = path.node.openingElement; + const namespace = contextNamespaceOf(opening.name); + if (namespace === null) return; + const valueAttribute = (opening.attributes ?? []).find( + (/** @type {any} */ a) => + a.type === 'JSXAttribute' && a.name?.name === 'value', + ); + if ( + !valueAttribute || + valueAttribute.value?.type !== 'JSXExpressionContainer' + ) { + return; + } + const value = valueAttribute.value.expression; + + /** @type {any[]} */ + const props = []; + /** @type {any[]} */ + const leftovers = []; + if (value.type === 'ObjectExpression') { + for (const property of value.properties) { + const key = + property.type === 'Property' || property.type === 'ObjectProperty' + ? (property.key.name ?? property.key.value) + : null; + const prop = key == null ? null : PROP_FOR_KEY.get(key); + if (prop == null) { + leftovers.push(property); + continue; + } + const expression = + property.shorthand && property.value.type === 'Identifier' + ? property.value + : property.value; + props.push( + j.jsxAttribute( + j.jsxIdentifier(prop), + j.jsxExpressionContainer(expression), + ), + ); + } + } else { + for (const [key, prop] of PROP_FOR_KEY) { + props.push( + j.jsxAttribute( + j.jsxIdentifier(prop), + j.jsxExpressionContainer( + j.memberExpression(value, j.identifier(key)), + ), + ), + ); + } + } + + const providerName = + namespace === '' + ? j.jsxIdentifier(PROVIDER) + : j.jsxMemberExpression( + j.jsxIdentifier(namespace), + j.jsxIdentifier(PROVIDER), + ); + if (namespace === '') needsNamedProvider = true; + + const otherAttributes = (opening.attributes ?? []).filter( + (/** @type {any} */ a) => a !== valueAttribute, + ); + opening.name = providerName; + opening.attributes = [...otherAttributes, ...props]; + if (path.node.closingElement) { + path.node.closingElement.name = providerName; + } + if (leftovers.length > 0) { + // Keep what has no provider input in sight, behind a TODO. + const kept = j.jsxExpressionContainer(j.objectExpression(leftovers)); + const attribute = j.jsxAttribute( + j.jsxIdentifier('data-astryx-upgrade-leftover'), + kept, + ); + attribute.comments = [j.commentBlock(TODO, true, false)]; + opening.attributes.push(attribute); + } + changed = true; + }); + + if (!changed) return undefined; + + // Imports: add the provider beside the context; drop the context when the + // file no longer names it. + const stillReadsContext = (/** @type {string} */ localName) => + root + .find(j.Identifier, {name: localName}) + .filter((/** @type {any} */ p) => { + const parent = p.parent?.node; + return !( + parent && + (parent.type === 'ImportSpecifier' || parent.type === 'JSXIdentifier') + ); + }) + .size() > 0 || root.find(j.JSXIdentifier, {name: localName}).size() > 0; + + if (needsNamedProvider) { + const hasProvider = astryxImports.some((/** @type {any} */ path) => + (path.node.specifiers ?? []).some( + (/** @type {any} */ s) => + s.type === 'ImportSpecifier' && s.imported?.name === PROVIDER, + ), + ); + for (const path of astryxImports) { + const specifiers = path.node.specifiers ?? []; + const contextSpecifier = specifiers.find( + (/** @type {any} */ s) => + s.type === 'ImportSpecifier' && s.imported?.name === CONTEXT, + ); + if (!contextSpecifier) continue; + if (!hasProvider) { + specifiers.push( + j.importSpecifier(j.identifier(PROVIDER), j.identifier(PROVIDER)), + ); + } + const localName = contextSpecifier.local?.name ?? CONTEXT; + if (!stillReadsContext(localName)) { + path.node.specifiers = specifiers.filter( + (/** @type {any} */ s) => s !== contextSpecifier, + ); + } + break; + } + } + + return root.toSource({quote: 'single'}); +} From 0ac8edfdfe228d021111562a5a7df8a782433d7b Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 11 Oct 2026 18:27:58 -0700 Subject: [PATCH 04/36] docs(i18n): scope the breaking entry to the hooks this revision moves; qualify the bundle claim MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit At this revision a raw context value still drives the components' strings through useTranslator(); only useLocale, useDirection and useCollator — and the components reading the locale through them — stop following it, and the sweep's changeset takes the strings when the components move. CONTRIBUTING names the apps the slicing saves bytes for. --- .changeset/i18n-en-namespace-slices.md | 2 +- CONTRIBUTING.md | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.changeset/i18n-en-namespace-slices.md b/.changeset/i18n-en-namespace-slices.md index 27c5645117631..9f6f85e9525bb 100644 --- a/.changeset/i18n-en-namespace-slices.md +++ b/.changeset/i18n-en-namespace-slices.md @@ -2,6 +2,6 @@ '@astryxdesign/core': minor --- -[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives core components' strings or `useLocale`, `useDirection` and `useCollator`. 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. `astryx upgrade` runs `migrate-internationalization-context`, which performs the rewrite and leaves a `translate` key behind a TODO. The provider now writes an internal runtime context that those hooks and every core component 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. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice. The slices are not importable. +[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives `useLocale`, `useDirection` and `useCollator`, nor the components that read the locale or direction through them (the date, time and number inputs, Calendar, Chat, PowerSearch, Table sorting, Timestamp). Its strings still follow such a value through `useTranslator()` until the components move to their own slices, which stops that too. 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. `astryx upgrade` runs `migrate-internationalization-context`, which performs the rewrite and leaves a `translate` key behind a TODO. 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. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice. The slices are not importable. @vjeux diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cdaebd90b9c51..6cf5b35096d62 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -294,7 +294,9 @@ export * from './MyComponent'; 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 -bundles only the strings of the components it renders: +that neither mounts `InternationalizationProvider` nor calls `useTranslator()` +(both carry the whole catalog) bundles only the strings of the components it +renders: ```tsx import {useComponentTranslator} from '../i18n/useComponentTranslator'; From 7df8e752cc008bdb929efd8c28aa2cdbea41391b Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 11 Oct 2026 19:16:03 -0700 Subject: [PATCH 05/36] fix(cli): the context codemod edits only what it can prove and rewrite safely MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per the consumer file-modification contract: an element is rewritten only when its name resolves, unshadowed, to the Astryx import (a shadowed local and a type-only import prove nothing); a variable value maps field by field and an inline object literal key by key, each with a TODO for the value's `translate`, which the provider has no input for; any other value — a call, a spread into a literal, a conditional — is left unchanged behind a TODO that says why, since a call would run once per prop and a spread of the ambient value would mount a provider without the app's catalogs. An existing aliased provider import is reused instead of referencing an unbound name. A second run changes nothing. Fixtures cover each case, including idempotence, shadowing and type-only imports; both changesets say what the transform leaves behind, and the breaking entry's component list is corrected. --- .changeset/i18n-context-codemod.md | 2 +- .changeset/i18n-en-namespace-slices.md | 2 +- ...rate-internationalization-context.test.mjs | 94 +++++-- .../migrate-internationalization-context.mjs | 247 +++++++++++------- 4 files changed, 223 insertions(+), 122 deletions(-) diff --git a/.changeset/i18n-context-codemod.md b/.changeset/i18n-context-codemod.md index 93b490adc6de1..224aa27aa4b7e 100644 --- a/.changeset/i18n-context-codemod.md +++ b/.changeset/i18n-context-codemod.md @@ -2,6 +2,6 @@ '@astryxdesign/cli': patch --- -[feat] `astryx upgrade` runs `migrate-internationalization-context`, which rewrites `` (or its `.Provider`) to ``: a variable maps field by field, an inline object key by key, and a `translate` key, which has no provider input, stays behind a TODO. It rewrites JSX bound to an Astryx import (named, aliased, or namespace) and adds the provider import; a file that only reads the context is left alone. +[feat] `astryx upgrade` runs `migrate-internationalization-context`, which rewrites `` (or its `.Provider`) to ``: a variable maps field by field, an inline object literal key by key, and every rewrite carries a TODO for the value's `translate`, which has no provider input (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 index 9f6f85e9525bb..b2d6fbf922b68 100644 --- a/.changeset/i18n-en-namespace-slices.md +++ b/.changeset/i18n-en-namespace-slices.md @@ -2,6 +2,6 @@ '@astryxdesign/core': minor --- -[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives `useLocale`, `useDirection` and `useCollator`, nor the components that read the locale or direction through them (the date, time and number inputs, Calendar, Chat, PowerSearch, Table sorting, Timestamp). Its strings still follow such a value through `useTranslator()` until the components move to their own slices, which stops that too. 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. `astryx upgrade` runs `migrate-internationalization-context`, which performs the rewrite and leaves a `translate` key behind a TODO. 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. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice. The slices are not importable. +[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives `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). Its strings still follow such a value through `useTranslator()`, as does the locale of `DateTimeInput`'s touch field, until the components move to their own slices, which stops that too. 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. `astryx upgrade` runs `migrate-internationalization-context`: a variable or an inline object literal is rewritten to the provider with a TODO for its `translate`; any other value (a call, a spread into a literal, a conditional) is left unchanged behind a TODO saying why, since a spread of the ambient value would mount a provider without the app's catalogs. 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. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice. The slices are not importable. @vjeux 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 index d6d08deb18d2b..6172d309d9641 100644 --- 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 @@ -12,17 +12,32 @@ function apply(source) { return transform({source, path: 'test.tsx'}, api) ?? source; } -/** The printer wraps long attribute lists; compare with whitespace folded. */ -const folded = (/** @type {string} */ text) => text.replace(/\s+/g, ' '); +/** + * 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('rewrites a context value from a variable to the provider, prop by prop', () => { + 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(folded(output)).toContain( + 'overrides={i18n.overrides}>', ); + expect(output).toContain(TRANSLATE_TODO); expect(output).toContain( "import {InternationalizationProvider} from '@astryxdesign/core/i18n';", ); @@ -37,55 +52,85 @@ const app = ( );`; const output = apply(input); - expect(output).toContain( + expect(folded(output)).toContain( "", ); expect(output).toContain(''); + expect(output).toContain(TRANSLATE_TODO); expect(output).not.toContain('overrides='); }); - it('leaves a translate key behind a TODO rather than dropping it', () => { + 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( - 'TODO(astryx upgrade): InternationalizationProvider has no `translate` input', - ); + expect(output).toContain(TRANSLATE_TODO); expect(output).toContain('translate: myTranslate'); }); - it('keeps the context import when the file still reads the context', () => { + 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(' { + it('reuses an aliased provider import and handles a namespace and an aliased context', () => { const input = `import * as i18n from '@astryxdesign/core/i18n'; -import {InternationalizationContext as Ctx} 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('', + "import { InternationalizationProvider as IP } 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'; @@ -97,4 +142,13 @@ const app = { + 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/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index e956956934bfa..0e6a07910f7cd 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -7,21 +7,28 @@ * configures Astryx: `useLocale`, `useDirection`, `useCollator` and every * core component read a runtime context that only `InternationalizationProvider` * writes. The provider takes the same configuration under its own prop names, - * so the rewrite is mechanical: + * so the rewrite is mechanical where the value is plain: * - * → locale={v.locale} - * dir={v.direction} - * messages={v.messages} - * overrides={v.overrides}> + * → locale={v.locale} + * dir={v.direction} + * messages={v.messages} + * overrides={v.overrides}> * - * An inline object literal maps key by key and keeps only the keys it has. A - * `translate` key has no provider input — the provider resolves from - * `messages` and `overrides` — so it is left behind a TODO rather than - * dropped. Only elements bound to an Astryx import are rewritten (named, - * aliased, or namespace); the import gains `InternationalizationProvider` - * when the file does not already have it, and loses the context import when - * nothing else reads it. + * A variable maps field by field; 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). + * 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; @@ -36,15 +43,22 @@ const PROP_FOR_KEY = new Map([ ['overrides', 'overrides'], ]); -const TODO = - ' TODO(astryx upgrade): InternationalizationProvider has no `translate` input; ' + - 'express these strings as `messages` (per locale) or `overrides`. '; +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_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. '; export const meta = { title: 'Migrate a raw InternationalizationContext value to InternationalizationProvider', description: - 'Rewrites `` (or its `.Provider`) to ``, the only way to configure Astryx.', + 'Rewrites `` (or its `.Provider`) to ``, the only way to configure Astryx; a `translate` field and any non-literal value are left behind a TODO.', fileExtensions: ['.tsx', '.jsx', '.ts', '.js', '.mjs', '.cjs'], }; @@ -59,11 +73,14 @@ export default function migrateInternationalizationContext(file, api) { const j = api.jscodeshift; const root = j(file.source); - // Local names bound to the Astryx context (named/aliased) and namespaces. + // 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 providerLocalName = null; /** @type {any[]} */ const astryxImports = []; root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => { @@ -73,11 +90,12 @@ export default function migrateInternationalizationContext(file, api) { astryxImports.push(path); for (const specifier of path.node.specifiers ?? []) { if (specifier.importKind === 'type') continue; - if ( - specifier.type === 'ImportSpecifier' && - specifier.imported?.name === CONTEXT - ) { - contextNames.add(specifier.local?.name ?? CONTEXT); + if (specifier.type === 'ImportSpecifier') { + if (specifier.imported?.name === CONTEXT) { + contextNames.add(specifier.local?.name ?? CONTEXT); + } else if (specifier.imported?.name === PROVIDER) { + providerLocalName = specifier.local?.name ?? PROVIDER; + } } else if (specifier.type === 'ImportNamespaceSpecifier') { namespaceNames.add(specifier.local.name); } @@ -85,15 +103,24 @@ export default function migrateInternationalizationContext(file, api) { }); if (contextNames.size === 0 && namespaceNames.size === 0) return undefined; + /** The binding a JSX identifier resolves to is the module-level import. */ + const isImportBinding = ( + /** @type {any} */ path, + /** @type {string} */ name, + ) => { + const scope = path.scope?.lookup(name); + return scope?.path.node.type === 'Program'; + }; + /** - * The namespace a JSX name renders the context through, or `''` for a - * named binding, or null when the element is not the Astryx context. - * Accepts `Ctx`, `Ctx.Provider`, `ns.Ctx` and `ns.Ctx.Provider`. - * @param {any} name a JSXOpeningElement name + * 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 = name => { - // Peel a trailing `.Provider`. + const contextNamespaceOf = path => { + let name = path.node.openingElement.name; if ( name.type === 'JSXMemberExpression' && name.property?.type === 'JSXIdentifier' && @@ -102,26 +129,38 @@ export default function migrateInternationalizationContext(file, api) { name = name.object; } if (name.type === 'JSXIdentifier') { - return contextNames.has(name.name) ? '' : null; + 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) + 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 opening = path.node.openingElement; - const namespace = contextNamespaceOf(opening.name); + 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', @@ -137,50 +176,59 @@ export default function migrateInternationalizationContext(file, api) { /** @type {any[]} */ const props = []; /** @type {any[]} */ - const leftovers = []; - if (value.type === 'ObjectExpression') { - for (const property of value.properties) { - const key = - property.type === 'Property' || property.type === 'ObjectProperty' - ? (property.key.name ?? property.key.value) - : null; - const prop = key == null ? null : PROP_FOR_KEY.get(key); - if (prop == null) { - leftovers.push(property); - continue; - } - const expression = - property.shorthand && property.value.type === 'Identifier' - ? property.value - : property.value; + const keptKeys = []; + if (value.type === 'Identifier') { + for (const [key, prop] of PROP_FOR_KEY) { props.push( j.jsxAttribute( j.jsxIdentifier(prop), - j.jsxExpressionContainer(expression), + j.jsxExpressionContainer( + j.memberExpression(j.identifier(value.name), j.identifier(key)), + ), ), ); } - } else { - for (const [key, prop] of PROP_FOR_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( - j.memberExpression(value, j.identifier(key)), - ), + j.jsxExpressionContainer(property.value), ), ); } + } else { + // A call, a spread, a conditional: nothing mechanical is safe. + if (addComment(valueAttribute, TODO_EXPRESSION)) changed = true; + return; } const providerName = namespace === '' - ? j.jsxIdentifier(PROVIDER) + ? j.jsxIdentifier(providerLocalName ?? PROVIDER) : j.jsxMemberExpression( j.jsxIdentifier(namespace), j.jsxIdentifier(PROVIDER), ); - if (namespace === '') needsNamedProvider = true; + if (namespace === '' && providerLocalName === null) { + needsNamedProvider = true; + } const otherAttributes = (opening.attributes ?? []).filter( (/** @type {any} */ a) => a !== valueAttribute, @@ -190,63 +238,62 @@ export default function migrateInternationalizationContext(file, api) { if (path.node.closingElement) { path.node.closingElement.name = providerName; } - if (leftovers.length > 0) { - // Keep what has no provider input in sight, behind a TODO. - const kept = j.jsxExpressionContainer(j.objectExpression(leftovers)); - const attribute = j.jsxAttribute( - j.jsxIdentifier('data-astryx-upgrade-leftover'), - kept, + // 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)), ); - attribute.comments = [j.commentBlock(TODO, true, false)]; - opening.attributes.push(attribute); + addComment(kept, TODO_TRANSLATE); + opening.attributes.push(kept); + } else { + addComment(todo, TODO_TRANSLATE); } changed = true; }); if (!changed) return undefined; - // Imports: add the provider beside the context; drop the context when the - // file no longer names it. - const stillReadsContext = (/** @type {string} */ localName) => - root - .find(j.Identifier, {name: localName}) - .filter((/** @type {any} */ p) => { - const parent = p.parent?.node; - return !( - parent && - (parent.type === 'ImportSpecifier' || parent.type === 'JSXIdentifier') - ); - }) - .size() > 0 || root.find(j.JSXIdentifier, {name: localName}).size() > 0; - if (needsNamedProvider) { - const hasProvider = astryxImports.some((/** @type {any} */ path) => - (path.node.specifiers ?? []).some( - (/** @type {any} */ s) => - s.type === 'ImportSpecifier' && s.imported?.name === PROVIDER, - ), - ); for (const path of astryxImports) { const specifiers = path.node.specifiers ?? []; - const contextSpecifier = specifiers.find( - (/** @type {any} */ s) => - s.type === 'ImportSpecifier' && s.imported?.name === CONTEXT, - ); - if (!contextSpecifier) continue; - if (!hasProvider) { - specifiers.push( - j.importSpecifier(j.identifier(PROVIDER), j.identifier(PROVIDER)), - ); - } - const localName = contextSpecifier.local?.name ?? CONTEXT; - if (!stillReadsContext(localName)) { - path.node.specifiers = specifiers.filter( - (/** @type {any} */ s) => s !== contextSpecifier, - ); + if ( + !specifiers.some( + (/** @type {any} */ s) => + s.type === 'ImportSpecifier' && s.imported?.name === CONTEXT, + ) + ) { + continue; } + specifiers.push( + j.importSpecifier(j.identifier(PROVIDER), j.identifier(PROVIDER)), + ); break; } } + // Drop the context import when the file no longer names it anywhere. + 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) { + path.node.specifiers = (path.node.specifiers ?? []).filter( + (/** @type {any} */ s) => + !( + s.type === 'ImportSpecifier' && + s.imported?.name === CONTEXT && + (s.local?.name ?? CONTEXT) === localName + ), + ); + } + } + return root.toSource({quote: 'single'}); } From e3f5f145acfad5742133d17e903715f5380a7fa4 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 11 Oct 2026 19:51:48 -0700 Subject: [PATCH 06/36] fix(cli): the context codemod resolves block scopes The generic scope model gives a block no scope of its own, so a same-named local declared in a module-level block was rewritten into the provider and a real use beside a block-level redeclaration inside a function was skipped. The binding check now walks from the element to the module and treats a declaration of the name in any block, switch, loop head, function parameter list, named function expression or catch clause on the way as a shadow. Fixture: four shadowed uses stay, the one unshadowed use beside them is rewritten, and the import is kept. --- ...rate-internationalization-context.test.mjs | 36 +++++ .../migrate-internationalization-context.mjs | 137 +++++++++++++++++- 2 files changed, 166 insertions(+), 7 deletions(-) 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 index 6172d309d9641..0f0901c9ef521 100644 --- 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 @@ -109,6 +109,42 @@ const b = ;`; ); }); + it('resolves block scopes: a block-level local shadows, and a use beside one is still rewritten', () => { + 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('leaves a shadowed name and a type-only import alone', () => { const shadowed = `import {InternationalizationContext as Ctx} from '@astryxdesign/core/i18n'; function Row({Ctx}) { diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index 0e6a07910f7cd..2409d62f0501c 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -25,7 +25,9 @@ * 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). + * rewritten (named, aliased, or namespace; a type-only import proves nothing; + * a same-named declaration in any block, function, loop head or catch clause + * between the element and the module shadows it). * 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. @@ -103,13 +105,134 @@ export default function migrateInternationalizationContext(file, api) { }); if (contextNames.size === 0 && namespaceNames.size === 0) return undefined; - /** The binding a JSX identifier resolves to is the module-level import. */ - const isImportBinding = ( - /** @type {any} */ path, - /** @type {string} */ name, + /** The identifiers a binding pattern declares. */ + const patternNames = ( + /** @type {any} */ node, + /** @type {string[]} */ out = [], ) => { - const scope = path.scope?.lookup(name); - return scope?.path.node.type === 'Program'; + 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 statement list declares `name` (as a variable, function or class). */ + const bodyDeclares = ( + /** @type {any[]} */ statements, + /** @type {string} */ name, + ) => + statements.some((/** @type {any} */ statement) => { + if (statement.type === 'VariableDeclaration') { + return statement.declarations.some((/** @type {any} */ d) => + patternNames(d.id).includes(name), + ); + } + if ( + statement.type === 'FunctionDeclaration' || + statement.type === 'ClassDeclaration' + ) { + return statement.id?.name === name; + } + return false; + }); + + /** + * 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); + 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 'FunctionDeclaration': + case 'FunctionExpression': + case 'ArrowFunctionExpression': + case 'ObjectMethod': + case 'ClassMethod': + if ( + node.params.some((/** @type {any} */ param) => + patternNames(param).includes(name), + ) + ) { + return false; + } + if (node.type === 'FunctionExpression' && node.id?.name === name) { + return false; + } + break; + case 'CatchClause': + if (node.param && patternNames(node.param).includes(name)) + return false; + break; + default: + break; + } + } + return false; }; /** From 58003b9d48aaacd5f1564a92c584429b0b376c6d Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 11 Oct 2026 20:21:47 -0700 Subject: [PATCH 07/36] fix(cli): the context codemod imports the provider under a free name and sees hoisted vars MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A module that already binds InternationalizationProvider — its own wrapper of that name, or an import from its own module — now gets the Astryx provider under a free alias instead of a second binding of the same name. A `var` anywhere in the enclosing function (a nested block, a loop head) and a named class expression's own name shadow the import like a parameter does. Fixtures for each shape. --- ...rate-internationalization-context.test.mjs | 52 ++++++++ .../migrate-internationalization-context.mjs | 115 +++++++++++++++++- 2 files changed, 162 insertions(+), 5 deletions(-) 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 index 0f0901c9ef521..e7da43aed3a54 100644 --- 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 @@ -145,6 +145,58 @@ function F({flag}) { ); }); + 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 shadowed = `import {InternationalizationContext as Ctx} from '@astryxdesign/core/i18n'; function Row({Ctx}) { diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index 2409d62f0501c..1ebe60708e55c 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -27,7 +27,10 @@ * 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, function, loop head or catch clause - * between the element and the module shadows it). + * between the element and the module shadows it, as does 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. * 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. @@ -105,6 +108,59 @@ export default function migrateInternationalizationContext(file, api) { }); 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.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.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). + if (providerLocalName === null) { + let candidate = PROVIDER; + for (let n = 2; boundNames.has(candidate); n += 1) { + candidate = `${PROVIDER}${n}`; + } + providerLocalName = candidate; + } + const providerNeedsImport = !astryxImports.some((/** @type {any} */ path) => + (path.node.specifiers ?? []).some( + (/** @type {any} */ s) => + s.type === 'ImportSpecifier' && s.imported?.name === PROVIDER, + ), + ); + /** The identifiers a binding pattern declares. */ const patternNames = ( /** @type {any} */ node, @@ -143,6 +199,46 @@ export default function migrateInternationalizationContext(file, api) { 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' + ) { + 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, @@ -177,7 +273,9 @@ export default function migrateInternationalizationContext(file, api) { const node = p.node; switch (node.type) { case 'Program': - return !bodyDeclares(node.body, name); + return ( + !bodyDeclares(node.body, name) && !declaresVar(node.body, name) + ); case 'BlockStatement': if (bodyDeclares(node.body, name)) return false; break; @@ -223,6 +321,10 @@ export default function migrateInternationalizationContext(file, api) { 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)) @@ -344,12 +446,12 @@ export default function migrateInternationalizationContext(file, api) { const providerName = namespace === '' - ? j.jsxIdentifier(providerLocalName ?? PROVIDER) + ? j.jsxIdentifier(providerLocalName) : j.jsxMemberExpression( j.jsxIdentifier(namespace), j.jsxIdentifier(PROVIDER), ); - if (namespace === '' && providerLocalName === null) { + if (namespace === '' && providerNeedsImport) { needsNamedProvider = true; } @@ -390,7 +492,10 @@ export default function migrateInternationalizationContext(file, api) { continue; } specifiers.push( - j.importSpecifier(j.identifier(PROVIDER), j.identifier(PROVIDER)), + j.importSpecifier( + j.identifier(PROVIDER), + j.identifier(providerLocalName), + ), ); break; } From 17e3421204d53de9dfe749eab409a5583f562991 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 11 Oct 2026 20:51:16 -0700 Subject: [PATCH 08/36] fix(cli): the context codemod checks the provider name it writes; trim the runtime half The provider name written must itself resolve to the provider's value import at the edit site: a `type` specifier of the provider no longer counts as its import, a local that shadows the provider import leaves the element behind the TODO, and an element whose value arrives through spread props gets the same TODO. Fixtures for each. The lint rule's message edits stay; its formatting reflow is dropped. The slice-coverage rule of check:i18n-catalog moves to the component sweep, where its first callers land. --- .../no-hardcoded-i18n-string.js | 59 ++--- ...rate-internationalization-context.test.mjs | 33 +++ .../migrate-internationalization-context.mjs | 28 ++- scripts/check-i18n-catalog.mjs | 231 +----------------- scripts/check-i18n-catalog.test.mjs | 145 ----------- 5 files changed, 82 insertions(+), 414 deletions(-) diff --git a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js index cfdb10f06ebf4..a9a3efc8a45d2 100644 --- a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js +++ b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js @@ -111,15 +111,15 @@ const ARIA_TEXT_ATTRS = new Set([ * one of these is flagged. */ const SUFFIX_PATTERNS = [ - /Label$/, // saveButtonLabel, cancelLabel, previousLabel, ... - /Text$/, // emptySearchText, helperText, errorText, ... - /Placeholder$/, // searchPlaceholder, timePlaceholder, ... - /Title$/, // dialogTitle, ... - /Message$/, // disabledMessage, errorMessage, ... - /Tooltip$/, // ... - /Hint$/, // ... - /Description$/, // ... - /Summary$/, // ... + /Label$/, // saveButtonLabel, cancelLabel, previousLabel, ... + /Text$/, // emptySearchText, helperText, errorText, ... + /Placeholder$/,// searchPlaceholder, timePlaceholder, ... + /Title$/, // dialogTitle, ... + /Message$/, // disabledMessage, errorMessage, ... + /Tooltip$/, // ... + /Hint$/, // ... + /Description$/,// ... + /Summary$/, // ... ]; function isUserFacingName(name) { @@ -154,11 +154,7 @@ function looksUserFacing(value) { return false; } // All-caps enum constant like `IS_ANY_OF` - if ( - value === value.toUpperCase() && - /[A-Z_]/.test(value) && - !/\s/.test(value) - ) { + if (value === value.toUpperCase() && /[A-Z_]/.test(value) && !/\s/.test(value)) { return false; } // Single lowercase word (identifier-shaped: `contains`, `email`, `foo123`) @@ -231,20 +227,8 @@ function reportUserFacingLiteralsIn(expr, name, context, isDefault, opts = {}) { } return; case 'ConditionalExpression': - reportUserFacingLiteralsIn( - expr.consequent, - name, - context, - isDefault, - opts, - ); - reportUserFacingLiteralsIn( - expr.alternate, - name, - context, - isDefault, - opts, - ); + reportUserFacingLiteralsIn(expr.consequent, name, context, isDefault, opts); + reportUserFacingLiteralsIn(expr.alternate, name, context, isDefault, opts); return; case 'LogicalExpression': // Only the right side can be a fallback/default string; the left is a @@ -270,14 +254,14 @@ const rule = { messages: { hardcodedString: 'Hardcoded user-facing string {{value}} in `{{name}}`. ' + - "Route through `t('..')` via `useComponentTranslator()` (in core; `useTranslator()` elsewhere) 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 ' + - "`const {{name}} = {{name}}FromProps ?? t('..');` inside the body.", + '`const {{name}} = {{name}}FromProps ?? t(\'..\');` inside the body.', hardcodedCallArg: 'Hardcoded user-facing string {{value}} passed to `{{name}}()`. ' + - "Route through `t('..')` via `useComponentTranslator()` (in core; `useTranslator()` elsewhere) so it can be localized.", + 'Route through `t(\'..\')` via `useComponentTranslator()` (in core; `useTranslator()` elsewhere) so it can be localized.', }, schema: [ { @@ -308,7 +292,10 @@ const rule = { // 1. JSX attribute string literals: JSXAttribute(node) { if (!node.name || node.name.type === 'JSXNamespacedName') return; - const name = node.name.type === 'JSXIdentifier' ? node.name.name : null; + const name = + node.name.type === 'JSXIdentifier' + ? node.name.name + : null; if (!isUserFacingName(name)) return; // 1. Bare string-literal attribute: @@ -347,8 +334,8 @@ const rule = { node.key.type === 'Identifier' ? node.key.name : node.key.type === 'Literal' - ? node.key.value - : null; + ? node.key.value + : null; if (!isUserFacingName(name)) return; if ( node.value.type !== 'Literal' || @@ -379,8 +366,8 @@ const rule = { property.key.type === 'Identifier' ? property.key.name : property.key.type === 'Literal' - ? property.key.value - : null; + ? property.key.value + : null; if (!isUserFacingName(name)) return; reportUserFacingLiteralsIn( node.right, 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 index e7da43aed3a54..879c0cea6eb9e 100644 --- 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 @@ -197,6 +197,39 @@ const app = { + 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(); + expect(apply(input).match(new RegExp(EXPRESSION_TODO, 'g'))).toHaveLength( + 2, + ); + }); + it('leaves a shadowed name and a type-only import alone', () => { const shadowed = `import {InternationalizationContext as Ctx} from '@astryxdesign/core/i18n'; function Row({Ctx}) { diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index 1ebe60708e55c..69d3802cf6021 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -30,7 +30,9 @@ * between the element and the module shadows it, as does 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. + * `InternationalizationProvider` to something of its own, and the name + * written must itself reach that import at the edit site. An element whose + * value arrives through spread props gets the TODO and no rewrite. * 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. @@ -154,10 +156,14 @@ export default function migrateInternationalizationContext(file, api) { } providerLocalName = candidate; } + // 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.imported?.name === PROVIDER, + s.type === 'ImportSpecifier' && + s.importKind !== 'type' && + s.imported?.name === PROVIDER, ), ); @@ -390,12 +396,16 @@ export default function migrateInternationalizationContext(file, api) { (/** @type {any} */ a) => a.type === 'JSXAttribute' && a.name?.name === 'value', ); - if ( - !valueAttribute || - valueAttribute.value?.type !== 'JSXExpressionContainer' - ) { + 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; const value = valueAttribute.value.expression; /** @type {any[]} */ @@ -444,6 +454,12 @@ export default function migrateInternationalizationContext(file, api) { 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, TODO_EXPRESSION)) changed = true; + return; + } const providerName = namespace === '' ? j.jsxIdentifier(providerLocalName) diff --git a/scripts/check-i18n-catalog.mjs b/scripts/check-i18n-catalog.mjs index ae39a9526f550..0ad65b71c9f54 100644 --- a/scripts/check-i18n-catalog.mjs +++ b/scripts/check-i18n-catalog.mjs @@ -31,15 +31,6 @@ * gate and that lint rule cannot disagree about what a key reference is. A * reference whose key is not statically knowable is reported as unverifiable * rather than passed or failed silently. - * - * 4. Slice coverage. A component in packages/core/src renders with - * `useComponentTranslator()`, where the slice is the English - * catalog of one namespace (`generated-locales/en/.generated`) - * or a module-level spread of several. Every `@astryx..*` key - * the file reads must belong to a namespace its slice carries, or the - * component would show the key at runtime. A file that reads keys but - * calls no translator hook (it is handed `t`) is covered by the slices - * of the hook callers in its component directory. */ import fs from 'node:fs'; @@ -76,15 +67,6 @@ const LOCALE_MISSING_KEYS_ARE_FATAL = false; * exclusions the crowdin-download workflow applies to this directory. */ const NOT_A_SHIPPED_LOCALE = new Set(['en.json', 'pseudo.json']); -/** The package whose components carry their own English slices (rule 4). */ -const SLICED_SRC_DIR = 'packages/core/src'; -const COMPONENT_HOOK = 'useComponentTranslator'; -const CONSUMER_HOOK = 'useTranslator'; -/** The public context, which binds the whole catalog to its `translate`. */ -const CONSUMER_CONTEXT = 'InternationalizationContext'; -const SLICE_MODULE_RE = - /\/i18n\/generated-locales\/en\/([A-Za-z0-9]+)\.generated$/; - /** Translator call targets, per the i18n-key-format lint rule. */ const TRANSLATOR_CALL_NAMES = new Set(['t', 'translator', 'translate']); @@ -597,187 +579,6 @@ function extractKeyRefs(source, fileName) { return {refs, unresolved}; } -/** - * The namespace of an astryx key: `@astryx.button.loading` → `button`. - */ -function namespaceOf(key) { - return key.slice(KEY_PREFIX.length).split('.')[0]; -} - -/** - * Rule 4's view of one source file: which translator hooks it calls and the - * namespaces of the slices it passes them. - * - * A slice argument is an identifier that is either the default import of a - * `generated-locales/en/.generated` module, or a module-level - * `const` whose initializer spreads such imports. Anything else is reported - * as an unresolvable slice. - * - * @param {string} source file contents - * @param {string} fileName display name (drives .tsx parsing) - * @returns {{hookCalls: {line: number, namespaces: string[] | null}[], - * consumerHookImports: {line: number, name: string}[]}} - */ -function extractSliceUsage(source, fileName) { - const sourceFile = ts.createSourceFile( - fileName, - source, - ts.ScriptTarget.Latest, - true, - fileName.endsWith('.tsx') || fileName.endsWith('.jsx') - ? ts.ScriptKind.TSX - : ts.ScriptKind.TS, - ); - const lineOf = node => - sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + - 1; - - // Default imports of slice modules, by local name → namespace; and the - // lines where the consumer hook is imported from an i18n module. - const sliceImports = new Map(); - const consumerHookImports = []; - for (const statement of sourceFile.statements) { - if (!ts.isImportDeclaration(statement)) continue; - if (!ts.isStringLiteral(statement.moduleSpecifier)) continue; - const specifier = statement.moduleSpecifier.text; - const clause = statement.importClause; - if (!clause) continue; - const sliceMatch = specifier.match(SLICE_MODULE_RE); - if (sliceMatch && clause.name) { - sliceImports.set(clause.name.text, sliceMatch[1]); - } - if ( - /(^|\/)i18n(\/[^/]+)?$/.test(specifier) && - clause.namedBindings && - ts.isNamedImports(clause.namedBindings) - ) { - for (const element of clause.namedBindings.elements) { - const imported = (element.propertyName ?? element.name).text; - if ( - (imported === CONSUMER_HOOK || imported === CONSUMER_CONTEXT) && - !element.isTypeOnly - ) { - consumerHookImports.push({line: lineOf(element), name: imported}); - } - } - } - } - - // Module-level `const x = {...a, ...b}` over slice imports. - const merged = new Map(); - for (const statement of sourceFile.statements) { - if (!ts.isVariableStatement(statement)) continue; - for (const decl of statement.declarationList.declarations) { - if (!ts.isIdentifier(decl.name) || !decl.initializer) continue; - const init = unwrap(decl.initializer); - if (!ts.isObjectLiteralExpression(init)) continue; - const namespaces = []; - let resolvable = true; - for (const prop of init.properties) { - if ( - ts.isSpreadAssignment(prop) && - ts.isIdentifier(prop.expression) && - sliceImports.has(prop.expression.text) - ) { - namespaces.push(sliceImports.get(prop.expression.text)); - } else { - resolvable = false; - } - } - if (resolvable && namespaces.length > 0) { - merged.set(decl.name.text, namespaces); - } - } - } - - const resolveSlice = node => { - const n = unwrap(node); - if (!n || !ts.isIdentifier(n)) return null; - if (sliceImports.has(n.text)) return [sliceImports.get(n.text)]; - if (merged.has(n.text)) return merged.get(n.text); - return null; - }; - - const hookCalls = []; - const visit = node => { - if ( - ts.isCallExpression(node) && - ts.isIdentifier(node.expression) && - node.expression.text === COMPONENT_HOOK - ) { - const arg = node.arguments[0]; - hookCalls.push({ - line: lineOf(node), - namespaces: arg ? resolveSlice(arg) : null, - }); - } - ts.forEachChild(node, visit); - }; - visit(sourceFile); - - return {hookCalls, consumerHookImports}; -} - -/** - * Rule 4 over the sliced package: every key a file reads is carried by the - * slices it (or, for a file handed `t`, its component directory) renders - * with. Pure over the per-file facts, so it is unit-testable. - * - * @param {Map} files keyed by - * path relative to the sliced source dir - * @returns {string[]} human-readable problems (empty = covered) - */ -function checkSliceCoverage(files) { - const problems = []; - const coveredByDir = new Map(); - for (const [rel, {hookCalls}] of files) { - const dir = rel.split('/')[0]; - const set = coveredByDir.get(dir) ?? new Set(); - for (const call of hookCalls) { - for (const ns of call.namespaces ?? []) set.add(ns); - } - coveredByDir.set(dir, set); - } - for (const [rel, {refs, hookCalls}] of files) { - for (const call of hookCalls) { - if (call.namespaces === null) { - problems.push( - `${rel}:${call.line} ${COMPONENT_HOOK}: the slice is not a default import of ` + - `generated-locales/en/.generated, or a module-level spread of such imports`, - ); - } - } - // A file that calls no component hook reads its keys through the - // consumer hook or a `t` it was handed; only a slice-rendering file, or a - // file in a directory that has one, is held to its slices. - const dirCovered = coveredByDir.get(rel.split('/')[0]); - if ( - refs.length === 0 || - (hookCalls.length === 0 && (dirCovered == null || dirCovered.size === 0)) - ) { - continue; - } - const own = new Set(); - for (const call of hookCalls) { - for (const ns of call.namespaces ?? []) own.add(ns); - } - const covering = - hookCalls.length > 0 ? own : (coveredByDir.get(rel.split('/')[0]) ?? own); - const where = hookCalls.length > 0 ? 'its slice' : "its directory's slices"; - for (const {line, key} of refs) { - const ns = namespaceOf(key); - if (!covering.has(ns)) { - problems.push( - `${rel}:${line} ${key} is outside ${where} (${[...covering].sort().join(', ') || 'none'})`, - ); - } - } - } - return problems; -} - /** * Validate the shape of the source catalog: every entry needs a usable * `defaultMessage` and a non-empty `description`. @@ -890,21 +691,16 @@ function main() { const unverifiable = []; let refCount = 0; const seen = new Set(); - const slicedFiles = new Map(); for (const dir of SRC_DIRS) { const abs = path.join(ROOT, dir); if (!fs.existsSync(abs)) continue; for (const file of walk(abs)) { const rel = path.relative(ROOT, file); - const source = fs.readFileSync(file, 'utf8'); - const {refs, unresolved} = extractKeyRefs(source, file); - if (dir === SLICED_SRC_DIR && !rel.includes('/i18n/')) { - slicedFiles.set(path.relative(abs, file), { - refs, - ...extractSliceUsage(source, file), - }); - } + const {refs, unresolved} = extractKeyRefs( + fs.readFileSync(file, 'utf8'), + file, + ); refCount += refs.length; for (const {line, key} of refs) { seen.add(key); @@ -924,18 +720,6 @@ function main() { }); } - // 4. Slice coverage - const sliceProblems = checkSliceCoverage(slicedFiles); - if (sliceProblems.length > 0) { - errors.push({ - title: `${sliceProblems.length} slice coverage problem(s) in ${SLICED_SRC_DIR}`, - lines: sliceProblems, - hint: - `Render with ${COMPONENT_HOOK}() where the slice imports ` + - `generated-locales/en/.generated for every namespace the file reads.`, - }); - } - // 2. Locale parity const localeFiles = fs .readdirSync(path.join(ROOT, LOCALES_DIR)) @@ -1028,13 +812,8 @@ function main() { process.exit(1); } - const slicedHookCalls = [...slicedFiles.values()].reduce( - (n, f) => n + f.hookCalls.length, - 0, - ); console.log( `✓ check:i18n-catalog — ${seen.size} key(s) over ${refCount} reference(s) resolve; ` + - `${slicedHookCalls} ${COMPONENT_HOOK} call(s) carry the namespaces their files read; ` + `${enKeys.size} en and ${translatedMessageCount} translated message(s) parsed and contract-checked; ` + `plural categories evaluated with runtime CLDR ${process.versions.cldr}; ` + `${localeFiles.length} locale(s) consistent`, @@ -1049,8 +828,6 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) { export { extractKeyRefs, - extractSliceUsage, - checkSliceCoverage, validateSourceCatalog, compareLocale, parseIcuMessage, diff --git a/scripts/check-i18n-catalog.test.mjs b/scripts/check-i18n-catalog.test.mjs index f62b19be5032d..b3495d2d81884 100644 --- a/scripts/check-i18n-catalog.test.mjs +++ b/scripts/check-i18n-catalog.test.mjs @@ -13,8 +13,6 @@ import {describe, it, expect} from 'vitest'; import { extractKeyRefs, - extractSliceUsage, - checkSliceCoverage, validateSourceCatalog, compareLocale, parseIcuMessage, @@ -483,146 +481,3 @@ describe('ICU plural categories', () => { ]); }); }); - -describe('extractSliceUsage — the slices a component renders with', () => { - const usage = source => extractSliceUsage(source, 'Test.tsx'); - - it('resolves a slice import passed to the component hook', () => { - const {hookCalls, consumerHookImports} = usage(` - import {useComponentTranslator} from '../i18n/useComponentTranslator'; - import buttonMessages from '../i18n/generated-locales/en/button.generated'; - function Button() { const t = useComponentTranslator(buttonMessages); return t('@astryx.button.loading'); } - `); - expect(hookCalls).toEqual([{line: 4, namespaces: ['button']}]); - expect(consumerHookImports).toEqual([]); - }); - - it('resolves a module-level spread of several slices', () => { - const {hookCalls} = usage(` - import {useComponentTranslator} from '../i18n/useComponentTranslator'; - import dateInputMessages from '../i18n/generated-locales/en/dateInput.generated'; - import timeInputMessages from '../i18n/generated-locales/en/timeInput.generated'; - const messages = {...dateInputMessages, ...timeInputMessages}; - function Field() { const t = useComponentTranslator(messages); return t('@astryx.dateInput.open'); } - `); - expect(hookCalls).toEqual([ - {line: 6, namespaces: ['dateInput', 'timeInput']}, - ]); - }); - - it('declares an argument it cannot trace to slice imports unresolvable', () => { - const {hookCalls} = usage(` - import {useComponentTranslator} from '../i18n/useComponentTranslator'; - const messages = {'@astryx.button.loading': 'Loading'}; - function Button() { const t = useComponentTranslator(messages); return t('@astryx.button.loading'); } - `); - expect(hookCalls).toEqual([{line: 4, namespaces: null}]); - }); - - it('reports a value import of the consumer hook or the public context, and not a type import', () => { - expect( - usage(`import {useLocale, useTranslator} from '../i18n';`) - .consumerHookImports, - ).toEqual([{line: 1, name: 'useTranslator'}]); - expect( - usage(`import {useTranslator} from '../../../i18n/useTranslator';`) - .consumerHookImports, - ).toEqual([{line: 1, name: 'useTranslator'}]); - expect( - usage(`import {InternationalizationContext} from '../i18n';`) - .consumerHookImports, - ).toEqual([{line: 1, name: 'InternationalizationContext'}]); - expect( - usage( - `import {useLocale, type TranslatorFn, type InternationalizationContextValue} from '../i18n';`, - ).consumerHookImports, - ).toEqual([]); - }); -}); - -describe('checkSliceCoverage — every key a file reads is in a slice it renders with', () => { - const file = (refs, hookCalls, consumerHookImports = []) => ({ - refs: refs.map((key, i) => ({line: i + 1, key})), - hookCalls, - consumerHookImports, - }); - - it('passes a file whose keys are all in its slices', () => { - expect( - checkSliceCoverage( - new Map([ - [ - 'DateInput/DateInput.tsx', - file( - ['@astryx.dateInput.open', '@astryx.calendar.today'], - [{line: 9, namespaces: ['dateInput', 'calendar']}], - ), - ], - ]), - ), - ).toEqual([]); - }); - - it('names the key, the line and the slices when a key is outside them', () => { - expect( - checkSliceCoverage( - new Map([ - [ - 'Button/Button.tsx', - file( - ['@astryx.button.loading'], - [{line: 9, namespaces: ['pagination']}], - ), - ], - ]), - ), - ).toEqual([ - 'Button/Button.tsx:1 @astryx.button.loading is outside its slice (pagination)', - ]); - }); - - it('covers a file handed `t` by the hook callers of its component directory', () => { - const files = new Map([ - [ - 'PowerSearch/PowerSearchToken.tsx', - file([], [{line: 3, namespaces: ['powersearch']}]), - ], - [ - 'PowerSearch/formatFilterValue.ts', - file(['@astryx.powersearch.between'], []), - ], - ['Table/helper.ts', file(['@astryx.powersearch.between'], [])], - [ - 'Table/Table.tsx', - file(['@astryx.table.sort'], [{line: 3, namespaces: ['table']}]), - ], - ]); - expect(checkSliceCoverage(files)).toEqual([ - "Table/helper.ts:1 @astryx.powersearch.between is outside its directory's slices (table)", - ]); - }); - - it('leaves a file that renders with no component hook, in a directory with none, alone', () => { - expect( - checkSliceCoverage( - new Map([['Legacy/Legacy.tsx', file(['@astryx.legacy.label'], [])]]), - ), - ).toEqual([]); - }); - - it('reports an unresolvable slice', () => { - expect( - checkSliceCoverage( - new Map([ - [ - 'Spinner/Spinner.tsx', - file(['@astryx.spinner.loading'], [{line: 9, namespaces: null}]), - ], - ]), - ), - ).toEqual([ - 'Spinner/Spinner.tsx:9 useComponentTranslator: the slice is not a default import of generated-locales/en/.generated, or a module-level spread of such imports', - 'Spinner/Spinner.tsx:1 @astryx.spinner.loading is outside its slice (none)', - ]); - }); -}); From db490871ec30694420cb9c4a474a101752de2454 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 11 Oct 2026 21:23:28 -0700 Subject: [PATCH 09/36] fix(cli): type the codemod's provider name as a string The CLI's strict typecheck refused `string | null` where a string goes; the name is resolved once, up front, and never null. --- .../next/migrate-internationalization-context.mjs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index 69d3802cf6021..172b4cba56843 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -87,7 +87,7 @@ export default function migrateInternationalizationContext(file, api) { /** @type {Set} */ const namespaceNames = new Set(); /** @type {string | null} */ - let providerLocalName = null; + let importedProviderName = null; /** @type {any[]} */ const astryxImports = []; root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => { @@ -101,7 +101,7 @@ export default function migrateInternationalizationContext(file, api) { if (specifier.imported?.name === CONTEXT) { contextNames.add(specifier.local?.name ?? CONTEXT); } else if (specifier.imported?.name === PROVIDER) { - providerLocalName = specifier.local?.name ?? PROVIDER; + importedProviderName = specifier.local?.name ?? PROVIDER; } } else if (specifier.type === 'ImportNamespaceSpecifier') { namespaceNames.add(specifier.local.name); @@ -149,12 +149,12 @@ export default function migrateInternationalizationContext(file, api) { // 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). - if (providerLocalName === null) { - let candidate = PROVIDER; - for (let n = 2; boundNames.has(candidate); n += 1) { - candidate = `${PROVIDER}${n}`; + /** @type {string} */ + let providerLocalName = importedProviderName ?? PROVIDER; + if (importedProviderName === null) { + for (let n = 2; boundNames.has(providerLocalName); n += 1) { + providerLocalName = `${PROVIDER}${n}`; } - providerLocalName = candidate; } // A `type` specifier of the provider proves nothing at runtime, so it does // not count as an import either. From 80d6ebfdd0b24ce1190c429e3d7544c61ea7fce7 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 11 Oct 2026 22:07:32 -0700 Subject: [PATCH 10/36] fix(cli): the context codemod maps only a variable's required fields; qualify the check-rule mentions `overrides` is the one optional field of a context value, so a variable whose inferred type lacks it would fail to typecheck as `v.overrides`; a variable now maps `locale`, `direction` (as `dir`) and `messages`, and its TODO names `overrides` beside `translate`. A fixture typechecks the rewritten output against the real i18n source types with tsc, and shows the naive `overrides={v.overrides}` is TS2339. CONTRIBUTING and the comments in resolve.ts, resolve.test.ts and useComponentTranslator.ts say the slice-coverage rule lands with the component sweep. --- CONTRIBUTING.md | 3 +- ...rate-internationalization-context.test.mjs | 77 +++++++++++++++++-- .../migrate-internationalization-context.mjs | 27 +++++-- .../core/src/i18n/__tests__/resolve.test.ts | 3 +- packages/core/src/i18n/resolve.ts | 3 +- .../core/src/i18n/useComponentTranslator.ts | 3 +- 6 files changed, 99 insertions(+), 17 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6cf5b35096d62..69c2733ef12af 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -312,7 +312,8 @@ 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. The +`pnpm check:i18n-catalog` gains a slice-coverage rule with the component +sweep, failing a key read outside the file's slice. 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 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 index 879c0cea6eb9e..59219b99f93f9 100644 --- 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 @@ -1,9 +1,17 @@ // 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 from '../migrate-internationalization-context.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: () => {}}; @@ -32,12 +40,11 @@ describe('migrate-internationalization-context', () => { const app = ;`; const output = apply(input); expect(folded(output)).toContain( - 'locale={i18n.locale} dir={i18n.direction} messages={i18n.messages}', - ); - expect(folded(output)).toContain( - 'overrides={i18n.overrides}>', + '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';", ); @@ -137,7 +144,7 @@ function F({flag}) { expect(output).toContain('; }'); // The one unshadowed use is rewritten. expect(output).toContain( - '', + '', ); // The context import stays: the file still names Ctx. expect(output).toMatch( @@ -163,7 +170,7 @@ const ok = ;`; expect(output.match(//g)).toHaveLength(2); expect(output).toContain(''); expect(output).toContain( - '', + '', ); }); @@ -177,7 +184,7 @@ function InternationalizationProvider({children}) { "import {InternationalizationProvider as InternationalizationProvider2} from '@astryxdesign/core/i18n';", ); expect(output).toContain( - '{children}', + '{children}', ); expect(output).toContain( 'function InternationalizationProvider({children})', @@ -264,6 +271,62 @@ const app = { + // 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('is idempotent', () => { const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; const a = ; diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index 172b4cba56843..8ecaefcaa3857 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -12,11 +12,11 @@ * → locale={v.locale} * dir={v.direction} - * messages={v.messages} - * overrides={v.overrides}> + * messages={v.messages}> * - * A variable maps field by field; an inline object literal maps key by key - * and keeps only the keys it has. The provider has no `translate` input, and + * 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 @@ -50,10 +50,21 @@ const PROP_FOR_KEY = new Map([ ['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_EXPRESSION = `${TODO_PREFIX}a raw InternationalizationContext value no longer configures Astryx; ` + 'mount InternationalizationProvider with this value\u2019s `locale`, `direction` (as `dir`), ' + @@ -413,7 +424,8 @@ export default function migrateInternationalizationContext(file, api) { /** @type {any[]} */ const keptKeys = []; if (value.type === 'Identifier') { - for (const [key, prop] of PROP_FOR_KEY) { + for (const key of REQUIRED_KEYS) { + const prop = /** @type {string} */ (PROP_FOR_KEY.get(key)); props.push( j.jsxAttribute( j.jsxIdentifier(prop), @@ -489,7 +501,10 @@ export default function migrateInternationalizationContext(file, api) { addComment(kept, TODO_TRANSLATE); opening.attributes.push(kept); } else { - addComment(todo, TODO_TRANSLATE); + addComment( + todo, + value.type === 'Identifier' ? TODO_VARIABLE : TODO_TRANSLATE, + ); } changed = true; }); diff --git a/packages/core/src/i18n/__tests__/resolve.test.ts b/packages/core/src/i18n/__tests__/resolve.test.ts index 43a700fa9ee37..8433db2bd2e9b 100644 --- a/packages/core/src/i18n/__tests__/resolve.test.ts +++ b/packages/core/src/i18n/__tests__/resolve.test.ts @@ -93,7 +93,8 @@ describe('resolve — basic lookup', () => { ), ).toBe('Go to next page'); // A key of another namespace is not in the slice: the key comes back and - // the one-time warning fires, which is what check:i18n-catalog prevents. + // the one-time warning fires, which is what check:i18n-catalog's + // slice-coverage rule (landing with the component sweep) prevents. expect( resolve( '@astryx.button.loading', diff --git a/packages/core/src/i18n/resolve.ts b/packages/core/src/i18n/resolve.ts index 6d488afd7cba5..568f9496628d7 100644 --- a/packages/core/src/i18n/resolve.ts +++ b/packages/core/src/i18n/resolve.ts @@ -130,7 +130,8 @@ export function getResolve( // Fires ONLY when a key is missing from every source including the // caller's English fallback — a real bug (typo, stale catalog, deleted // key, or a component reading a key outside its own namespace slice; - // `check:i18n-catalog` catches the last one before it ships). + // `check:i18n-catalog`'s slice-coverage rule, which lands with the + // component sweep, catches the last one before it ships). // Fallback to `en` from a non-en locale is expected and stays silent, // matching the FormatJS / i18next default. warnOnce( diff --git a/packages/core/src/i18n/useComponentTranslator.ts b/packages/core/src/i18n/useComponentTranslator.ts index 3fe36726498f6..475571f4f8ed3 100644 --- a/packages/core/src/i18n/useComponentTranslator.ts +++ b/packages/core/src/i18n/useComponentTranslator.ts @@ -17,7 +17,8 @@ * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/i18n/useTranslator.ts * - /packages/core/src/i18n/resolve.ts - * - /scripts/check-i18n-catalog.mjs (the slice-coverage rule) + * - /scripts/check-i18n-catalog.mjs (its slice-coverage rule lands with the + * component sweep) */ import {use, useMemo} from 'react'; From d99cf19e663fb37cc05884b1b61bd66dbd1c9f39 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 11 Oct 2026 22:44:30 -0700 Subject: [PATCH 11/36] docs(cli): say what the context codemod maps for a variable The codemod changeset, the breaking entry and the transform's description match the transform: a variable maps locale, dir and messages and leaves overrides and translate to the TODO; an inline literal maps key by key. --- .changeset/i18n-context-codemod.md | 2 +- .changeset/i18n-en-namespace-slices.md | 2 +- .../transforms/next/migrate-internationalization-context.mjs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.changeset/i18n-context-codemod.md b/.changeset/i18n-context-codemod.md index 224aa27aa4b7e..fe26b98d3bad2 100644 --- a/.changeset/i18n-context-codemod.md +++ b/.changeset/i18n-context-codemod.md @@ -2,6 +2,6 @@ '@astryxdesign/cli': patch --- -[feat] `astryx upgrade` runs `migrate-internationalization-context`, which rewrites `` (or its `.Provider`) to ``: a variable maps field by field, an inline object literal key by key, and every rewrite carries a TODO for the value's `translate`, which has no provider input (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. +[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 index b2d6fbf922b68..78c2359ffcc2b 100644 --- a/.changeset/i18n-en-namespace-slices.md +++ b/.changeset/i18n-en-namespace-slices.md @@ -2,6 +2,6 @@ '@astryxdesign/core': minor --- -[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives `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). Its strings still follow such a value through `useTranslator()`, as does the locale of `DateTimeInput`'s touch field, until the components move to their own slices, which stops that too. 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. `astryx upgrade` runs `migrate-internationalization-context`: a variable or an inline object literal is rewritten to the provider with a TODO for its `translate`; any other value (a call, a spread into a literal, a conditional) is left unchanged behind a TODO saying why, since a spread of the ambient value would mount a provider without the app's catalogs. 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. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice. The slices are not importable. +[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives `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). Its strings still follow such a value through `useTranslator()`, as does the locale of `DateTimeInput`'s touch field, until the components move to their own slices, which stops that too. 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. `astryx upgrade` runs `migrate-internationalization-context`: a variable is rewritten to the provider's `locale`, `dir` and `messages` with a TODO for its `overrides` and `translate`; an inline object literal maps key by key with a TODO for `translate`; any other value (a call, a spread into a literal, a conditional) is left unchanged behind a TODO saying why, since a spread of the ambient value would mount a provider without the app's catalogs. 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. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice. The slices are not importable. @vjeux diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index 8ecaefcaa3857..c2dc0f06ffe65 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -76,7 +76,7 @@ export const meta = { title: 'Migrate a raw InternationalizationContext value to InternationalizationProvider', description: - 'Rewrites `` (or its `.Provider`) to ``, the only way to configure Astryx; a `translate` field and any non-literal value are left behind a TODO.', + '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'], }; From d359e1b6df3561498c02b2c5b7c0c66e15cb4b9a Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 11 Oct 2026 23:21:05 -0700 Subject: [PATCH 12/36] test(cli): the context codemod leaves the consumer shape in the wild alone A code search found three uses of InternationalizationContext outside Astryx (two internal, one public), all of one shape: read the ambient value with useContext, re-mount InternationalizationProvider with a derived one. The transform over those three files returned no change; this fixture is that shape. --- ...rate-internationalization-context.test.mjs | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) 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 index 59219b99f93f9..59b8e95ff77c9 100644 --- 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 @@ -327,6 +327,31 @@ export const app =
{ + // 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('is idempotent', () => { const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; const a = ; From 011b8aef6b0547aba4ff7d0b6b33b415efb083c3 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 11 Oct 2026 23:59:08 -0700 Subject: [PATCH 13/36] fix(cli): the context codemod's TODO names the local that shadows the provider When a local shadows the provider import at the edit site, the TODO said the value was an expression; it now names the shadowing local as the cause. --- .../migrate-internationalization-context.test.mjs | 6 ++++-- .../next/migrate-internationalization-context.mjs | 10 +++++++++- 2 files changed, 13 insertions(+), 3 deletions(-) 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 index 59b8e95ff77c9..d0fb51a404ff2 100644 --- 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 @@ -232,9 +232,11 @@ const spread = ', ); expect(output.match(new RegExp(EXPRESSION_TODO, 'g'))).toBeNull(); - expect(apply(input).match(new RegExp(EXPRESSION_TODO, 'g'))).toHaveLength( - 2, + 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('leaves a shadowed name and a type-only import alone', () => { diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index c2dc0f06ffe65..73924bbcf45a1 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -72,6 +72,12 @@ const TODO_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', @@ -469,7 +475,9 @@ export default function migrateInternationalizationContext(file, api) { // 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, TODO_EXPRESSION)) changed = true; + if (addComment(valueAttribute, todoShadowedProvider(providerLocalName))) { + changed = true; + } return; } const providerName = From 33cfa85acf730f54e7fa330a85a37e5aa33138ef Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 12 Oct 2026 00:56:47 -0700 Subject: [PATCH 14/36] fix(cli): the context codemod leaves an empty literal behind the TODO on its attribute An empty value={{}} has nothing to map; its TODO sat on the opening element, where the printer rendered it as text between the tags. It now stays on the value attribute, as a comment. --- ...rate-internationalization-context.test.mjs | 19 +++++++++++++++++++ .../migrate-internationalization-context.mjs | 7 +++++++ 2 files changed, 26 insertions(+) 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 index d0fb51a404ff2..67eb1770f40d7 100644 --- 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 @@ -354,6 +354,25 @@ export function WithRowWording({children}: {children: ReactNode}) { 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 = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; const a =
; diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index 73924bbcf45a1..a8d677505ad2a 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -471,6 +471,13 @@ export default function migrateInternationalizationContext(file, api) { 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. From ed99b8d8333b3d75ba2ffc3a07a56fbec00c0d99 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 12 Oct 2026 01:39:32 -0700 Subject: [PATCH 15/36] fix(cli): the context codemod sees private-method parameters, static blocks and namespace bodies A class private method's parameter, a declaration in a class `static {}` block and one in a TypeScript `namespace` body shadow the import like any other scope on the way to the module; a `var` search no longer crosses into a private method or a static block. Fixture for each. The context and codemod headers describe a component as reading the runtime context once it adopts its slice, not before. --- ...rate-internationalization-context.test.mjs | 22 +++++++++++++++ .../migrate-internationalization-context.mjs | 28 +++++++++++++------ .../src/i18n/InternationalizationContext.ts | 7 +++-- 3 files changed, 46 insertions(+), 11 deletions(-) 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 index 67eb1770f40d7..0392be262aef6 100644 --- 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 @@ -239,6 +239,28 @@ const spread = { + 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 = ; +} +export const ok = ;`; + const output = folded(apply(input)); + expect(output.match(//g)).toHaveLength(3); + expect(output).toContain( + '', + ); + expect(output).toContain( + '', + ); + }); + it('leaves a shadowed name and a type-only import alone', () => { const shadowed = `import {InternationalizationContext as Ctx} from '@astryxdesign/core/i18n'; function Row({Ctx}) { diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index a8d677505ad2a..044d4e1292537 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -4,9 +4,9 @@ * @file Migrate a raw `InternationalizationContext` value to the provider. * * Rendering a value straight into `InternationalizationContext` no longer - * configures Astryx: `useLocale`, `useDirection`, `useCollator` and every - * core component read a runtime context that only `InternationalizationProvider` - * writes. The provider takes the same configuration under its own prop names, + * 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: * * → patternNames(param).includes(name), diff --git a/packages/core/src/i18n/InternationalizationContext.ts b/packages/core/src/i18n/InternationalizationContext.ts index 6e1ff984454aa..43de892de8bd1 100644 --- a/packages/core/src/i18n/InternationalizationContext.ts +++ b/packages/core/src/i18n/InternationalizationContext.ts @@ -9,11 +9,12 @@ * @position Context definition for client-side locale + messages: the public * context a consumer reads. Its `translate` resolves every `@astryx.*` key, * falling back to the shipped English catalog, so this module carries that - * catalog; the components inside this package read - * TranslationRuntimeContext instead and carry only their own slices. Both + * catalog; the locale hooks inside this package read + * TranslationRuntimeContext instead, and a component moves to it (carrying + * only its own slice) as it adopts useComponentTranslator. Both contexts * are written by InternationalizationProvider, which is how an app * configures Astryx: a value rendered straight into this context reaches - * consumers of this context and nothing inside the package. + * consumers of this context and nothing that reads the runtime context. * * Separated from InternationalizationProvider.tsx so components can consume * the context without pulling in the full provider implementation. From fab7ed121de5ff9edea1cae90507ba4cf385c4e3 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 12 Oct 2026 02:21:06 -0700 Subject: [PATCH 16/36] fix(cli): the context codemod sees an exported namespace member as a shadow; drops an emptied import `export const Ctx` inside a namespace body declares the name like a bare `const`; the statement-list check now looks through `export`. An Astryx import declaration the transform leaves with no specifier is removed instead of staying behind as a bare side-effect import. Fixtures for both. --- ...rate-internationalization-context.test.mjs | 21 ++++++++++++++++++- .../migrate-internationalization-context.mjs | 12 +++++++++-- 2 files changed, 30 insertions(+), 3 deletions(-) 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 index 0392be262aef6..00247ef84743e 100644 --- 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 @@ -250,9 +250,13 @@ namespace Local { const Ctx = Other; export const out = ; } +namespace Exported { + export const Ctx = Other; + export const out = ; +} export const ok = ;`; const output = folded(apply(input)); - expect(output.match(//g)).toHaveLength(3); + expect(output.match(//g)).toHaveLength(4); expect(output).toContain( '', ); @@ -395,6 +399,21 @@ const app = ( expect(output).toMatch(/ { + const input = `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(folded(output)).toContain( + ' { const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; const a = ; diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index 044d4e1292537..985b0c298307b 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -272,7 +272,12 @@ export default function migrateInternationalizationContext(file, api) { /** @type {any[]} */ statements, /** @type {string} */ name, ) => - statements.some((/** @type {any} */ statement) => { + 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), @@ -559,7 +564,8 @@ export default function migrateInternationalizationContext(file, api) { } } - // Drop the context import when the file no longer names it anywhere. + // 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 @@ -570,6 +576,7 @@ export default function migrateInternationalizationContext(file, api) { .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) => !( @@ -578,6 +585,7 @@ export default function migrateInternationalizationContext(file, api) { (s.local?.name ?? CONTEXT) === localName ), ); + if (before > 0 && path.node.specifiers.length === 0) path.prune(); } } From 627acf07a16b8c24690ec1b2e2f1a93fd54e0fe0 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 12 Oct 2026 03:04:44 -0700 Subject: [PATCH 17/36] fix(cli): the context codemod sees import-equals and ambient declarations; keeps an emptied import's comments In a namespace body, `import Ctx = Other.Context`, `declare function Ctx` and `enum Ctx` declare the name like a const does. When an emptied Astryx import is removed, the comments that sat on it (a license header) move to the next statement, and the printer's stray semicolon after a directive is taken out, so `'use client';` stays as written. Fixtures for each. --- ...rate-internationalization-context.test.mjs | 21 ++++++++++--- .../migrate-internationalization-context.mjs | 31 +++++++++++++++++-- 2 files changed, 45 insertions(+), 7 deletions(-) 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 index 00247ef84743e..a8e62d2125dd8 100644 --- 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 @@ -112,7 +112,7 @@ const b = ;`; expect(output).toContain(''); expect(output).not.toContain('; } +namespace Aliased { + import Ctx = Other.Context; + export const out = ; +} +namespace Declared { + declare function Ctx(props: {value: unknown}): null; + export const out = ; +} export const ok = ;`; const output = folded(apply(input)); - expect(output.match(//g)).toHaveLength(4); + expect(output.match(//g)).toHaveLength(6); expect(output).toContain( '', ); @@ -399,8 +407,10 @@ const app = ( expect(output).toMatch(/ { - const input = `import {InternationalizationContext} from '@astryxdesign/core'; + it('removes an Astryx import declaration it empties, keeping its comments and the directive', () => { + const input = `'use client'; +// Copyright (c) Example. +import {InternationalizationContext} from '@astryxdesign/core'; import {InternationalizationProvider} from '@astryxdesign/core/i18n'; const app = ;`; const output = apply(input); @@ -409,6 +419,9 @@ const app = 0 && path.node.specifiers.length === 0) path.prune(); + 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'}); + 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;') + ); } From c44090dc7d6265bbb0cd265ccbeebed50cae30e9 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 12 Oct 2026 03:42:34 -0700 Subject: [PATCH 18/36] fix(cli): the context codemod counts a nested namespace as a binding `namespace Ctx {}` inside a namespace body declares the name, so `` under it stays as written; and a module that declares `namespace InternationalizationProvider` binds that name, so the provider import takes a free alias and the rewritten element renders the alias rather than the namespace. Fixtures for both. --- ...rate-internationalization-context.test.mjs | 22 +++++++++++++++++++ .../migrate-internationalization-context.mjs | 12 +++++++--- 2 files changed, 31 insertions(+), 3 deletions(-) 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 index a8e62d2125dd8..7a70a45283e52 100644 --- 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 @@ -262,9 +262,14 @@ 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( '', ); @@ -273,6 +278,23 @@ export const ok = ;`; ); }); + 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}) { diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index 9f5ed9f78893d..06a548607a1df 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -142,7 +142,11 @@ export default function migrateInternationalizationContext(file, api) { ((parent.type === 'FunctionDeclaration' || parent.type === 'FunctionExpression' || parent.type === 'ClassDeclaration' || - parent.type === 'ClassExpression') && + 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' || @@ -288,9 +292,11 @@ export default function migrateInternationalizationContext(file, api) { statement.type === 'ClassDeclaration' || statement.type === 'TSDeclareFunction' || statement.type === 'TSEnumDeclaration' || - statement.type === 'TSImportEqualsDeclaration' + statement.type === 'TSImportEqualsDeclaration' || + statement.type === 'TSModuleDeclaration' ) { - // `declare function Ctx()`, `enum Ctx`, `import Ctx = Other.Thing`. + // `declare function Ctx()`, `enum Ctx`, `import Ctx = Other.Thing`, + // `namespace Ctx {}`. return statement.id?.name === name; } return false; From 25a4e58ff8e1e64e9678db8bd614fb54b9c0a27d Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 12 Oct 2026 04:19:48 -0700 Subject: [PATCH 19/36] fix(cli): the context codemod sees a dotted namespace as binding its own name Inside `namespace Outer.Ctx {}`, `Ctx` names that namespace, so a `` there stays as written, and inside `namespace Outer.i18n {}` the namespace-import form is left alone rather than becoming an unbound member. A TSModuleDeclaration on the element's path binds its last segment. Fixture beside the namespace cases. --- ...rate-internationalization-context.test.mjs | 22 +++++++++++++++++++ .../migrate-internationalization-context.mjs | 17 ++++++++++++++ 2 files changed, 39 insertions(+) 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 index 7a70a45283e52..b276825f32e91 100644 --- 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 @@ -278,6 +278,28 @@ export const ok = ;`; ); }); + 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 { diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index 06a548607a1df..680de31eea032 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -302,6 +302,18 @@ export default function migrateInternationalizationContext(file, api) { 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 @@ -355,6 +367,11 @@ export default function migrateInternationalizationContext(file, api) { 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': From 88c434027420c95a957d5c094a4173f4b990e3ca Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 12 Oct 2026 08:51:05 -0700 Subject: [PATCH 20/36] docs: importing InternationalizationContext also carries the whole catalog The contributing guide's bundle sentence names the third way an app pulls in every string: the public context module imports the English catalog for its default translate. --- CONTRIBUTING.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 69c2733ef12af..13ed565e0927d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -294,9 +294,9 @@ export * from './MyComponent'; 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` nor calls `useTranslator()` -(both carry the whole catalog) bundles only the strings of the components it -renders: +that neither mounts `InternationalizationProvider`, calls `useTranslator()` nor +imports `InternationalizationContext` (each carries the whole catalog) bundles +only the strings of the components it renders: ```tsx import {useComponentTranslator} from '../i18n/useComponentTranslator'; From b0588ffec1b934a0be7ad377220ea1467cac782f Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 22 Oct 2026 12:05:29 -0700 Subject: [PATCH 21/36] fix(cli): the context codemod declines a spread that follows value JSX attributes apply in order, so in `` a `props.value` wins and the effective value is not provable from the source; the element now stays as written behind a TODO that says so. A spread BEFORE `value` is overridden by it and is kept in place: the mapped props take `value`'s slot in the attribute list, so the spread still comes first and is still overridden. Fixtures for both orders, and for a spread on each side. --- ...rate-internationalization-context.test.mjs | 29 ++++++++++++++++ .../migrate-internationalization-context.mjs | 34 ++++++++++++++++--- 2 files changed, 58 insertions(+), 5 deletions(-) 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 index b276825f32e91..0a5d01e70c7df 100644 --- 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 @@ -471,6 +471,35 @@ const app = { + const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; +const app = ;`; + const output = folded(apply(input)); + expect(output).toContain( + '', + ); + }); + + it('declines a spread AFTER value, whose own value may override it', () => { + // JSX attributes apply in order: with props.value = w, the effective + // value is w, not v — the provider must not be built from v. + const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; +const a = ; +const b = ;`; + const output = apply(input); + expect(folded(output)).toContain( + '', + ); + expect(folded(output)).toContain( + '', + ); + expect(output).not.toContain(' { const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; const a = ; diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs index 680de31eea032..4437ac637f5e6 100644 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs @@ -34,7 +34,9 @@ * 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 whose - * value arrives through spread props gets the TODO and no rewrite. + * value arrives through spread props, or whose explicit `value` is followed + * by a spread that may override it, gets the TODO and no rewrite; a spread + * before `value` is overridden by it and is kept in place. * 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. @@ -67,6 +69,12 @@ 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_AFTER_VALUE = + `${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 spread after `value` may ' + + 'carry its own `value` and override this one, so the effective value is not ' + + 'provable. '; const TODO_EXPRESSION = `${TODO_PREFIX}a raw InternationalizationContext value no longer configures Astryx; ` + 'mount InternationalizationProvider with this value\u2019s `locale`, `direction` (as `dir`), ' + @@ -467,6 +475,19 @@ export default function migrateInternationalizationContext(file, api) { return; } if (valueAttribute.value?.type !== 'JSXExpressionContainer') return; + // JSX attributes apply in order: a spread AFTER `value` may carry its own + // `value` and win, so the effective value cannot be proven from here. A + // spread before it is overridden by the explicit `value` and stays put. + const attributes = opening.attributes ?? []; + const valueIndex = attributes.indexOf(valueAttribute); + if ( + attributes + .slice(valueIndex + 1) + .some((/** @type {any} */ a) => a.type === 'JSXSpreadAttribute') + ) { + if (addComment(valueAttribute, TODO_SPREAD_AFTER_VALUE)) changed = true; + return; + } const value = valueAttribute.value.expression; /** @type {any[]} */ @@ -542,11 +563,14 @@ export default function migrateInternationalizationContext(file, api) { needsNamedProvider = true; } - const otherAttributes = (opening.attributes ?? []).filter( - (/** @type {any} */ a) => a !== valueAttribute, - ); + // The mapped props take `value`'s slot, so a spread that came before it + // still comes before them and is still overridden, as it was. opening.name = providerName; - opening.attributes = [...otherAttributes, ...props]; + opening.attributes = [ + ...attributes.slice(0, valueIndex), + ...props, + ...attributes.slice(valueIndex + 1), + ]; if (path.node.closingElement) { path.node.closingElement.name = providerName; } From df7c3f544788e4b9dfdb183becc7103374be3ea7 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 23 Oct 2026 07:38:07 -0700 Subject: [PATCH 22/36] chore(cli): the context codemod moves to its own stacked pull request The upgrade transform, its fixtures and its changeset leave this PR so the runtime half stays within the review size; the breaking entry points at the stacked PR that carries them. CONTRIBUTING's bundle sentence names PowerSearch, whose caller-supplied operator keys keep the whole catalog. --- .changeset/i18n-context-codemod.md | 7 - .changeset/i18n-en-namespace-slices.md | 2 +- CONTRIBUTING.md | 4 +- ...rate-internationalization-context.test.mjs | 511 -------------- .../assets/codemods/transforms/next/index.mjs | 12 +- .../migrate-internationalization-context.mjs | 665 ------------------ 6 files changed, 5 insertions(+), 1196 deletions(-) delete mode 100644 .changeset/i18n-context-codemod.md delete mode 100644 packages/cli/assets/codemods/transforms/next/__tests__/migrate-internationalization-context.test.mjs delete mode 100644 packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs diff --git a/.changeset/i18n-context-codemod.md b/.changeset/i18n-context-codemod.md deleted file mode 100644 index fe26b98d3bad2..0000000000000 --- a/.changeset/i18n-context-codemod.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@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 index 78c2359ffcc2b..d5530e0f50e6d 100644 --- a/.changeset/i18n-en-namespace-slices.md +++ b/.changeset/i18n-en-namespace-slices.md @@ -2,6 +2,6 @@ '@astryxdesign/core': minor --- -[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives `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). Its strings still follow such a value through `useTranslator()`, as does the locale of `DateTimeInput`'s touch field, until the components move to their own slices, which stops that too. 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. `astryx upgrade` runs `migrate-internationalization-context`: a variable is rewritten to the provider's `locale`, `dir` and `messages` with a TODO for its `overrides` and `translate`; an inline object literal maps key by key with a TODO for `translate`; any other value (a call, a spread into a literal, a conditional) is left unchanged behind a TODO saying why, since a spread of the ambient value would mount a provider without the app's catalogs. 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. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice. The slices are not importable. +[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives `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). Its strings still follow such a value through `useTranslator()`, as does the locale of `DateTimeInput`'s touch field, until the components move to their own slices, which stops that too. 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. An `astryx upgrade` codemod for this rewrite, `migrate-internationalization-context`, ships in the pull request stacked on this one. 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. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice. The slices are not importable. @vjeux diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 13ed565e0927d..0d076d876bc1d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -295,7 +295,9 @@ 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) bundles +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 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 deleted file mode 100644 index 0a5d01e70c7df..0000000000000 --- a/packages/cli/assets/codemods/transforms/next/__tests__/migrate-internationalization-context.test.mjs +++ /dev/null @@ -1,511 +0,0 @@ -// 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 from '../migrate-internationalization-context.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('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( - ' { - const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; -const app = ;`; - const output = folded(apply(input)); - expect(output).toContain( - '', - ); - }); - - it('declines a spread AFTER value, whose own value may override it', () => { - // JSX attributes apply in order: with props.value = w, the effective - // value is w, not v — the provider must not be built from v. - const input = `import {InternationalizationContext} from '@astryxdesign/core/i18n'; -const a =
; -const b = ;`; - const output = apply(input); - 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 c6aa776a0e725..2af3bdfcf09ad 100644 --- a/packages/cli/assets/codemods/transforms/next/index.mjs +++ b/packages/cli/assets/codemods/transforms/next/index.mjs @@ -7,14 +7,4 @@ * this file into the resolved version folder. */ -import migrateInternationalizationContext, { - meta as migrateInternationalizationContextMeta, -} from './migrate-internationalization-context.mjs'; - -export default [ - { - name: 'migrate-internationalization-context', - transform: migrateInternationalizationContext, - meta: migrateInternationalizationContextMeta, - }, -]; +export default []; diff --git a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs b/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs deleted file mode 100644 index 4437ac637f5e6..0000000000000 --- a/packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs +++ /dev/null @@ -1,665 +0,0 @@ -// 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 whose - * value arrives through spread props, or whose explicit `value` is followed - * by a spread that may override it, gets the TODO and no rewrite; a spread - * before `value` is overridden by it and is kept in place. - * 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_AFTER_VALUE = - `${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 spread after `value` may ' + - 'carry its own `value` and override this one, so the effective value is not ' + - 'provable. '; -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; - // JSX attributes apply in order: a spread AFTER `value` may carry its own - // `value` and win, so the effective value cannot be proven from here. A - // spread before it is overridden by the explicit `value` and stays put. - const attributes = opening.attributes ?? []; - const valueIndex = attributes.indexOf(valueAttribute); - if ( - attributes - .slice(valueIndex + 1) - .some((/** @type {any} */ a) => a.type === 'JSXSpreadAttribute') - ) { - if (addComment(valueAttribute, TODO_SPREAD_AFTER_VALUE)) 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, so a spread that came before it - // still comes before them and is still overridden, as it was. - 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;') - ); -} From 8da012c8b02b3c7aa91e747782a9dcb5dd578611 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 23 Oct 2026 08:56:00 -0700 Subject: [PATCH 23/36] docs(i18n): the breaking entry carries the migration as the changelog will The core changelog takes this entry verbatim, so it names the `astryx upgrade` transform and what it rewrites rather than pointing at the pull request that ships it. CONTRIBUTING's PowerSearch clause moves to the component sweep, where the hook it names exists. --- .changeset/i18n-en-namespace-slices.md | 2 +- CONTRIBUTING.md | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/.changeset/i18n-en-namespace-slices.md b/.changeset/i18n-en-namespace-slices.md index d5530e0f50e6d..ea7ae90473e61 100644 --- a/.changeset/i18n-en-namespace-slices.md +++ b/.changeset/i18n-en-namespace-slices.md @@ -2,6 +2,6 @@ '@astryxdesign/core': minor --- -[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives `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). Its strings still follow such a value through `useTranslator()`, as does the locale of `DateTimeInput`'s touch field, until the components move to their own slices, which stops that too. 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. An `astryx upgrade` codemod for this rewrite, `migrate-internationalization-context`, ships in the pull request stacked on this one. 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. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice. The slices are not importable. +[breaking] An app that sets `InternationalizationContext` directly — rendering `` (or its `.Provider`) instead of `InternationalizationProvider` — no longer drives `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). Its strings still follow such a value through `useTranslator()`, as does the locale of `DateTimeInput`'s touch field, until the components move to their own slices, which stops that too. 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. Groundwork for components carrying only their own English strings: the English catalog is also emitted one namespace at a time, the resolver takes its English fallback per call, and an internal `useComponentTranslator(slice)` lets a core component render with its own slice. The slices are not importable. @vjeux diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0d076d876bc1d..13ed565e0927d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -295,9 +295,7 @@ 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 +imports `InternationalizationContext` (each carries the whole catalog) bundles only the strings of the components it renders: ```tsx From 0de5c8e3f45ae9ffce71d665399676d682daea02 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 23 Oct 2026 10:00:10 -0700 Subject: [PATCH 24/36] fix(build): the Vite locale alias takes one path segment, so a slice stays the package's own `astryxStylex()` aliased `@astryxdesign/core/locales/(.+).generated.js` straight to the source tree, which let a Vite app resolve the per-namespace English slices the exports map keeps out of reach with a `null` target. The capture now takes a single segment, the whole-catalog case; a slice specifier under `locales/en/` resolves to nothing the package ships. Test for the slice specifier beside the existing catalog cases. --- .changeset/vite-locale-alias-one-segment.md | 7 +++++++ packages/build/src/vite.test.ts | 21 +++++++++++++++++++++ packages/build/src/vite.ts | 7 ++++++- 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 .changeset/vite-locale-alias-one-segment.md 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/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', From f9267e0c6176fce375c3aa8a56cca1b9ff0d1622 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sun, 25 Oct 2026 06:27:56 -0700 Subject: [PATCH 25/36] test(i18n): resolve the locale exports through the package's self-reference The docsite's server routes trace this package's files, and the test ran its resolver from apps/sandbox, a path the tracer follows: the search route then shipped the whole sandbox app (190.3 MB, over the docsite's 150 MB function budget), so every preview deploy of this branch failed. The package's self-reference applies the same exports map a consumer's import does, so the test now resolves from the package's own directory; the route is back to 59.0 MB (main: 58.9 MB), and the test still fails when the ./locales/en/* null export is removed. --- .../src/i18n/__tests__/locale-exports.test.mjs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/core/src/i18n/__tests__/locale-exports.test.mjs b/packages/core/src/i18n/__tests__/locale-exports.test.mjs index f8217b91b4781..430b23e2871e7 100644 --- a/packages/core/src/i18n/__tests__/locale-exports.test.mjs +++ b/packages/core/src/i18n/__tests__/locale-exports.test.mjs @@ -3,7 +3,8 @@ /** * @file locale-exports.test.mjs * @input The package's exports map, read through Node's own package - * resolution from a workspace app that depends on the package + * resolution: the package's self-reference, which applies the same map a + * consumer's import does * @output Verifies the public locale surface: every whole catalog under * `@astryxdesign/core/locales/.generated.js` resolves, and the * per-namespace English slices under `locales/en/` do not — they are the @@ -17,12 +18,15 @@ import {fileURLToPath} from 'node:url'; import {describe, expect, it} from 'vitest'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); -const REPO_ROOT = path.resolve(__dirname, '../../../../..'); +const CORE_ROOT = path.resolve(__dirname, '../../..'); /** * Resolve a specifier the way a consumer's bundler or Node would: through - * the package's exports map, from a module inside a workspace app that - * depends on the package. `import.meta.resolve` consults the map only and + * the package's exports map. The package's own directory resolves its name + * through that same map (a self-reference), so no other package is involved: + * the docsite's server routes trace this package's files, and a path from + * here into another directory would make them ship that whole directory. + * `import.meta.resolve` consults the map only and * never reads the target, so a built `dist/` is not needed: a matching * pattern yields its target path, and a `null` target or no match is * ERR_PACKAGE_PATH_NOT_EXPORTED. Run in a fresh process so the test's own @@ -40,7 +44,7 @@ function resolveFromConsumer(specifier) { process.execPath, ['--input-type=module', '--eval', script], { - cwd: path.join(REPO_ROOT, 'apps/sandbox'), + cwd: CORE_ROOT, encoding: 'utf8', }, ); From 8500a5056b6f17bd1ef7d3aeefb80d722a183c96 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 23 Oct 2026 07:45:03 -0700 Subject: [PATCH 26/36] feat(cli): migrate a raw InternationalizationContext value to the provider MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `astryx upgrade` runs `migrate-internationalization-context`, the codemod for the retirement that the stacked runtime change declares: a `` (or `.Provider`) whose value is a variable maps `locale`, `direction` (as `dir`) and `messages` to `` with a TODO for `overrides` and `translate`; an inline object literal maps key by key with a TODO for `translate`; any other value — a call, a conditional, a literal with a spread, an empty literal — and any element that spreads props stay as written behind a TODO that says why (a spread after `value` may override it; a spread anywhere may carry `dir`, `messages` or `overrides`, which the context ignored but the provider would read). Only an element whose name resolves, unshadowed, to the Astryx import is touched: blocks, loop heads, catch clauses, parameters (private methods too), hoisted `var`s, named class and function expressions, `static {}` blocks, namespace bodies (including `export`, `import X =`, `declare function`, `enum`, nested and dotted namespaces) all shadow it; a type-only import proves nothing. The provider is imported under a free alias when the module already binds its name, and an emptied import goes with its comments carried forward and the directive left intact. A second run changes nothing. Fixtures cover each shape; one typechecks the rewritten output with tsc against the real i18n source types; one is the read-and-re-mount shape every real consumer found by a code search has (the transform leaves it alone). --- .changeset/i18n-context-codemod.md | 7 + ...rate-internationalization-context.test.mjs | 517 ++++++++++++++ .../assets/codemods/transforms/next/index.mjs | 12 +- .../migrate-internationalization-context.mjs | 666 ++++++++++++++++++ 4 files changed, 1201 insertions(+), 1 deletion(-) create mode 100644 .changeset/i18n-context-codemod.md create mode 100644 packages/cli/assets/codemods/transforms/next/__tests__/migrate-internationalization-context.test.mjs create mode 100644 packages/cli/assets/codemods/transforms/next/migrate-internationalization-context.mjs 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/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 2af3bdfcf09ad..c6aa776a0e725 100644 --- a/packages/cli/assets/codemods/transforms/next/index.mjs +++ b/packages/cli/assets/codemods/transforms/next/index.mjs @@ -7,4 +7,14 @@ * this file into the resolved version folder. */ -export default []; +import migrateInternationalizationContext, { + meta as migrateInternationalizationContextMeta, +} from './migrate-internationalization-context.mjs'; + +export default [ + { + 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;') + ); +} From 78331766a5d72412e710cfaf9768c22986f58b6f Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 10 Oct 2026 11:44:53 -0700 Subject: [PATCH 27/36] refactor(core): components render with useComponentTranslator and their own English slice Mechanical sweep over every core component that called useTranslator(): - import {useTranslator} from '../i18n'; + import {useComponentTranslator} from '../i18n/useComponentTranslator'; + import buttonMessages from '../i18n/generated-locales/en/button.generated'; - const t = useTranslator(); + const t = useComponentTranslator(buttonMessages); A file that reads several namespaces merges their slices once at module level (`const messages = {...dateInputMessages, ...timeInputMessages}`) and passes that. Two PowerSearch files hand `t` to helpers and carry the helpers' namespace. No call site, key or string changes; check:i18n-catalog verifies that every slice covers the keys its file reads. --- packages/core/src/AlertDialog/AlertDialog.tsx | 5 ++-- packages/core/src/AppShell/AppShell.tsx | 5 ++-- packages/core/src/Avatar/Avatar.tsx | 8 ++++-- packages/core/src/AvatarGroup/AvatarGroup.tsx | 5 ++-- .../src/AvatarGroup/AvatarGroupOverflow.tsx | 7 +++-- packages/core/src/Banner/Banner.tsx | 5 ++-- packages/core/src/Breadcrumbs/Breadcrumbs.tsx | 5 ++-- packages/core/src/Button/Button.tsx | 7 +++-- packages/core/src/Calendar/Calendar.tsx | 8 ++++-- packages/core/src/Carousel/Carousel.tsx | 5 ++-- packages/core/src/Chat/ChatComposer.tsx | 5 ++-- packages/core/src/Chat/ChatComposerDrawer.tsx | 9 ++++-- packages/core/src/Chat/ChatComposerInput.tsx | 5 ++-- .../core/src/Chat/ChatDictationButton.tsx | 5 ++-- packages/core/src/Chat/ChatLayout.tsx | 5 ++-- .../core/src/Chat/ChatLayoutScrollButton.tsx | 5 ++-- packages/core/src/Chat/ChatMessage.tsx | 5 ++-- packages/core/src/Chat/ChatMessageList.tsx | 5 ++-- .../core/src/Chat/ChatMessageMetadata.tsx | 5 ++-- .../core/src/Chat/ChatPastedTextToken.tsx | 5 ++-- packages/core/src/Chat/ChatSendButton.tsx | 5 ++-- packages/core/src/Chat/ChatToolCalls.tsx | 12 +++++--- .../core/src/Chat/useSpeechRecognition.ts | 6 ++-- packages/core/src/Chat/useTriggerMenu.tsx | 5 ++-- .../core/src/CheckboxInput/CheckboxInput.tsx | 5 ++-- .../src/CheckboxList/CheckboxListItem.tsx | 5 ++-- packages/core/src/Citation/Citation.tsx | 5 ++-- packages/core/src/CodeBlock/CodeBlock.tsx | 5 ++-- .../src/CommandPalette/CommandPalette.tsx | 5 ++-- .../CommandPalette/CommandPaletteFooter.tsx | 5 ++-- .../CommandPalette/CommandPaletteInput.tsx | 5 ++-- .../src/CommandPalette/CommandPaletteList.tsx | 5 ++-- .../src/ComplexSelector/ComplexSelector.tsx | 9 ++++-- packages/core/src/ContextMenu/ContextMenu.tsx | 9 ++++-- packages/core/src/DateInput/DateInput.tsx | 10 +++++-- .../core/src/DateInput/NativeDateField.tsx | 10 +++++-- .../core/src/DateInput/TouchDateField.tsx | 15 ++++++++-- .../src/DateRangeInput/DateRangeInput.tsx | 17 +++++++++-- .../core/src/DateTimeInput/DateTimeInput.tsx | 17 +++++++++-- .../src/DateTimeInput/NativeDateSegment.tsx | 6 ++-- .../src/DateTimeInput/NativeTimeSegment.tsx | 5 ++-- .../src/DateTimeInput/TouchDateTimeField.tsx | 20 ++++++++++--- packages/core/src/Dialog/DialogHeader.tsx | 5 ++-- packages/core/src/Drawer/DrawerHeader.tsx | 5 ++-- .../core/src/DropdownMenu/DropdownMenu.tsx | 7 +++-- .../src/DropdownMenu/DropdownMenuSubMenu.tsx | 9 ++++-- packages/core/src/Field/FieldLabel.tsx | 7 +++-- packages/core/src/Field/InputClearButton.tsx | 7 +++-- packages/core/src/FileInput/FileInput.tsx | 9 ++++-- packages/core/src/Lightbox/Lightbox.tsx | 5 ++-- packages/core/src/Link/Link.tsx | 5 ++-- packages/core/src/Markdown/Markdown.tsx | 6 ++-- .../Markdown/plugins/HeadingLinksRenderer.tsx | 5 ++-- .../core/src/MetadataList/MetadataList.tsx | 7 +++-- packages/core/src/MobileNav/MobileNav.tsx | 5 ++-- .../core/src/MobileNav/MobileNavToggle.tsx | 5 ++-- packages/core/src/MoreMenu/MoreMenu.tsx | 5 ++-- .../core/src/MultiSelector/MultiSelector.tsx | 16 +++++++++-- packages/core/src/NumberInput/NumberInput.tsx | 6 ++-- packages/core/src/Outline/Outline.tsx | 5 ++-- packages/core/src/Pagination/Pagination.tsx | 5 ++-- packages/core/src/Popover/usePopover.tsx | 5 ++-- packages/core/src/PowerSearch/PowerSearch.tsx | 5 ++-- .../PowerSearch/PowerSearchEditPopover.tsx | 9 +++--- .../core/src/PowerSearch/PowerSearchToken.tsx | 5 ++-- .../PowerSearch/PowerSearchValueEditor.tsx | 28 ++++++++++--------- .../src/PowerSearch/usePowerSearchSource.ts | 5 ++-- packages/core/src/Resizable/ResizeHandle.tsx | 5 ++-- packages/core/src/Selector/Selector.tsx | 16 +++++++++-- packages/core/src/SideNav/SideNav.tsx | 5 ++-- .../src/SideNav/SideNavCollapseButton.tsx | 5 ++-- packages/core/src/SideNav/SideNavHeading.tsx | 5 ++-- packages/core/src/SideNav/SideNavItem.tsx | 5 ++-- packages/core/src/Spinner/Spinner.tsx | 7 +++-- packages/core/src/Stepper/Step.tsx | 5 ++-- packages/core/src/Stepper/Stepper.tsx | 5 ++-- packages/core/src/Switch/Switch.tsx | 7 +++-- packages/core/src/TabList/TabList.tsx | 5 ++-- packages/core/src/Table/BaseTable.tsx | 5 ++-- packages/core/src/Table/Table.tsx | 5 ++-- .../core/src/Table/TableSelectionToolbar.tsx | 5 ++-- .../plugins/filtering/useTableFiltering.tsx | 24 ++++++++++------ .../groupedRows/useTableGroupedRows.tsx | 5 ++-- .../plugins/pagination/useTablePagination.tsx | 5 ++-- .../rowExpansion/useTableRowExpansion.tsx | 9 +++--- .../plugins/rowStatus/useTableRowStatus.tsx | 5 ++-- .../plugins/selection/useTableSelection.tsx | 7 +++-- .../plugins/sortable/useTableSortable.tsx | 10 ++++--- .../Table/plugins/tree/useTableTreeData.tsx | 9 +++--- packages/core/src/TextArea/TextArea.tsx | 9 ++++-- packages/core/src/TextInput/TextInput.tsx | 9 ++++-- packages/core/src/Thumbnail/Thumbnail.tsx | 9 ++++-- packages/core/src/TimeInput/TimeInput.tsx | 9 ++++-- .../core/src/TimeInput/TouchTimeField.tsx | 16 +++++++++-- packages/core/src/Timestamp/Timestamp.tsx | 5 ++-- .../core/src/Timestamp/TimestampHoverCard.tsx | 5 ++-- packages/core/src/Toast/Toast.tsx | 5 ++-- packages/core/src/Toast/ToastViewport.tsx | 5 ++-- packages/core/src/Token/Token.tsx | 5 ++-- packages/core/src/Tokenizer/Tokenizer.tsx | 9 ++++-- packages/core/src/TopNav/TopNav.tsx | 5 ++-- packages/core/src/TopNav/TopNavHeading.tsx | 5 ++-- packages/core/src/TreeList/TreeListItem.tsx | 5 ++-- packages/core/src/Typeahead/BaseTypeahead.tsx | 5 ++-- packages/core/src/Typeahead/Typeahead.tsx | 5 ++-- .../core/src/hooks/useInputStatusIcon.tsx | 5 ++-- packages/core/src/hooks/useKeyboardHint.tsx | 7 +++-- 107 files changed, 507 insertions(+), 256 deletions(-) diff --git a/packages/core/src/AlertDialog/AlertDialog.tsx b/packages/core/src/AlertDialog/AlertDialog.tsx index 838e3b6fb11b4..f1f2687b8eb0c 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'; 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 39f21b0fb8874..b2620864f7967 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'; // ============================================================================= @@ -463,7 +464,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 301bec0d9845c..11821bbe44676 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 * @@ -60,7 +60,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'; /** @@ -581,7 +582,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 a2e106e7caaa6..70f11bac54fb8 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 { @@ -344,7 +345,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 754f1abfa132e..5a2256a878560 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 9531dd1add500..d92d720d14b87 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 2376dd97a3818..e3c2ac8b0977a 100644 --- a/packages/core/src/Chat/ChatPastedTextToken.tsx +++ b/packages/core/src/Chat/ChatPastedTextToken.tsx @@ -25,7 +25,8 @@ import { import {Badge} from '../Badge'; import {Button} from '../Button'; import {HoverCard} from '../HoverCard'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +import chatMessages from '../i18n/generated-locales/en/chat.generated'; // ============================================================================= // Types @@ -89,7 +90,7 @@ export function ChatPastedTextToken({ text, onExpand, }: ChatPastedTextTokenProps) { - const t = useTranslator(); + const t = useComponentTranslator(chatMessages); const label = formatLabel(text); 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 a1d0e8d0ae143..27a4b859a0d37 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 95ef4d32a11bd..65cc0c55ead41 100644 --- a/packages/core/src/CodeBlock/CodeBlock.tsx +++ b/packages/core/src/CodeBlock/CodeBlock.tsx @@ -50,7 +50,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'; // --------------------------------------------------------------------------- @@ -935,7 +936,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 1fc573da53fae..67a109142dae3 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -84,7 +84,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, @@ -98,6 +100,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, @@ -324,7 +329,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 914a2c9ca333d..42faaa2af3e03 100644 --- a/packages/core/src/DateInput/DateInput.tsx +++ b/packages/core/src/DateInput/DateInput.tsx @@ -210,9 +210,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' @@ -531,7 +537,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 a9723205f8b5f..0484c77b5ced6 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 27f92f2016f1b..37b9cf21025f5 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 875bf11824131..211d432481194 100644 --- a/packages/core/src/DropdownMenu/DropdownMenu.tsx +++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx @@ -105,7 +105,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 @@ -625,7 +626,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); @@ -899,7 +900,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 b0ff1eb64a7b8..96d42f8ca5526 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'; 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 390a559cbb94a..0d9bd10a1e94d 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): string { if (bytes < 1024) { return `${bytes} B`; @@ -478,7 +483,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/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsx index 376ed067b64c7..ed4b2137c5675 100644 --- a/packages/core/src/Lightbox/Lightbox.tsx +++ b/packages/core/src/Lightbox/Lightbox.tsx @@ -44,7 +44,8 @@ import {LayerContentBoundary} from '../Layer/layerScopedContext'; 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'; @@ -325,7 +326,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 36d8422067106..0b1e67265d81b 100644 --- a/packages/core/src/Markdown/Markdown.tsx +++ b/packages/core/src/Markdown/Markdown.tsx @@ -92,7 +92,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; @@ -2121,7 +2123,7 @@ export function Markdown< 'data-testid': testId, ...props }: MarkdownProps): React.ReactElement { - const t = useTranslator(); + const t = useComponentTranslator(markdownMessages); const LinkComponent = useLinkComponent(); // Links read the caller's handler when clicked, so a handler recreated on // every caller render does not invalidate the memoized document below. 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 b32cf6e97984c..2690e2ba4e7ab 100644 --- a/packages/core/src/MobileNav/MobileNav.tsx +++ b/packages/core/src/MobileNav/MobileNav.tsx @@ -75,7 +75,8 @@ import {LayerDepthProvider} from '../Layer/LayerDepthContext'; 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'; // ============================================================================= @@ -473,7 +474,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 bffc2774c3241..4232c60504836 100644 --- a/packages/core/src/MultiSelector/MultiSelector.tsx +++ b/packages/core/src/MultiSelector/MultiSelector.tsx @@ -102,12 +102,24 @@ import {usePressFeedback} from '../hooks/usePressFeedback'; import {groupStyles} from '../InputGroup/groupStyles'; import {useInputGroup} from '../InputGroup/InputGroupContext'; 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__'; @@ -1152,7 +1164,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 49d40b1710930..dbc0e0a7825c8 100644 --- a/packages/core/src/NumberInput/NumberInput.tsx +++ b/packages/core/src/NumberInput/NumberInput.tsx @@ -220,7 +220,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'; @@ -583,7 +585,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/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.tsx b/packages/core/src/PowerSearch/PowerSearch.tsx index f91501832e0c0..f3c02207b66cb 100644 --- a/packages/core/src/PowerSearch/PowerSearch.tsx +++ b/packages/core/src/PowerSearch/PowerSearch.tsx @@ -58,7 +58,8 @@ 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 powersearchMessages from '../i18n/generated-locales/en/powersearch.generated'; import {useLocale} from '../i18n/useLocale'; import type {Locale} from '../i18n/types'; import type { @@ -585,7 +586,7 @@ export function PowerSearch({ const size = useSize(sizeProp, 'md'); const config = useInternalConfig(configProp); const searchSource = usePowerSearchSource(config, maxSearchResults); - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const locale = useLocale(); const label = labelFromProps ?? t('@astryx.powersearch.label'); const placeholder = diff --git a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx index 156e7a87fd279..f6f2e2fce5522 100644 --- a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx +++ b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx @@ -19,7 +19,8 @@ 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 powersearchMessages from '../i18n/generated-locales/en/powersearch.generated'; import {isImeKeyEvent} from '../utils/ime'; import {spacingVars, typeScaleVars} from '../theme/tokens.stylex'; import { @@ -264,7 +265,7 @@ function NestedSubFilterRow({ maxMenuItems, isReadOnly, }: NestedSubFilterRowProps) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const fieldOptions = useMemo( () => config.getVisibleFields().map(field => ({ @@ -397,7 +398,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 +662,7 @@ export function PowerSearchEditPopover({ maxMenuItems, isReadOnly = false, }: PowerSearchEditPopoverProps) { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const saveButtonLabel = saveButtonLabelFromProps ?? t('@astryx.powersearch.editor.apply'); const [partialFilter, setPartialFilter] = diff --git a/packages/core/src/PowerSearch/PowerSearchToken.tsx b/packages/core/src/PowerSearch/PowerSearchToken.tsx index cd55ba5a800e6..fc1b3e4808299 100644 --- a/packages/core/src/PowerSearch/PowerSearchToken.tsx +++ b/packages/core/src/PowerSearch/PowerSearchToken.tsx @@ -12,7 +12,8 @@ import React from 'react'; import * as stylex from '@stylexjs/stylex'; import {Token} from '../Token'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +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,7 +45,7 @@ export function PowerSearchToken({ isDisabled, }: PowerSearchTokenProps) { const config = useInternalConfig(configProp); - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); const locale = useLocale(); const fieldLabel = field.label; 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/usePowerSearchSource.ts b/packages/core/src/PowerSearch/usePowerSearchSource.ts index df6b0d6d6de6c..fa6c6f958b782 100644 --- a/packages/core/src/PowerSearch/usePowerSearchSource.ts +++ b/packages/core/src/PowerSearch/usePowerSearchSource.ts @@ -15,7 +15,8 @@ import {useMemo} from 'react'; import type {SearchSource} from '../Typeahead/types'; import {groupItems} from '../utils'; -import {useTranslator} from '../i18n'; +import {useComponentTranslator} from '../i18n/useComponentTranslator'; +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,7 +30,7 @@ export function usePowerSearchSource( config: InternalConfig, maxTypedResults: number, ): SearchSource { - const t = useTranslator(); + const t = useComponentTranslator(powersearchMessages); return useMemo(() => { const allItems = buildFieldItems(config); // Resolver stays inline — `t()` internally memoizes both catalog 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 6e84970591fa0..5b4f05232d228 100644 --- a/packages/core/src/Selector/Selector.tsx +++ b/packages/core/src/Selector/Selector.tsx @@ -96,12 +96,24 @@ import {usePressFeedback} from '../hooks/usePressFeedback'; import {groupStyles} from '../InputGroup/groupStyles'; import {useInputGroup} from '../InputGroup/InputGroupContext'; 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: { @@ -943,7 +955,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 0beb29afd292a..3bffbc3ce47c2 100644 --- a/packages/core/src/SideNav/SideNavItem.tsx +++ b/packages/core/src/SideNav/SideNavItem.tsx @@ -71,7 +71,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'; // ============================================================================= @@ -504,7 +505,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 bd353a5450dc8..eb85164183993 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'; @@ -1003,7 +1004,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 022504b8d494b..b807163d10bcd 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'; @@ -571,7 +572,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 adabb5e99734b..455b70c20ed06 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 * @@ -33,7 +33,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, @@ -303,7 +304,7 @@ function ExpansionChevron({ isExpanded: boolean; onToggle: () => void; }) { - const t = useTranslator(); + const t = useComponentTranslator(tableRowExpansionMessages); const ctx = useTableContext(); return (