diff --git a/__tests__/lib/i18n/index.test.ts b/__tests__/lib/i18n/index.test.ts new file mode 100644 index 000000000..26a589bc7 --- /dev/null +++ b/__tests__/lib/i18n/index.test.ts @@ -0,0 +1,43 @@ +import { getLocales } from 'expo-localization'; + +import { storage } from '../../../src/lib/storage'; + +jest.mock('../../../src/lib/storage', () => ({ + storage: { + getString: jest.fn(), + }, +})); + +jest.mock('expo-localization', () => ({ + getLocales: jest.fn(), +})); + +const mockGetString = storage.getString as jest.Mock; +const mockGetLocales = getLocales as jest.Mock; + +function loadI18n() { + let i18n: typeof import('i18next').default | undefined; + jest.isolateModules(() => { + i18n = (require('../../../src/lib/i18n') as { default: typeof import('i18next').default }).default; + }); + return i18n!; +} + +describe('i18n initialization', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockGetLocales.mockReturnValue([{ languageTag: 'es-ES' }]); + }); + + it('should use the language selected in the app', () => { + mockGetString.mockReturnValue('en'); + + expect(loadI18n().language).toBe('en'); + }); + + it('should use the OS language when no language is selected', () => { + mockGetString.mockReturnValue(undefined); + + expect(loadI18n().language).toBe('es-ES'); + }); +}); diff --git a/__tests__/lib/i18n/sync-language-with-os.test.ts b/__tests__/lib/i18n/sync-language-with-os.test.ts new file mode 100644 index 000000000..1dede8332 --- /dev/null +++ b/__tests__/lib/i18n/sync-language-with-os.test.ts @@ -0,0 +1,163 @@ +import type { AppStateStatus } from 'react-native'; +import { renderHook } from '@testing-library/react-native'; +import { getLocales } from 'expo-localization'; +import i18n from 'i18next'; +import { AppState } from 'react-native'; + +import { storage } from '../../../src/lib/storage'; +import { + resolveLanguage, + syncLanguageWithOS, + useSyncLanguageWithOS, +} from '../../../src/lib/i18n/utils'; + +jest.mock('../../../src/lib/storage', () => ({ + storage: { + getString: jest.fn(), + }, +})); + +jest.mock('expo-localization', () => ({ + getLocales: jest.fn(), +})); + +jest.mock('i18next', () => { + const mockI18n = { + language: 'en-US', + changeLanguage: jest.fn(), + t: jest.fn(), + }; + return { + __esModule: true, + default: mockI18n, + changeLanguage: mockI18n.changeLanguage, + t: mockI18n.t, + }; +}); + +const mockGetString = storage.getString as jest.Mock; +const mockGetLocales = getLocales as jest.Mock; +const mockChangeLanguage = i18n.changeLanguage as jest.Mock; + +function mockDeviceLanguage(languageTag: string) { + mockGetLocales.mockReturnValue([{ languageTag }]); +} + +describe('resolveLanguage', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('should return the language selected in the app', () => { + mockGetString.mockReturnValue('en'); + mockDeviceLanguage('es-ES'); + + expect(resolveLanguage()).toBe('en'); + }); + + it('should return the OS language when no language is selected', () => { + mockGetString.mockReturnValue(undefined); + mockDeviceLanguage('es-ES'); + + expect(resolveLanguage()).toBe('es-ES'); + }); + + it('should return undefined when no language is available', () => { + mockGetString.mockReturnValue(undefined); + mockGetLocales.mockReturnValue([]); + + expect(resolveLanguage()).toBeUndefined(); + }); +}); + +describe('syncLanguageWithOS', () => { + beforeEach(() => { + jest.clearAllMocks(); + i18n.language = 'en-US'; + }); + + it('should change the language when the OS language changed and none is selected', () => { + mockGetString.mockReturnValue(undefined); + mockDeviceLanguage('es-ES'); + + syncLanguageWithOS(); + + expect(mockChangeLanguage).toHaveBeenCalledWith('es-ES'); + }); + + it('should not change the language when the OS language did not change', () => { + mockGetString.mockReturnValue(undefined); + mockDeviceLanguage('en-US'); + + syncLanguageWithOS(); + + expect(mockChangeLanguage).not.toHaveBeenCalled(); + }); + + it('should not change the language when a language is selected', () => { + mockGetString.mockReturnValue('en'); + mockDeviceLanguage('es-ES'); + + syncLanguageWithOS(); + + expect(mockChangeLanguage).not.toHaveBeenCalled(); + }); +}); + +describe('useSyncLanguageWithOS', () => { + let listener: ((state: AppStateStatus) => void) | undefined; + const mockRemove = jest.fn(); + + beforeEach(() => { + jest.clearAllMocks(); + i18n.language = 'en-US'; + listener = undefined; + jest.spyOn(AppState, 'addEventListener').mockImplementation((_, handler) => { + listener = handler as (state: AppStateStatus) => void; + return { remove: mockRemove }; + }); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('should update the language when the app comes to the foreground', () => { + mockGetString.mockReturnValue(undefined); + mockDeviceLanguage('es-ES'); + renderHook(() => useSyncLanguageWithOS()); + + listener?.('active'); + + expect(AppState.addEventListener).toHaveBeenCalledWith('change', expect.any(Function)); + expect(mockChangeLanguage).toHaveBeenCalledWith('es-ES'); + }); + + it('should not update the language when the app goes to the background', () => { + mockGetString.mockReturnValue(undefined); + mockDeviceLanguage('es-ES'); + renderHook(() => useSyncLanguageWithOS()); + + listener?.('background'); + + expect(mockChangeLanguage).not.toHaveBeenCalled(); + }); + + it('should not update the language on foreground when a language is selected', () => { + mockGetString.mockReturnValue('en'); + mockDeviceLanguage('es-ES'); + renderHook(() => useSyncLanguageWithOS()); + + listener?.('active'); + + expect(mockChangeLanguage).not.toHaveBeenCalled(); + }); + + it('should remove the listener on unmount', () => { + const { unmount } = renderHook(() => useSyncLanguageWithOS()); + + unmount(); + + expect(mockRemove).toHaveBeenCalled(); + }); +}); diff --git a/docs/src/content/docs/guides/internationalization.mdx b/docs/src/content/docs/guides/internationalization.mdx index 6dc9d4272..280335631 100644 --- a/docs/src/content/docs/guides/internationalization.mdx +++ b/docs/src/content/docs/guides/internationalization.mdx @@ -60,6 +60,14 @@ Additionally, the `useSetLanguage` hook will save the selected language in devic +## Following the OS language + +When no language has been selected in the app, the app uses the OS language. The `useSyncLanguageWithOS` hook, mounted once in `src/app/_layout.tsx`, reads the OS language again every time the app comes back to the foreground and updates the current language if the user changed it in the device settings. Once a language is selected in the app, it always takes precedence over the OS language. + +:::note +The RTL layout direction is only applied at startup, so switching between LTR and RTL OS languages while the app is running takes effect after the app is restarted. +::: + ## Robust translation **Typescript support** diff --git a/src/app/_layout.tsx b/src/app/_layout.tsx index a105f26b8..ab9442cd6 100644 --- a/src/app/_layout.tsx +++ b/src/app/_layout.tsx @@ -13,7 +13,12 @@ import { APIProvider } from '@/api'; import interceptors from '@/api/common/interceptors'; import { AuthProvider, useAuth } from '@/components/providers/auth'; -import { hydrateAuth, loadSelectedTheme, useIsFirstTime } from '@/lib'; +import { + hydrateAuth, + loadSelectedTheme, + useIsFirstTime, + useSyncLanguageWithOS, +} from '@/lib'; import { useThemeConfig } from '@/lib/use-theme-config'; // Import global CSS file import '../../global.css'; @@ -74,6 +79,8 @@ function GuardedStack() { } export default function RootLayout() { + useSyncLanguageWithOS(); + return ( diff --git a/src/lib/i18n/index.tsx b/src/lib/i18n/index.tsx index ea3a97e63..dafae733e 100644 --- a/src/lib/i18n/index.tsx +++ b/src/lib/i18n/index.tsx @@ -1,18 +1,16 @@ -import { getLocales } from 'expo-localization'; import i18n, { dir, use } from 'i18next'; import { initReactI18next } from 'react-i18next'; import { I18nManager } from 'react-native'; import { resources } from './resources'; +import { resolveLanguage } from './utils'; export * from './utils'; -const locales = getLocales(); - // eslint-disable-next-line react-hooks/rules-of-hooks void use(initReactI18next).init({ resources, - lng: locales[0]?.languageTag, // TODO: if you are not supporting multiple languages or languages with multiple directions you can set the default value to `en` + lng: resolveLanguage(), // TODO: if you are not supporting multiple languages or languages with multiple directions you can set the default value to `en` fallbackLng: 'en', compatibilityJSON: 'v3', // By default React Native projects does not support Intl diff --git a/src/lib/i18n/utils.tsx b/src/lib/i18n/utils.tsx index a8e30d6eb..1fe0974a6 100644 --- a/src/lib/i18n/utils.tsx +++ b/src/lib/i18n/utils.tsx @@ -1,10 +1,11 @@ import type { TOptions } from 'i18next'; import type { Language, resources } from './resources'; import type { RecursiveKeyOf } from './types'; -import { changeLanguage as i18nChangeLanguage, t } from 'i18next'; +import { getLocales } from 'expo-localization'; +import i18n, { changeLanguage as i18nChangeLanguage, t } from 'i18next'; import memoize from 'lodash.memoize'; -import { useCallback } from 'react'; -import { NativeModules, Platform } from 'react-native'; +import { useCallback, useEffect } from 'react'; +import { AppState, NativeModules, Platform } from 'react-native'; import { useMMKVString } from 'react-native-mmkv'; import RNRestart from 'react-native-restart'; @@ -17,6 +18,40 @@ export const LOCAL = 'local'; export const getLanguage = () => storage.getString(LOCAL); // 'Marc' getItem(LOCAL); +// Language tag of the first preferred OS locale, e.g. 'en-US' +export function getDeviceLanguage(): string | undefined { + return getLocales()[0]?.languageTag; +} + +// The language selected in the app wins over the OS language +export function resolveLanguage(): string | undefined { + return getLanguage() ?? getDeviceLanguage(); +} + +// Follows the OS language when no language was selected in the app +export function syncLanguageWithOS() { + if (getLanguage() !== undefined) { + return; + } + const deviceLanguage = getDeviceLanguage(); + if (deviceLanguage !== undefined && deviceLanguage !== i18n.language) { + void i18nChangeLanguage(deviceLanguage); + } +} + +// The OS language can change while the app is in the background, +// so it is read again every time the app comes back to the foreground +export function useSyncLanguageWithOS() { + useEffect(() => { + const subscription = AppState.addEventListener('change', (state) => { + if (state === 'active') { + syncLanguageWithOS(); + } + }); + return () => subscription.remove(); + }, []); +} + export const translate = memoize( (key: TxKeyPath, options?: Record) => t(key, options as TOptions),