Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions __tests__/lib/i18n/index.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
163 changes: 163 additions & 0 deletions __tests__/lib/i18n/sync-language-with-os.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
8 changes: 8 additions & 0 deletions docs/src/content/docs/guides/internationalization.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ Additionally, the `useSetLanguage` hook will save the selected language in devic

<CodeBlock file="src/lib/i18n/utils.tsx" />

## 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**
Expand Down
9 changes: 8 additions & 1 deletion src/app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -74,6 +79,8 @@ function GuardedStack() {
}

export default function RootLayout() {
useSyncLanguageWithOS();

return (
<Providers>
<RouterContent />
Expand Down
6 changes: 2 additions & 4 deletions src/lib/i18n/index.tsx
Original file line number Diff line number Diff line change
@@ -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

Expand Down
41 changes: 38 additions & 3 deletions src/lib/i18n/utils.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -17,6 +18,40 @@ export const LOCAL = 'local';

export const getLanguage = () => storage.getString(LOCAL); // 'Marc' getItem<Language | undefined>(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);
Comment thread
fernandatoledo marked this conversation as resolved.
Resolved
}
}

// 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<string, unknown>) => t(key, options as TOptions),
Expand Down
Loading