Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(i18n): expose provider-backed locale hooks (#5194)

nynexman44647616d6adc0db
diff --git a/.changeset/provider-backed-locale-hooks.md b/.changeset/provider-backed-locale-hooks.md
new file mode 100644
index 0000000000..9edc0d6bb1
--- /dev/null
+++ b/.changeset/provider-backed-locale-hooks.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Export `useLocale` and `useCollator` for provider-backed formatting and comparison
+@nynexman4464
diff --git a/packages/core/src/i18n/InternationalizationContext.ts b/packages/core/src/i18n/InternationalizationContext.ts
index 8c87840374..d6131c2413 100644
--- a/packages/core/src/i18n/InternationalizationContext.ts
+++ b/packages/core/src/i18n/InternationalizationContext.ts
@@ -16,6 +16,8 @@
* - /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
*/
diff --git a/packages/core/src/i18n/__tests__/useCollator.test.tsx b/packages/core/src/i18n/__tests__/useCollator.test.tsx
new file mode 100644
index 0000000000..4700399d19
--- /dev/null
+++ b/packages/core/src/i18n/__tests__/useCollator.test.tsx
@@ -0,0 +1,115 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useCollator.test.tsx
+ * @input packages/core/src/i18n/useCollator.ts, InternationalizationProvider
+ * @output Unit tests for the internal provider-aware Intl.Collator hook
+ * @position Colocated tests; targets the default (no-provider) fallback,
+ * locale-driven comparison order, option threading, and memoization.
+ */
+
+import type {ReactNode} from 'react';
+import {describe, expect, test} from 'vitest';
+import {render, renderHook} from '@testing-library/react';
+import {useCollator} from '../useCollator';
+import {InternationalizationProvider} from '../InternationalizationProvider';
+
+function wrapperFor(locale: string) {
+ return ({children}: {children: ReactNode}) => (
+ <InternationalizationProvider locale={locale}>
+ {children}
+ </InternationalizationProvider>
+ );
+}
+
+describe('useCollator', () => {
+ test('compares using the en fallback when rendered without a provider', () => {
+ const {result} = renderHook(() => useCollator());
+ expect(result.current.compare('a', 'b')).toBeLessThan(0);
+ });
+
+ test('orders "ä" before "z" under Swedish, and after "z" under German', () => {
+ const {result: sv} = renderHook(() => useCollator(), {
+ wrapper: wrapperFor('sv-SE'),
+ });
+ expect(['z', 'ä'].sort((a, b) => sv.current.compare(a, b))).toEqual([
+ 'z',
+ 'ä',
+ ]);
+
+ const {result: de} = renderHook(() => useCollator(), {
+ wrapper: wrapperFor('de-DE'),
+ });
+ expect(['z', 'ä'].sort((a, b) => de.current.compare(a, b))).toEqual([
+ 'ä',
+ 'z',
+ ]);
+ });
+
+ test('threads options through to the underlying Intl.Collator (numeric)', () => {
+ const {result} = renderHook(() => useCollator({numeric: true}));
+ expect(
+ ['item2', 'item10'].sort((a, b) => result.current.compare(a, b)),
+ ).toEqual(['item2', 'item10']);
+ });
+
+ test('without numeric, orders "item10" before "item2" lexicographically', () => {
+ const {result} = renderHook(() => useCollator());
+ expect(
+ ['item2', 'item10'].sort((a, b) => result.current.compare(a, b)),
+ ).toEqual(['item10', 'item2']);
+ });
+
+ test('memoizes the collator when locale and options identity are unchanged', () => {
+ const options = {numeric: true} satisfies Intl.CollatorOptions;
+ const {result, rerender} = renderHook(
+ ({collatorOptions}) => useCollator(collatorOptions),
+ {
+ initialProps: {collatorOptions: options},
+ wrapper: wrapperFor('en'),
+ },
+ );
+ const first = result.current;
+ rerender({collatorOptions: options});
+ expect(result.current).toBe(first);
+ });
+
+ test('rebuilds the collator when options identity changes', () => {
+ const {result, rerender} = renderHook(
+ ({collatorOptions}) => useCollator(collatorOptions),
+ {
+ initialProps: {
+ collatorOptions: {numeric: true} satisfies Intl.CollatorOptions,
+ },
+ wrapper: wrapperFor('en'),
+ },
+ );
+ const first = result.current;
+ rerender({collatorOptions: {numeric: true}});
+ expect(result.current).not.toBe(first);
+ });
+
+ test('re-renders with a new collator when the provider locale changes', () => {
+ let latestCollator: Intl.Collator | undefined;
+ function Probe() {
+ latestCollator = useCollator();
+ const order = ['z', 'ä'].sort((a, b) => latestCollator!.compare(a, b));
+ return <span data-testid="order">{order.join(',')}</span>;
+ }
+ const {getByTestId, rerender} = render(
+ <InternationalizationProvider locale="sv-SE">
+ <Probe />
+ </InternationalizationProvider>,
+ );
+ expect(getByTestId('order').textContent).toBe('z,ä');
+ const svCollator = latestCollator;
+
+ rerender(
+ <InternationalizationProvider locale="de-DE">
+ <Probe />
+ </InternationalizationProvider>,
+ );
+ expect(getByTestId('order').textContent).toBe('ä,z');
+ expect(latestCollator).not.toBe(svCollator);
+ });
+});
diff --git a/packages/core/src/i18n/__tests__/useLocale.test.tsx b/packages/core/src/i18n/__tests__/useLocale.test.tsx
new file mode 100644
index 0000000000..4f3f1a8b38
--- /dev/null
+++ b/packages/core/src/i18n/__tests__/useLocale.test.tsx
@@ -0,0 +1,52 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useLocale.test.tsx
+ * @input packages/core/src/i18n/useLocale.ts, InternationalizationProvider
+ * @output Unit tests for the internal provider-aware locale accessor
+ * @position Colocated tests; targets the default (no-provider) fallback, the
+ * provider locale, and re-rendering when the provider locale changes.
+ */
+
+import type {ReactNode} from 'react';
+import {describe, expect, test} from 'vitest';
+import {render, renderHook} from '@testing-library/react';
+import {useLocale} from '../useLocale';
+import {InternationalizationProvider} from '../InternationalizationProvider';
+
+describe('useLocale', () => {
+ test('returns en when rendered without a provider', () => {
+ const {result} = renderHook(() => useLocale());
+ expect(result.current).toBe('en');
+ });
+
+ test('returns the provider locale', () => {
+ const {result} = renderHook(() => useLocale(), {
+ wrapper: ({children}: {children: ReactNode}) => (
+ <InternationalizationProvider locale="fr">
+ {children}
+ </InternationalizationProvider>
+ ),
+ });
+ expect(result.current).toBe('fr');
+ });
+
+ test('re-renders with the new locale when the provider locale changes', () => {
+ function Probe() {
+ return <span data-testid="locale">{useLocale()}</span>;
+ }
+ const {getByTestId, rerender} = render(
+ <InternationalizationProvider locale="en">
+ <Probe />
+ </InternationalizationProvider>,
+ );
+ expect(getByTestId('locale').textContent).toBe('en');
+
+ rerender(
+ <InternationalizationProvider locale="ja-JP">
+ <Probe />
+ </InternationalizationProvider>,
+ );
+ expect(getByTestId('locale').textContent).toBe('ja-JP');
+ });
+});
diff --git a/packages/core/src/i18n/index.ts b/packages/core/src/i18n/index.ts
index 0cf581ca0e..927b7a559c 100644
--- a/packages/core/src/i18n/index.ts
+++ b/packages/core/src/i18n/index.ts
@@ -10,12 +10,16 @@
* The public API is deliberately small:
* - InternationalizationProvider — provider component
* - useTranslator — hook returning a translator function
+ * - useLocale — hook returning the provider locale
+ * - useCollator — provider-bound locale-aware comparison
* - useDirection — hook returning the ambient text direction
* - getLocaleDirection — server-safe locale → direction helper
* - Translator — interface for consumer-injected runtimes
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/index.ts
+ * - /packages/core/src/i18n/useLocale.ts
+ * - /packages/core/src/i18n/useCollator.ts
* - /packages/core/src/i18n/useDirection.ts
* - /packages/core/src/i18n/getLocaleDirection.ts
*/
@@ -26,6 +30,8 @@ export {InternationalizationContext} from './InternationalizationContext';
export type {InternationalizationContextValue} from './InternationalizationContext';
export {useTranslator} from './useTranslator';
export type {TranslatorFn} from './useTranslator';
+export {useLocale} from './useLocale';
+export {useCollator} from './useCollator';
export {useDirection} from './useDirection';
export {getLocaleDirection} from './getLocaleDirection';
export type {Translator} from './translator';
diff --git a/packages/core/src/i18n/useCollator.doc.mjs b/packages/core/src/i18n/useCollator.doc.mjs
new file mode 100644
index 0000000000..e8b2b4e817
--- /dev/null
+++ b/packages/core/src/i18n/useCollator.doc.mjs
@@ -0,0 +1,84 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'useCollator',
+ displayName: 'useCollator',
+ category: 'utilities',
+ keywords: [
+ 'i18n',
+ 'internationalization',
+ 'locale',
+ 'collation',
+ 'compare',
+ 'sort',
+ 'table',
+ 'hook',
+ ],
+ params: [
+ {
+ name: 'options',
+ type: 'Intl.CollatorOptions',
+ description:
+ 'Optional collation behavior such as numeric ordering, sensitivity, punctuation handling, and case order.',
+ required: false,
+ },
+ ],
+ returns: [
+ {
+ name: 'collator',
+ type: 'Intl.Collator',
+ description:
+ 'A memoized collator bound to the active InternationalizationProvider locale.',
+ },
+ ],
+ usage: {
+ description:
+ 'Returns the sanctioned locale-aware comparator for custom sorting. The collator is recreated when the provider locale or an option changes.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Reuse collator.compare in custom Table comparators and other user-visible string ordering.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Construct Intl.Collator directly or call localeCompare; those bypass the provider-backed locale contract.',
+ },
+ ],
+ },
+ relatedComponents: ['InternationalizationProvider', 'Table'],
+ relatedHooks: ['useLocale'],
+ importPath: '@astryxdesign/core',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ 'Returns a memoized Intl.Collator bound to the active InternationalizationProvider locale.',
+ paramDescriptions: {
+ options:
+ 'optional Intl.CollatorOptions: numeric ordering, sensitivity, punctuation, case order, etc.',
+ },
+ returnDescriptions: {
+ collator:
+ 'memoized provider-bound collator for locale-aware comparison and sorting.',
+ },
+ usage: {
+ description:
+ 'Use collator.compare for custom user-visible string ordering instead of raw Intl.Collator or localeCompare.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Reuse collator.compare in custom Table comparators and string sorting.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Construct raw Intl.Collator or call localeCompare directly.',
+ },
+ ],
+ },
+};
diff --git a/packages/core/src/i18n/useCollator.ts b/packages/core/src/i18n/useCollator.ts
new file mode 100644
index 0000000000..57cfbbe5de
--- /dev/null
+++ b/packages/core/src/i18n/useCollator.ts
@@ -0,0 +1,44 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useCollator.ts
+ * @input InternationalizationContext (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
+ * locale-correct sorting without constructing a raw Intl.Collator. Raw
+ * collator construction stays centralized in this hook.
+ *
+ * Falls back to `'en'` when called outside a provider, matching the
+ * useTranslator/useDirection/useLocale fallback.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/i18n/InternationalizationContext.ts
+ * - /packages/core/src/i18n/useLocale.ts
+ * - /packages/core/src/i18n/useCollator.doc.mjs
+ * - /packages/core/src/i18n/index.ts
+ * - /packages/core/src/i18n/__tests__/useCollator.test.tsx
+ */
+
+import {use, useMemo} from 'react';
+import {InternationalizationContext} from './InternationalizationContext';
+
+/**
+ * Returns an `Intl.Collator` for the active provider locale, memoized across
+ * renders where the locale and options object are unchanged.
+ *
+ * @example
+ * ```
+ * const collator = useCollator({numeric: true});
+ * const sorted = [...items].sort((a, b) => collator.compare(a.name, b.name));
+ * ```
+ */
+export function useCollator(options?: Intl.CollatorOptions): Intl.Collator {
+ const ctx = use(InternationalizationContext);
+ return useMemo(
+ () => new Intl.Collator(ctx.locale, options),
+ [ctx.locale, options],
+ );
+}
diff --git a/packages/core/src/i18n/useLocale.doc.mjs b/packages/core/src/i18n/useLocale.doc.mjs
new file mode 100644
index 0000000000..778dc47634
--- /dev/null
+++ b/packages/core/src/i18n/useLocale.doc.mjs
@@ -0,0 +1,70 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'useLocale',
+ displayName: 'useLocale',
+ category: 'utilities',
+ keywords: [
+ 'i18n',
+ 'internationalization',
+ 'localization',
+ 'locale',
+ 'language',
+ 'provider',
+ 'hook',
+ ],
+ params: [],
+ returns: [
+ {
+ name: 'locale',
+ type: 'Locale',
+ description:
+ "The active InternationalizationProvider BCP 47 locale. Falls back to 'en' when no provider is present.",
+ },
+ ],
+ usage: {
+ description:
+ 'Reads the authoritative Astryx locale. Use it to thread the provider locale into pure formatting helpers and sibling-package APIs; do not derive a second locale from navigator.language or a hardcoded literal.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Pass the returned locale to pure Astryx helpers or package APIs that require an explicit locale.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use navigator.language or a hardcoded display locale as a fallback; InternationalizationProvider is the locale source.',
+ },
+ ],
+ },
+ relatedComponents: ['InternationalizationProvider'],
+ relatedHooks: ['useCollator', 'useTranslator', 'useDirection'],
+ importPath: '@astryxdesign/core',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ "Returns the active InternationalizationProvider locale, falling back to 'en' without a provider.",
+ usage: {
+ description:
+ 'Use as the sole locale source for pure formatting helpers and sibling-package APIs.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Thread this locale into pure helpers requiring an explicit locale.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Fall back to navigator.language or a hardcoded display locale.',
+ },
+ ],
+ },
+ returnDescriptions: {
+ locale: "active provider BCP 47 locale; 'en' without a provider.",
+ },
+};
diff --git a/packages/core/src/i18n/useLocale.ts b/packages/core/src/i18n/useLocale.ts
new file mode 100644
index 0000000000..a5dda8a01c
--- /dev/null
+++ b/packages/core/src/i18n/useLocale.ts
@@ -0,0 +1,34 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useLocale.ts
+ * @input InternationalizationContext (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
+ * the provider locale into pure formatting helpers. Returns `'en'` when
+ * called outside a provider, matching useTranslator/useDirection.
+ *
+ * This is the approved way to read the locale that feeds a formatting helper
+ * (`plainDateFormat`, `formatInstant`, chart formatters, …) or `useCollator()`.
+ * Reading `InternationalizationContext` directly for just its `locale` field,
+ * or reaching for `navigator.language`/a hardcoded literal, bypasses that
+ * provider-backed contract.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/i18n/InternationalizationContext.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 type {Locale} from './types';
+
+export function useLocale(): Locale {
+ const ctx = use(InternationalizationContext);
+ return ctx.locale;
+}
diff --git a/packages/core/src/i18n/useTranslator.doc.mjs b/packages/core/src/i18n/useTranslator.doc.mjs
index 9cb5550794..168455c37e 100644
--- a/packages/core/src/i18n/useTranslator.doc.mjs
+++ b/packages/core/src/i18n/useTranslator.doc.mjs
@@ -4,7 +4,7 @@
export const docs = {
name: 'useTranslator',
displayName: 'useTranslator',
- group: 'Utilities',
+ category: 'utilities',
keywords: [
'i18n',
'internationalization',