-
Notifications
You must be signed in to change notification settings - Fork 199
/
l10n.ts
41 lines (33 loc) · 1.45 KB
/
l10n.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use client'
import { ReactLocalization, useLocalization } from '@fluent/react'
import { createElement, Fragment } from 'react'
/**
* Equivalent to ReactLocalization.getString, but returns a React Fragment.
*
* This is useful because it allows you to replace tags in localised strings
* with HTML elements, without needing to reach out to <Localized>.
*
* (This method got booted out of @fluent/react proper because it's so simple,
* but it's pretty useful:
* https://github.com/projectfluent/fluent.js/pull/595#discussion_r967011632)
*/
export type GetFragment = (
id: Parameters<ReactLocalization['getString']>[0],
args?: Parameters<ReactLocalization['getElement']>[2],
fallback?: Parameters<ReactLocalization['getString']>[2]
) => ReturnType<ReactLocalization['getElement']>;
export type ExtendedReactLocalization = ReactLocalization & {
getFragment: GetFragment;
};
export const useL10n = (): ExtendedReactLocalization => {
const { l10n } = useLocalization()
const getFragment: GetFragment = (id, args, fallback) =>
l10n.getElement(createElement(Fragment, null, fallback ?? id), id, args)
const extendedL10n: ExtendedReactLocalization =
l10n as ExtendedReactLocalization
extendedL10n.getFragment = getFragment
return extendedL10n
}