-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathi18n-number.js
432 lines (400 loc) · 11.7 KB
/
i18n-number.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
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
/**
@license https://github.com/t2ym/i18n-number/blob/master/LICENSE.md
Copyright (c) 2016, Tetsuya Mori <t2y3141592@gmail.com>. All rights reserved.
*/
/**
`<i18n-number>` renders a number in international formats by Intl.NumberFormat
(http://www.ecma-international.org/ecma-402/1.0/#sec-11.1) object.
If Intl.NumberFormat is unavailable, [Intl.js Polyfill](https://github.com/andyearnshaw/Intl.js) and
its locale modules are dynamically loaded as a fallback.
<i18n-number lang="en"
options='{ "style": "currency", "currency": "USD" }'
offset="1"
>123456.78</i18n-number>
This example renders the following number string.
$123,455.78
@element i18n-number
@hero hero.svg
@demo demo/index.html
*/
import { polyfill } from 'wc-putty/polyfill.js';
import { html, render } from 'lit-html/lit-html.js';
const formatCache = new Map();
export class I18nNumber extends polyfill(HTMLElement) {
static get is() {
return 'i18n-number';
}
static get observedAttributes() {
return [ 'lang', 'options', 'offset' ];
}
__render() {
return html`<span id="number">${this.formatted || ''}</span>`;
}
/**
* Fired whenever the formatted text is rendered.
*
* @event rendered
*/
constructor() {
super();
/**
* Default locale constant 'en'
*/
this.DEFAULT_LANG = 'en';
/**
* The locale for the formatted number.
* The typical value is bound to `{{effectiveLang}}` when the containing element has
* `BehaviorsStore.I18nBehavior`.
*/
//this.lang = this.DEFAULT_LANG; // put off to connectedCallback
/**
* Offset for number
*
* Note: number = rawNumber - offset
*/
this.offset = 0;
/**
* Raw string synchronized with textContent
*/
//this.raw = undefined;
/**
* Options object for Intl.NumberFormat
* (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat)
*/
//this.options = undefined;
/**
* Raw number parsed from raw
*/
//this.rawNumber = undefined;
/**
* Number calculated from rawNumber and offset
*/
//this.number = undefined;
/**
* Formatted string rendered for UI
*/
//this.formatted = undefined;
}
attributeChangedCallback(name, oldValue, newValue) {
switch (name) {
case 'lang':
this._langChanged(newValue);
break;
case 'options':
try {
this.options = JSON.parse(newValue);
}
catch (ex) {
this.options = undefined;
}
break;
case 'offset':
this.offset = parseInt(newValue);
break;
/* istanbul ignore next */
default:
/* istanbul ignore next */
break;
}
}
/**
* root property to imitate a Polymer element
*/
get root() {
return this.shadowRoot;
}
/**
* options property for options object for Intl.NumberFormat
* (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat)
*
* Note: _optionsChanged() is called on every change
*/
get options() {
return this._options;
}
set options(value) {
this._optionsChanged(this._options = value);
}
/**
* raw property to store a raw number string from textContent
*
* Note: _rawChanged() is called on every change
*/
get raw() {
return this._raw;
}
set raw(value) {
this._rawChanged(this._raw = value);
}
/**
* Offset for number
*
* Note:
* - Calculation: number = rawNumber - offset
* - _offsetChanged() is called on every change
*/
get offset() {
return this._offset;
}
set offset(value) {
this._offsetChanged(this._offset = value);
}
/**
* connectedCallback for custom elements
*
* Tasks:
* - Sets this.lang if not set
* - Sets up observers if not set up
* - Sets this.raw from this.textNode.data
* - Triggers rendering
*/
connectedCallback() {
if (!this.lang) {
this.lang = this.DEFAULT_LANG;
}
if (!this.observer) {
this._setupObservers();
}
this.raw = this.textNode.data;
this.invalidate();
}
/**
* Sets up observers of textContent mutations
*/
_setupObservers() {
let i = 0;
do {
this.textNode = this.childNodes[i++];
if (!this.textNode) {
this.textNode = this.childNodes[0];
break;
}
}
while (this.textNode.nodeType !== this.textNode.TEXT_NODE);
if (!this.textNode) {
this.appendChild(document.createTextNode(''));
this.textNode = this.childNodes[0];
}
this.observer = new MutationObserver(this._textMutated.bind(this));
this.observer.observe(this.textNode, { characterData: true });
this.nodeObserver = new MutationObserver(function (mutations) {
mutations.forEach(function(mutation) {
switch (mutation.type) {
case 'childList':
let i = 0;
do {
if (mutation.addedNodes[i] &&
mutation.addedNodes[i].nodeType === mutation.addedNodes[i].TEXT_NODE) {
this.textNode = mutation.addedNodes[i];
this.raw = this.textNode.data;
//console.log('i18n-number: text node added with ' + this.raw);
this.observer.observe(this.textNode, { characterData: true });
break;
}
i++;
}
while (i < mutation.addedNodes.length);
break;
/* istanbul ignore next */
default:
/* istanbul ignore next: mutation.type is characterData or attributes */
break;
}
}, this);
}.bind(this));
this.nodeObserver.observe(this, { childList: true });
}
/**
* MutationObserver callback of the child text node to re-render on text mutations.
*
* @param {Array} mutations Array of MutationRecord (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver).
*/
_textMutated(mutations) {
mutations.forEach(function(mutation) {
switch (mutation.type) {
case 'characterData':
//console.log('i18n-number: _textMutated: raw = ' + mutation.target.data);
if (this.raw !== mutation.target.data) {
this.raw = mutation.target.data;
}
break;
/* istanbul ignore next: mutation.type is characterData */
default:
/* istanbul ignore next: mutation.type is characterData */
break;
}
}, this);
}
/**
* Observer of `raw` property to re-render the formatted number.
*
* @param {string} raw New raw number string.
*/
_rawChanged(raw) {
if (this.textNode) {
if (raw !== this.textNode.data) {
this.textNode.data = raw;
}
//console.log('i18n-number: _rawChanged: raw = ' + raw);
this._render(this.lang, this.options, raw, this.offset);
}
}
/**
* Observer of `lang` property to re-render the formatted number.
*
* @param {string} lang New locale.
*/
_langChanged(lang) {
if (!lang || lang === 'null') {
this.lang = this.DEFAULT_LANG;
lang = this.lang;
}
if (this.textNode) {
//console.log('i18n-number: _langChanged: lang = ' + lang);
this._render(lang, this.options, this.raw, this.offset);
}
}
/**
* Observer of `options` property to re-render the formatted number.
*
* @param {Object} options New options for Intl.NumberFormat.
*/
_optionsChanged(options) {
if (this.textNode) {
//console.log('i18n-number: _optionsChanged: options = ' + JSON.stringify(options));
this._render(this.lang, options, this.raw, this.offset);
}
}
/**
* Partially emulates notifyPath() in Polymer library
* Just calls _onOptionsPropertyChanged() to re-render
*/
notifyPath(path, value) {
this._onOptionsPropertyChanged();
}
/**
* Observer of `options` sub-properties to re-render the formatted number.
*/
_onOptionsPropertyChanged(/* changeRecord */) {
if (this.textNode) {
//console.log('_onOptionsPropertyChanged: path = ' + changeRecord.path + ' value = ' + JSON.stringify(changeRecord.value));
this._render(this.lang, this.options, this.raw, this.offset);
}
}
/**
* Observer of `offset` property to re-render the formatted number.
*
* @param {number} offset New offset.
*/
_offsetChanged(offset) {
if (this.textNode) {
//console.log('i18n-number: _offsetChanged: offset = ' + offset);
this._render(this.lang, this.options, this.raw, offset);
}
}
/**
* Gets a cached Intl.NumberFormat object
*
* @param {string} lang Locale for formatting.
* @param {Object} options Options for Intl.NumberFormat.
* @return {Object} Intl.NumberFormat object.
*/
_getNumberFormatObject(lang, options) {
if (!lang || lang === 'null') {
lang = this.DEFAULT_LANG;
}
let formatId = lang + JSON.stringify(options);
let formatObject = formatCache.get(formatId);
if (!formatObject) {
formatObject = new Intl.NumberFormat(lang, options);
formatCache.set(formatId, formatObject);
}
return formatObject;
}
/**
* Formats the number
*
* @param {string} lang Locale for formatting.
* @param {Object} options Options for Intl.NumberFormat.
* @param {number} number Number to format.
* @return {string} Formatted number string.
*/
_formatNumber(lang, options, number) {
if (!lang) {
lang = this.DEFAULT_LANG;
}
try {
return this._getNumberFormatObject(lang, options).format(number);
}
catch (e) {
return number.toString();
}
}
/**
* Renders the formatted number
*
* @param {string} lang Locale for formatting.
* @param {Object} options Options for Intl.NumberFormat.
* @param {string} raw Raw number string.
* @param {number} offset Offset for number.
*/
_render(lang, options, raw, offset) {
// TODO: rendering may be done redundantly on property initializations
raw = raw.trim();
if (!raw && !this.formatted) {
//console.log('i18n-number: skipping _render as raw is null');
return;
}
if (raw) {
this.rawNumber = Number(raw);
this.number = this.rawNumber - offset;
this.formatted = this._formatNumber(lang, options, this.number);
}
else {
this.rawNumber = undefined;
this.number = undefined;
this.formatted = '';
}
this.invalidate();
//console.log('i18n-number: _render ' + this.formatted);
}
/**
* Renders shadowRoot with this.__render()
*/
invalidate() {
if (!this.needsRender) {
this.needsRender = true;
Promise.resolve().then(() => {
this.needsRender = false;
if (!this.shadowRoot) {
this.attachShadow({ mode: 'open' });
}
render(this.__render(), this.shadowRoot);
//console.log(`rendered "${this.formatted}"`);
if (typeof this.formatted !== 'undefined') {
this.dispatchEvent(new Event('rendered', { bubbles: true, cancelable: false, composed: true }));
}
});
}
}
/**
* Renders the formatted number with the current parameters
*
* Note: (As of Polymer 1.2.3)
* Explicit render() call is needed whenever the observer
* `_onOptionsPropertyChanged(options.*)` is NOT invoked
* after a property of `options` is changed. An explicit call
* `this.notifyPath('options', this.options, true)` can also
* trigger re-rendering.
*
* If the changed property of `options` is bound in an annotation
* like `{{options.currency}}`, the observer `_onOptionsPropertyChanged(options.*)`
* is automatically called whenever the property value is changed
* and thus no explicit call of `render()` or `notifyPath()` is
* required.
*/
render() {
this._render(this.lang, this.options, this.raw, this.offset);
}
}
customElements.define(I18nNumber.is, I18nNumber);