use-intl 2.4.1 → 2.7.0

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.
Files changed (40) hide show
  1. package/README.md +1 -0
  2. package/dist/AbstractIntlMessages.d.ts +9 -0
  3. package/dist/Formats.d.ts +2 -1
  4. package/dist/IntlContext.d.ts +2 -2
  5. package/dist/IntlError.d.ts +1 -0
  6. package/dist/IntlMessages.d.ts +2 -4
  7. package/dist/IntlProvider.d.ts +3 -3
  8. package/dist/NumberFormatOptions.d.ts +1 -3
  9. package/dist/index.d.ts +1 -1
  10. package/dist/use-intl.cjs.development.js +137 -63
  11. package/dist/use-intl.cjs.development.js.map +1 -1
  12. package/dist/use-intl.cjs.production.min.js +1 -1
  13. package/dist/use-intl.cjs.production.min.js.map +1 -1
  14. package/dist/use-intl.esm.js +127 -56
  15. package/dist/use-intl.esm.js.map +1 -1
  16. package/dist/useIntl.d.ts +2 -1
  17. package/dist/useTranslations.d.ts +22 -5
  18. package/dist/useTranslationsImpl.d.ts +12 -0
  19. package/dist/utils/MessageKeys.d.ts +5 -0
  20. package/dist/utils/NamespaceKeys.d.ts +5 -0
  21. package/dist/utils/NestedKeyOf.d.ts +4 -0
  22. package/dist/utils/NestedValueOf.d.ts +2 -0
  23. package/dist/validateMessages.d.ts +3 -0
  24. package/package.json +17 -13
  25. package/src/AbstractIntlMessages.tsx +10 -0
  26. package/src/Formats.tsx +2 -1
  27. package/src/IntlContext.tsx +2 -2
  28. package/src/IntlError.tsx +1 -0
  29. package/src/IntlMessages.tsx +4 -2
  30. package/src/IntlProvider.tsx +15 -4
  31. package/src/NumberFormatOptions.tsx +1 -3
  32. package/src/index.tsx +1 -1
  33. package/src/useIntl.tsx +2 -1
  34. package/src/useTranslations.tsx +116 -298
  35. package/src/useTranslationsImpl.tsx +328 -0
  36. package/src/utils/MessageKeys.tsx +9 -0
  37. package/src/utils/NamespaceKeys.tsx +9 -0
  38. package/src/utils/NestedKeyOf.tsx +9 -0
  39. package/src/utils/NestedValueOf.tsx +12 -0
  40. package/src/validateMessages.tsx +42 -0
@@ -1,79 +1,13 @@
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';
1
+ import {ReactElement, ReactNodeArray} from 'react';
11
2
  import Formats from './Formats';
12
3
  import IntlError, {IntlErrorCode} from './IntlError';
13
- import IntlMessages from './IntlMessages';
14
4
  import TranslationValues, {RichTranslationValues} from './TranslationValues';
15
- import convertFormatsToIntlMessageFormat from './convertFormatsToIntlMessageFormat';
16
5
  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 (Object.keys(values).length === 0) return undefined;
52
-
53
- // Workaround for https://github.com/formatjs/formatjs/issues/1467
54
- const transformedValues: RichTranslationValues = {};
55
- Object.keys(values).forEach((key) => {
56
- let index = 0;
57
- const value = values[key];
58
-
59
- let transformed;
60
- if (typeof value === 'function') {
61
- transformed = (children: ReactNode) => {
62
- const result = value(children);
63
-
64
- return isValidElement(result)
65
- ? cloneElement(result, {key: key + index++})
66
- : result;
67
- };
68
- } else {
69
- transformed = value;
70
- }
71
-
72
- transformedValues[key] = transformed;
73
- });
74
-
75
- return transformedValues;
76
- }
6
+ import useTranslationsImpl from './useTranslationsImpl';
7
+ import MessageKeys from './utils/MessageKeys';
8
+ import NamespaceKeys from './utils/NamespaceKeys';
9
+ import NestedKeyOf from './utils/NestedKeyOf';
10
+ import NestedValueOf from './utils/NestedValueOf';
77
11
 
78
12
  /**
79
13
  * Translates messages from the given namespace by using the ICU syntax.
@@ -83,231 +17,115 @@ function prepareTranslationValues(values: RichTranslationValues) {
83
17
  * The namespace can also indicate nesting by using a dot
84
18
  * (e.g. `namespace.Component`).
85
19
  */
