use-intl 2.3.5 → 2.4.1-alpha.2

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