-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexm-token-input.html
More file actions
executable file
·659 lines (572 loc) · 17.1 KB
/
exm-token-input.html
File metadata and controls
executable file
·659 lines (572 loc) · 17.1 KB
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../iron-input/iron-input.html">
<link rel="import" href="../paper-input/paper-input-container.html">
<link rel="import" href="../paper-input/paper-input-error.html">
<link rel="import" href="../iron-flex-layout/iron-flex-layout.html">
<link rel="import" href="../iron-form-element-behavior/iron-form-element-behavior.html">
<link rel="import" href="../iron-validatable-behavior/iron-validatable-behavior.html">
<link rel="import" href="../iron-icons/iron-icons.html">
<link rel="import" href="../paper-button/paper-button.html">
<link rel="import" href="../iron-a11y-keys-behavior/iron-a11y-keys-behavior.html">
<link rel="import" href="../iron-selector/iron-selector.html">
<link rel="import" href="exm-token-input-dropdown.html">
<!--
`exm-token-input`
Paper style token input element
@demo demo/index.html
-->
<dom-module id="exm-token-input">
<template>
<style>
:host {
display: block;
}
:host([hidden]) {
display: none !important;
}
.tokens {
margin-right: 6px;
min-height: 24px;
position: relative;
width: 100%;
}
.tokens paper-button {
background: var(--exm-token-input-badge-color, --default-primary-color);
margin: 2px 0;
color: var(--exm-token-input-badge-text-color, --text-primary-color);
height: 18px;
font-size: 12px;
min-width: initial;
max-width: 100%
}
.tokens paper-button span {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.tokens paper-button iron-icon {
height: 16px;
width: 16px;
}
input[is="iron-input"] {
font: inherit;
outline: none;
box-shadow: none;
border: none;
width: auto;
max-width: 100%;
min-width: 1.8em;
}
.container {
@apply(--layout-horizontal);
}
iron-selector > * {
padding: 16px 16px;
}
.horizontal-section {
padding: 0;
}
.iron-selected {
background-color: var(--exm-token-input-dropdown-selected-color, --default-primary-color);
color: var(--exm-token-input-dropdown-selected-text-color, --text-primary-color);
}
label,
.container {
cursor:text;
}
::content [prefix] {
margin-right: 4px;
}
</style>
<paper-input-container
always-float-label="[[_computeAlwaysFloatLabel(value, alwaysFloatLabel)]]"
attr-for-value="value"
on-tap="_handleContainerTap"
disabled$="[[disabled]]"
invalid="[[invalid]]">
<label id="label" hidden$="[[!label]]" aria-hidden="true">[[label]]</label>
<content select="[prefix]"></content>
<div class="container">
<span class="tokens">
<template
is="dom-repeat"
items="[[_tokens]]"
as="token">
<paper-button
tabindex="-1"
on-tap="_handleDeleteToken"
data-token$="[[_getItemValue(token)]]"><span>[[_getItemLabel(token)]]</span><iron-icon icon="clear"></iron-icon></paper-button>
</template>
<input
id="inputValue"
is="iron-input"
aria-labelledby="label"
required$="[[required]]"
bind-value="{{_inputValue}}"
allowed-pattern="[[allowedPattern]]"
prevent-invalid-input="[[preventInvalidInput]]"
autofocus$="[[autofocus]]"
autocomplete="off"
disabled$="[[disabled]]">
</span>
</div>
<content select="[suffix]"></content>
<template is="dom-if" if="[[errorMessage]]">
<paper-input-error aria-live="assertive">[[errorMessage]]</paper-input-error>
</template>
</paper-input-container>
<span id="inputWidthHelper">[[_inputValue]]</span>
<exm-token-input-dropdown id="dropdownInput" auto-fit-on-attach no-overlap vertical-align="top" horizontal-align="left">
<div class="dropdown-content">
<iron-selector id="itemList">
<template is="dom-repeat" items="{{_filteredItems}}" as="item">
<div name="[[_getItemValue(item)]]">[[_getItemLabel(item)]]</div>
</template>
</iron-selector>
</div>
</exm-token-input-dropdown>
</template>
<script>
Polymer({
is: 'exm-token-input',
properties: {
/**
* The label for this input.
*/
label: String,
/**
* Value contains a comma seperated list of the selected items. In case you use data objects the value property will contain a comma seperated list of values located at the dataValuePath.
*/
value: {
notify: true,
type: String,
value: function() {
return '';
}
},
/**
* The data attribute can be used to set the list box options. This method expects an array or function of objects or string values. If using an array of objects the default properties are value and label [{"value": 21, "label": "Mark"},{...}]
*/
data: {
type: Object,
observer: '_dataChanged',
value: function() { return {}; }
},
/**
* The data label path attribute can be used to change the default path "value" to a custom path. For example if set to "id" the data objects should look something like this {"id": 21, "label": "Mark"}.
*/
dataValuePath: {
type: String,
value: 'value'
},
/**
* The data label path attribute can be used to change the default path "label" to a custom path. For example if set to "name" the data objects should look something like this {"value": 21, "name": "Mark"}
*/
dataLabelPath: {
type: String,
value: 'label'
},
/**
* Optionaly you can supply the element with a list of items which will populate the dropdown list
*/
_items: {
notify: true,
type: Array,
value: function() {
return [];
}
},
allowedDuplicateValues: {
type: Boolean,
value: false
},
/**
* Regular expression that list the characters allowed as input. This pattern represents the allowed characters for the field; as the user inputs text, each individual character will be checked against the pattern (rather than checking the entire value as a whole). The recommended format should be a list of allowed characters; for example, [a-zA-Z0-9-!]
*/
allowedPattern: {
type: String
},
/**
* Set to true to auto-validate the input value.
*/
autoValidate: {
type: Boolean,
value: false
},
autofocus: {
type: Boolean
},
/**
* Set to true to disable this input.
*/
disabled: {
type: Boolean,
value: false
},
/**
* The error message to display when the input is invalid.
*/
errorMessage: {
type: String
},
/**
* Set to true to prevent the user from entering invalid input. If allowedPattern is set, any character typed by the user will be matched against that pattern, and rejected if it's not a match. Pasted input will have each character checked individually; if any character doesn't match allowedPattern, the entire pasted string will be rejected. If allowedPattern is not set, it will use the type attribute (only supported for type=number).
*/
preventInvalidInput: {
type: Boolean,
value: false
},
_modeDropDown: {
type: Boolean,
value: false
},
/**
* alwaysFloatLabel
*/
alwaysFloatLabel: {
type: Boolean,
value: false
},
/**
* Maximum number of tokens allowed in value
*/
maxTokens: {
type: Number
},
/**
* This is the internal working list for the dropdown box. This list will exclude the potential selected tokens.
*/
_filteredItems: {
notify: true,
type: Array,
value: function() {
return [];
}
},
/**
* Helper method to determine if the token input has an dropdown item list
*/
_hasDropDown: {
type: Boolean,
computed: '_computeHasDropDown(_items)'
},
/**
* Set to true to mark the input as required. If you're using PaperInputBehavior to
* implement your own paper-input-like element, bind this to
* the `<input is="iron-input">`'s `required` property.
*/
required: {
type: Boolean,
value: false
},
/**
* This field will be bind to the actual input field
*/
_inputValue: {
type: String,
notify: true,
value: ''
},
_tokens: {
type: Array,
computed: '_valueAsItemArray(value, _modeDropDown)'
}
},
behaviors: [
Polymer.IronFormElementBehavior,
Polymer.IronA11yKeysBehavior,
Polymer.IronValidatableBehavior
],
listeners: {
'inputValue.keyup': '_handleUpDown',
'inputValue.focus': '_handleInputFocus',
'item-selected': '_handleItemSelected'
},
observers: [
'_observeInputChange(_inputValue)',
'_filterItems(value)',
'_itemsChanged(_items.splice)'
],
keyBindings: {
'enter': '_onEnter',
'backspace': '_onBackspace'
},
/**
* Returns a reference to the input element.
*/
get inputElement() {
return this.$.inputValue;
},
attached: function() {
/* Initialize the input helper span element for determining the actual width of the input text. This width will be used to create a dynamic width on the input field */
this.$.inputWidthHelper.style = window.getComputedStyle(this.$.inputValue, null).cssText;
this.$.inputWidthHelper.style.position = 'absolute';
this.$.inputWidthHelper.style.top = '-999px';
this.$.inputWidthHelper.style.left = '0';
this.$.inputWidthHelper.style.padding = '0';
this.$.inputWidthHelper.style.width = 'auto';
this.$.inputWidthHelper.style['white-space'] = 'pre';
this._filterItems();
},
/**
* This will return an array of the selected objects
*/
getSelectedItems: function() {
if(this._modeDropDown) {
return this._tokens();
}
},
_setDataSource: function(dataSource) {
this.dataSource = dataSource;
this._initializeItems();
},
_dataChanged: function(data) {
if (typeof data === 'function') {
this._setDataSource(data);
}
if (Array.isArray(data)) {
this.async(function() {
this._setDataSource(function() {
return data;
});
}.bind(this));
}
},
_initializeItems: function() {
if (this.dataSource) {
var data = this.dataSource();
if(data && data instanceof Promise) {
data.then(function(res) {
this._setItems(res);
}.bind(this));
} else {
this._setItems(data);
}
}
},
_setItems: function(data) {
if(data.length > 0 && typeof data[0] === 'string') {
var items = [];
data.forEach(function(value) {
var item = {};
item[this.dataValuePath] = item[this.dataLabelPath] = value;
items.push(item);
}.bind(this));
this.set('_items', items);
} else {
this.set('_items', data);
}
this.set('_modeDropDown', true);
},
/**
* This method will automaticly set the label float.
*/
_computeAlwaysFloatLabel: function(value, alwaysFloatLabel) {
if(alwaysFloatLabel) {
return true;
}
return !(this._valueAsArray().length === 0 && this.$.inputValue !== document.activeElement);
},
_itemsChanged: function(items) {
this._filterItems();
},
_lookupItemByPath: function(item, path) {
if(item === undefined) {
return;
}
var parts = path.split(".");
if (parts.length === 1){
return item[parts[0]];
}
return this._lookupItemByPath(item[parts[0]], parts.slice(1).join("."));
},
_getItemLabel: function(item) {
return this._lookupItemByPath(item, this.dataLabelPath);
},
_getItemValue: function(item) {
return this._lookupItemByPath(item, this.dataValuePath);
},
_valueAsArray: function() {
var value = this.value.split(',');
return value.length === 1 && value[0] === '' ? [] : value;
},
_valueAsItemArray: function() {
var values = this._valueAsArray();
var items = [];
values.forEach(function(value) {
var item = {};
item[this.dataValuePath] = item[this.dataLabelPath] = value;
if(this._modeDropDown) {
item = this._items.find(function(item) {
return this._getItemValue(item) === value;
}.bind(this));
}
items.push(item);
}.bind(this));
return items;
},
_handleItemSelected: function(e) {
var item = this._items.find(function(item) {
return e.detail === this._getItemValue(item);
}.bind(this));
this._addToken(item);
this.async(function() {
this.focus();
}.bind(this));
},
/**
* Recalculate string width after input change
*/
_observeInputChange: function() {
this.$.inputValue.style.width = (this.$.inputWidthHelper.offsetWidth + 10) + 'px';
this._filterItems();
},
_filterItems: function() {
if(this._hasDropDown && this._filteredItems) {
this.splice('_filteredItems', 0, this._filteredItems.length);
var filtered = this._items.filter(function(item) {
return this._inputValue.length === 0 || (this._getItemLabel(item).toLowerCase()).indexOf(this._inputValue.toLowerCase()) !== -1;
}.bind(this));
this._items.forEach(function(item) {
var values = this._valueAsArray();
var itemIndex = filtered.findIndex(function(filteredItem) {
return this._getItemValue(filteredItem) === this._getItemValue(item);
}.bind(this));
if(itemIndex !== -1) {
if(this.allowedDuplicateValues || values.indexOf(this._getItemValue(item)) === -1) {
this.push('_filteredItems', item);
}
}
}.bind(this));
}
},
_handleUpDown: function(event) {
event.preventDefault();
if(this._hasDropDown && this.$.dropdownInput.dropdown.opened) {
var ironSelector = this.$$('iron-selector');
if (event.keyCode === 38) {
if(ironSelector.selected) {
ironSelector.selectPrevious();
}
} else if (event.keyCode === 40) {
if(ironSelector.selected === undefined) {
ironSelector.selectIndex(0);
} else {
ironSelector.selectNext();
}
}
} else if(event.keyCode === 38 || event.keyCode === 40){
this._openDropdown();
}
},
_onBackspace: function(e) {
if(this._inputValue.length === 0) {
this._removeLastToken();
}
},
_onEnter: function() {
if(this.$.dropdownInput.dropdown.opened && this._filteredItems.length > 0) {
var item = this._items.find(function(item) {
return this._getItemValue(item) === this.$$('iron-selector').selectedItem.name;
}.bind(this));
this._addToken(item);
} else {
if(this._inputValue && this._inputValue.length > 0 && !this._modeDropDown) {
var item = {};
item[this.dataValuePath] = item[this.dataLabelPath] = this._inputValue;
this._addToken(item);
}
}
this._openDropdown();
},
_handleDeleteToken: function(e) {
var el = (e.target.tagName === 'IRON-ICON' ? e.target.parentElement : e.target);
this._removeToken(el.dataset.token);
this.focus();
e.stopPropagation();
},
_removeLastToken: function() {
var value = this._valueAsArray();
if(value.length > 0) {
this._removeToken(value[value.length - 1]);
}
},
_addToken: function(item) {
var values = this._valueAsArray();
if(this.maxTokens && values.length >= this.maxTokens) {
return;
}
values.push(this._getItemValue(item));
this.set('value', values.toString());
this._resetInput();
this._autoValidate();
},
_resetInput: function() {
this.set('_inputValue', '');
if(this._hasDropDown && this._filteredItems.length > 0) {
this.$$('iron-selector').selectIndex(0);
}
},
_removeToken: function(token) {
var value = this._valueAsArray();
value.splice(value.indexOf(token), 1);
this.set('value', value.toString());
this._autoValidate();
},
_autoValidate: function() {
if(this.autoValidate) {
this.validate();
}
},
/**
* Returns true if `value` is valid. The validator provided in `validator` will be used first,
* then any constraints.
* @return {boolean} True if the value is valid.
*/
validate: function() {
var valid = true;
// Empty, required input is invalid
if (this.required && this.value === '') {
valid = false;
} else if (this.hasValidator()) {
valid = Polymer.IronValidatableBehavior.validate.call(this, this.value);
}
this.invalid = !valid;
this.fire('iron-input-validate');
return valid;
},
_handleContainerTap: function(e) {
this._openDropdown();
this.focus();
},
_openDropdown: function() {
if(this._hasDropDown && !this.$.dropdownInput.dropdown.opened) {
this.$.dropdownInput.open();
this.$$('iron-selector').selected = this.$$('iron-selector').selected || 0;
}
},
_handleInputFocus: function(e) {
this._triggerComputeFloatLabel();
},
_triggerComputeFloatLabel: function() {
// Hack to manualy trigger compute function
this.alwaysFloatLabel = !this.alwaysFloatLabel;
this.alwaysFloatLabel = !this.alwaysFloatLabel;
},
/**
* this method can be used to set the focus of the element
*/
focus: function() {
this.$.inputValue.focus();
},
_getValidity: function() {
var validValue = this._valueAsArray().length > 0;
this.$$('paper-input-container').invalid = !validValue;
return validValue;
},
_computeHasDropDown: function() {
return this._items && this._items.length > 0;
}
});
</script>
</dom-module>