use-intl 2.3.4 → 2.4.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ // This module is intended to be overridden
2
+ // by the consumer for optional type safety
3
+
4
+ // type Messages = typeof import('./en.json');
5
+
6
+ // eslint-disable-next-line @typescript-eslint/ban-types
7
+ type Unknown = {};
8
+
9
+ // eslint-disable-next-line @typescript-eslint/no-empty-interface
10
+ interface GlobalMessages
11
+ // Messages,
12
+ extends Unknown {}
13
+
14
+ export default GlobalMessages;
@@ -2,6 +2,7 @@ import {createContext} from 'react';
2
2
  import Formats from './Formats';
3
3
  import IntlError from './IntlError';
4
4
  import IntlMessages from './IntlMessages';
5
+ import {RichTranslationValues} from './TranslationValues';
5
6
 
6
7
  export type IntlContextShape = {
7
8
  messages?: IntlMessages;
@@ -15,6 +16,7 @@ export type IntlContextShape = {
15
16
  namespace?: string;
16
17
  }): string;
17
18
  now?: Date;
19
+ defaultTranslationValues?: RichTranslationValues;
18
20
  };
19
21
 
20
22
  const IntlContext = createContext<IntlContextShape | undefined>(undefined);
@@ -1,3 +1,5 @@
1
- type IntlMessages = {[id: string]: IntlMessages | string};
1
+ type IntlMessages = {
2
+ [id: string]: IntlMessages | string;
3
+ };
2
4
 
3
5
  export default IntlMessages;
@@ -2,6 +2,7 @@ import React, {ReactNode} from 'react';
2
2
  import Formats from './Formats';
3
3
  import IntlContext from './IntlContext';
4
4
  import IntlMessages from './IntlMessages';
5
+ import {RichTranslationValues} from './TranslationValues';
5
6
  import {IntlError} from '.';
6
7
 
