Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to specify available locales on the i18nProvider #7758

Merged
merged 3 commits into from
May 30, 2022
Merged
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
14 changes: 6 additions & 8 deletions docs/LocalesMenuButton.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ The `<LocalesMenuButton>` component, also known as the "language switcher", disp

## Usage

Add the `<LocalesMenuButton>` to a custom `<AppBar>`, and list the locales available to end users:
Add the `<LocalesMenuButton>` to a custom `<AppBar>`:

```jsx
import { LocalesMenuButton, AppBar } from 'react-admin';
Expand All @@ -20,12 +20,7 @@ import { Typography } from '@mui/material';
export const MyAppBar = (props) => (
<AppBar {...props}>
<Typography flex="1" variant="h6" id="react-admin-title"></Typography>
<LocalesMenuButton
languages={[
{ locale: 'en', name: 'English' },
{ locale: 'fr', name: 'Français' },
]}
/>
<LocalesMenuButton />
</AppBar>
);
```
Expand All @@ -44,6 +39,7 @@ const MyLayout = (props) => <Layout {...props} appBar={MyAppBar} />;

const i18nProvider = polyglotI18nProvider(
locale => (locale === 'fr' ? frenchMessages : englishMessages),
getLocales: () => [{ locale: 'en', name: 'English' }, { locale: 'fr', name: 'Français' }],
'en' // Default locale
);

Expand All @@ -58,9 +54,11 @@ const App = () => (
);
```

**Tip**: the `<LocalesMenuButton>` will be added to the `<AppBar>` automatically if you have multiple locales declared in the `getLocales` method of your `i18nProvider`.

## `languages`

An array of objects (`{ locale, name }`) representing the key and the label of the languages available to end users.
An array of objects (`{ locale, name }`) representing the key and the label of the languages available to end users. You can omit this prop if your `i18nProvider` has a `getLocales` function.

```jsx
<LocalesMenuButton languages={[
Expand Down
3 changes: 2 additions & 1 deletion docs/Translation.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@ You will use translation features mostly via the `i18nProvider`, and a set of ho

## Introducing the `i18nProvider`

Just like for data fetching and authentication, react-admin relies on a simple object for translations. It's called the `i18nProvider`, and it manages translation and language changes using tree methods:
Just like for data fetching and authentication, react-admin relies on a simple object for translations. It's called the `i18nProvider`, and it manages translation and language changes using the following methods:

```js
const i18nProvider = {
translate: (key, options) => string,
changeLocale: locale => Promise,
getLocale: () => string,
getLocales: () => [{ locale: string; name: string; }], // Optional. Used by LocalesMenuButton if available
}
```

Expand Down
1 change: 1 addition & 0 deletions packages/ra-core/src/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export * from './TranslatableContextProvider';
export * from './TranslationUtils';
export * from './useLocaleState';
export * from './useLocale';
export * from './useLocales';
export * from './useSetLocale';
export * from './useTranslatable';
export * from './useTranslatableContext';
Expand Down
36 changes: 36 additions & 0 deletions packages/ra-core/src/i18n/useLocales.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { useMemo } from 'react';
import { useI18nProvider } from './useI18nProvider';

/**
* A hook that gets the available locales from the i18nProvider.
* @example
*
* import { useLocales } from 'react-admin';
*
* const LocaleSelector = () => {
* const locales = useLocales();
* const [currentLocale, setCurrentLocale] = useLocaleState();
*
* return (
* <select onChange={event => setCurrentLocale(event.target.value)}>
* {locales.map(locale => (
* <option key={locale.locale} value={locale.locale}>
* {locale.name}
* </option>
* )}
* </select>
* );
* }
*/
export const useLocales = (options?: UseLocalesOptions) => {
const i18nProvider = useI18nProvider();
const locales = useMemo(
() => (i18nProvider?.getLocales ? i18nProvider?.getLocales() : []),
[i18nProvider]
);
return options?.locales ?? locales;
};

export interface UseLocalesOptions {
locales?: { locale: string; name: string }[];
}
6 changes: 6 additions & 0 deletions packages/ra-core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,16 @@ export const I18N_CHANGE_LOCALE = 'I18N_CHANGE_LOCALE';

export type Translate = (key: string, options?: any) => string;

export type Locale = {
locale: string;
name: string;
};

export type I18nProvider = {
translate: Translate;
changeLocale: (locale: string, options?: any) => Promise<void>;
getLocale: () => string;
getLocales?: () => Locale[];
[key: string]: any;
};

Expand Down
8 changes: 5 additions & 3 deletions packages/ra-ui-materialui/src/button/LocalesMenuButton.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import { MouseEvent, useState } from 'react';
import { useLocaleState } from 'ra-core';
import { useLocaleState, useLocales } from 'ra-core';
import { Box, Button, Menu, MenuItem, styled } from '@mui/material';
import LanguageIcon from '@mui/icons-material/Translate';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
Expand All @@ -25,8 +25,9 @@ import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
* </AppBar>
* );
*/
export const LocalesMenuButton = ({ languages }: LocalesMenuButtonProps) => {
export const LocalesMenuButton = (props: LocalesMenuButtonProps) => {
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
const languages = useLocales({ locales: props.languages });
const [locale, setLocale] = useLocaleState();

const getNameForLocale = (locale: string): string => {
Expand Down Expand Up @@ -73,6 +74,7 @@ export const LocalesMenuButton = ({ languages }: LocalesMenuButtonProps) => {
<MenuItem
key={language.locale}
onClick={changeLocale(language.locale)}
selected={language.locale === locale}
>
{language.name}
</MenuItem>
Expand All @@ -98,5 +100,5 @@ const Root = styled(Box, {
}));

export interface LocalesMenuButtonProps {
languages: { locale: string; name: string }[];
languages?: { locale: string; name: string }[];
}
7 changes: 6 additions & 1 deletion packages/ra-ui-materialui/src/layout/AppBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@ import {
useMediaQuery,
Theme,
} from '@mui/material';
import { ComponentPropType } from 'ra-core';
import { ComponentPropType, useLocales } from 'ra-core';

import { SidebarToggleButton } from './SidebarToggleButton';
import { LoadingIndicator } from './LoadingIndicator';
import { UserMenu } from './UserMenu';
import { HideOnScroll } from './HideOnScroll';
import { LocalesMenuButton } from '../button';

/**
* The AppBar component renders a custom MuiAppBar.
Expand Down Expand Up @@ -65,6 +66,7 @@ export const AppBar: FC<AppBarProps> = memo(props => {
...rest
} = props;

const locales = useLocales();
const isXSmall = useMediaQuery<Theme>(theme =>
theme.breakpoints.down('sm')
);
Expand Down Expand Up @@ -92,6 +94,9 @@ export const AppBar: FC<AppBarProps> = memo(props => {
) : (
children
)}
{locales && locales.length > 1 ? (
<LocalesMenuButton />
) : null}
<LoadingIndicator />
{typeof userMenu === 'boolean' ? (
userMenu === true ? (
Expand Down