diff --git a/apps/mobile/src/features/threads/messageTimestamp.test.ts b/apps/mobile/src/features/threads/messageTimestamp.test.ts index 0fb993e1e8f0d..7f0930141d380 100644 --- a/apps/mobile/src/features/threads/messageTimestamp.test.ts +++ b/apps/mobile/src/features/threads/messageTimestamp.test.ts @@ -1,8 +1,16 @@ import { describe, expect, it, vi } from "vite-plus/test"; -import { createMessageTimeFormatter, formatMessageTimestamp } from "./messageTimestamp"; +import { createMessageTimeFormatter } from "./messageTimestamp"; + +function mockDeviceLocale(deviceLocale: string) { + const DateTimeFormat = Intl.DateTimeFormat; + return vi.spyOn(Intl, "DateTimeFormat").mockImplementation(function (locale, options) { + return new DateTimeFormat(locale ?? deviceLocale, options); + }); +} describe("formatMessageTimestamp", () => { + const formatMessageTimestamp = createMessageTimeFormatter(undefined); const now = new Date(2026, 10, 8, 20, 0).getTime(); const time = (date: Date) => date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" }); @@ -55,10 +63,29 @@ describe("createMessageTimeFormatter", () => { const now = new Date(2026, 0, 1, 20, 0).getTime(); it("follows the system clock preference over the locale's hour cycle", () => { - const format24 = createMessageTimeFormatter(true, "en-US"); - expect(format24(new Date(2026, 0, 1, 15, 7).toISOString(), now)).toBe("15:07"); - expect(format24(new Date(2026, 0, 1, 0, 7).toISOString(), now)).toBe("00:07"); - const format12 = createMessageTimeFormatter(false, "en-GB"); + { + using _deviceLocale = mockDeviceLocale("en-US"); + const format24 = createMessageTimeFormatter(true); + expect(format24(new Date(2026, 0, 1, 15, 7).toISOString(), now)).toBe("15:07"); + expect(format24(new Date(2026, 0, 1, 0, 7).toISOString(), now)).toBe("00:07"); + } + using _deviceLocale = mockDeviceLocale("en-GB"); + const format12 = createMessageTimeFormatter(false); expect(format12(new Date(2026, 0, 1, 15, 7).toISOString(), now)).toMatch(/^3:07\spm$/i); }); + + it("writes earlier days in the given locale's date order", () => { + const format = createMessageTimeFormatter(true, "de"); + const june = new Date(2026, 5, 1, 20, 0).getTime(); + expect(format(new Date(2026, 2, 5, 15, 7).toISOString(), june)).toBe("5.3. 15:07"); + expect(format(new Date(2025, 2, 5, 15, 7).toISOString(), june)).toBe("5.3.2025 15:07"); + }); + + it("formats dates in the UI locale and keeps the device clock when no override is available", () => { + using _deviceLocale = mockDeviceLocale("en-US"); + const format = createMessageTimeFormatter(undefined, "de"); + const june = new Date(2026, 5, 1, 20, 0).getTime(); + expect(format(new Date(2026, 5, 1, 15, 7).toISOString(), june)).toMatch(/^3:07\sPM$/); + expect(format(new Date(2026, 2, 5, 15, 7).toISOString(), june)).toMatch(/^5\.3\. 3:07\sPM$/); + }); }); diff --git a/apps/mobile/src/features/threads/messageTimestamp.ts b/apps/mobile/src/features/threads/messageTimestamp.ts index 0b7cd95e1bf03..f8715876cbdc1 100644 --- a/apps/mobile/src/features/threads/messageTimestamp.ts +++ b/apps/mobile/src/features/threads/messageTimestamp.ts @@ -1,65 +1,54 @@ // Formatters pin the default zone when built, and Hermes keeps Date's local offset until a cold // start (react/react-native#59131), so formatting and day checks follow the zone Intl reports. -function buildFormatters(timeZone: string) { +function buildFormatters(timeZone: string, dateLocales: Intl.LocalesArgument, is24Hour?: boolean) { return { timeZone, - time: new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit", timeZone }), - date: new Intl.DateTimeFormat(undefined, { month: "numeric", day: "numeric", timeZone }), - dateWithYear: new Intl.DateTimeFormat(undefined, { + time: new Intl.DateTimeFormat(undefined, { + hour: "numeric", + minute: "2-digit", + timeZone, + ...(is24Hour === undefined ? {} : { hourCycle: is24Hour ? "h23" : "h12" }), + }), + date: new Intl.DateTimeFormat(dateLocales, { month: "numeric", day: "numeric", timeZone }), + dateWithYear: new Intl.DateTimeFormat(dateLocales, { month: "numeric", day: "numeric", year: "numeric", timeZone, }), - year: new Intl.DateTimeFormat(undefined, { year: "numeric", timeZone }), + year: new Intl.DateTimeFormat(dateLocales, { year: "numeric", timeZone }), }; } // Reading the zone builds a formatter (tens of µs), so feed rows share one read per second. const ZONE_RECHECK_MS = 1_000; -let formatters: ReturnType | null = null; +let timeZone: string | undefined; let zoneCheckedAt = 0; -function currentFormatters() { +function currentTimeZone(): string { const now = Date.now(); - if (formatters && Math.abs(now - zoneCheckedAt) < ZONE_RECHECK_MS) return formatters; + if (timeZone !== undefined && Math.abs(now - zoneCheckedAt) < ZONE_RECHECK_MS) return timeZone; zoneCheckedAt = now; - const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; - if (!formatters || formatters.timeZone !== timeZone) formatters = buildFormatters(timeZone); - return formatters; -} - -/** Time only for today's messages; older ones lead with the day and month. */ -export function formatMessageTimestamp( - input: string, - nowMs: number = Date.now(), - timeFormatter?: Intl.DateTimeFormat, -): string { - const timestamp = Date.parse(input); - if (Number.isNaN(timestamp)) return ""; - const f = currentFormatters(); - const time = (timeFormatter ?? f.time).format(timestamp); - const dateWithYear = f.dateWithYear.format(timestamp); - if (dateWithYear === f.dateWithYear.format(nowMs)) return time; - const sameYear = f.year.format(timestamp) === f.year.format(nowMs); - return `${sameYear ? f.date.format(timestamp) : dateWithYear} ${time}`; + timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; + return timeZone; } -/** `is24Hour` overrides the locale's hour cycle with the system clock preference when known. */ -export function createMessageTimeFormatter(is24Hour: boolean | undefined, locale?: string) { - let cached: { timeZone: string; formatter: Intl.DateTimeFormat } | null = null; - return (input: string, nowMs?: number): string => { - const { timeZone } = currentFormatters(); - if (cached?.timeZone !== timeZone) { - cached = { - timeZone, - formatter: new Intl.DateTimeFormat(locale, { - hour: "numeric", - minute: "2-digit", - timeZone, - ...(is24Hour === undefined ? {} : { hourCycle: is24Hour ? "h23" : "h12" }), - }), - }; - } - return formatMessageTimestamp(input, nowMs, cached.formatter); +/** + * Time uses the device locale and clock preference. Older messages also show the date in `dateLocales`. + */ +export function createMessageTimeFormatter( + is24Hour: boolean | undefined, + dateLocales?: Intl.LocalesArgument, +) { + let f: ReturnType | null = null; + return (input: string, nowMs: number = Date.now()): string => { + const timestamp = Date.parse(input); + if (Number.isNaN(timestamp)) return ""; + const zone = currentTimeZone(); + if (f?.timeZone !== zone) f = buildFormatters(zone, dateLocales, is24Hour); + const time = f.time.format(timestamp); + const dateWithYear = f.dateWithYear.format(timestamp); + if (dateWithYear === f.dateWithYear.format(nowMs)) return time; + const sameYear = f.year.format(timestamp) === f.year.format(nowMs); + return `${sameYear ? f.date.format(timestamp) : dateWithYear} ${time}`; }; } diff --git a/apps/mobile/src/features/threads/useMessageTimeFormatter.ts b/apps/mobile/src/features/threads/useMessageTimeFormatter.ts index 2320d369762ca..271949bd00cb8 100644 --- a/apps/mobile/src/features/threads/useMessageTimeFormatter.ts +++ b/apps/mobile/src/features/threads/useMessageTimeFormatter.ts @@ -1,6 +1,9 @@ +import { formattingLocales } from "@t3tools/client-runtime/locales"; import { requireNativeModule } from "expo"; +import { useLocale } from "gt-react-native"; import { useEffect, useMemo, useState } from "react"; import { AppState, Platform } from "react-native"; +import { readDeviceLocales } from "../../i18n/deviceLocales"; import { createMessageTimeFormatter } from "./messageTimestamp"; function systemUses24HourClock() { @@ -18,5 +21,12 @@ export function useMessageTimeFormatter() { }); return () => subscription.remove(); }, []); - return useMemo(() => createMessageTimeFormatter(is24Hour), [is24Hour]); + const locale = useLocale(); + return useMemo(() => { + const { preferredLanguages, regionalLocale } = readDeviceLocales(); + return createMessageTimeFormatter( + is24Hour, + formattingLocales(locale, preferredLanguages, regionalLocale), + ); + }, [is24Hour, locale]); } diff --git a/apps/mobile/src/i18n/I18nProvider.tsx b/apps/mobile/src/i18n/I18nProvider.tsx index fc13df01081a6..252bf5e82d951 100644 --- a/apps/mobile/src/i18n/I18nProvider.tsx +++ b/apps/mobile/src/i18n/I18nProvider.tsx @@ -4,9 +4,10 @@ import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import { GTProvider, initializeGT, useLocale } from "gt-react-native"; import { useDeferredValue, useEffect, type ReactNode } from "react"; -import { Platform, TurboModuleRegistry, View, type TurboModule } from "react-native"; +import { View } from "react-native"; import { mobilePreferencesAtom } from "../state/preferences"; +import { readDeviceLocales } from "./deviceLocales"; import { DEFAULT_LOCALE, SUPPORTED_LOCALES } from "./locales"; import { setActiveLocale } from "./messages"; @@ -33,22 +34,6 @@ initializeGT({ cacheExpiryTime: null, }); -// Read the device languages from gt-react-native's own native module: GT's getLocale() prefers -// the last locale passed to GTProvider, which it persists, so it can't express "system". -function readSystemLocales(): ReadonlyArray { - try { - const locales = - TurboModuleRegistry.get<{ getNativeLocales(): string[] } & TurboModule>( - "GtReactNative", - )?.getNativeLocales() ?? []; - // On iOS the first entry is NSLocale.currentLocale, whose language is the app's bundle - // localization (English only), not the user's; preferredLanguages follow it. - return Platform.OS === "ios" ? locales.slice(1) : locales; - } catch { - return []; - } -} - export function useLanguagePreference(): string { const preferences = useAtomValue(mobilePreferencesAtom); return AsyncResult.isSuccess(preferences) @@ -61,7 +46,12 @@ export function I18nProvider(props: { readonly children: ReactNode }) { // GT suspends while a locale's catalog loads. Deferring the switch keeps the current language // on screen until then, instead of GT's full-screen spinner. const locale = useDeferredValue( - resolveLocale(useLanguagePreference(), readSystemLocales(), SUPPORTED_LOCALES, DEFAULT_LOCALE), + resolveLocale( + useLanguagePreference(), + readDeviceLocales().preferredLanguages, + SUPPORTED_LOCALES, + DEFAULT_LOCALE, + ), ); return ( }> diff --git a/apps/mobile/src/i18n/deviceLocales.test.ts b/apps/mobile/src/i18n/deviceLocales.test.ts new file mode 100644 index 0000000000000..8936589b95328 --- /dev/null +++ b/apps/mobile/src/i18n/deviceLocales.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { readDeviceLocales } from "./deviceLocales"; + +vi.mock("react-native", () => ({ + Platform: { OS: "ios" }, + TurboModuleRegistry: { + get: () => ({ getNativeLocales: () => ["en_GB@calendar=gregorian", "en-US"] }), + }, +})); + +describe("readDeviceLocales", () => { + it("reads the iOS region setting as a language tag", () => { + expect(readDeviceLocales()).toEqual({ regionalLocale: "en-GB", preferredLanguages: ["en-US"] }); + }); +}); diff --git a/apps/mobile/src/i18n/deviceLocales.ts b/apps/mobile/src/i18n/deviceLocales.ts new file mode 100644 index 0000000000000..07ac5c6fcc8d0 --- /dev/null +++ b/apps/mobile/src/i18n/deviceLocales.ts @@ -0,0 +1,23 @@ +import { Platform, TurboModuleRegistry, type TurboModule } from "react-native"; + +// GT's getLocale() reads the last saved UI locale, so get the device languages directly. +export function readDeviceLocales() { + let locales: ReadonlyArray = []; + try { + locales = + TurboModuleRegistry.get<{ getNativeLocales(): string[] } & TurboModule>( + "GtReactNative", + )?.getNativeLocales() ?? []; + } catch { + // The native module is optional. + } + const regionalLocale = locales[0]; + if (Platform.OS !== "ios") { + return { regionalLocale, preferredLanguages: locales }; + } + // iOS puts its region setting first as an NSLocale identifier, ahead of its language tags. + return { + regionalLocale: regionalLocale?.trim().replace(/@.*$/, "").replaceAll("_", "-"), + preferredLanguages: locales.slice(1), + }; +} diff --git a/packages/client-runtime/src/locales.test.ts b/packages/client-runtime/src/locales.test.ts new file mode 100644 index 0000000000000..e04231dcb864f --- /dev/null +++ b/packages/client-runtime/src/locales.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { formattingLocales } from "./locales.js"; + +describe("formattingLocales", () => { + it.each([ + { uiLocale: "en", systemLocales: ["en-GB"], expected: ["en-GB", "en"] }, + { uiLocale: "de", systemLocales: ["en-US", "de-AT", "de-DE"], expected: ["de-AT", "de"] }, + { uiLocale: "de", systemLocales: ["en-US"], expected: ["de-US", "de"] }, + { uiLocale: "pt-BR", systemLocales: ["en-US"], expected: ["pt-BR"] }, + { + uiLocale: "pt-BR", + systemLocales: ["pt-PT"], + regionalLocale: "pt-PT", + expected: ["pt-BR"], + }, + { uiLocale: "zh", systemLocales: ["zh-Hant-HK"], expected: ["zh"] }, + { uiLocale: "zh", systemLocales: ["zh-Hant-HK", "zh-Hans-SG"], expected: ["zh-Hans-SG", "zh"] }, + { uiLocale: "en", systemLocales: ["nl-NL"], expected: ["en-NL", "en"] }, + { + uiLocale: "en", + systemLocales: ["nl-NL", "en-US"], + regionalLocale: "nl-NL", + expected: ["en-NL", "en"], + }, + { uiLocale: "en", systemLocales: [], expected: ["en"] }, + ])("formats $uiLocale with system locales $systemLocales as $expected", (testCase) => { + expect( + formattingLocales(testCase.uiLocale, testCase.systemLocales, testCase.regionalLocale), + ).toEqual(testCase.expected); + }); +}); diff --git a/packages/client-runtime/src/locales.ts b/packages/client-runtime/src/locales.ts index c137032fb2fa3..0d44c7bc16f42 100644 --- a/packages/client-runtime/src/locales.ts +++ b/packages/client-runtime/src/locales.ts @@ -43,3 +43,45 @@ export function resolveLocale( } return fallback; } + +function parseSystemLocale(tag: string): Intl.Locale | undefined { + try { + return new Intl.Locale(tag); + } catch { + return undefined; + } +} + +/** + * Locales for Intl formatters from normalized language tags. Keep an explicit UI region; + * otherwise prefer a compatible system variant or region, with the UI locale as a fallback + * since Hermes on Android formats a tag ICU lacks (such as de-US) in the device locale. + */ +export function formattingLocales( + uiLocale: string, + systemLocales: ReadonlyArray, + regionalLocale?: string, +): ReadonlyArray { + const ui = new Intl.Locale(uiLocale); + if (ui.region) return [uiLocale]; + const compatible = [uiLocale, ui.language]; + const preferredRegion = regionalLocale ? parseSystemLocale(regionalLocale)?.region : undefined; + let region: string | undefined; + let variant: string | undefined; + for (const tag of systemLocales) { + const system = parseSystemLocale(tag); + if (!system) continue; + region ??= system.region; + if (matchSupportedLocale(system.baseName, compatible)) { + variant = system.baseName; + break; + } + } + const locale = variant ?? uiLocale; + const formattingRegion = preferredRegion ?? (variant ? undefined : region); + const regional = formattingRegion + ? new Intl.Locale(locale, { region: formattingRegion }).baseName + : locale; + const preferred = matchSupportedLocale(regional, compatible) ? regional : locale; + return preferred === uiLocale ? [uiLocale] : [preferred, uiLocale]; +}