86
- export default function useTranslations(namespace?: string) {
87
- const {
88
- defaultTranslationValues,
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({...defaultTranslationValues, ...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
- defaultTranslationValues
310
- ]);
20
+ export default function useTranslations<
21
+ NestedKey extends NamespaceKeys<IntlMessages, NestedKeyOf<IntlMessages>>
22
+ >(
23
+ namespace?: NestedKey
24
+ ): // Explicitly defining the return type is necessary as TypeScript would get it wrong
25
+ {
26
+ // Default invocation
27
+ <
28
+ TargetKey extends MessageKeys<
29
+ NestedValueOf<
30
+ {'!': IntlMessages},
31
+ NamespaceKeys<IntlMessages, NestedKeyOf<IntlMessages>> extends NestedKey
32
+ ? '!'
33
+ : `!.${NestedKey}`
34
+ >,
35
+ NestedKeyOf<
36
+ NestedValueOf<
37
+ {'!': IntlMessages},
38
+ NamespaceKeys<
39
+ IntlMessages,
40
+ NestedKeyOf<IntlMessages>
41
+ > extends NestedKey
42
+ ? '!'
43
+ : `!.${NestedKey}`
44
+ >
45
+ >
46
+ >
47
+ >(
48
+ key: TargetKey,
49
+ values?: TranslationValues,
50
+ formats?: Partial<Formats>
51
+ ): string;
52
+
53
+ // `rich`
54
+ rich<
55
+ TargetKey extends MessageKeys<
56
+ NestedValueOf<
57
+ {'!': IntlMessages},
58
+ NamespaceKeys<IntlMessages, NestedKeyOf<IntlMessages>> extends NestedKey
59
+ ? '!'
60
+ : `!.${NestedKey}`
61
+ >,
62
+ NestedKeyOf<
63
+ NestedValueOf<
64
+ {'!': IntlMessages},
65
+ NamespaceKeys<
66
+ IntlMessages,
67
+ NestedKeyOf<IntlMessages>
68
+ > extends NestedKey
69
+ ? '!'
70
+ : `!.${NestedKey}`
71
+ >
72
+ >
73
+ >
74
+ >(
75
+ key: TargetKey,
76
+ values?: RichTranslationValues,
77
+ formats?: Partial<Formats>
78
+ ): string | ReactElement | ReactNodeArray;
79
+
80
+ // `raw`
81
+ raw<
82
+ TargetKey extends MessageKeys<
83
+ NestedValueOf<
84
+ {'!': IntlMessages},
85
+ NamespaceKeys<IntlMessages, NestedKeyOf<IntlMessages>> extends NestedKey
86
+ ? '!'
87
+ : `!.${NestedKey}`
88
+ >,
89
+ NestedKeyOf<
90
+ NestedValueOf<
91
+ {'!': IntlMessages},
92
+ NamespaceKeys<
93
+ IntlMessages,
94
+ NestedKeyOf<IntlMessages>
95
+ > extends NestedKey
96
+ ? '!'
97
+ : `!.${NestedKey}`
98
+ >
99
+ >
100
+ >
101
+ >(
102
+ key: TargetKey
103
+ ): any;
104
+ } {
105
+ const context = useIntlContext();
106
+
107
+ const messages = context.messages as IntlMessages;
108
+ if (!messages) {
109
+ const intlError = new IntlError(
110
+ IntlErrorCode.MISSING_MESSAGE,
111
+ __DEV__ ? `No messages were configured on the provider.` : undefined
112
+ );
113
+ context.onError(intlError);
114
+ throw intlError;
115
+ }
311
116
 
312
- return translate;
117
+ // We have to wrap the actual hook so the type inference for the optional
118
+ // namespace works correctly. See https://stackoverflow.com/a/71529575/343045
119
+ // The prefix ("!"") is arbitrary, but we have to use some.
120
+ return useTranslationsImpl<
121
+ {'!': IntlMessages},
122
+ NamespaceKeys<IntlMessages, NestedKeyOf<IntlMessages>> extends NestedKey
123
+ ? '!'
124
+ : `!.${NestedKey}`
125
+ >(
126
+ {'!': messages},
127
+ // @ts-ignore
128
+ namespace ? `!.${namespace}` : '!',
129
+ '!'
130
+ );
313
131
  }