-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtranslation.ts
463 lines (418 loc) · 11.5 KB
/
translation.ts
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/*!
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import type { AppTranslations, Translations } from './registry.ts'
import { generateFilePath } from '@nextcloud/router'
import { getLanguage, getLocale } from './locale.ts'
import {
getAppTranslations,
hasAppTranslations,
registerAppTranslations,
unregisterAppTranslations,
} from './registry.ts'
import DOMPurify from 'dompurify'
import escapeHTML from 'escape-html'
interface TranslationOptions {
/** enable/disable auto escape of placeholders (by default enabled) */
escape?: boolean
/** enable/disable sanitization (by default enabled) */
sanitize?: boolean
/**
* This is only intended for internal usage.
* @private
*/
bundle?: AppTranslations
}
interface TranslationVariableReplacementObject<T> {
/** The value to use for the replacement */
value: T
/** Overwrite the `escape` option just for this replacement */
escape: boolean
}
/**
* Extracts variables from a translation key
*/
type ExtractedVariables<T extends string> =
T extends `${string}{${infer Variable}}${infer Rest}`
? Variable | ExtractedVariables<Rest>
: never
type TranslationVariables<K extends string> = Record<ExtractedVariables<K>, string | number | TranslationVariableReplacementObject<string | number>>
export function translate<T extends string>(app: string, text: T, placeholders?: TranslationVariables<T>, options?: TranslationOptions): string
export function translate<T extends string>(app: string, text: T, number?: number, options?: TranslationOptions): string
/**
* @inheritdoc
* @deprecated This overload is deprecated either use placeholders or a number but not both
*/
export function translate<T extends string>(app: string, text: T, placeholders?: TranslationVariables<T>, number?: number, options?: TranslationOptions): string
/**
* Translate a string
*
* @param app the id of the app for which to translate the string
* @param text the string to translate
* @param placeholdersOrNumber map of placeholder key to value or a number replacing `%n`
* @param optionsOrNumber the translation options or a number to replace `%n` with
* @param options options object
* @param options.escape enable/disable auto escape of placeholders (by default enabled)
* @param options.sanitize enable/disable sanitization (by default enabled)
*/
export function translate<T extends string>(
app: string,
text: T,
placeholdersOrNumber?: TranslationVariables<T>|number,
optionsOrNumber?: number|TranslationOptions,
options?: TranslationOptions,
): string {
const vars = typeof placeholdersOrNumber === 'object' ? placeholdersOrNumber : undefined
const number = typeof optionsOrNumber === 'number' ? optionsOrNumber : (typeof placeholdersOrNumber === 'number' ? placeholdersOrNumber : undefined)
const allOptions = {
// defaults
escape: true,
sanitize: true,
// overwrite with user config
...(
typeof options === 'object'
? options
: (
typeof optionsOrNumber === 'object'
? optionsOrNumber
: {}
)
),
}
const identity = <T, >(value: T): T => value
const optSanitize = allOptions.sanitize ? DOMPurify.sanitize : identity
const optEscape = allOptions.escape ? escapeHTML : identity
const isValidReplacement = (value: unknown) => typeof value === 'string' || typeof value === 'number'
// TODO: cache this function to avoid inline recreation
// of the same function over and over again in case
// translate() is used in a loop
const _build = (text: string, vars?: TranslationVariables<T>, number?: number) => {
return text.replace(/%n/g, '' + number).replace(/{([^{}]*)}/g, (match, key: ExtractedVariables<T>) => {
if (vars === undefined || !(key in vars)) {
return optEscape(match)
}
const replacement = vars[key]
if (isValidReplacement(replacement)) {
return optEscape(`${replacement}`)
} else if (typeof replacement === 'object' && isValidReplacement(replacement.value)) {
// Replacement is an object so indiviual escape handling
const escape = replacement.escape !== false ? escapeHTML : identity
return escape(`${replacement.value}`)
} else {
/* This should not happen,
* but the variables are used defined so not allowed types could still be given,
* in this case ignore the replacement and use the placeholder
*/
return optEscape(match)
}
})
}
const bundle = options?.bundle ?? getAppTranslations(app)
let translation = bundle.translations[text] || text
translation = Array.isArray(translation) ? translation[0] : translation
if (typeof vars === 'object' || number !== undefined) {
return optSanitize(_build(
translation,
vars,
number,
))
} else {
return optSanitize(translation)
}
}
/**
* Translate a string containing an object which possibly requires a plural form
*
* @param {string} app the id of the app for which to translate the string
* @param {string} textSingular the string to translate for exactly one object
* @param {string} textPlural the string to translate for n objects
* @param {number} number number to determine whether to use singular or plural
* @param {object} vars of placeholder key to value
* @param {object} options options object
*/
export function translatePlural<T extends string, K extends string, >(
app: string,
textSingular: T,
textPlural: K,
number: number,
vars?: TranslationVariables<T> & TranslationVariables<K>,
options?: TranslationOptions,
): string {
const identifier = '_' + textSingular + '_::_' + textPlural + '_'
const bundle = options?.bundle ?? getAppTranslations(app)
const value = bundle.translations[identifier]
if (typeof value !== 'undefined') {
const translation = value
if (Array.isArray(translation)) {
const plural = bundle.pluralFunction(number)
return translate(app, translation[plural], vars, number, options)
}
}
// vars type is casted to allow extra keys without runtime filtering (they are harmless), and without allowing wrong keys in translate
if (number === 1) {
return translate(app, textSingular, vars as TranslationVariables<T>, number, options)
} else {
return translate(app, textPlural, vars as TranslationVariables<K>, number, options)
}
}
/**
* Load an app's translation bundle if not loaded already.
*
* @param {string} appName name of the app
* @param {Function} callback callback to be called when
* the translations are loaded
* @return {Promise} promise
*/
export function loadTranslations(appName: string, callback: (...args: []) => unknown) {
interface TranslationBundle {
translations: Translations
pluralForm: string
}
if (hasAppTranslations(appName) || getLocale() === 'en') {
return Promise.resolve().then(callback)
}
const url = generateFilePath(appName, 'l10n', getLocale() + '.json')
const promise = new Promise<TranslationBundle>((resolve, reject) => {
const request = new XMLHttpRequest()
request.open('GET', url, true)
request.onerror = () => {
reject(new Error(request.statusText || 'Network error'))
}
request.onload = () => {
if (request.status >= 200 && request.status < 300) {
try {
const bundle = JSON.parse(request.responseText)
if (typeof bundle.translations === 'object') resolve(bundle)
} catch (error) {
// error is probably a SyntaxError due to invalid response text, this is handled by next line
}
reject(new Error('Invalid content of translation bundle'))
} else {
reject(new Error(request.statusText))
}
}
request.send()
})
// load JSON translation bundle per AJAX
return promise
.then((result) => {
register(appName, result.translations)
return result
})
.then(callback)
}
/**
* Register an app's translation bundle.
*
* @param {string} appName name of the app
* @param {Record<string, string>} bundle translation bundle
*/
export function register(appName: string, bundle: Translations) {
registerAppTranslations(appName, bundle, getPlural)
}
/**
* Unregister all translations of an app
*
* @param appName name of the app
* @since 2.1.0
*/
export function unregister(appName: string) {
return unregisterAppTranslations(appName)
}
/**
* Get array index of translations for a plural form
*
*
* @param {number} number the number of elements
* @param {string|undefined} language the language to use (or autodetect if not set)
* @return {number} 0 for the singular form(, 1 for the first plural form, ...)
*/
export function getPlural(number: number, language = getLanguage()) {
if (language === 'pt-BR') {
// temporary set a locale for brazilian
language = 'xbr'
}
if (language.length > 3) {
language = language.substring(0, language.lastIndexOf('-'))
}
/*
* The plural rules are derived from code of the Zend Framework (2010-09-25),
* which is subject to the new BSD license (http://framework.zend.com/license/new-bsd).
* Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
*/
switch (language) {
case 'az':
case 'bo':
case 'dz':
case 'id':
case 'ja':
case 'jv':
case 'ka':
case 'km':
case 'kn':
case 'ko':
case 'ms':
case 'th':
case 'tr':
case 'vi':
case 'zh':
return 0
case 'af':
case 'bn':
case 'bg':
case 'ca':
case 'da':
case 'de':
case 'el':
case 'en':
case 'eo':
case 'es':
case 'et':
case 'eu':
case 'fa':
case 'fi':
case 'fo':
case 'fur':
case 'fy':
case 'gl':
case 'gu':
case 'ha':
case 'he':
case 'hu':
case 'is':
case 'it':
case 'ku':
case 'lb':
case 'ml':
case 'mn':
case 'mr':
case 'nah':
case 'nb':
case 'ne':
case 'nl':
case 'nn':
case 'no':
case 'oc':
case 'om':
case 'or':
case 'pa':
case 'pap':
case 'ps':
case 'pt':
case 'so':
case 'sq':
case 'sv':
case 'sw':
case 'ta':
case 'te':
case 'tk':
case 'ur':
case 'zu':
return number === 1 ? 0 : 1
case 'am':
case 'bh':
case 'fil':
case 'fr':
case 'gun':
case 'hi':
case 'hy':
case 'ln':
case 'mg':
case 'nso':
case 'xbr':
case 'ti':
case 'wa':
return number === 0 || number === 1 ? 0 : 1
case 'be':
case 'bs':
case 'hr':
case 'ru':
case 'sh':
case 'sr':
case 'uk':
return number % 10 === 1 && number % 100 !== 11
? 0
: number % 10 >= 2
&& number % 10 <= 4
&& (number % 100 < 10 || number % 100 >= 20)
? 1
: 2
case 'cs':
case 'sk':
return number === 1 ? 0 : number >= 2 && number <= 4 ? 1 : 2
case 'ga':
return number === 1 ? 0 : number === 2 ? 1 : 2
case 'lt':
return number % 10 === 1 && number % 100 !== 11
? 0
: number % 10 >= 2 && (number % 100 < 10 || number % 100 >= 20)
? 1
: 2
case 'sl':
return number % 100 === 1
? 0
: number % 100 === 2
? 1
: number % 100 === 3 || number % 100 === 4
? 2
: 3
case 'mk':
return number % 10 === 1 ? 0 : 1
case 'mt':
return number === 1
? 0
: number === 0 || (number % 100 > 1 && number % 100 < 11)
? 1
: number % 100 > 10 && number % 100 < 20
? 2
: 3
case 'lv':
return number === 0
? 0
: number % 10 === 1 && number % 100 !== 11
? 1
: 2
case 'pl':
return number === 1
? 0
: number % 10 >= 2
&& number % 10 <= 4
&& (number % 100 < 12 || number % 100 > 14)
? 1
: 2
case 'cy':
return number === 1
? 0
: number === 2
? 1
: number === 8 || number === 11
? 2
: 3
case 'ro':
return number === 1
? 0
: number === 0 || (number % 100 > 0 && number % 100 < 20)
? 1
: 2
case 'ar':
return number === 0
? 0
: number === 1
? 1
: number === 2
? 2
: number % 100 >= 3 && number % 100 <= 10
? 3
: number % 100 >= 11 && number % 100 <= 99
? 4
: 5
default:
return 0
}
}
// Export short-hand
export {
translate as t,
translatePlural as n,
}