forked from unicef-polymer/etools-currency-amount-input
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathetools-currency-amount-input.html
490 lines (439 loc) · 17 KB
/
etools-currency-amount-input.html
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../paper-input/paper-input.html">
<link rel="import" href="etools-currency-behavior.html">
<!--
`etools-currency-input`
A paper-input element that allows only currency amount values (US format). It accepts only digits, comma, a
a single floating point (period), and allows 2 decimals. The maximum number you can have 12 digits until floating point.
The value displayed it's paper-input's internal value. The `value` property of this element will update and format
the internal value and when internal value is changed, element's value will be updated with current float value.
### Usage
```html
<etools-currency-amount-input label="Amount value"
value="{{value}}" currency="$"></etools-currency-amount-input>
```
### Style
Use this css mixins to style this element.
All mixins are used to override the same mixin of paper-input.
Custom property | Description | Default
----------------|-------------|----------
`--etools-currency-input` | Mixin applied to currency element | `{}`
`--etools-currency-container-input` | Mixin applied to paper-input container input | `{}`
`--etools-currency-container-label` | Mixin applied to paper-input label | `{}`
`--etools-currency-container-label-focus` | Mixin applied to paper-input label when it's focused | `{}`
`--etools-currency-container-label-floating` | Mixin applied to paper-input label when it floats | `{}`
`--etools-currency-container-underline` | Mixin applied to the paper-input underline | `{}`
`--etools-currency-container-underline-focus` | Mixin applied to the paper-input underline when it's focused | `{}`
`--etools-currency-container-underline-disabled` | Mixin applied to the paper-input underline when it's disabled | `{}`
@demo demo/index.html
-->
<dom-module id="etools-currency-amount-input">
<template>
<style>
*[hidden] {
display: none !important;
}
:host {
display: block;
width: 100%;
@apply(--etools-currency-input);
--paper-input-prefix: {
margin-right: 5px;
};
}
paper-input {
--paper-input-container-input: {
@apply(--etools-currency-container-input);
};
--paper-input-container-label: {
@apply(--etools-currency-container-label);
};
--paper-input-container-label-focus: {
@apply(--etools-currency-container-label-focus);
};
--paper-input-container-label-floating: {
@apply(--etools-currency-container-label-floating);
};
--paper-input-container-underline: {
@apply(--etools-currency-container-underline);
};
--paper-input-container-underline-focus: {
@apply(--etools-currency-container-underline-focus);
};
--paper-input-container-underline-disabled: {
@apply(--etools-currency-container-underline-disabled);
}
}
</style>
<paper-input id="currencyInput"
label="[[label]]"
value="{{_internalValue}}"
allowed-pattern="[0-9\.\,]"
placeholder="[[placeholder]]"
disabled$="[[disabled]]"
on-keydown="_onKeyDown"
on-blur="_onBlur"
readonly$="[[readonly]]"
required$="[[required]]"
invalid="{{invalid}}"
auto-validate$="[[_computeAutovalidate(autoValidate, readonly)]]"
error-message="[[errorMessage]]"
no-label-float="[[noLabelFloat]]">
<div prefix class="prefix" hidden$=[[!currency]]>[[currency]]</div>
</paper-input>
</template>
<script>
(function() {
'use strict';
Polymer({
is: 'etools-currency-amount-input',
// eslint-disable-next-line no-undef
behaviors: [etoolsBehaviors.EtoolsCurrencyBehavior],
properties: {
label: String,
noLabelFloat: Boolean,
_internalValue: {
type: String,
notify: true,
observer: '_onInternalValueChange'
},
value: {
value: null,
notify: true,
observer: '_onValueChange'
},
placeholder: {
type: String,
value: '—'
},
readonly: {
type: Boolean,
value: false,
reflectToAttribute: true
},
disabled: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
required: {
type: Boolean,
value: false,
reflectToAttribute: true
},
autoValidate: {
type: Boolean,
value: false,
reflectToAttribute: true
},
invalid: {
type: Boolean,
value: false,
notify: true,
reflectToAttribute: true
},
errorMessage: {
type: String,
value: 'This field is required'
},
currency: String,
_currentKeyPressed: String,
_charsLimit: {
type: Number,
value: 12
}
},
observers: ['_updateStyles(readonly, disabled, invalid)'],
_updateStyles: function(readonly) {
if (readonly) {
this.set('invalid', false);
}
this.updateStyles();
},
_computeAutovalidate: function(autoValidate, readonly) {
if (readonly) {
return false;
}
return autoValidate;
},
validate: function() {
return this.$.currencyInput.validate();
},
_getStrValue: function(value) {
try {
if (value === 0) {
return '0';
} else {
return value.toString();
}
} catch (error) {
return '0';
}
},
_onValueChange: function(value) {
if (value === null && this._internalValue === '') {
return;
}
var currentValue = value;
if (currentValue === null || typeof currentValue === 'undefined') {
this.set('_internalValue', null);
}
currentValue = parseFloat(this._getValueWithoutFormat(value, 2, true)).toFixed(2);
if (isNaN(currentValue)) {
currentValue = null;
}
var internalVal = this._internalValue;
if (internalVal) {
internalVal = parseFloat(this._getValueWithoutFormat(this._internalValue, 2, true)).toFixed(2);
}
if (currentValue !== internalVal) {
this.set('_internalValue', currentValue);
}
},
_restoreDamagedInternalValue: function(value, ironInput, currentCursorPossition) {
// search for wrong delimiters and repair value's format
var formattedValue = this._formatValue(value);
var currentValCurrencyDelimitersNr = value.split(',').length;
var formattedValCurrencyDelimitersNr = formattedValue.split(',').length;
if (currentValCurrencyDelimitersNr === formattedValCurrencyDelimitersNr) {
// no change
return;
}
if (currentValCurrencyDelimitersNr > formattedValCurrencyDelimitersNr) {
// wrong delimiters added, keep prev cursor position as wrong delimiters is deleted
currentCursorPossition--;
} else {
if (this._currentKeyPressed === 'delete') {
// delete was used to delete a delimiter, jump to the next number
currentCursorPossition++;
}
}
// restore value and update cursor position
this._updateElementInternalValue(formattedValue, ironInput, currentCursorPossition);
},
/**
* Internal value changed, needs to be checked and changed to US currency format
*/
_onInternalValueChange: function(value, oldValue) {
if (typeof value === 'undefined' || value === null) {
return;
}
// get internal iron-input and ensure _internalValue is string
var ironInput = Polymer.dom(this.$.currencyInput.root).querySelector('#input');
value = this._getStrValue(value);
oldValue = this._getStrValue(oldValue);
if (value.substr(0, 1) === '0' && value.substr(1, 1) !== '.' && value.length > 1) {
this._updateElementInternalValue(oldValue, ironInput, 0);
return;
}
if (value === '.') {
this.set('_internalValue', null);
return;
}
// get cursor current position
var currentCursorPossition = ironInput.selectionStart;
// floating point/period can be added just one and only at the end of the string
var floatingPointPos = value.indexOf('.');
if (floatingPointPos > -1 && (floatingPointPos + 1) < value.length - (oldValue.indexOf('.') > -1 ? 4 : 3)) {
// floating point can be added only at the end of the string, starting with the last 2 digits
this._updateElementInternalValue(value.replace('.', ''), ironInput, currentCursorPossition - 1);
return;
}
var preserveFloatingPoint = false;
if (value.slice(-1) === '.') {
preserveFloatingPoint = true;
}
if (this._getValueWithoutFormat(value) === this._getValueWithoutFormat(oldValue) && !preserveFloatingPoint) {
// restore damaged internal value
this._restoreDamagedInternalValue(value, ironInput, currentCursorPossition);
return;
}
var charsAfterCursor = value.substr(currentCursorPossition).length;
if (value.substring(0, 1) === '.') {
// no integer value, only floating point and decimals
value = value.substring(0, 3);
} else {
// format new value
value = this._formatValue(value);
if (preserveFloatingPoint) {
value = value + '.';
}
}
// update cursor position
var updatedCursorPossition = this._getUpdatedCursorPosition(value, charsAfterCursor, oldValue);
this._updateElementInternalValue(value, ironInput, updatedCursorPossition);
this._setExternalValue(value, preserveFloatingPoint);
},
_getUpdatedCursorPosition: function(value, charsAfterCursor, oldValue) {
var updatedCursorPossition = value.length - charsAfterCursor;
var floatingPointPos = value.indexOf('.');
if (floatingPointPos > -1) {
// check cursor pos relative to floating point, only if floating point is not new
var newFloatingPoint = oldValue.indexOf('.') === -1;
if (updatedCursorPossition >= floatingPointPos + 1 && !newFloatingPoint) {
updatedCursorPossition++;
}
}
updatedCursorPossition = (updatedCursorPossition < 0) ? 0 : updatedCursorPossition;
return updatedCursorPossition;
},
/**
* Update element value with the float value of _internalValue
*/
_setExternalValue: function(value, preserveFloatingPoint) {
var cleanValStr = this._getValueWithoutFormat(value, 2);
var valuePieces = cleanValStr.split('.');
var limitExceeded = false;
if (valuePieces[0].length > this._charsLimit) {
// limit number integer part to max 12 digits
valuePieces[0] = valuePieces[0].slice(0, this._charsLimit);
limitExceeded = true;
}
cleanValStr = valuePieces.join('.');
if (preserveFloatingPoint) {
cleanValStr += '.';
}
if (limitExceeded) {
this.set('_internalValue', this.addCurrencyAmountDelimiter(cleanValStr));
return;
}
var realFloatValue = this._getRealNumberValue(cleanValStr);
if (realFloatValue !== this.value) {
// update value only if needed
this.set('value', realFloatValue);
} else {
// update internal value
this.set('_internalValue', this.addCurrencyAmountDelimiter(cleanValStr));
}
},
_formatValue: function(value) {
value = this._getValueWithoutFormat(value, 2);
// re-apply format
value = this._applyCurrencyAmountFormat(value);
return value.trim();
},
_updateElementInternalValue: function(value, ironInput, cursorPos) {
var currencyInput = this.$.currencyInput;
currencyInput.updateValueAndPreserveCaret(value);
try {
// "Not all elements might have selection, and even if they have the
// right properties, accessing them might throw an exception"(PaperInputBehavior)
ironInput.selectionStart = cursorPos;
ironInput.selectionEnd = cursorPos;
} catch (err) {
// IE11 throws unspecified error when setting selectionStart and selectionEnd
// no need to log this error, IE11
}
if (!this.readonly && this.autoValidate) {
currencyInput._handleAutoValidate();
}
},
_applyCurrencyAmountFormat: function(value) {
value = this._getStrValue(value);
var formattedValue = '';
var _valueParts = value.split('.');
/**
* _valueParts[0] - integer part
* _valueParts[1] - decimals, if any
*/
if (_valueParts[0] !== '') {
var decimalsPart = _valueParts[1];
formattedValue = this.addCurrencyAmountDelimiter(_valueParts[0]);
if (!this._emptyValue(decimalsPart)) {
formattedValue += '.' + decimalsPart;
}
}
return formattedValue;
},
_getValueWithoutFormat: function(value, decimalsNr, needsStrValue) {
if (!decimalsNr) {
decimalsNr = 0;
}
if (needsStrValue) {
value = this._getStrValue(value);
}
var _values = value.split('.');
var _decimals = '';
var _floatingPoints = _values.length - 1;
if (_floatingPoints === 1) {
_decimals = _values[_values.length - 1];
_values = _values.slice(0, _values.length - 1);
}
value = _values.join('');
if (_decimals !== '') {
if (decimalsNr > 0) {
_decimals = _decimals.slice(0, decimalsNr);
}
value += '.' + _decimals;
}
// remove commas and spaces and return value
return value.split(',').join('').split(' ').join('');
},
_emptyValue: function(value) {
if (value === null || typeof value === 'undefined') {
return true;
}
value = value.toString();
if (value === '') {
return true;
}
return false;
},
_getRealNumberValue: function(value, decimals) {
if (!decimals) {
decimals = false;
}
if (this._emptyValue(value)) {
return null;
}
value = this._getValueWithoutFormat(value, 2);
var floatVal = parseFloat(value);
if (isNaN(floatVal)) {
return null;
}
if (decimals) {
return parseFloat(floatVal.toFixed(decimals));
}
return floatVal;
},
_onKeyDown: function(e) {
e.stopImmediatePropagation();
var currentKey = null;
if (e.which === 46) {
currentKey = 'delete';
}
if (e.which === 190) {
// do not allow more then one period char ('.')
var currentInternalValue = this._internalValue ? this._internalValue.toString() : '';
var floatingPtsNr = currentInternalValue.split('.').length - 1;
if (floatingPtsNr === 1) {
// stop, we already have a period
e.preventDefault();
}
}
this.set('_currentKeyPressed', currentKey);
},
_onBlur: function(e) {
if (this._internalValue) {
// adjust decimals on focus lost
if (this._internalValue.substr(-1) === '.') {
this.set('_internalValue', this._internalValue + '00');
}
var _floatingPointPos = this._internalValue.indexOf('.');
if (_floatingPointPos === -1) {
this.set('_internalValue', this._internalValue + '.00');
} else {
if (this._internalValue.slice(_floatingPointPos + 1).length == 1) {
// add second missing decimal
this.set('_internalValue', this._internalValue + '0');
}
}
if (this._internalValue.substr(0, 1) === '.') {
this.set('_internalValue', '0' + this._internalValue);
}
}
}
});
})();
</script>
</dom-module>