use-intl 2.4.0 → 2.4.1-alpha.3

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.
@@ -1,79 +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 IntlError, { IntlErrorCode } from './IntlError';
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 (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
- }
3
+ import useTranslationsImpl from './useTranslationsImpl';
4
+ import NamespaceKeys from './utils/NamespaceKeys';
5
+ import NestedKeyOf from './utils/NestedKeyOf';
77
6
 
78
7
  /**
79
8
  * Translates messages from the given namespace by using the ICU syntax.
@@ -83,231 +12,35 @@ function prepareTranslationValues(values: RichTranslationValues) {
83
12
  * The namespace can also indicate nesting by using a dot
84
13
  * (e.g. `namespace.Component`).
85
14
  */
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
- }
15
+ export default function useTranslations<
16
+ NestedKey extends NamespaceKeys<GlobalMessages, NestedKeyOf<GlobalMessages>>
17
+ >(namespace?: NestedKey) {
18
+ const context = useIntlContext()
120
19
 
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
+ // @ts-ignore
21
+ const messages = context.messages as GlobalMessages;
22
+ if (!messages) {
23
+ const intlError = new IntlError(
24
+ IntlErrorCode.MISSING_MESSAGE,
25
+ __DEV__ ? `No messages were configured on the provider.` : undefined
26
+ );
27
+ context.onError(intlError);
28
+ throw intlError;
29
+ }
311
30
 
312
- return translate;
31
+ // We have to wrap the actual hook so the type inference for the optional
32
+ // namespace works correctly. See https://stackoverflow.com/a/71529575/343045
33
+ // The prefix ("!"") is arbitrary, but we have to use some.
34
+ return useTranslationsImpl<
35
+ // @ts-ignore
36
+ {'!': GlobalMessages},
37
+ NamespaceKeys<GlobalMessages, NestedKeyOf<GlobalMessages>> extends NestedKey
38
+ ? '!'
39
+ : `!.${NestedKey}`
40
+ >(
41
+ {'!': messages},
42
+ // @ts-ignore
43
+ namespace ? `!.${namespace}` : '!',
44
+ '!'
45
+ );
313
46
  }
