-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
index.ts
310 lines (283 loc) · 8.75 KB
/
index.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
import {
getInternalSlot,
setInternalSlot,
GetOption,
ResolveLocale,
invariant,
SupportedLocales,
IsWellFormedCurrencyCode,
getMultiInternalSlots,
DisplayNamesLocaleData,
unpackData,
DisplayNamesData,
ToString,
CanonicalizeLocaleList,
} from '@formatjs/ecma402-abstract';
export interface DisplayNamesOptions {
localeMatcher?: 'lookup' | 'best fit';
style?: 'narrow' | 'short' | 'long';
type: 'language' | 'region' | 'script' | 'currency';
fallback?: 'code' | 'none';
}
export interface DisplayNamesResolvedOptions {
locale: string;
style: NonNullable<DisplayNamesOptions['style']>;
type: NonNullable<DisplayNamesOptions['type']>;
fallback: NonNullable<DisplayNamesOptions['fallback']>;
}
export class DisplayNames {
constructor(
locales?: string | string[],
options: DisplayNamesOptions = Object.create(null)
) {
if (new.target === undefined) {
throw TypeError(`Constructor Intl.DisplayNames requires 'new'`);
}
const requestedLocales = CanonicalizeLocaleList(locales);
const matcher = GetOption(
options!,
'localeMatcher',
'string',
['lookup', 'best fit'],
'best fit'
);
const r = ResolveLocale(
DisplayNames.availableLocales,
requestedLocales,
{localeMatcher: matcher},
[], // there is no relevantExtensionKeys
DisplayNames.localeData,
DisplayNames.getDefaultLocale
);
const style = GetOption(
options,
'style',
'string',
['narrow', 'short', 'long'],
'long'
);
setSlot(this, 'style', style);
const type = GetOption(
options,
'type',
'string',
['language', 'currency', 'region', 'script'],
undefined
);
if (type === undefined) {
throw TypeError(`Intl.DisplayNames constructor requires "type" option`);
}
setSlot(this, 'type', type);
const fallback = GetOption(
options,
'fallback',
'string',
['code', 'none'],
'code'
);
setSlot(this, 'fallback', fallback);
setSlot(this, 'locale', r.locale);
const {dataLocale} = r;
const dataLocaleData = DisplayNames.localeData[dataLocale];
invariant(
dataLocaleData !== undefined,
`locale data for ${r.locale} does not exist.`
);
setSlot(this, 'localeData', dataLocaleData);
}
static supportedLocalesOf(
locales?: string | string[],
options?: Pick<DisplayNamesOptions, 'localeMatcher'>
) {
return SupportedLocales(
DisplayNames.availableLocales,
CanonicalizeLocaleList(locales),
options
);
}
static __addLocaleData(...data: DisplayNamesLocaleData[]) {
for (const datum of data) {
const availableLocales: string[] = datum.availableLocales;
for (const locale of availableLocales) {
try {
DisplayNames.localeData[locale] = unpackData(locale, datum);
} catch (e) {
// If we can't unpack this data, ignore the locale
}
}
}
DisplayNames.availableLocales = Object.keys(DisplayNames.localeData);
if (!DisplayNames.__defaultLocale) {
DisplayNames.__defaultLocale = DisplayNames.availableLocales[0];
}
}
of(code: string | number | object): string | undefined {
checkReceiver(this, 'of');
const type = getSlot(this, 'type');
const codeAsString = ToString(code);
if (!isValidCodeForDisplayNames(type, codeAsString)) {
throw RangeError('invalid code for Intl.DisplayNames.prototype.of');
}
const {localeData, style, fallback} = getMultiInternalSlots(
__INTERNAL_SLOT_MAP__,
this,
'localeData',
'style',
'fallback'
);
// Canonicalize the case.
let canonicalCode: string;
// This is only used to store extracted language region.
let regionSubTag: string | undefined;
switch (type) {
// Normalize the locale id and remove the region.
case 'language': {
canonicalCode = CanonicalizeLocaleList(codeAsString)[0];
const regionMatch = /-([a-z]{2}|\d{3})\b/i.exec(canonicalCode);
if (regionMatch) {
// Remove region subtag
canonicalCode =
canonicalCode.substring(0, regionMatch.index) +
canonicalCode.substring(regionMatch.index + regionMatch[0].length);
regionSubTag = regionMatch[1];
}
break;
}
// currency code should be all upper-case.
case 'currency':
canonicalCode = codeAsString.toUpperCase();
break;
// script code should be title case
case 'script':
canonicalCode =
codeAsString[0] + codeAsString.substring(1).toLowerCase();
break;
// region shold be all upper-case
case 'region':
canonicalCode = codeAsString.toUpperCase();
break;
}
const typesData = localeData.types[type];
// If the style of choice does not exist, fallback to "long".
const name =
typesData[style][canonicalCode] || typesData.long[canonicalCode];
if (name !== undefined) {
// If there is a region subtag in the language id, use locale pattern to interpolate the region
if (regionSubTag) {
// Retrieve region display names
const regionsData = localeData.types.region;
const regionDisplayName: string | undefined =
regionsData[style][regionSubTag] || regionsData.long[regionSubTag];
if (regionDisplayName || fallback === 'code') {
// Interpolate into locale-specific pattern.
const pattern = localeData.patterns.locale;
return pattern
.replace('{0}', name)
.replace('{1}', regionDisplayName || regionSubTag);
}
} else {
return name;
}
}
if (fallback === 'code') {
return codeAsString;
}
}
resolvedOptions(): DisplayNamesResolvedOptions {
checkReceiver(this, 'resolvedOptions');
return {
...getMultiInternalSlots(
__INTERNAL_SLOT_MAP__,
this,
'locale',
'style',
'type',
'fallback'
),
};
}
static localeData: Record<string, DisplayNamesData> = {};
private static availableLocales: string[] = [];
private static __defaultLocale = 'en';
private static getDefaultLocale() {
return DisplayNames.__defaultLocale;
}
public static readonly polyfilled = true;
}
// https://tc39.es/proposal-intl-displaynames/#sec-isvalidcodefordisplaynames
function isValidCodeForDisplayNames(
type: NonNullable<DisplayNamesOptions['type']>,
code: string
): boolean {
switch (type) {
case 'language':
// subset of unicode_language_id
// languageCode ["-" scriptCode] ["-" regionCode] *("-" variant)
// where:
// - languageCode is either a two letters ISO 639-1 language code or a three letters ISO 639-2 language code.
// - scriptCode is should be an ISO-15924 four letters script code
// - regionCode is either an ISO-3166 two letters region code, or a three digits UN M49 Geographic Regions.
return /^[a-z]{2,3}(-[a-z]{4})?(-([a-z]{2}|\d{3}))?(-([a-z\d]{5,8}|\d[a-z\d]{3}))*$/i.test(
code
);
case 'region':
// unicode_region_subtag
return /^([a-z]{2}|\d{3})$/i.test(code);
case 'script':
// unicode_script_subtag
return /^[a-z]{4}$/i.test(code);
case 'currency':
return IsWellFormedCurrencyCode(code);
}
}
try {
// IE11 does not have Symbol
if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
Object.defineProperty(DisplayNames.prototype, Symbol.toStringTag, {
value: 'Intl.DisplayNames',
configurable: true,
enumerable: false,
writable: false,
});
}
Object.defineProperty(DisplayNames, 'length', {
value: 2,
writable: false,
enumerable: false,
configurable: true,
});
} catch (e) {
// Make test 262 compliant
}
interface DisplayNamesInternalSlots {
locale: string;
style: NonNullable<DisplayNamesOptions['style']>;
type: NonNullable<DisplayNamesOptions['type']>;
fallback: NonNullable<DisplayNamesOptions['fallback']>;
// Note that this differs from `fields` slot in the spec.
localeData: DisplayNamesData;
}
const __INTERNAL_SLOT_MAP__ = new WeakMap<
DisplayNames,
DisplayNamesInternalSlots
>();
function getSlot<K extends keyof DisplayNamesInternalSlots>(
instance: DisplayNames,
key: K
): DisplayNamesInternalSlots[K] {
return getInternalSlot(__INTERNAL_SLOT_MAP__, instance, key);
}
function setSlot<K extends keyof DisplayNamesInternalSlots>(
instance: DisplayNames,
key: K,
value: DisplayNamesInternalSlots[K]
): void {
setInternalSlot(__INTERNAL_SLOT_MAP__, instance, key, value);
}
function checkReceiver(receiver: unknown, methodName: string) {
if (!(receiver instanceof DisplayNames)) {
throw TypeError(
`Method Intl.DisplayNames.prototype.${methodName} called on incompatible receiver`
);
}
}