An open source design system that's fully customizable and agent ready
TypeScript
fix(i18n): use provider locale outside date inputs (#5195)
nynexman4464f5841d14ce40
diff --git a/.changeset/provider-locale-migrations.md b/.changeset/provider-locale-migrations.mdnew file mode 100644index 0000000000..cfcc094b99--- /dev/null+++ b/.changeset/provider-locale-migrations.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Use the InternationalizationProvider locale for sorting, formatting, and speech defaults+@nynexman4464diff --git a/apps/storybook/stories/TableSortable.stories.tsx b/apps/storybook/stories/TableSortable.stories.tsxindex 0871c669d8..32a2196c2e 100644--- a/apps/storybook/stories/TableSortable.stories.tsx+++ b/apps/storybook/stories/TableSortable.stories.tsx@@ -10,6 +10,7 @@ import {useTableSelectionState,} from '@astryxdesign/core/Table';import type {TableColumn, TableSortState} from '@astryxdesign/core/Table';+import {useCollator} from '@astryxdesign/core';// =============================================================================// Sample Data@@ -141,6 +142,7 @@ export const MultiSort: Story = {export const CustomSortKey: Story = {render: () => {+ const collator = useCollator();const customColumns: TableColumn<Employee>[] = [{key: 'name', header: 'Name', sortable: true},{key: 'email', header: 'Email', sortable: {sortKey: 'emailSort'}},@@ -153,7 +155,7 @@ export const CustomSortKey: Story = {defaultSort: [{sortKey: 'yearsOld', direction: 'ascending'}],comparators: {yearsOld: (a, b) => a.age - b.age,- emailSort: (a, b) => a.email.localeCompare(b.email),+ emailSort: (a, b) => collator.compare(a.email, b.email),},});diff --git a/apps/storybook/stories/charts/Bar.stories.tsx b/apps/storybook/stories/charts/Bar.stories.tsxindex 9c5bfd6327..cb69224299 100644--- a/apps/storybook/stories/charts/Bar.stories.tsx+++ b/apps/storybook/stories/charts/Bar.stories.tsx@@ -3,6 +3,7 @@import type {Meta, StoryObj} from '@storybook/react';import {Chart, bar, ChartGrid, ChartAxis, currency} from '@astryxdesign/charts';import {monthlyData, groupedStackData, profitLossData} from './_data';+import {useLocale} from '@astryxdesign/core';const meta: Meta<typeof Chart> = {title: 'Charts/Bar',@@ -18,23 +19,26 @@ const axes = ();export const Simple: StoryObj = {- render: () => (- <Chart- data={monthlyData}- xKey="month"- title="Monthly Revenue"- series={[bar('revenue', {color: '#3b82f6'})]}- tooltip- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" tickFormat={currency()} />- </>- }- height={300}- />- ),+ render: () => {+ const locale = useLocale();+ return (+ <Chart+ data={monthlyData}+ xKey="month"+ title="Monthly Revenue"+ series={[bar('revenue', {color: '#3b82f6'})]}+ tooltip+ grid={<ChartGrid />}+ axes={+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" tickFormat={currency('$', locale)} />+ </>+ }+ height={300}+ />+ );+ },};export const Stacked: StoryObj = {diff --git a/apps/storybook/stories/charts/Tooltip.stories.tsx b/apps/storybook/stories/charts/Tooltip.stories.tsxindex cf01dacf45..7e4fb28351 100644--- a/apps/storybook/stories/charts/Tooltip.stories.tsx+++ b/apps/storybook/stories/charts/Tooltip.stories.tsx@@ -10,6 +10,7 @@ import {currency,} from '@astryxdesign/charts';import {monthlyData} from './_data';+import {useLocale} from '@astryxdesign/core';const meta: Meta<typeof Chart> = {title: 'Charts/Chrome/Tooltip',@@ -20,24 +21,27 @@ export default meta;/** Hover the chart: a grouped tooltip shows every series value at that x, with a* column highlight for bars and hover dots on lines. */export const Default: StoryObj = {- render: () => (- <Chart- data={monthlyData}- xKey="month"- series={[- bar('revenue', {color: '#3b82f6', label: 'Revenue', stack: 'x'}),- bar('costs', {color: '#ef4444', label: 'Costs', stack: 'x'}),- line('trend', {color: '#f59e0b', label: 'Trend'}),- ]}- tooltip- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" tickFormat={currency()} />- </>- }- height={320}- />- ),+ render: () => {+ const locale = useLocale();+ return (+ <Chart+ data={monthlyData}+ xKey="month"+ series={[+ bar('revenue', {color: '#3b82f6', label: 'Revenue', stack: 'x'}),+ bar('costs', {color: '#ef4444', label: 'Costs', stack: 'x'}),+ line('trend', {color: '#f59e0b', label: 'Trend'}),+ ]}+ tooltip+ grid={<ChartGrid />}+ axes={+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" tickFormat={currency('$', locale)} />+ </>+ }+ height={320}+ />+ );+ },};diff --git a/docs/CHARTV2_VERIFICATION_CHECKLIST.md b/docs/CHARTV2_VERIFICATION_CHECKLIST.mdindex 220069bc86..b1c25d0a71 100644--- a/docs/CHARTV2_VERIFICATION_CHECKLIST.md+++ b/docs/CHARTV2_VERIFICATION_CHECKLIST.md@@ -258,7 +258,7 @@ How we verify:## 13. Formatting / i18n-- `[ok]` `currency()` on axis.+- `[ok]` `currency('$', locale)` on axis.- `[?]` `percent`, `compactNumber`, `shortDate`, `monthYear` on axes + tooltip.- `[?]` Locale-awareness (decimal/grouping separators, date locale).- `[?]` RTL layout (axes, legend, tooltip placement).diff --git a/packages/charts/src/formatters.test.ts b/packages/charts/src/formatters.test.tsnew file mode 100644index 0000000000..bfc794bf55--- /dev/null+++ b/packages/charts/src/formatters.test.ts@@ -0,0 +1,76 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {+ compactNumber,+ currency,+ monthYear,+ percent,+ shortDate,+} from './formatters';++describe('chart formatters', () => {+ it('formats numbers with the requested locale and keeps caches locale-keyed', () => {+ const en = compactNumber(1_500_000, 'en-US');+ const de = compactNumber(1_500_000, 'de-DE');++ expect(en).toBe(+ new Intl.NumberFormat('en-US', {+ notation: 'compact',+ maximumFractionDigits: 1,+ }).format(1_500_000),+ );+ expect(de).toBe(+ new Intl.NumberFormat('de-DE', {+ notation: 'compact',+ maximumFractionDigits: 1,+ }).format(1_500_000),+ );+ expect(de).not.toBe(en);+ expect(compactNumber(1_500_000, 'en-US')).toBe(en);+ });++ it('formats currency and percentages with the requested locale', () => {+ expect(currency('€', 'de-DE')(1234.5)).toBe(+ `€${new Intl.NumberFormat('de-DE', {+ notation: 'compact',+ maximumFractionDigits: 1,+ }).format(1234.5)}`,+ );+ expect(percent(0.125, 'de-DE')).toBe(+ new Intl.NumberFormat('de-DE', {+ style: 'percent',+ maximumFractionDigits: 1,+ }).format(0.125),+ );+ });++ it('preserves the legacy symbol-only currency call', () => {+ expect(() => currency('€')(1234.5)).not.toThrow();+ expect(currency('€')(1234.5)).toMatch(/^€/);+ });++ it('formats dates with the requested locale', () => {+ const value = '2024-01-05';+ expect(shortDate(value, 'de-DE')).toBe(+ new Intl.DateTimeFormat('de-DE', {+ month: 'short',+ day: 'numeric',+ }).format(new Date(2024, 0, 5)),+ );+ expect(monthYear(value, 'de-DE')).toBe(+ new Intl.DateTimeFormat('de-DE', {+ month: 'short',+ year: 'numeric',+ }).format(new Date(2024, 0, 5)),+ );+ expect(shortDate(value, 'de-DE')).not.toBe(shortDate(value, 'en-US'));+ });++ it('passes through non-finite and unparseable values', () => {+ expect(compactNumber(Infinity, 'en-US')).toBe('Infinity');+ expect(percent('not-a-number', 'en-US')).toBe('not-a-number');+ expect(shortDate('not-a-date', 'en-US')).toBe('not-a-date');+ expect(monthYear(null, 'en-US')).toBe('null');+ });+});diff --git a/packages/charts/src/formatters.ts b/packages/charts/src/formatters.tsindex 114c1f77d4..63d51806b9 100644--- a/packages/charts/src/formatters.ts+++ b/packages/charts/src/formatters.ts@@ -12,34 +12,45 @@* across the full magnitude range (K/M/B/T and beyond).*/-/** Lazily create a value once and cache it — keeps `Intl` construction off the import path. */-function once<T>(create: () => T): () => T {- let cached: {value: T} | null = null;- return () => (cached ??= {value: create()}).value;+import type {Locale} from '@astryxdesign/core/i18n';++/** Lazily cache one formatter per locale, including the legacy host default. */+function byLocale<T>(+ create: (locale: Locale | undefined) => T,+): (locale: Locale | undefined) => T {+ const cache = new Map<Locale | undefined, T>();+ return locale => {+ let value = cache.get(locale);+ if (value === undefined) {+ value = create(locale);+ cache.set(locale, value);+ }+ return value;+ };}-const getCompactFormat = once(- () =>- new Intl.NumberFormat(undefined, {+const getCompactFormat = byLocale(+ locale =>+ new Intl.NumberFormat(locale, {notation: 'compact',maximumFractionDigits: 1,}),);-const getPercentFormat = once(- () =>- new Intl.NumberFormat(undefined, {+const getPercentFormat = byLocale(+ locale =>+ new Intl.NumberFormat(locale, {style: 'percent',maximumFractionDigits: 1,}),);-const getShortDateFormat = once(- () => new Intl.DateTimeFormat(undefined, {month: 'short', day: 'numeric'}),+const getShortDateFormat = byLocale(+ locale => new Intl.DateTimeFormat(locale, {month: 'short', day: 'numeric'}),);-const getMonthYearFormat = once(- () => new Intl.DateTimeFormat(undefined, {month: 'short', year: 'numeric'}),+const getMonthYearFormat = byLocale(+ locale => new Intl.DateTimeFormat(locale, {month: 'short', year: 'numeric'}),);/**@@ -48,12 +59,12 @@ const getMonthYearFormat = once(* Non-numeric values (e.g. category labels) and non-finite numbers pass through* unchanged, so it is safe to use as a general-purpose tick formatter.*/-export function compactNumber(value: unknown): string {+export function compactNumber(value: unknown, locale: Locale): string {const n = Number(value);if (!Number.isFinite(n)) {return String(value);}- return getCompactFormat().format(n);+ return getCompactFormat(locale).format(n);}/**@@ -64,12 +75,15 @@ export function compactNumber(value: unknown): string {** @example* ```- * <ChartAxis tickFormat={currency()} /> // $1.5K- * <ChartAxis tickFormat={currency('€')} /> // €1.5K- * <ChartAxis tickFormat={currency('¥')} /> // ¥1.5K+ * <ChartAxis tickFormat={currency('$', locale)} /> // $1.5K+ * <ChartAxis tickFormat={currency('€', locale)} /> // €1.5K+ * <ChartAxis tickFormat={currency('¥', locale)} /> // ¥1.5K* ```*/-export function currency(symbol = '$'): (value: unknown) => string {+export function currency(+ symbol = '$',+ locale?: Locale,+): (value: unknown) => string {return (value: unknown) => {const n = Number(value);if (!Number.isFinite(n)) {@@ -78,7 +92,9 @@ export function currency(symbol = '$'): (value: unknown) => string {const sign = n < 0 ? '-' : '';const abs = Math.abs(n);const body =- abs >= 1000 ? getCompactFormat().format(abs) : abs.toLocaleString();+ abs >= 1000+ ? getCompactFormat(locale).format(abs)+ : abs.toLocaleString(locale);return `${sign}${symbol}${body}`;};}@@ -89,12 +105,12 @@ export function currency(symbol = '$'): (value: unknown) => string {* The input is a ratio; it is multiplied by 100 and localized. Whole percents* render without a decimal, and up to one fractional digit is shown otherwise.*/-export function percent(value: unknown): string {+export function percent(value: unknown, locale: Locale): string {const n = Number(value);if (!Number.isFinite(n)) {return String(value);}- return getPercentFormat().format(n);+ return getPercentFormat(locale).format(n);}/**@@ -144,24 +160,20 @@ function toDate(value: unknown): Date {return new Date(NaN);}-/**- * Date formatter — short date (e.g. "Jan 5", "Mar 12").- */-export function shortDate(value: unknown): string {+/** Date formatter — short date (e.g. "Jan 5", "Mar 12"). */+export function shortDate(value: unknown, locale: Locale): string {const d = toDate(value);if (Number.isNaN(d.getTime())) {return String(value);}- return getShortDateFormat().format(d);+ return getShortDateFormat(locale).format(d);}-/**- * Date formatter — month/year (e.g. "Jan 2024", "Mar 2025").- */-export function monthYear(value: unknown): string {+/** Date formatter — month/year (e.g. "Jan 2024", "Mar 2025"). */+export function monthYear(value: unknown, locale: Locale): string {const d = toDate(value);if (Number.isNaN(d.getTime())) {return String(value);}- return getMonthYearFormat().format(d);+ return getMonthYearFormat(locale).format(d);}diff --git a/packages/core/src/Chat/useChatDictation.test.ts b/packages/core/src/Chat/useChatDictation.test.tsxsimilarity index 88%rename from packages/core/src/Chat/useChatDictation.test.tsrename to packages/core/src/Chat/useChatDictation.test.tsxindex 3d062f0ba8..cc9ea9d0bc 100644--- a/packages/core/src/Chat/useChatDictation.test.ts+++ b/packages/core/src/Chat/useChatDictation.test.tsx@@ -1,7 +1,9 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import type {ReactNode} from 'react';import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {renderHook, act} from '@testing-library/react';+import {InternationalizationProvider} from '../i18n';import {useSpeechRecognition} from './useSpeechRecognition';import {useChatDictation} from './useChatDictation';@@ -50,8 +52,7 @@ let originalSR: unknown;beforeEach(() => {lastInstance = null;- originalSR = (window as unknown as Record<string, unknown>)- .SpeechRecognition;+ originalSR = (window as unknown as Record<string, unknown>).SpeechRecognition;(window as unknown as Record<string, unknown>).SpeechRecognition =MockSRConstructor;});@@ -85,6 +86,28 @@ describe('useSpeechRecognition', () => {expect(result.current.isSupported).toBe(true);});+ it('uses the provider locale by default and preserves an explicit override', () => {+ const wrapper = ({children}: {children: ReactNode}) => (+ <InternationalizationProvider locale="fr-FR">+ {children}+ </InternationalizationProvider>+ );+ const provider = renderHook(() => useSpeechRecognition(), {wrapper});++ act(() => {+ provider.result.current.start();+ });+ expect(lastInstance?.lang).toBe('fr-FR');++ const explicit = renderHook(() => useSpeechRecognition({lang: 'ja-JP'}), {+ wrapper,+ });+ act(() => {+ explicit.result.current.start();+ });+ expect(lastInstance?.lang).toBe('ja-JP');+ });+it('starts and sets isListening', () => {const {result} = renderHook(() => useSpeechRecognition());@@ -145,9 +168,7 @@ describe('useSpeechRecognition', () => {const onStart = vi.fn();const onEnd = vi.fn();- const {result} = renderHook(() =>- useSpeechRecognition({onStart, onEnd}),- );+ const {result} = renderHook(() => useSpeechRecognition({onStart, onEnd}));act(() => {result.current.start();@@ -194,9 +215,7 @@ describe('useSpeechRecognition', () => {it('handles interim results and updates interimTranscript', () => {const onTranscript = vi.fn();- const {result} = renderHook(() =>- useSpeechRecognition({onTranscript}),- );+ const {result} = renderHook(() => useSpeechRecognition({onTranscript}));act(() => {result.current.start();@@ -294,9 +313,7 @@ describe('useChatDictation', () => {const onStart = vi.fn();const onEnd = vi.fn();- const {result} = renderHook(() =>- useChatDictation({onStart, onEnd}),- );+ const {result} = renderHook(() => useChatDictation({onStart, onEnd}));act(() => {result.current.start();@@ -312,9 +329,7 @@ describe('useChatDictation', () => {it('handles final transcript via onResult', () => {const onResult = vi.fn();- const {result} = renderHook(() =>- useChatDictation({onResult}),- );+ const {result} = renderHook(() => useChatDictation({onResult}));act(() => {result.current.start();diff --git a/packages/core/src/Chat/useChatDictation.ts b/packages/core/src/Chat/useChatDictation.tsindex 429d9642ea..3384d2f8e6 100644--- a/packages/core/src/Chat/useChatDictation.ts+++ b/packages/core/src/Chat/useChatDictation.ts@@ -22,7 +22,7 @@ import {useSpeechRecognition} from './useSpeechRecognition';// =============================================================================export interface UseChatDictationOptions {- /** BCP-47 language tag. @default navigator.language */+ /** BCP-47 language tag. @default InternationalizationProvider locale */lang?: string;/** Whether recognition continues until explicitly stopped. @default true */continuous?: boolean;diff --git a/packages/core/src/Chat/useSpeechRecognition.ts b/packages/core/src/Chat/useSpeechRecognition.tsindex cd870bfdcd..20c6e568e4 100644--- a/packages/core/src/Chat/useSpeechRecognition.ts+++ b/packages/core/src/Chat/useSpeechRecognition.ts@@ -14,14 +14,14 @@*/import {useState, useCallback, useEffect, useMemo, useRef} from 'react';-import {useTranslator} from '../i18n';+import {useLocale, useTranslator} from '../i18n';// =============================================================================// Types// =============================================================================export interface UseSpeechRecognitionOptions {- /** BCP-47 language tag. @default navigator.language */+ /** BCP-47 language tag. @default InternationalizationProvider locale */lang?: string;/** Whether recognition continues until explicitly stopped. @default true */continuous?: boolean;@@ -260,6 +260,7 @@ export function useSpeechRecognition(options: UseSpeechRecognitionOptions = {},): UseSpeechRecognitionReturn {const t = useTranslator();+ const providerLocale = useLocale();const {lang,continuous = true,@@ -348,7 +349,7 @@ export function useSpeechRecognition(}recognitionRef.current?.abort();const recognition = new SR();- recognition.lang = lang ?? navigator.language;+ recognition.lang = lang ?? providerLocale;recognition.continuous = continuous;recognition.interimResults = interimResults;@@ -418,6 +419,7 @@ export function useSpeechRecognition(recognition.start();}, [lang,+ providerLocale,continuous,interimResults,startVolumePolling,diff --git a/packages/core/src/PowerSearch/PowerSearch.tsx b/packages/core/src/PowerSearch/PowerSearch.tsxindex 0635cd1ddb..29c560258c 100644--- a/packages/core/src/PowerSearch/PowerSearch.tsx+++ b/packages/core/src/PowerSearch/PowerSearch.tsx@@ -50,12 +50,17 @@ import {mergeRefs} from '../utils';import {useSize} from '../SizeContext/SizeContext';import {useInternalConfig} from './useInternalConfig';import {usePowerSearchSource} from './usePowerSearchSource';-import {formatFilterValue} from './formatFilterValue';+import {+ formatFilterValue,+ formatDateAbsoluteCompact,+} from './formatFilterValue';import {PowerSearchEditPopover} from './PowerSearchEditPopover';import {resolveOperatorLabel} from './resolveOperatorLabel';import {themeProps} from '../utils/themeProps';import {truncateCharacters} from '../utils/characters';import {useTranslator} from '../i18n';+import {useLocale} from '../i18n/useLocale';+import type {Locale} from '../i18n/types';import type {PowerSearchConfig,PowerSearchFilter,@@ -131,10 +136,12 @@ function PowerSearchTokenValue({operatorValue,filterValue,maxLength,+ locale,}: {operatorValue: OperatorValue;filterValue: FilterValue;maxLength: number;+ locale: Locale;}) {switch (filterValue.type) {case 'empty':@@ -276,12 +283,10 @@ function PowerSearchTokenValue({);case 'date_absolute': {- const date = new Date(filterValue.unixSeconds * 1000);- const formatted = new Intl.DateTimeFormat(undefined, {- year: 'numeric',- month: 'short',- day: 'numeric',- }).format(date);+ const formatted = formatDateAbsoluteCompact(+ filterValue.unixSeconds,+ locale,+ );return (<span {...stylex.props(tokenValueStyles.value)}>{truncateString(formatted, maxLength)}@@ -556,6 +561,7 @@ export function PowerSearch({const config = useInternalConfig(configProp);const searchSource = usePowerSearchSource(config);const t = useTranslator();+ const locale = useLocale();const label = labelFromProps ?? t('@astryx.powersearch.label');const placeholder =placeholderFromProps ?? t('@astryx.powersearch.placeholder');@@ -625,6 +631,7 @@ export function PowerSearch({filter.value,maxTokenLength,t,+ locale,timezoneID,): '';@@ -644,7 +651,7 @@ export function PowerSearch({},};});- }, [filters, config, maxTokenLength, timezoneID, t]);+ }, [filters, config, maxTokenLength, timezoneID, t, locale]);// Handle tokenizer onChange (field selected from typeahead)const handleTokenizerChange = useCallback(@@ -820,6 +827,7 @@ export function PowerSearch({operatorValue={operator.value}filterValue={filter.value}maxLength={adjustedMaxLength}+ locale={locale}/>) : undefined;@@ -858,6 +866,7 @@ export function PowerSearch({config,configProp,maxTokenLength,+ locale,size,isReadOnly,isDisabled,diff --git a/packages/core/src/PowerSearch/PowerSearchToken.tsx b/packages/core/src/PowerSearch/PowerSearchToken.tsxindex 2f0de6a843..cd55ba5a80 100644--- a/packages/core/src/PowerSearch/PowerSearchToken.tsx+++ b/packages/core/src/PowerSearch/PowerSearchToken.tsx@@ -13,6 +13,7 @@ import React from 'react';import * as stylex from '@stylexjs/stylex';import {Token} from '../Token';import {useTranslator} from '../i18n';+import {useLocale} from '../i18n/useLocale';import {fontWeightVars} from '../theme/tokens.stylex';import {formatFilterValue} from './formatFilterValue';import {resolveOperatorLabel} from './resolveOperatorLabel';@@ -44,6 +45,7 @@ export function PowerSearchToken({}: PowerSearchTokenProps) {const config = useInternalConfig(configProp);const t = useTranslator();+ const locale = useLocale();const fieldLabel = field.label;const resolvedOperatorLabel = resolveOperatorLabel(operator, t);@@ -63,6 +65,7 @@ export function PowerSearchToken({filter.value,adjustedMaxLength,t,+ locale,);const valueContent = valueStr ? (diff --git a/packages/core/src/PowerSearch/formatFilterValue.test.ts b/packages/core/src/PowerSearch/formatFilterValue.test.tsindex 4e7fa91716..147d178842 100644--- a/packages/core/src/PowerSearch/formatFilterValue.test.ts+++ b/packages/core/src/PowerSearch/formatFilterValue.test.ts@@ -31,7 +31,15 @@ const fmt = (maxLength = 20,timezoneID?: string,): string =>- formatFilterValue({} as never, operator, value, maxLength, t, timezoneID);+ formatFilterValue(+ {} as never,+ operator,+ value,+ maxLength,+ t,+ 'en-US',+ timezoneID,+ );const ELLIPSIS = '…';@@ -87,8 +95,20 @@ describe('formatFilterValue', () => {});describe('integer / float', () => {+ it('formats the same number differently when the locale changes', () => {+ const args = [+ {} as never,+ {type: 'float'} as OperatorValue,+ {type: 'float', value: 1234.5} as FilterValue,+ 40,+ t,+ ] as const;+ expect(formatFilterValue(...args, 'en-US')).toBe('1,234.5');+ expect(formatFilterValue(...args, 'de-DE')).toBe('1.234,5');+ });+it('formats an integer with locale grouping', () => {- const expected = new Intl.NumberFormat().format(1234567);+ const expected = new Intl.NumberFormat('en-US').format(1234567);expect(fmt({type: 'integer'}, {type: 'integer', value: 1234567}, 40),).toBe(expected);diff --git a/packages/core/src/PowerSearch/formatFilterValue.ts b/packages/core/src/PowerSearch/formatFilterValue.tsindex 3b98c2141e..ff01cbed77 100644--- a/packages/core/src/PowerSearch/formatFilterValue.ts+++ b/packages/core/src/PowerSearch/formatFilterValue.ts@@ -12,7 +12,7 @@import type {OperatorValue, FilterValue, EnumItem} from './types';import type {InternalConfig} from './useInternalConfig';-import type {TranslatorFn} from '../i18n';+import type {Locale, TranslatorFn} from '../i18n';import {truncateCharacters} from '../utils/characters';function truncate(str: string, maxLength: number): string {@@ -27,12 +27,16 @@ function formatEnumLabel(return item?.label ?? value;}-function formatNumber(value: number, units?: string): string {- const formatted = new Intl.NumberFormat().format(value);+function formatNumber(value: number, locale: Locale, units?: string): string {+ const formatted = new Intl.NumberFormat(locale).format(value);return units ? `${formatted} ${units}` : formatted;}-function formatDateAbsolute(unixSeconds: number, timezoneID?: string): string {+export function formatDateAbsolute(+ unixSeconds: number,+ locale: Locale,+ timezoneID?: string,+): string {const options: Intl.DateTimeFormatOptions = {year: 'numeric',month: 'short',@@ -41,7 +45,25 @@ function formatDateAbsolute(unixSeconds: number, timezoneID?: string): string {minute: '2-digit',...(timezoneID ? {timeZone: timezoneID} : {}),};- return new Intl.DateTimeFormat(undefined, options).format(unixSeconds * 1000);+ return new Intl.DateTimeFormat(locale, options).format(unixSeconds * 1000);+}++/**+ * Compact date-only rendering (no time-of-day) for the token pill's inline+ * value display, which has less room than the editor's full summary. Kept+ * separate from {@link formatDateAbsolute} rather than reusing it with+ * different options threaded through a param, since the two callers want+ * genuinely different shapes, not a parameterization of the same one.+ */+export function formatDateAbsoluteCompact(+ unixSeconds: number,+ locale: Locale,+): string {+ return new Intl.DateTimeFormat(locale, {+ year: 'numeric',+ month: 'short',+ day: 'numeric',+ }).format(unixSeconds * 1000);}function formatRelativeDate(value: string): string {@@ -62,6 +84,7 @@ export function formatFilterValue(filterValue: FilterValue,maxLength: number,t: TranslatorFn,+ locale: Locale,timezoneID?: string,): string {switch (filterValue.type) {@@ -74,12 +97,14 @@ export function formatFilterValue(case 'integer':return formatNumber(filterValue.value,+ locale,operatorValue.type === 'integer' ? operatorValue.units : undefined,);case 'float':return formatNumber(filterValue.value,+ locale,operatorValue.type === 'float' ? operatorValue.units : undefined,);@@ -157,7 +182,7 @@ export function formatFilterValue(case 'date_absolute':return truncate(- formatDateAbsolute(filterValue.unixSeconds, timezoneID),+ formatDateAbsolute(filterValue.unixSeconds, locale, timezoneID),maxLength,);diff --git a/packages/core/src/Table/plugins/sortable/useTableSortableState.test.tsx b/packages/core/src/Table/plugins/sortable/useTableSortableState.test.tsxindex 47521757eb..5b1b7777f1 100644--- a/packages/core/src/Table/plugins/sortable/useTableSortableState.test.tsx+++ b/packages/core/src/Table/plugins/sortable/useTableSortableState.test.tsx@@ -17,6 +17,7 @@ import {useTableSortable} from './useTableSortable';import type {TableSortState} from './useTableSortable';import {useTableSortableState} from './useTableSortableState';import type {UseTableSortableStateConfig} from './useTableSortableState';+import {InternationalizationProvider} from '../../../i18n';// =============================================================================// Test Data@@ -119,6 +120,39 @@ describe('useTableSortableState', () => {]);});+ it('re-sorts strings when the provider locale changes', () => {+ const localeData: Employee[] = [+ {+ id: '1',+ name: 'z',+ age: 1,+ department: 'Test',+ salary: 1,+ },+ {+ id: '2',+ name: 'ä',+ age: 2,+ department: 'Test',+ salary: 2,+ },+ ];+ const table = (locale: string) => (+ <InternationalizationProvider locale={locale}>+ <SortableStateTable+ data={localeData}+ defaultSort={[{sortKey: 'name', direction: 'ascending'}]}+ />+ </InternationalizationProvider>+ );++ const {rerender} = render(table('sv-SE'));+ expect(getNameColumnValues()).toEqual(['z', 'ä']);++ rerender(table('de-DE'));+ expect(getNameColumnValues()).toEqual(['ä', 'z']);+ });+it('renders unsorted when no defaultSort', () => {render(<SortableStateTable />);diff --git a/packages/core/src/Table/plugins/sortable/useTableSortableState.tsx b/packages/core/src/Table/plugins/sortable/useTableSortableState.tsxindex 74d6a5af3d..292347089f 100644--- a/packages/core/src/Table/plugins/sortable/useTableSortableState.tsx+++ b/packages/core/src/Table/plugins/sortable/useTableSortableState.tsx@@ -18,10 +18,8 @@*/import {useState, useMemo, useCallback, useRef} from 'react';-import type {- TableSortState,- UseTableSortableConfig,-} from './useTableSortable';+import type {TableSortState, UseTableSortableConfig} from './useTableSortable';+import {useCollator} from '../../../i18n/useCollator';// =============================================================================// Comparator Types@@ -104,14 +102,16 @@ export interface UseTableSortableStateConfig<* two row items. Comparators should sort ascending — the hook flips the* sign for descending.*- * For keys not in this map, the hook falls back to `localeCompare` with- * `{ numeric: true }` on the stringified values.+ * For keys not in this map, the hook falls back to an `Intl.Collator`+ * comparison (`{numeric: true}`) on the stringified values, bound to the+ * active `InternationalizationProvider` locale.** @example* ```+ * const collator = useCollator({numeric: true});* comparators: {* age: (a, b) => a.age - b.age,- * name: (a, b) => a.name.localeCompare(b.name),+ * name: (a, b) => collator.compare(a.name, b.name),* }* ```*/@@ -164,6 +164,7 @@ function defaultCompare<T extends Record<string, unknown>>(a: T,b: T,sortKey: string,+ collator: Intl.Collator,): number {const aVal = a[sortKey];const bVal = b[sortKey];@@ -171,8 +172,10 @@ function defaultCompare<T extends Record<string, unknown>>(// null/undefined/NaN sort to the end. NaN must not reach the numeric fast// path: a NaN comparator result reads as "equal" to Array.sort, which makes// the comparator inconsistent and corrupts the order of the other rows.- const aMissing = aVal == null || (typeof aVal === 'number' && Number.isNaN(aVal));- const bMissing = bVal == null || (typeof bVal === 'number' && Number.isNaN(bVal));+ const aMissing =+ aVal == null || (typeof aVal === 'number' && Number.isNaN(aVal));+ const bMissing =+ bVal == null || (typeof bVal === 'number' && Number.isNaN(bVal));if (aMissing && bMissing) {return 0;}@@ -188,14 +191,9 @@ function defaultCompare<T extends Record<string, unknown>>(return aVal - bVal;}- // string comparison with numeric collation- return toSortableString(aVal).localeCompare(- toSortableString(bVal),- undefined,- {- numeric: true,- },- );+ // string comparison with numeric collation, bound to the provider locale+ // via useCollator() rather than a raw localeCompare(value, locale) call.+ return collator.compare(toSortableString(aVal), toSortableString(bVal));}// =============================================================================@@ -208,7 +206,8 @@ function sortData<>(data: T[],sortState: TableSortState<TSortKey>,- comparators?: Partial<Record<TSortKey, TableSortComparator<T>>>,+ comparators: Partial<Record<TSortKey, TableSortComparator<T>>> | undefined,+ collator: Intl.Collator,): T[] {if (sortState.length === 0) {return data;@@ -218,7 +217,9 @@ function sortData<for (const entry of sortState) {const {sortKey, direction} = entry;const customCmp = comparators?.[sortKey];- const cmp = customCmp ? customCmp(a, b) : defaultCompare(a, b, sortKey);+ const cmp = customCmp+ ? customCmp(a, b)+ : defaultCompare(a, b, sortKey, collator);if (cmp !== 0) {return direction === 'ascending' ? cmp : -cmp;@@ -265,6 +266,7 @@ export function useTableSortableState<allowUnsortedState,isMultiSortEnabled,} = config;+ const collator = useCollator({numeric: true});// Internal state (used in uncontrolled mode)const [internalSort, setInternalSort] =@@ -287,14 +289,15 @@ export function useTableSortableState<// Sorted data — memoized on sort state + data identityconst sortedData = useMemo(- () => sortData(data, sort, comparatorsRef.current),- [data, sort],+ () => sortData(data, sort, comparatorsRef.current, collator),+ [data, sort, collator],);// applySort — lets consumers sort arbitrary data with the current stateconst applySort = useCallback(- (inputData: T[]): T[] => sortData(inputData, sort, comparatorsRef.current),- [sort],+ (inputData: T[]): T[] =>+ sortData(inputData, sort, comparatorsRef.current, collator),+ [sort, collator],);// Config ready for useTableSortablediff --git a/packages/core/src/Timestamp/Timestamp.test.tsx b/packages/core/src/Timestamp/Timestamp.test.tsxindex 9405d7bcca..595d0b265b 100644--- a/packages/core/src/Timestamp/Timestamp.test.tsx+++ b/packages/core/src/Timestamp/Timestamp.test.tsx@@ -257,6 +257,26 @@ describe('Timestamp', () => {// --- Standard display formats ---+ it('updates absolute output when the provider locale changes', () => {+ const value = '2026-01-25T12:00:00Z';+ const timestamp = (locale: string) => (+ <InternationalizationProvider locale={locale}>+ <Timestamp+ value={value}+ format="date_long"+ hasTooltip={false}+ data-testid="ts"+ />+ </InternationalizationProvider>+ );++ const {rerender} = render(timestamp('en-US'));+ expect(screen.getByTestId('ts')).toHaveTextContent('January 25, 2026');++ rerender(timestamp('de-DE'));+ expect(screen.getByTestId('ts')).toHaveTextContent('25. Januar 2026');+ });+it('renders date format', () => {render(<Timestamp value="2026-02-19T17:00:00Z" format="date" data-testid="ts" />,@@ -441,7 +461,7 @@ describe('Timestamp', () => {);const longTz =- new Intl.DateTimeFormat(undefined, {timeZoneName: 'long'})+ new Intl.DateTimeFormat('en', {timeZoneName: 'long'}).formatToParts(oneHourAgo).find(p => p.type === 'timeZoneName')?.value ?? '';expect(longTz).not.toBe('');@@ -462,7 +482,7 @@ describe('Timestamp', () => {);const tzPart = (form: 'short' | 'long') =>- new Intl.DateTimeFormat(undefined, {timeZoneName: form})+ new Intl.DateTimeFormat('en', {timeZoneName: form}).formatToParts(date).find(p => p.type === 'timeZoneName')?.value ?? '';const text = screen.getByTestId('ts').textContent ?? '';@@ -673,7 +693,7 @@ describe('Timestamp', () => {// no-break spaces that jest-dom's matcher normalization would break on.const normalize = (s: string) => s.replace(/\s+/g, ' ');const datetime = new Date(el.getAttribute('datetime') ?? '');- const expected = new Intl.DateTimeFormat(undefined, {+ const expected = new Intl.DateTimeFormat('en', {year: 'numeric',month: 'long',day: 'numeric',@@ -789,7 +809,7 @@ describe('Timestamp', () => {const datetime = new Date(screen.getByTestId('ts').getAttribute('datetime') ?? '',);- const expected = new Intl.DateTimeFormat(undefined, {+ const expected = new Intl.DateTimeFormat('en', {year: 'numeric',month: 'long',day: 'numeric',@@ -1252,7 +1272,7 @@ describe('Timestamp', () => {data-testid="ts"/>,);- const [line] = formatTooltipLines(new Date(VALUE), [{format}]);+ const [line] = formatTooltipLines(new Date(VALUE), [{format}], 'en');expect(line.value).toBe(screen.getByTestId('ts').textContent);},);@@ -1275,10 +1295,10 @@ describe('Timestamp', () => {);const date = new Date(VALUE);const tzPart = (form: 'short' | 'long') =>- new Intl.DateTimeFormat(undefined, {timeZoneName: form})+ new Intl.DateTimeFormat('en', {timeZoneName: form}).formatToParts(date).find(p => p.type === 'timeZoneName')?.value ?? '';- const [line] = formatTooltipLines(date, [{format: 'full'}]);+ const [line] = formatTooltipLines(date, [{format: 'full'}], 'en');expect(screen.getByTestId('ts').getAttribute('aria-label')).toBe(line.value.replace(tzPart('short'), tzPart('long')),);diff --git a/packages/core/src/Timestamp/Timestamp.tsx b/packages/core/src/Timestamp/Timestamp.tsxindex cec0f4ef75..8e6128be35 100644--- a/packages/core/src/Timestamp/Timestamp.tsx+++ b/packages/core/src/Timestamp/Timestamp.tsx@@ -23,6 +23,7 @@ import type {TextType, TextSize, TextColor, TextWeight} from '../theme/types';import {mergeProps, mergeRefs} from '../utils';import {useDevWarning} from '../hooks/useDevWarning';import {useTranslator} from '../i18n';+import {useLocale} from '../i18n/useLocale';import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';import {formatInstant} from './formatInstant';@@ -419,6 +420,7 @@ export function Timestamp({'data-testid': testId,}: TimestampProps) {const t = useTranslator();+ const locale = useLocale();const timeRef = useRef<HTMLTimeElement>(null);const [now, setNow] = useState(() => new Date());@@ -448,16 +450,18 @@ export function Timestamp({: effectiveFormat === 'relative_short'? getRelativeTimeShortString(date, now): isAbsoluteFormat(effectiveFormat)- ? formatInstant(date, effectiveFormat, {isTimezoneShown})+ ? formatInstant(date, effectiveFormat, locale, {isTimezoneShown}): '';// Full absolute text for the tooltip (visible — keeps the compact timezone// abbreviation) and for the AT-facing aria-label, which spells the timezone// out in full: abbreviations like "PST" or "GMT+2" are unexpanded// abbreviations to a screen-reader user (WCAG 3.1.4).- const fullAbsoluteText = isValidDate ? formatInstant(date, 'full') : '';+ const fullAbsoluteText = isValidDate+ ? formatInstant(date, 'full', locale)+ : '';const ariaLabelText = isValidDate- ? formatInstant(date, 'full', {timeZoneNameStyle: 'long'})+ ? formatInstant(date, 'full', locale, {timeZoneNameStyle: 'long'}): '';// Live updates@@ -506,7 +510,7 @@ export function Timestamp({const lines: ReadonlyArray<TimestampTooltipLine> =entries === undefined? [{value: fullAbsoluteText, isCopyable: true}]- : formatTooltipLines(date, entries);+ : formatTooltipLines(date, entries, locale);const timestampProps = mergeProps(themeProps('timestamp', {format: effectiveFormat}),diff --git a/packages/core/src/Timestamp/formatInstant.ts b/packages/core/src/Timestamp/formatInstant.tsindex 906f443b06..1a40316e61 100644--- a/packages/core/src/Timestamp/formatInstant.ts+++ b/packages/core/src/Timestamp/formatInstant.ts@@ -30,6 +30,7 @@*/import {SHARED_DATE_FORMAT_OPTIONS, getTimeZoneParts} from '../utils/plainDate';+import type {Locale} from '../i18n/types';import type {TimestampFormat} from './Timestamp';// =============================================================================@@ -159,12 +160,13 @@ function getWallClock(date: Date, timeZone: string | undefined): WallClock {/*** Renders one instant in one absolute format.*- * Pure: the same arguments always produce the same string for a given host+ * Pure: the same arguments always produce the same string for the requested* locale (and, when no `timeZone` is given, host zone).*/export function formatInstant(date: Date,format: InstantFormat,+ locale: Locale,{timeZone,isTimezoneShown = false,@@ -176,39 +178,39 @@ export function formatInstant(switch (format) {case 'full':- return new Intl.DateTimeFormat(undefined, {+ return new Intl.DateTimeFormat(locale, {...FULL_OPTIONS,timeZoneName: timeZoneNameStyle,...zone,}).format(date);case 'date':- return new Intl.DateTimeFormat(undefined, {+ return new Intl.DateTimeFormat(locale, {...SHARED_DATE_FORMAT_OPTIONS.date,...zone,}).format(date);case 'date_long':- return new Intl.DateTimeFormat(undefined, {+ return new Intl.DateTimeFormat(locale, {...SHARED_DATE_FORMAT_OPTIONS.date_long,...zone,}).format(date);case 'date_weekday':- return new Intl.DateTimeFormat(undefined, {+ return new Intl.DateTimeFormat(locale, {...SHARED_DATE_FORMAT_OPTIONS.date_weekday,...zone,}).format(date);case 'date_time':- return new Intl.DateTimeFormat(undefined, {+ return new Intl.DateTimeFormat(locale, {...DATE_TIME_OPTIONS,...zoneName,...zone,}).format(date);case 'time':- return new Intl.DateTimeFormat(undefined, {+ return new Intl.DateTimeFormat(locale, {...TIME_OPTIONS,...zoneName,...zone,diff --git a/packages/core/src/Timestamp/tooltipEntries.test.ts b/packages/core/src/Timestamp/tooltipEntries.test.tsindex a5f52d56dd..9d7e79424a 100644--- a/packages/core/src/Timestamp/tooltipEntries.test.ts+++ b/packages/core/src/Timestamp/tooltipEntries.test.ts@@ -16,12 +16,17 @@import {describe, it, expect, vi} from 'vitest';import {SHARED_DATE_FORMAT_OPTIONS} from '../utils/plainDate';-import {formatTooltipLines} from './tooltipEntries';+import {formatTooltipLines as formatTooltipLinesForLocale} from './tooltipEntries';++const formatTooltipLines = (+ date: Parameters<typeof formatTooltipLinesForLocale>[0],+ entries: Parameters<typeof formatTooltipLinesForLocale>[1],+) => formatTooltipLinesForLocale(date, entries, 'en-US');/** 2026-02-19T17:00:00Z — chosen so several zones land on different dates. */const INSTANT = new Date('2026-02-19T17:00:00Z');-const LOCAL_ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone;+const LOCAL_ZONE = Intl.DateTimeFormat('en-US').resolvedOptions().timeZone;describe('formatTooltipLines', () => {// --- Explicit zones: exact, locale-free, TZ-agnostic ---@@ -86,7 +91,7 @@ describe('formatTooltipLines', () => {for (const timezoneID of ['UTC', 'Asia/Tokyo']) {const [line] = formatTooltipLines(INSTANT, [{timezoneID, format}]);expect(line.value).toBe(- new Intl.DateTimeFormat(undefined, {+ new Intl.DateTimeFormat('en-US', {...SHARED_DATE_FORMAT_OPTIONS[format],timeZone: timezoneID,}).format(INSTANT),@@ -208,7 +213,7 @@ describe('formatTooltipLines', () => {{format: 'date_time'},{format: 'system_date_time'},]);- const localName = new Intl.DateTimeFormat(undefined, {+ const localName = new Intl.DateTimeFormat('en-US', {timeZoneName: 'short',}).formatToParts(INSTANT)@@ -230,7 +235,7 @@ describe('formatTooltipLines', () => {// aria-describedby, and that element's accessible name is the LOCAL// absolute time. A lone foreign-zone line with no marker is therefore// announced right after a local time, with nothing to say it is not one.- const zoneName = new Intl.DateTimeFormat(undefined, {+ const zoneName = new Intl.DateTimeFormat('en-US', {timeZone: 'Asia/Tokyo',timeZoneName: 'short',})@@ -248,7 +253,7 @@ describe('formatTooltipLines', () => {// The consumer never named a zone, so there is nothing to disambiguate// against — this must stay as bare as the visible text is by default.const [line] = formatTooltipLines(INSTANT, [{format: 'date_time'}]);- const localName = new Intl.DateTimeFormat(undefined, {+ const localName = new Intl.DateTimeFormat('en-US', {timeZoneName: 'short',}).formatToParts(INSTANT)diff --git a/packages/core/src/Timestamp/tooltipEntries.ts b/packages/core/src/Timestamp/tooltipEntries.tsindex 1e739d856a..36ce3dcfc3 100644--- a/packages/core/src/Timestamp/tooltipEntries.ts+++ b/packages/core/src/Timestamp/tooltipEntries.ts@@ -24,6 +24,7 @@import {devWarn} from '../utils/devWarning';import {formatInstant} from './formatInstant';import type {InstantFormat} from './formatInstant';+import type {Locale} from '../i18n/types';// =============================================================================// Types@@ -130,7 +131,9 @@ function resolveTimezoneID(timezoneID: string | undefined): string | undefined {// degrade to the viewer's zone and say so, mirroring how an unparseable// `value` is handled in Timestamp.tsx.try {- new Intl.DateTimeFormat(undefined, {timeZone: timezoneID});+ // Locale does not affect time-zone identifier validity; pin one so this+ // validation path stays explicit and deterministic.+ new Intl.DateTimeFormat('en-US', {timeZone: timezoneID});} catch {if (!warnedTimezoneIDs.has(timezoneID)) {warnedTimezoneIDs.add(timezoneID);@@ -202,6 +205,7 @@ function shouldShowZoneName(export function formatTooltipLines(date: Date,entries: ReadonlyArray<TimestampTooltipEntry>,+ locale: Locale,): ReadonlyArray<TimestampTooltipLine> {const resolved = entries.map(entry => resolveTimezoneID(entry.timezoneID));const hasMultipleZones = new Set(resolved.map(zoneKey)).size > 1;@@ -213,7 +217,7 @@ export function formatTooltipLines(return {...(entry.label === undefined ? {} : {label: entry.label}),isCopyable: entry.isCopyable ?? false,- value: formatInstant(date, format, {+ value: formatInstant(date, format, locale, {timeZone,isTimezoneShown: shouldShowZoneName(format,diff --git a/packages/core/src/i18n/__tests__/e2e-powersearch.test.tsx b/packages/core/src/i18n/__tests__/e2e-powersearch.test.tsxindex a437d370e0..905c2b575e 100644--- a/packages/core/src/i18n/__tests__/e2e-powersearch.test.tsx+++ b/packages/core/src/i18n/__tests__/e2e-powersearch.test.tsx@@ -23,7 +23,11 @@ import {describe, test, expect} from 'vitest';import {render, screen} from '@testing-library/react';import React, {useMemo} from 'react';import {PowerSearch, usePowerSearchConfig} from '../../PowerSearch';-import type {FieldDefinition, PowerSearchFilter} from '../../PowerSearch';+import type {+ FieldDefinition,+ PowerSearchConfig,+ PowerSearchFilter,+} from '../../PowerSearch';import {InternationalizationProvider} from '../InternationalizationProvider';import pseudoCatalog from '../../../locales/pseudo.json';@@ -112,6 +116,38 @@ describe('PowerSearch × i18n — end to end', () => {expect(screen.getByText(/Name: contient/)).toBeInTheDocument();});+ test('date tokens update when the provider locale changes', () => {+ const config: PowerSearchConfig = {+ name: 'Dates',+ fields: [+ {+ key: 'created',+ label: 'Created',+ defaultOperator: 'is',+ operators: [{key: 'is', label: 'is', value: {type: 'date_absolute'}}],+ },+ ],+ };+ const filters: PowerSearchFilter[] = [+ {+ field: 'created',+ operator: 'is',+ value: {type: 'date_absolute', unixSeconds: 1769342400},+ },+ ];+ const search = (locale: string) => (+ <InternationalizationProvider locale={locale}>+ <PowerSearch config={config} filters={filters} onChange={() => {}} />+ </InternationalizationProvider>+ );++ const {rerender} = render(search('en-US'));+ expect(screen.getByText('Jan 25, 2026')).toBeInTheDocument();++ rerender(search('de-DE'));+ expect(screen.getByText('25. Jan. 2026')).toBeInTheDocument();+ });+test('resultCount ICU plural swaps under provider overrides', () => {render(<InternationalizationProvider