@@ -0,0 +1,322 @@
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';
16
+ import useIntlContext from './useIntlContext';
17
+ import MessageKeys from './utils/MessageKeys';
18
+ import NestedKeyOf from './utils/NestedKeyOf';
19
+ import NestedValueOf from './utils/NestedValueOf';
20
+
21
+ function resolvePath(
22
+ messages: IntlMessages | undefined,
23
+ idPath: string,
24
+ namespace?: string
25
+ ) {
26
+ if (!messages) {
27
+ throw new Error(
28
+ __DEV__ ? `No messages available at \`${namespace}\`.` : undefined
29
+ );
30
+ }
31
+
32
+ let message = messages;
33
+
34
+ idPath.split('.').forEach((part) => {
35
+ const next = (message as any)[part];
36
+
37
+ if (part == null || next == null) {
38
+ throw new Error(
39
+ __DEV__
40
+ ? `Could not resolve \`${idPath}\` in ${
41
+ namespace ? `\`${namespace}\`` : 'messages'
42
+ }.`
43
+ : undefined
44
+ );
45
+ }
46
+
47
+ message = next;
48
+ });
49
+
50
+ return message;
51
+ }
52
+
53
+ function prepareTranslationValues(values: RichTranslationValues) {
54
+ if (Object.keys(values).length === 0) return undefined;
55
+
56
+ // Workaround for https://github.com/formatjs/formatjs/issues/1467
57
+ const transformedValues: RichTranslationValues = {};
58
+ Object.keys(values).forEach((key) => {
59
+ let index = 0;
60
+ const value = values[key];
61
+
62
+ let transformed;
63
+ if (typeof value === 'function') {
64
+ transformed = (children: ReactNode) => {
65
+ const result = value(children);
66
+
67
+ return isValidElement(result)
68
+ ? cloneElement(result, {key: key + index++})
69
+ : result;
70
+ };
71
+ } else {
72
+ transformed = value;
73
+ }
74
+
75
+ transformedValues[key] = transformed;
76
+ });
77
+
78
+ return transformedValues;
79
+ }
80
+
81
+ export default function useTranslationsImpl<
82
+ Messages extends IntlMessages,
83
+ NestedKey extends NestedKeyOf<Messages>
84
+ >(allMessages: Messages, namespace: NestedKey, namespacePrefix: string) {
85
+ const {
86
+ defaultTranslationValues,
87
+ formats: globalFormats,
88
+ getMessageFallback,
89
+ locale,
90
+ onError,
91
+ timeZone
92
+ } = useIntlContext();
93
+
94
+ // The `namespacePrefix` is part of the type system.
95
+ // See the comment in the hook invocation.
96
+ allMessages = allMessages[namespacePrefix] as Messages;
97
+ namespace = (namespace === namespacePrefix
98
+ ? undefined
99
+ : namespace.slice((namespacePrefix + '.').length)) as NestedKey;
100
+
101
+ const cachedFormatsByLocaleRef = useRef<
102
+ Record<string, Record<string, IntlMessageFormat>>
103
+ >({});
104
+
105
+ const messagesOrError = useMemo(() => {
106
+ try {
107
+ if (!allMessages) {
108
+ throw new Error(
109
+ __DEV__ ? `No messages were configured on the provider.` : undefined
110
+ );
111
+ }
112
+
113
+ const retrievedMessages = namespace
114
+ ? resolvePath(allMessages, namespace)
115
+ : allMessages;
116
+
117
+ if (!retrievedMessages) {
118
+ throw new Error(
119
+ __DEV__
120
+ ? `No messages for namespace \`${namespace}\` found.`
121
+ : undefined
122
+ );
123
+ }
124
+
125
+ return retrievedMessages;
126
+ } catch (error) {
127
+ const intlError = new IntlError(
128
+ IntlErrorCode.MISSING_MESSAGE,
129
+ (error as Error).message
130
+ );
131
+ onError(intlError);
132
+ return intlError;
133
+ }
134
+ }, [allMessages, namespace, onError]);
135
+
136
+ const translate = useMemo(() => {
137
+ function getFallbackFromErrorAndNotify(
138
+ key: string,
139
+ code: IntlErrorCode,
140
+ message?: string
141
+ ) {
142
+ const error = new IntlError(code, message);
143
+ onError(error);
144
+ return getMessageFallback({error, key, namespace});
145
+ }
146
+
147
+ function translateBaseFn(
148
+ /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */
149
+ key: string,
150
+ /** Key value pairs for values to interpolate into the message. */
151
+ values?: RichTranslationValues,
152
+ /** Provide custom formats for numbers, dates and times. */
153
+ formats?: Partial<Formats>
154
+ ): string | ReactElement | ReactNodeArray {
155
+ const cachedFormatsByLocale = cachedFormatsByLocaleRef.current;
156
+
157
+ if (messagesOrError instanceof IntlError) {
158
+ // We have already warned about this during render
159
+ return getMessageFallback({
160
+ error: messagesOrError,
161
+ key,
162
+ namespace
163
+ });
164
+ }
165
+ const messages = messagesOrError;
166
+
167
+ const cacheKey = [namespace, key]
168
+ .filter((part) => part != null)
169
+ .join('.');
170
+
171
+ let messageFormat;
172
+ if (cachedFormatsByLocale[locale]?.[cacheKey]) {
173
+ messageFormat = cachedFormatsByLocale[locale][cacheKey];
174
+ } else {
175
+ let message;
176
+ try {
177
+ message = resolvePath(messages, key, namespace);
178
+ } catch (error) {
179
+ return getFallbackFromErrorAndNotify(
180
+ key,
181
+ IntlErrorCode.MISSING_MESSAGE,
182
+ (error as Error).message
183
+ );
184
+ }
185
+
186
+ if (typeof message === 'object') {
187
+ return getFallbackFromErrorAndNotify(
188
+ key,
189
+ IntlErrorCode.INSUFFICIENT_PATH,
190
+ __DEV__
191
+ ? `Insufficient path specified for \`${key}\` in \`${
192
+ namespace ? `\`${namespace}\`` : 'messages'
193
+ }\`.`
194
+ : undefined
195
+ );
196
+ }
197
+
198
+ try {
199
+ messageFormat = new IntlMessageFormat(
200
+ message,
201
+ locale,
202
+ convertFormatsToIntlMessageFormat(
203
+ {...globalFormats, ...formats},
204
+ timeZone
205
+ )
206
+ );
207
+ } catch (error) {
208
+ return getFallbackFromErrorAndNotify(
209
+ key,
210
+ IntlErrorCode.INVALID_MESSAGE,
211
+ (error as Error).message
212
+ );
213
+ }
214
+
215
+ if (!cachedFormatsByLocale[locale]) {
216
+ cachedFormatsByLocale[locale] = {};
217
+ }
218
+ cachedFormatsByLocale[locale][cacheKey] = messageFormat;
219
+ }
220
+
221
+ try {
222
+ const formattedMessage = messageFormat.format(
223
+ prepareTranslationValues({...defaultTranslationValues, ...values})
224
+ );
225
+
226
+ if (formattedMessage == null) {
227
+ throw new Error(
228
+ __DEV__
229
+ ? `Unable to format \`${key}\` in ${
230
+ namespace ? `namespace \`${namespace}\`` : 'messages'
231
+ }`
232
+ : undefined
233
+ );
234
+ }
235
+
236
+ // Limit the function signature to return strings or React elements
237
+ return isValidElement(formattedMessage) ||
238
+ // Arrays of React elements
239
+ Array.isArray(formattedMessage) ||
240
+ typeof formattedMessage === 'string'
241
+ ? formattedMessage
242
+ : String(formattedMessage);
243
+ } catch (error) {
244
+ return getFallbackFromErrorAndNotify(
245
+ key,
246
+ IntlErrorCode.FORMATTING_ERROR,
247
+ (error as Error).message
248
+ );
249
+ }
250
+ }
251
+
252
+ function translateFn<
253
+ TargetKey extends MessageKeys<
254
+ NestedValueOf<Messages, NestedKey>,
255
+ NestedKeyOf<NestedValueOf<Messages, NestedKey>>
256
+ >
257
+ >(
258
+ /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */
259
+ key: TargetKey,
260
+ /** Key value pairs for values to interpolate into the message. */
261
+ values?: TranslationValues,
262
+ /** Provide custom formats for numbers, dates and times. */
263
+ formats?: Partial<Formats>
264
+ ): string {
265
+ const message = translateBaseFn(key, values, formats);
266
+
267
+ if (typeof message !== 'string') {
268
+ return getFallbackFromErrorAndNotify(
269
+ key,
270
+ IntlErrorCode.INVALID_MESSAGE,
271
+ __DEV__
272
+ ? `The message \`${key}\` in ${
273
+ namespace ? `namespace \`${namespace}\`` : 'messages'
274
+ } didn't resolve to a string. If you want to format rich text, use \`t.rich\` instead.`
275
+ : undefined
276
+ );
277
+ }
278
+
279
+ return message;
280
+ }
281
+
282
+ translateFn.rich = translateBaseFn;
283
+
284
+ translateFn.raw = (
285
+ /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */
286
+ key: string
287
+ ): any => {
288
+ if (messagesOrError instanceof IntlError) {
289
+ // We have already warned about this during render
290
+ return getMessageFallback({
291
+ error: messagesOrError,
292
+ key,
293
+ namespace
294
+ });
295
+ }
296
+ const messages = messagesOrError;
297
+
298
+ try {
299
+ return resolvePath(messages, key, namespace);
300
+ } catch (error) {
301
+ return getFallbackFromErrorAndNotify(
302
+ key,
303
+ IntlErrorCode.MISSING_MESSAGE,
304
+ (error as Error).message
305
+ );
306
+ }
307
+ };
308
+
309
+ return translateFn;
310
+ }, [
311
+ onError,
312
+ getMessageFallback,
313
+ namespace,
314
+ messagesOrError,
315
+ locale,
316
+ globalFormats,
317
+ timeZone,
318
+ defaultTranslationValues
319
+ ]);
320
+
321
+ return translate;
322
+ }
@@ -0,0 +1,9 @@
1
+ import NestedValueOf from './NestedValueOf';
2
+
3
+ type MessageKeys<ObjectType, Keys extends string> = {
4
+ [Property in Keys]: NestedValueOf<ObjectType, Property> extends string
5
+ ? Property
6
+ : never;
7
+ }[Keys];
8
+
9
+ export default MessageKeys;
@@ -0,0 +1,9 @@
1
+ import NestedValueOf from './NestedValueOf';
2
+
3
+ type NamespaceKeys<ObjectType, Keys extends string> = {
4
+ [Property in Keys]: NestedValueOf<ObjectType, Property> extends string
5
+ ? never
6
+ : Property;
7
+ }[Keys];
8
+
9
+ export default NamespaceKeys;
@@ -0,0 +1,9 @@
1
+ type NestedKeyOf<ObjectType> = ObjectType extends object
2
+ ? {
3
+ [Key in keyof ObjectType]:
4
+ | `${Key & string}`
5
+ | `${Key & string}.${NestedKeyOf<ObjectType[Key]>}`;
6
+ }[keyof ObjectType]
7
+ : never;
8
+
9
+ export default NestedKeyOf;
@@ -0,0 +1,12 @@
1
+ type NestedValueOf<
2
+ ObjectType,
3
+ Property extends string
4
+ > = Property extends `${infer Key}.${infer Rest}`
5
+ ? Key extends keyof ObjectType
6
+ ? NestedValueOf<ObjectType[Key], Rest>
7
+ : never
8
+ : Property extends keyof ObjectType
9
+ ? ObjectType[Property]
10
+ : never;
11
+
12
+ export default NestedValueOf;