-
Notifications
You must be signed in to change notification settings - Fork 2
/
paper-autocomplete-input.html
870 lines (761 loc) · 23.3 KB
/
paper-autocomplete-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
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../paper-material/paper-material.html">
<link rel="import" href="../paper-input/paper-input-behavior.html">
<link rel="import" href="../paper-input/paper-input.html">
<link rel="import" href="../paper-progress/paper-progress.html">
<link rel="import" href="../paper-item/paper-item.html">
<link rel="import" href="../iron-ajax/iron-ajax.html">
<link rel="import" href="../iron-input/iron-input.html">
<link rel="import" href="../iron-form-element-behavior/iron-form-element-behavior.html">
<link rel="import" href="paper-autocomplete-item.html">
<!--
paper-input with personalizable autocompletion feature
Example:
<paper-autocomplete-input
label="Autocompleting input"
autoc-url="data.json"
autoc-fields='["name"]'></paper-autocomplete-input>
The element will request the given url with the `value` parameter.
This one contain the typed input value that used to filter your items.
Your server should respond with a JSON array of items like following:
[
{"name": "John Lenon", "color": "orange", "fruit": "banana"},
{"name": "Vol Demor", "color": "black", "fruit": "pineapple"},
{"name": "Han Solo", "color": "green", "fruit": "potato"},
...
]
Then, you specify which field you want to watch to autocomplete the input value using the `autoc-fields` array attribute.
To get the selected item the `item-selected` event is fired :
<paper-autocomplete-input
label="Autocompleting input"
autoc-url="data.json"
autoc-fields='["name"]'
on-item-selected="onItemSelected"></paper-autocomplete-input>
...
onItemSelected: function (e, detail) {
var mySelectedItem = detail;
}
You also can specify you own item template so you can customize as you want your item list.
<paper-autocomplete-input
autoc-url="data.json"
label="Custom autocompletion input"
autoc-fields='["name"]'>
<template>
<paper-item>
<paper-item-body two-line>
<div>[[item.first_name]] - [[item.last_name]]</div>
<div secondary>This is the number [[index]]</div>
</paper-item-body>
<iron-icon icon="perm-identity"></iron-icon>
</paper-item>
</template>
</paper-autocomplete-input>
The following custom properties and mixins are also available for styling:
Custom property | Description | Default
----------------|-------------|----------
`--paper-autocomplete-input-list-margin-top` | Margin top from the item list | 2px
`--paper-autocomplete-item` | Mixin for the item | {}
`--paper-autocomplete-input-list-background` | List background | white
@group Paper Elements
@demo demo/index.html
@element paper-autocomplete-input
-->
<dom-module id="paper-autocomplete-input">
<template>
<style>
:host {
display: block;
position: relative;
}
paper-input {
width: 100%;
--paper-input-container: {
padding-bottom: 0;
};
}
paper-autocomplete-item {
cursor: pointer;
position: relative;
background-color: white;
@apply --paper-autocomplete-item;
}
paper-autocomplete-item:not(:last-of-type) {
border-bottom: solid 1px var(--divider-color);
}
paper-autocomplete-item:last-of-type {
border-radius: 0 0 2px 2px;
}
paper-autocomplete-item:focus:before {
display: none;
}
paper-autocomplete-item.selected {
background-color: var(--divider-color);
}
[hidden] {
display: none !important;
}
#itemListDiv {
overflow: visible;
-webkit-overflow-scrolling: touch;
position: absolute;
min-width: 100%;
left: 0;
margin-top: var(--paper-autocomplete-input-list-margin-top, 2px);
background-color: white;
z-index: 10;
}
#itemListDiv div {
width: 100%;
}
#itemListDiv div paper-material {
overflow: visible;
-webkit-overflow-scrolling: touch;
border-radius: 0 0 2px 2px;
background: var(--paper-autocomplete-input-list-background, white);
width: 100%;
}
paper-progress {
width: 100%;
position: absolute;
}
</style>
<iron-ajax
id="getAutocItemsRequest"
url="{{ autocUrl }}"
loading="{{suggestionsLoading}}"
last-response="{{ items }}"
on-response="_onAutocItemsResponse"></iron-ajax>
<paper-input
id="input"
label="[[label]]"
value="{{value}}"
disabled="[[disabled]]"
invalid="{{invalid}}"
allowed-pattern="[[allowedPattern]]"
type="[[type]]"
pattern="[[pattern]]"
required="[[required]]"
error-message="[[errorMessage]]"
char-counter="[[charCounter]]"
no-label-float="[[noLabelFloat]]"
always-float-label="[[alwaysFloatLabel]]"
autoValidate="[[autoValidate]]"
validator="[[validator]]"
autofocus="[[autofocus]]"
inputmode="[[inputmode]]"
name="[[name]]"
placeholder="[[placeholder]]"
readonly="[[readonly]]"
on-keyup="_onKeyUp"
on-focusout="_onFocusOut"
focused="{{focused}}">
<slot name="prefix" slot="prefix"></slot>
<slot name="suffix" slot="suffix"></slot>
</paper-input>
<div id="itemListDiv">
<template is="dom-if" if="[[!hideLoadingBar]]">
<paper-progress indeterminate="[[suggestionsLoading]]" hidden="[[!suggestionsLoading]]"></paper-progress>
</template>
<div>
<paper-material elevation="3" hidden="[[ _hideResults ]]">
<template id="itemListTemplate" is="dom-repeat" items="[[ filteredItems ]]">
<paper-autocomplete-item
on-tap="_onItemTap"
class$="[[ _isKeySelectedItemClass(item, _keySelectedItem) ]]"
template-class="[[_itemTemplateClass]]"
item="[[item]]"
index="[[index]]"></paper-autocomplete-item>
</template>
</paper-material>
</div>
</div>
<template id="defaultTemplate">
<paper-item>
[[ getItemString(item) ]]
</paper-item>
</template>
</template>
</dom-module>
<script>
Polymer({
is: 'paper-autocomplete-input',
behaviors: [
Polymer.IronFormElementBehavior
],
properties: {
/**
* The label for this input. If you're using PaperInputBehavior to
* implement your own paper-input-like element, bind this to
* `<label>`'s content and `hidden` property, e.g.
* `<label hidden$="[[!label]]">[[label]]</label>` in your `template`
*/
label: {
type: String
},
/**
* The value for this input. If you're using PaperInputBehavior to
* implement your own paper-input-like element, bind this to
* the `<iron-input>`'s `bindValue`
* property, or the value property of your input that is `notify:true`.
*/
value: {
notify: true,
type: String
},
/**
* Set to true to disable this input. If you're using PaperInputBehavior to
* implement your own paper-input-like element, bind this to
* both the `<paper-input-container>`'s and the input's `disabled` property.
*/
disabled: {
type: Boolean,
value: false
},
/**
* Returns true if the value is invalid. If you're using PaperInputBehavior to
* implement your own paper-input-like element, bind this to both the
* `<paper-input-container>`'s and the input's `invalid` property.
*
* If `autoValidate` is true, the `invalid` attribute is managed automatically,
* which can clobber attempts to manage it manually.
*/
invalid: {
type: Boolean,
value: false,
notify: true
},
/**
* Set this to specify the pattern allowed by `preventInvalidInput`. If
* you're using PaperInputBehavior to implement your own paper-input-like
* element, bind this to the `<input is="iron-input">`'s `allowedPattern`
* property.
*/
allowedPattern: {
type: String
},
/**
* The type of the input. The supported types are `text`, `number` and `password`.
* If you're using PaperInputBehavior to implement your own paper-input-like element,
* bind this to the `<input is="iron-input">`'s `type` property.
*/
type: {
type: String
},
/**
* A pattern to validate the `input` with. If you're using PaperInputBehavior to
* implement your own paper-input-like element, bind this to
* the `<input is="iron-input">`'s `pattern` property.
*/
pattern: {
type: String
},
/**
* 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
},
/**
* The error message to display when the input is invalid. If you're using
* PaperInputBehavior to implement your own paper-input-like element,
* bind this to the `<paper-input-error>`'s content, if using.
*/
errorMessage: {
type: String
},
/**
* Set to true to show a character counter.
*/
charCounter: {
type: Boolean,
value: false
},
/**
* Set to true to disable the floating label. If you're using PaperInputBehavior to
* implement your own paper-input-like element, bind this to
* the `<paper-input-container>`'s `noLabelFloat` property.
*/
noLabelFloat: {
type: Boolean,
value: false
},
/**
* Set to true to always float the label. If you're using PaperInputBehavior to
* implement your own paper-input-like element, bind this to
* the `<paper-input-container>`'s `alwaysFloatLabel` property.
*/
alwaysFloatLabel: {
type: Boolean,
value: false
},
/**
* Set to true to auto-validate the input value. If you're using PaperInputBehavior to
* implement your own paper-input-like element, bind this to
* the `<paper-input-container>`'s `autoValidate` property.
*/
autoValidate: {
type: Boolean,
value: false
},
/**
* Name of the validator to use. If you're using PaperInputBehavior to
* implement your own paper-input-like element, bind this to
* the `<input is="iron-input">`'s `validator` property.
*/
validator: {
type: String
},
/**
* If you're using PaperInputBehavior to implement your own paper-input-like
* element, bind this to the `<input is="iron-input">`'s `autofocus` property.
*/
autofocus: {
type: Boolean,
observer: '_autofocusChanged'
},
/**
* If you're using PaperInputBehavior to implement your own paper-input-like
* element, bind this to the `<input is="iron-input">`'s `inputmode` property.
*/
inputmode: {
type: String
},
/**
* The minimum length of the input value.
* If you're using PaperInputBehavior to implement your own paper-input-like
* element, bind this to the `<input is="iron-input">`'s `minlength` property.
*/
minlength: {
type: Number
},
/**
* The maximum length of the input value.
* If you're using PaperInputBehavior to implement your own paper-input-like
* element, bind this to the `<input is="iron-input">`'s `maxlength` property.
*/
maxlength: {
type: Number
},
/**
* If you're using PaperInputBehavior to implement your own paper-input-like
* element, bind this to the `<input is="iron-input">`'s `name` property.
*/
name: {
type: String
},
/**
* A placeholder string in addition to the label. If this is set, the label will always float.
*/
placeholder: {
type: String,
// need to set a default so _computeAlwaysFloatLabel is run
value: ''
},
/**
* If you're using PaperInputBehavior to implement your own paper-input-like
* element, bind this to the `<input is="iron-input">`'s `readonly` property.
*/
readonly: {
type: Boolean,
value: false
},
/**
* If you're using PaperInputBehavior to implement your own paper-input-like
* element, bind this to the `<input is="iron-input">`'s `autocapitalize` property.
*/
autocapitalize: {
type: String,
value: 'none'
},
/**
* `items` is the item list resulting by the autocompleting filter.
*
* @type Array
*/
items: {
type: Array,
observer: "_onItemsChange"
},
/**
* `filteredItems` is the list of items client side filtered and sorted.
*
* @type Array
*/
filteredItems: {
type: Array,
notify: true,
readOnly: true
},
/**
* `autocUrl` is the url to request to get the autocompleting data.
*
* @type String
*/
autocUrl: String,
/**
* `autocFields` is the list of fields from it should get the autocompleting data.
*
* @type Array
*/
autocFields: {
type: Array
},
_hideResults: {
type: Boolean,
value: true,
observer: '_onHideResultsChange'
},
/**
* `_keySelectedItem` is the item selected by the arrow keys.
*
* @type: Object
*/
_keySelectedItem: {
type: Object,
notify: true,
value: null
},
/**
* `selectedItem` is the item selected from the input.
*
* @type Object
*/
selectedItem: {
type: Object,
observer: '_onSelectedItemChange',
notify: true
},
/**
* `params` is the params you want to send to the server for filtering purpose.
*
* @type Object
* @default {}
*/
params: {
type: Object,
value: function () { return {}; }
},
/**
* `displayListOnFocus` permit to display the list even if the have not typed anything yet
*
* @type Boolean
* @default false
*/
displayListOnFocus: {
type: Boolean,
value: false,
notify: true
},
/**
* `focused` permit to know if the input is on focus or not.
*
* @type Boolean
* @default false
*/
focused: {
type: Boolean,
value: false,
observer: "_onFocusedChanged"
},
/**
* `suggestionsLoading` notify when the input is currently loading to retrieve suggestions
*
* @type Boolean
* @readOnly
*/
suggestionsLoading: {
type: Boolean,
value: false
},
_itemTemplate: Object,
/**
* Template for the autocomplete item
*
* @type Object
* @readOnly
*/
_itemTemplateClass: Object,
/**
* permit to hide the loading bar
*
* @type Boolean
* @default false
*/
hideLoadingBar: {
type: Boolean,
value: false,
notify: true
},
/**
* start the request after a timeout of non user activity in the input
*/
timeout: {
type: Number,
value: 0
},
_timeout: Number,
/**
* `firstRequestStart` is the character's count after the first request is started
*/
firstRequestStart: {
type: Number,
value: 0
}
},
ready: function () {
var template = Polymer.dom(this).querySelector('template:not(#defaultTemplate)');
var dataHost = this;
if (!template) {
template = this.$.defaultTemplate;
}
this.set("_itemTemplate", template);
this.set("_itemTemplateClass", Polymer.Templatize.templatize(template, dataHost));
},
_onItemTap: function (e, detail) {
this.set('selectedItem', e.model.item);
},
/**
* The `_getFilteredItems` permit to return the filtered items.
*/
_getFilteredItems: function () {
var that = this;
var r = RegExp(this.value, 'i');
var filteredItems = this.items.filter(function(item) {
var item_string = that.getItemString(item);
return r.test(item_string);
});
return filteredItems;
},
/**
* The `_onAutocItemsResponse` is used when the autocompleting items request has been responded.
*
* @private
*/
_onAutocItemsResponse: function () {
this.fire("autoc-items-change", this.items);
},
/**
* The `_onKeyUp` event is used when the input value changes by typing in it or when the user pressed the ESC key.
*
* @param e
* @param detail
*/
_onKeyUp: function (e, detail) {
if (e.keyCode === 40) {
this.selectNextItem();
return;
}
if (e.keyCode === 38) {
this.selectPreviousItem();
return;
}
if (e.keyCode === 13) {
this.set('selectedItem', this._keySelectedItem || this.filteredItems[0]);
return;
}
if (e.keyCode == 27) {
this.$.input.blur();
return;
}
this.value = this.value || "";
if (this.value.length < this.firstRequestStart) return;
var that = this;
if (!this.autocUrl) {
if (!!this.items) this._udpateFilteredItems();
return;
}
if (this.timeout > 0) {
clearTimeout(this._timeout);
this._timeout = setTimeout(function () {
that.loadList();
}, this.timeout);
return;
}
this.loadList();
},
/**
* The `selectNextItem` method is used to select the next item in the list
*/
selectNextItem: function () {
if (!this.filteredItems.length > 0) {
return;
}
var currentIndex = this.filteredItems.indexOf(this._keySelectedItem);
if (!this._keySelectedItem || currentIndex === -1) {
this.set('_keySelectedItem', this.filteredItems[0]);
return;
}
var nextIndex = currentIndex < this.filteredItems.length - 1 ? currentIndex + 1 : currentIndex;
this.set('_keySelectedItem', this.filteredItems[nextIndex]);
},
/**
* The `selectPreviousItem` method is used to select the previous item in the list
*/
selectPreviousItem: function () {
if (!this.filteredItems.length > 0) {
return;
}
var currentIndex = this.filteredItems.indexOf(this._keySelectedItem);
if (!this._keySelectedItem || currentIndex === -1) {
this.set('_keySelectedItem', this.filteredItems[0]);
return;
}
var nextIndex = currentIndex > 0 ? currentIndex - 1 : currentIndex;
this.set('_keySelectedItem', this.filteredItems[nextIndex]);
},
/**
* The `_onSelectedItemChange` is used when the selected item change.
*/
_onSelectedItemChange: function (n, o) {
if (n === undefined) return;
this.value = this.getItemString(n);
if (n) {
this._hideResults = true;
this.$.input.blur();
if (this.autocUrl) this.set('items', null);
}
this.fire("item-selected", n);
},
/**
* The `item-selected` event is fired when an item is selected.
*
* @event item-selected
*/
/**
* The `_onItemsChange` the item list is sorted and the filtered items is set.
*/
_onItemsChange: function (n, o) {
if (!this.items) {
return;
}
var that = this;
this.set("items", this.items.sort(function (item1, item2) {
var item1_string = that.getItemString(item1);
var item2_string = that.getItemString(item2);
if (item1_string < item2_string) {
return -1;
}
else if (item1_string > item2_string) {
return 1;
}
else {
return 0;
}
}));
this._udpateFilteredItems();
},
/**
* `_udpateFilteredItems` permit to update the list of filtered items.
*/
_udpateFilteredItems: function () {
this._setFilteredItems(this.displayListOnFocus && !this.value ? this.items : this._getFilteredItems());
this._hideResults = !((this.value || this.displayListOnFocus) && this.focused);
this.fire("items-change", {"items": this.items, "filtered_items": this.filteredItems});
},
/**
* The `items-change` event is fired when the item list change.
*
* @event items-change
*/
/**
* The `_onFocusOut` is used when the user leaves the focus.
*/
_onFocusOut: function (e) {
e.preventDefault();
this.async(function () {
if (this.value === "" || this.value === null) {
this.selectedItem = null;
}
this.cancelTyping();
}, 100);
return false;
},
_onFocusedChanged: function (n, o) {
if (!n) {
return;
}
if (!this.displayListOnFocus) {
return;
}
this.loadList();
},
/**
* The `loadList` method permit to load the autocompletion item list send the current input value and params.
*/
loadList: function () {
var p = {
"value": this.value,
"params": JSON.stringify(this.params)
};
this.$.getAutocItemsRequest.params = p;
this.$.getAutocItemsRequest.generateRequest();
},
/**
* The `cancelTyping` method permit to cancel the current typing action.
*/
cancelTyping: function () {
this.value = this.getItemString(this.selectedItem);
this._hideResults = true;
this.fire("typing-cancelled", this.value);
},
/**
* The `typing-cancelled` event is fired when the cancelTyping` method is called`
*
* @event typing-cancelled
*/
/**
* The `reset` method permit to clear the input and the selected item.
*/
reset: function () {
this.selectedItem = null;
this.items = null;
this.value = null;
},
/** The `_isKeySelectedItemClass` method return "selected" if the given item is selected by keys.
*
* @param item
* @param _keySelectedItem
* @returns {string}
* @private
*/
_isKeySelectedItemClass: function (item, _keySelectedItem) {
return item == _keySelectedItem ? "selected" : "";
},
_onHideResultsChange: function (n, o) {
console.log()
if (n === undefined) return;
if (n) {
return;
}
this.set('_keySelectedItem', null);
},
/**
* Permit to retrieve the item string based on the autocFields property
*
* @param item
* @returns {string}
*/
getItemString: function (item) {
if (!this.autocFields) {
return null;
}
if (!item) {
return null;
}
var item_string = "";
for (var i = 0; i < this.autocFields.length; i++) {
if (!item[this.autocFields[i]]) {
continue;
}
item_string += item[this.autocFields[i]];
if (i < this.autocFields.length - 1 && item[this.autocFields[i + 1]]) {
item_string += " - ";
}
}
return item_string;
}
});
</script>