7
8
  type Props = {
@@ -39,6 +40,10 @@ type Props = {
39
40
  * afterwards the current date will be returned continuously.
40
41
  */
41
42
  now?: Date;
43
+ /** Global default values for translation values and rich text elements.
44
+ * Can be used for consistent usage or styling of rich text elements.
45
+ * Defaults will be overidden by locally provided values. */
46
+ defaultTranslationValues?: RichTranslationValues;
42
47
  };
43
48
 
44
49
  function defaultGetMessageFallback({
package/src/en.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "About": {
3
+ "title": "About",
4
+ "lastUpdated": "This example was updated {lastUpdatedRelative} ({lastUpdated, date, short}).",
5
+ "nested": {
6
+ "hello": "Hello"
7
+ }
8
+ },
9
+ "Index": {
10
+ "title": "Home",
11
+ "description": "<p>Only the minimum of <code>{locale}</code> messages are loaded to render this page.</p><p>These namespaces are available:</p>"
12
+ },
13
+ "Navigation": {
14
+ "index": "Home",
15
+ "about": "About",
16
+ "switchLocale": "Switch to {locale, select, de {German} en {English}}"
17
+ },
18
+ "NotFound": {
19
+ "title": "Sorry, this page could not be found."
20
+ },
21
+ "PageLayout": {
22
+ "pageTitle": "next-intl"
23
+ },
24
+ "Test": {
25
+ "nested": {
26
+ "hello": "Hello",
27
+ "another": {
28
+ "level": "Level"
29
+ }
30
+ }
31
+ }
32
+ }
package/src/index.tsx CHANGED
@@ -1,5 +1,6 @@
1
1
  export {default as IntlProvider} from './IntlProvider';
2
2
  export {default as IntlMessages} from './IntlMessages';
3
+ export {default as GlobalMessages} from './GlobalMessages';
3
4
  export {default as useTranslations} from './useTranslations';
4
5
  export {
5
6
  default as TranslationValues,
@@ -1,80 +1,8 @@
1
- import IntlMessageFormat from 'intl-messageformat';
2
- import {
3
- cloneElement,
4
- isValidElement,
5
- ReactElement,
6
- ReactNode,
7
- ReactNodeArray,
8
- useMemo,
9
- useRef
10
- } from 'react';
11
- import Formats from './Formats';
12
- import IntlError, {IntlErrorCode} from './IntlError';
13
- import IntlMessages from './IntlMessages';
14
- import TranslationValues, {RichTranslationValues} from './TranslationValues';
15
- import convertFormatsToIntlMessageFormat from './convertFormatsToIntlMessageFormat';
1
+ import GlobalMessages from './GlobalMessages';
16
2
  import useIntlContext from './useIntlContext';
17
-
18
- function resolvePath(
19
- messages: IntlMessages | undefined,
20
- idPath: string,
21
- namespace?: string
22
- ) {
23
- if (!messages) {
24
- throw new Error(
25
- __DEV__ ? `No messages available at \`${namespace}\`.` : undefined
26
- );
27
- }
28
-
29
- let message = messages;
30
-
31
- idPath.split('.').forEach((part) => {
32
- const next = (message as any)[part];
33
-
34
- if (part == null || next == null) {
35
- throw new Error(
36
- __DEV__
37
- ? `Could not resolve \`${idPath}\` in ${
38
- namespace ? `\`${namespace}\`` : 'messages'
39
- }.`
40
- : undefined
41
- );
42
- }
43
-
44
- message = next;
45
- });
46
-
47
- return message;
48
- }
49
-
50
- function prepareTranslationValues(values?: RichTranslationValues) {
51
- if (!values) return values;
52
-
53
- // Workaround for https://github.com/formatjs/formatjs/issues/1467
54
- const transformedValues: RichTranslationValues = {};
55
- Object.keys(values).forEach((key) => {
56
- const value = values[key];
57
-
58
- let transformed;
59
- if (typeof value === 'function') {
60
- transformed = (children: ReactNode) => {
61
- const result = value(children);
62
-
63
- return isValidElement(result)
64
- ? cloneElement(result, {
65
- key: result.key || key + String(children)
66
- })
67
- : result;
68
- };
69
- } else {
70
- transformed = value;
71
- }
72
-
73
- transformedValues[key] = transformed;
74
- });
75
-
76
- return transformedValues;
77
- }
3
+ import useTranslationsImpl from './useTranslationsImpl';
4
+ import NamespaceKeys from './utils/NamespaceKeys';
5
+ import NestedKeyOf from './utils/NestedKeyOf';
78
6
 
79
7
  /**
80
8
  * Translates messages from the given namespace by using the ICU syntax.
@@ -84,229 +12,23 @@ function prepareTranslationValues(values?: RichTranslationValues) {
84
12
  * The namespace can also indicate nesting by using a dot
85
13
  * (e.g. `namespace.Component`).
86
14
  */
87
- export default function useTranslations(namespace?: string) {
88
- const {
89
- formats: globalFormats,
90
- getMessageFallback,
91
- locale,
92
- messages: allMessages,
93
- onError,
94
- timeZone
95
- } = useIntlContext();
96
-
97
- const cachedFormatsByLocaleRef = useRef<
98
- Record<string, Record<string, IntlMessageFormat>>
99
- >({});
100
-
101
- const messagesOrError = useMemo(() => {
102
- try {
103
- if (!allMessages) {
104
- throw new Error(
105
- __DEV__ ? `No messages were configured on the provider.` : undefined
106
- );
107
- }
108
-
109
- const retrievedMessages = namespace
110
- ? resolvePath(allMessages, namespace)
111
- : allMessages;
112
-
113
- if (!retrievedMessages) {
114
- throw new Error(
115
- __DEV__
116
- ? `No messages for namespace \`${namespace}\` found.`
117
- : undefined
118
- );
119
- }
120
-
121
- return retrievedMessages;
122
- } catch (error) {
123
- const intlError = new IntlError(
124
- IntlErrorCode.MISSING_MESSAGE,
125
- (error as Error).message
126
- );
127
- onError(intlError);
128
- return intlError;
129
- }
130
- }, [allMessages, namespace, onError]);
131
-
132
- const translate = useMemo(() => {
133
- function getFallbackFromErrorAndNotify(
134
- key: string,
135
- code: IntlErrorCode,
136
- message?: string
137
- ) {
138
- const error = new IntlError(code, message);
139
- onError(error);
140
- return getMessageFallback({error, key, namespace});
141
- }
142
-
143
- function translateBaseFn(
144
- /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */
145
- key: string,
146
- /** Key value pairs for values to interpolate into the message. */
147
- values?: RichTranslationValues,
148
- /** Provide custom formats for numbers, dates and times. */
149
- formats?: Partial<Formats>
150
- ): string | ReactElement | ReactNodeArray {
151
- const cachedFormatsByLocale = cachedFormatsByLocaleRef.current;
152
-
153
- if (messagesOrError instanceof IntlError) {
154
- // We have already warned about this during render
155
- return getMessageFallback({
156
- error: messagesOrError,
157
- key,
158
- namespace
159
- });
160
- }
161
- const messages = messagesOrError;
162
-
163
- const cacheKey = [namespace, key]
164
- .filter((part) => part != null)
165
- .join('.');
166
-
167
- let messageFormat;
168
- if (cachedFormatsByLocale[locale]?.[cacheKey]) {
169
- messageFormat = cachedFormatsByLocale[locale][cacheKey];
170
- } else {
171
- let message;
172
- try {
173
- message = resolvePath(messages, key, namespace);
174
- } catch (error) {
175
- return getFallbackFromErrorAndNotify(
176
- key,
177
- IntlErrorCode.MISSING_MESSAGE,
178
- (error as Error).message
179
- );
180
- }
181
-
182
- if (typeof message === 'object') {
183
- return getFallbackFromErrorAndNotify(
184
- key,
185
- IntlErrorCode.INSUFFICIENT_PATH,
186
- __DEV__
187
- ? `Insufficient path specified for \`${key}\` in \`${
188
- namespace ? `\`${namespace}\`` : 'messages'
189
- }\`.`
190
- : undefined
191
- );
192
- }
193
-
194
- try {
195
- messageFormat = new IntlMessageFormat(
196
- message,
197
- locale,
198
- convertFormatsToIntlMessageFormat(
199
- {...globalFormats, ...formats},
200
- timeZone
201
- )
202
- );
203
- } catch (error) {
204
- return getFallbackFromErrorAndNotify(
205
- key,
206
- IntlErrorCode.INVALID_MESSAGE,
207
- (error as Error).message
208
- );
209
- }
210
-
211
- if (!cachedFormatsByLocale[locale]) {
212
- cachedFormatsByLocale[locale] = {};
213
- }
214
- cachedFormatsByLocale[locale][cacheKey] = messageFormat;
215
- }
216
-
217
- try {
218
- const formattedMessage = messageFormat.format(
219
- prepareTranslationValues(values)
220
- );
221
-
222
- if (formattedMessage == null) {
223
- throw new Error(
224
- __DEV__
225
- ? `Unable to format \`${key}\` in ${
226
- namespace ? `namespace \`${namespace}\`` : 'messages'
227
- }`
228
- : undefined
229
- );
230
- }
231
-
232
- // Limit the function signature to return strings or React elements
233
- return isValidElement(formattedMessage) ||
234
- // Arrays of React elements
235
- Array.isArray(formattedMessage) ||
236
- typeof formattedMessage === 'string'
237
- ? formattedMessage
238
- : String(formattedMessage);
239
- } catch (error) {
240
- return getFallbackFromErrorAndNotify(
241
- key,
242
- IntlErrorCode.FORMATTING_ERROR,
243
- (error as Error).message
244
- );
245
- }
246
- }
247
-
248
- function translateFn(
249
- /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */
250
- key: string,
251
- /** Key value pairs for values to interpolate into the message. */
252
- values?: TranslationValues,
253
- /** Provide custom formats for numbers, dates and times. */
254
- formats?: Partial<Formats>
255
- ): string {
256
- const message = translateBaseFn(key, values, formats);
257
-
258
- if (typeof message !== 'string') {
259
- return getFallbackFromErrorAndNotify(
260
- key,
261
- IntlErrorCode.INVALID_MESSAGE,
262
- __DEV__
263
- ? `The message \`${key}\` in ${
264
- namespace ? `namespace \`${namespace}\`` : 'messages'
265
- } didn't resolve to a string. If you want to format rich text, use \`t.rich\` instead.`
266
- : undefined
267
- );
268
- }
269
-
270
- return message;
271
- }
272
-
273
- translateFn.rich = translateBaseFn;
274
-
275
- translateFn.raw = (
276
- /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */
277
- key: string
278
- ): any => {
279
- if (messagesOrError instanceof IntlError) {
280
- // We have already warned about this during render
281
- return getMessageFallback({
282
- error: messagesOrError,
283
- key,
284
- namespace
285
- });
286
- }
287
- const messages = messagesOrError;
288
-
289
- try {
290
- return resolvePath(messages, key, namespace);
291
- } catch (error) {
292
- return getFallbackFromErrorAndNotify(
293
- key,
294
- IntlErrorCode.MISSING_MESSAGE,
295
- (error as Error).message
296
- );
297
- }
298
- };
299
-
300
- return translateFn;
301
- }, [
302
- getMessageFallback,
303
- globalFormats,
304
- locale,
305
- messagesOrError,
306
- namespace,
307
- onError,
308
- timeZone
309
- ]);
310
-
311
- return translate;
15
+ export default function useTranslations<
16
+ NestedKey extends NamespaceKeys<GlobalMessages, NestedKeyOf<GlobalMessages>>
17
+ >(namespace?: NestedKey) {
18
+ // @ts-ignore
19
+ const messages = useIntlContext().messages as GlobalMessages;
20
+ if (!messages) throw new Error('TODO')
21
+
22
+ // We have to wrap the actual hook so the type inference for the optional
23
+ // namespace works correctly. See https://stackoverflow.com/a/71529575/343045
24
+ return useTranslationsImpl<
25
+ // @ts-ignore
26
+ {__private: GlobalMessages},
27
+ NamespaceKeys<GlobalMessages, NestedKeyOf<GlobalMessages>> extends NestedKey
28
+ ? '__private'
29
+ : `__private.${NestedKey}`
30
+ >(
31
+ {__private: messages},
32
+ namespace ? `__private.${namespace}` : '__private'
33
+ );
312
34
  }