This repository has been archived by the owner on May 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathcore.js
278 lines (227 loc) · 8.27 KB
/
core.js
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
/*
Copyright (c) 2014, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License.
See the accompanying LICENSE file for terms.
*/
/* jslint esnext: true */
import {extend, hop} from './utils';
import {defineProperty, objCreate} from './es5';
import Compiler from './compiler';
import parser from 'intl-messageformat-parser';
export default MessageFormat;
// -- MessageFormat --------------------------------------------------------
function MessageFormat(message, locales, formats) {
// Parse string messages into an AST.
var ast = typeof message === 'string' ?
MessageFormat.__parse(message) : message;
if (!(ast && ast.type === 'messageFormatPattern')) {
throw new TypeError('A message must be provided as a String or AST.');
}
// Creates a new object with the specified `formats` merged with the default
// formats.
formats = this._mergeFormats(MessageFormat.formats, formats);
// Defined first because it's used to build the format pattern.
defineProperty(this, '_locale', {value: this._resolveLocale(locales)});
// Compile the `ast` to a pattern that is highly optimized for repeated
// `format()` invocations. **Note:** This passes the `locales` set provided
// to the constructor instead of just the resolved locale.
var pluralFn = this._findPluralRuleFunction(this._locale);
var pattern = this._compilePattern(ast, locales, formats, pluralFn);
// "Bind" `format()` method to `this` so it can be passed by reference like
// the other `Intl` APIs.
var messageFormat = this;
this.format = function (values) {
try {
return messageFormat._format(pattern, values);
} catch (e) {
if (e.variableId) {
throw new Error(
'The intl string context variable \'' + e.variableId + '\'' +
' was not provided to the string \'' + message + '\''
);
} else {
throw e;
}
}
};
}
// Default format options used as the prototype of the `formats` provided to the
// constructor. These are used when constructing the internal Intl.NumberFormat
// and Intl.DateTimeFormat instances.
defineProperty(MessageFormat, 'formats', {
enumerable: true,
value: {
number: {
'currency': {
style: 'currency'
},
'percent': {
style: 'percent'
}
},
date: {
'short': {
month: 'numeric',
day : 'numeric',
year : '2-digit'
},
'medium': {
month: 'short',
day : 'numeric',
year : 'numeric'
},
'long': {
month: 'long',
day : 'numeric',
year : 'numeric'
},
'full': {
weekday: 'long',
month : 'long',
day : 'numeric',
year : 'numeric'
}
},
time: {
'short': {
hour : 'numeric',
minute: 'numeric'
},
'medium': {
hour : 'numeric',
minute: 'numeric',
second: 'numeric'
},
'long': {
hour : 'numeric',
minute : 'numeric',
second : 'numeric',
timeZoneName: 'short'
},
'full': {
hour : 'numeric',
minute : 'numeric',
second : 'numeric',
timeZoneName: 'short'
}
}
}
});
// Define internal private properties for dealing with locale data.
defineProperty(MessageFormat, '__localeData__', {value: objCreate(null)});
defineProperty(MessageFormat, '__addLocaleData', {value: function (data) {
if (!(data && data.locale)) {
throw new Error(
'Locale data provided to IntlMessageFormat is missing a ' +
'`locale` property'
);
}
MessageFormat.__localeData__[data.locale.toLowerCase()] = data;
}});
// Defines `__parse()` static method as an exposed private.
defineProperty(MessageFormat, '__parse', {value: parser.parse});
// Define public `defaultLocale` property which defaults to English, but can be
// set by the developer.
defineProperty(MessageFormat, 'defaultLocale', {
enumerable: true,
writable : true,
value : undefined
});
MessageFormat.prototype.resolvedOptions = function () {
// TODO: Provide anything else?
return {
locale: this._locale
};
};
MessageFormat.prototype._compilePattern = function (ast, locales, formats, pluralFn) {
var compiler = new Compiler(locales, formats, pluralFn);
return compiler.compile(ast);
};
MessageFormat.prototype._findPluralRuleFunction = function (locale) {
var localeData = MessageFormat.__localeData__;
var data = localeData[locale.toLowerCase()];
// The locale data is de-duplicated, so we have to traverse the locale's
// hierarchy until we find a `pluralRuleFunction` to return.
while (data) {
if (data.pluralRuleFunction) {
return data.pluralRuleFunction;
}
data = data.parentLocale && localeData[data.parentLocale.toLowerCase()];
}
throw new Error(
'Locale data added to IntlMessageFormat is missing a ' +
'`pluralRuleFunction` for :' + locale
);
};
MessageFormat.prototype._format = function (pattern, values) {
var result = '',
i, len, part, id, value, err;
for (i = 0, len = pattern.length; i < len; i += 1) {
part = pattern[i];
// Exist early for string parts.
if (typeof part === 'string') {
result += part;
continue;
}
id = part.id;
// Enforce that all required values are provided by the caller.
if (!(values && hop.call(values, id))) {
err = new Error('A value must be provided for: ' + id);
err.variableId = id;
throw err;
}
value = values[id];
// Recursively format plural and select parts' option — which can be a
// nested pattern structure. The choosing of the option to use is
// abstracted-by and delegated-to the part helper object.
if (part.options) {
result += this._format(part.getOption(value), values);
} else {
result += part.format(value);
}
}
return result;
};
MessageFormat.prototype._mergeFormats = function (defaults, formats) {
var mergedFormats = {},
type, mergedType;
for (type in defaults) {
if (!hop.call(defaults, type)) { continue; }
mergedFormats[type] = mergedType = objCreate(defaults[type]);
if (formats && hop.call(formats, type)) {
extend(mergedType, formats[type]);
}
}
return mergedFormats;
};
MessageFormat.prototype._resolveLocale = function (locales) {
if (typeof locales === 'string') {
locales = [locales];
}
// Create a copy of the array so we can push on the default locale.
locales = (locales || []).concat(MessageFormat.defaultLocale);
var localeData = MessageFormat.__localeData__;
var i, len, localeParts, data;
// Using the set of locales + the default locale, we look for the first one
// which that has been registered. When data does not exist for a locale, we
// traverse its ancestors to find something that's been registered within
// its hierarchy of locales. Since we lack the proper `parentLocale` data
// here, we must take a naive approach to traversal.
for (i = 0, len = locales.length; i < len; i += 1) {
localeParts = locales[i].toLowerCase().split('-');
while (localeParts.length) {
data = localeData[localeParts.join('-')];
if (data) {
// Return the normalized locale string; e.g., we return "en-US",
// instead of "en-us".
return data.locale;
}
localeParts.pop();
}
}
var defaultLocale = locales.pop();
throw new Error(
'No locale data has been added to IntlMessageFormat for: ' +
locales.join(', ') + ', or the default locale: ' + defaultLocale
);
};