use-intl 2.4.1 → 2.5.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.
@@ -0,0 +1,324 @@
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 AbstractIntlMessages from './AbstractIntlMessages';
12
+ import Formats from './Formats';
13
+ import IntlError, {IntlErrorCode} from './IntlError';
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: AbstractIntlMessages | 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 AbstractIntlMessages,
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 = (
98
+ namespace === namespacePrefix
99
+ ? undefined
100
+ : namespace.slice((namespacePrefix + '.').length)
101
+ ) as NestedKey;
102
+
103
+ const cachedFormatsByLocaleRef = useRef<
104
+ Record<string, Record<string, IntlMessageFormat>>
105
+ >({});
106
+
107
+ const messagesOrError = useMemo(() => {
108
+ try {
109
+ if (!allMessages) {
110
+ throw new Error(
111
+ __DEV__ ? `No messages were configured on the provider.` : undefined
112
+ );
113
+ }
114
+
115
+ const retrievedMessages = namespace
116
+ ? resolvePath(allMessages, namespace)
117
+ : allMessages;
118
+
119
+ if (!retrievedMessages) {
120
+ throw new Error(
121
+ __DEV__
122
+ ? `No messages for namespace \`${namespace}\` found.`
123
+ : undefined
124
+ );
125
+ }
126
+
127
+ return retrievedMessages;
128
+ } catch (error) {
129
+ const intlError = new IntlError(
130
+ IntlErrorCode.MISSING_MESSAGE,
131
+ (error as Error).message
132
+ );
133
+ onError(intlError);
134
+ return intlError;
135
+ }
136
+ }, [allMessages, namespace, onError]);
137
+
138
+ const translate = useMemo(() => {
139
+ function getFallbackFromErrorAndNotify(
140
+ key: string,
141
+ code: IntlErrorCode,
142
+ message?: string
143
+ ) {
144
+ const error = new IntlError(code, message);
145
+ onError(error);
146
+ return getMessageFallback({error, key, namespace});
147
+ }
148
+
149
+ function translateBaseFn(
150
+ /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */
151
+ key: string,
152
+ /** Key value pairs for values to interpolate into the message. */
153
+ values?: RichTranslationValues,
154
+ /** Provide custom formats for numbers, dates and times. */
155
+ formats?: Partial<Formats>
156
+ ): string | ReactElement | ReactNodeArray {
157
+ const cachedFormatsByLocale = cachedFormatsByLocaleRef.current;
158
+
159
+ if (messagesOrError instanceof IntlError) {
160
+ // We have already warned about this during render
161
+ return getMessageFallback({
162
+ error: messagesOrError,
163
+ key,
164
+ namespace
165
+ });
166
+ }
167
+ const messages = messagesOrError;
168
+
169
+ const cacheKey = [namespace, key]
170
+ .filter((part) => part != null)
171
+ .join('.');
172
+
173
+ let messageFormat;
174
+ if (cachedFormatsByLocale[locale]?.[cacheKey]) {
175
+ messageFormat = cachedFormatsByLocale[locale][cacheKey];
176
+ } else {
177
+ let message;
178
+ try {
179
+ message = resolvePath(messages, key, namespace);
180
+ } catch (error) {
181
+ return getFallbackFromErrorAndNotify(
182
+ key,
183
+ IntlErrorCode.MISSING_MESSAGE,
184
+ (error as Error).message
185
+ );
186
+ }
187
+
188
+ if (typeof message === 'object') {
189
+ return getFallbackFromErrorAndNotify(
190
+ key,
191
+ IntlErrorCode.INSUFFICIENT_PATH,
192
+ __DEV__
193
+ ? `Insufficient path specified for \`${key}\` in \`${
194
+ namespace ? `\`${namespace}\`` : 'messages'
195
+ }\`.`
196
+ : undefined
197
+ );
198
+ }
199
+
200
+ try {
201
+ messageFormat = new IntlMessageFormat(
202
+ message,
203
+ locale,
204
+ convertFormatsToIntlMessageFormat(
205
+ {...globalFormats, ...formats},
206
+ timeZone
207
+ )
208
+ );
209
+ } catch (error) {
210
+ return getFallbackFromErrorAndNotify(
211
+ key,
212
+ IntlErrorCode.INVALID_MESSAGE,
213
+ (error as Error).message
214
+ );
215
+ }
216
+
217
+ if (!cachedFormatsByLocale[locale]) {
218
+ cachedFormatsByLocale[locale] = {};
219
+ }
220
+ cachedFormatsByLocale[locale][cacheKey] = messageFormat;
221
+ }
222
+
223
+ try {
224
+ const formattedMessage = messageFormat.format(
225
+ prepareTranslationValues({...defaultTranslationValues, ...values})
226
+ );
227
+
228
+ if (formattedMessage == null) {
229
+ throw new Error(
230
+ __DEV__
231
+ ? `Unable to format \`${key}\` in ${
232
+ namespace ? `namespace \`${namespace}\`` : 'messages'
233
+ }`
234
+ : undefined
235
+ );
236
+ }
237
+
238
+ // Limit the function signature to return strings or React elements
239
+ return isValidElement(formattedMessage) ||
240
+ // Arrays of React elements
241
+ Array.isArray(formattedMessage) ||
242
+ typeof formattedMessage === 'string'
243
+ ? formattedMessage
244
+ : String(formattedMessage);
245
+ } catch (error) {
246
+ return getFallbackFromErrorAndNotify(
247
+ key,
248
+ IntlErrorCode.FORMATTING_ERROR,
249
+ (error as Error).message
250
+ );
251
+ }
252
+ }
253
+
254
+ function translateFn<
255
+ TargetKey extends MessageKeys<
256
+ NestedValueOf<Messages, NestedKey>,
257
+ NestedKeyOf<NestedValueOf<Messages, NestedKey>>
258
+ >
259
+ >(
260
+ /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */
261
+ key: TargetKey,
262
+ /** Key value pairs for values to interpolate into the message. */
263
+ values?: TranslationValues,
264
+ /** Provide custom formats for numbers, dates and times. */
265
+ formats?: Partial<Formats>
266
+ ): string {
267
+ const message = translateBaseFn(key, values, formats);
268
+
269
+ if (typeof message !== 'string') {
270
+ return getFallbackFromErrorAndNotify(
271
+ key,
272
+ IntlErrorCode.INVALID_MESSAGE,
273
+ __DEV__
274
+ ? `The message \`${key}\` in ${
275
+ namespace ? `namespace \`${namespace}\`` : 'messages'
276
+ } didn't resolve to a string. If you want to format rich text, use \`t.rich\` instead.`
277
+ : undefined
278
+ );
279
+ }
280
+
281
+ return message;
282
+ }
283
+
284
+ translateFn.rich = translateBaseFn;
285
+
286
+ translateFn.raw = (
287
+ /** Use a dot to indicate a level of nesting (e.g. `namespace.nestedLabel`). */
288
+ key: string
289
+ ): any => {
290
+ if (messagesOrError instanceof IntlError) {
291
+ // We have already warned about this during render
292
+ return getMessageFallback({
293
+ error: messagesOrError,
294
+ key,
295
+ namespace
296
+ });
297
+ }
298
+ const messages = messagesOrError;
299
+
300
+ try {
301
+ return resolvePath(messages, key, namespace);
302
+ } catch (error) {
303
+ return getFallbackFromErrorAndNotify(
304
+ key,
305
+ IntlErrorCode.MISSING_MESSAGE,
306
+ (error as Error).message
307
+ );
308
+ }
309
+ };
310
+
311
+ return translateFn;
312
+ }, [
313
+ onError,
314
+ getMessageFallback,
315
+ namespace,
316
+ messagesOrError,
317
+ locale,
318
+ globalFormats,
319
+ timeZone,
320
+ defaultTranslationValues
321
+ ]);
322
+
323
+ return translate;
324
+ }
@@ -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;