-
-
Notifications
You must be signed in to change notification settings - Fork 206
/
transCore.tsx
300 lines (266 loc) 路 7.71 KB
/
transCore.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import {
I18nConfig,
I18nDictionary,
LoaderConfig,
LoggerProps,
TranslationQuery,
} from '.'
import { Translate } from './index'
function splitNsKey(key: string, nsSeparator: string | false) {
if (!nsSeparator) return { i18nKey: key }
const i = key.indexOf(nsSeparator)
if (i < 0) return { i18nKey: key }
return {
namespace: key.slice(0, i),
i18nKey: key.slice(i + nsSeparator.length),
}
}
export default function transCore({
config,
allNamespaces,
pluralRules,
lang,
}: {
config: LoaderConfig
allNamespaces: Record<string, I18nDictionary>
pluralRules: Intl.PluralRules
lang: string | undefined
}): Translate {
const {
logger = missingKeyLogger,
// An optional parameter allowEmptyStrings - true as default.
// If allowEmptyStrings parameter is marked as false,
// it should log an error when an empty string is attempted to be translated
// and return the namespace and key as result of the translation.
allowEmptyStrings = true,
} = config
const interpolateUnknown = (
value: unknown,
query?: TranslationQuery | null
): typeof value => {
if (Array.isArray(value)) {
return value.map((val) => interpolateUnknown(val, query))
}
if (value instanceof Object) {
return objectInterpolation({
obj: value as Record<string, unknown>,
query,
config,
lang,
})
}
return interpolation({ text: value as string, query, config, lang })
}
const t: Translate = (key = '', query, options) => {
const k = Array.isArray(key) ? key[0] : key
const { nsSeparator = ':', loggerEnvironment = 'browser' } = config
const { i18nKey, namespace = options?.ns ?? config.defaultNS } = splitNsKey(
k,
nsSeparator
)
const dic = (namespace && allNamespaces[namespace]) || {}
const keyWithPlural = plural(
pluralRules,
dic,
i18nKey,
config,
query,
options
)
const dicValue = getDicValue(dic, keyWithPlural, config, options)
const value =
typeof dicValue === 'object'
? JSON.parse(JSON.stringify(dicValue))
: dicValue
const empty =
typeof value === 'undefined' ||
(typeof value === 'object' && !Object.keys(value).length) ||
(value === '' && !allowEmptyStrings)
const fallbacks =
typeof options?.fallback === 'string'
? [options.fallback]
: options?.fallback || []
if (
empty &&
(loggerEnvironment === 'both' ||
loggerEnvironment ===
(typeof window === 'undefined' ? 'node' : 'browser'))
) {
logger({ namespace, i18nKey })
}
// Fallbacks
if (empty && Array.isArray(fallbacks) && fallbacks.length) {
const [firstFallback, ...restFallbacks] = fallbacks
if (typeof firstFallback === 'string') {
return t(firstFallback, query, { ...options, fallback: restFallbacks })
}
}
if (
empty &&
options &&
// options.default could be a nullish value so check that the property exists
options.hasOwnProperty('default') &&
!fallbacks?.length
) {
// if options.default is falsey there's no reason to do interpolation
return options.default
? interpolateUnknown(options.default, query)
: options.default
}
// no need to try interpolation
if (empty) {
return k
}
// this can return an empty string if either value was already empty
// or it contained only an interpolation (e.g. "{{name}}") and the query param was empty
return interpolateUnknown(value, query)
}
return t
}
/**
* Get value from key (allow nested keys as parent.children)
*/
function getDicValue(
dic: I18nDictionary,
key: string = '',
config: I18nConfig,
options: { returnObjects?: boolean; fallback?: string | string[] } = {
returnObjects: false,
}
): unknown | undefined {
const { keySeparator = '.' } = config || {}
const keyParts = keySeparator ? key.split(keySeparator) : [key]
if (key === keySeparator && options.returnObjects) return dic
const value: string | object = keyParts.reduce(
(val: I18nDictionary | string, key: string) => {
if (typeof val === 'string') {
return {}
}
const res = val[key as keyof typeof val]
// pass all truthy values or (empty) strings
return res || (typeof res === 'string' ? res : {})
},
dic
)
if (
typeof value === 'string' ||
((value as unknown) instanceof Object &&
options.returnObjects &&
Object.keys(value).length > 0)
) {
return value
}
if (Array.isArray(value) && options.returnObjects) return value
return undefined
}
/**
* Control plural keys depending the {{count}} variable
*/
function plural(
pluralRules: Intl.PluralRules,
dic: I18nDictionary,
key: string,
config: I18nConfig,
query?: TranslationQuery | null,
options?: {
returnObjects?: boolean
fallback?: string | string[]
}
): string {
if (!query || typeof query.count !== 'number') return key
const numKey = `${key}_${query.count}`
if (getDicValue(dic, numKey, config, options) !== undefined) return numKey
const pluralKey = `${key}_${pluralRules.select(query.count)}`
if (getDicValue(dic, pluralKey, config, options) !== undefined) {
return pluralKey
}
const nestedNumKey = `${key}.${query.count}`
if (getDicValue(dic, nestedNumKey, config, options) !== undefined)
return nestedNumKey
const nestedKey = `${key}.${pluralRules.select(query.count)}`
if (getDicValue(dic, nestedKey, config, options) !== undefined)
return nestedKey
return key
}
/**
* Replace {{variables}} to query values
*/
function interpolation({
text,
query,
config,
lang,
}: {
text?: string
query?: TranslationQuery | null
config: I18nConfig
lang?: string | undefined
}): string {
if (!text || !query) return text || ''
const escapeRegex = (str: string) =>
str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
const {
format = null,
prefix = '{{',
suffix = '}}',
} = config.interpolation || {}
const regexEnd =
suffix === '' ? '' : `(?:[\\s,]+([\\w-]*))?\\s*${escapeRegex(suffix)}`
return Object.keys(query).reduce((all, varKey) => {
const regex = new RegExp(
`${escapeRegex(prefix)}\\s*${varKey}${regexEnd}`,
'gm'
)
// $1 is the first match group
return all.replace(regex, (_match, $1) => {
// $1 undefined can mean either no formatting requested: "{{name}}"
// or no format name given: "{{name, }}" -> ignore
return $1 && format
? (format(query[varKey], $1, lang) as string)
: (query[varKey] as string)
})
}, text)
}
function objectInterpolation({
obj,
query,
config,
lang,
}: {
obj: Record<string, string | unknown>
query?: TranslationQuery | null
config: I18nConfig
lang?: string
}): any {
if (!query || Object.keys(query).length === 0) return obj
Object.keys(obj).forEach((key) => {
if (obj[key] instanceof Object)
objectInterpolation({
obj: obj[key] as Record<string, string | unknown>,
query,
config,
lang,
})
if (typeof obj[key] === 'string')
obj[key] = interpolation({
text: obj[key] as string,
query,
config,
lang,
})
})
return obj
}
function missingKeyLogger({ namespace, i18nKey }: LoggerProps): void {
if (process.env.NODE_ENV === 'production') return
// This means that instead of "ns:value", "value" has been misspelled (without namespace)
if (!namespace) {
console.warn(
`[next-translate] The text "${i18nKey}" has no namespace in front of it.`
)
return
}
console.warn(
`[next-translate] "${namespace}:${i18nKey}" is missing in current namespace configuration. Try adding "${i18nKey}" to the namespace "${namespace}".`
)
}