forked from predixdesignsystem/px-dropdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
px-dropdown.html
701 lines (684 loc) · 23.5 KB
/
px-dropdown.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
<link rel="import" href="../polymer/polymer.html" />
<link rel="import" href="../px-polymer-font-awesome/px-icon-set.html" />
<link rel="import" href="../iron-dropdown/iron-dropdown.html" />
<link rel="import" href="../iron-selector/iron-selector.html" />
<link rel="import" href="../iron-a11y-keys/iron-a11y-keys.html" />
<!--
This element provides a dropdown from which users can select one or more values.
It can also be used in conjunction with px-validation, similar to px-forms-design, to apply validation states - simply add the `validation-error`, `validation-warning`, and `validation-success` classes to alter the border color of the component.
### Usage
Simple:
```
<px-dropdown items='["One","Two"]'></px-dropdown>
<px-dropdown items='[{"key":"one", "val": "One"}, {"key":"two", "val": "Two"}]'></px-dropdown>
```
Complex:
```
<px-dropdown items='[{"key":"one", "val": "One", "selected": "true"}]'
display-value="Click me"
prevent-close-on-outside-click="true"
allow-outside-scroll="true"
multi="true"
select-by="key"
selected-values='["1","3"]'
bound-target=".parentDiv"
search-mode="true"
sort-mode="val">
</px-dropdown>
```
### Styling
The following custom properties are available for styling:
Custom property | Description | Default
----------------|-------------|----------
`--px-dropdown-max-height` | Max height for the dropdown menu container | `300px`
`--px-dropdown-max-width` | Max width for the dropdown menu container | `400px`
`--px-dropdown-bg-color` | Background color for the dropdown menu container |
`--px-dropdown-bg-color--hover` | Background color of a hovered menu item |
`--px-dropdown-bg-color--selected` | Background color of a selected menu item |
`--px-dropdown-text-color--disabled` | Text color of a disabled dropdown menu button |
@element px-dropdown
@blurb Element providing a dropdown solution.
@homepage index.html
@demo index.html
-->
<link rel="import" href="css/px-dropdown-styles.html">
<dom-module id="px-dropdown">
<template>
<style include="px-dropdown-styles"></style>
<iron-a11y-keys
id="keys"
keys="up down space enter tab esc"
target="[[_keyBindingsTarget]]"
on-keys-pressed="_handleKeyPress">
</iron-a11y-keys>
<div id="button" class$="btn dropdown-trigger {{_getDisabledClass(disabled)}} {{_getClass(buttonStyle)}}" on-tap="toggle" tabindex="0">
<div id="label" title="{{_displayValueSelected}}" class="dropdown-label">{{_displayValueSelected}}</div>
<template is="dom-if" if="{{_showClearButton(opened,selected,selectedValues,selectedValues.*)}}">
<iron-icon class="dropdown-icon" icon="px:close" on-tap="_clear"></iron-icon>
</template>
<template is="dom-if" if="{{_showChevron(hideChevron,opened,selected,selectedValues,selectedValues.*)}}">
<iron-icon class="dropdown-icon" icon="px:chevron-down"></iron-icon>
</template>
</div>
<iron-dropdown
id="dropdown"
class="dropdown"
auto-fit-on-attach
fit-into="{{_getElement(boundTarget)}}"
no-overlap
dynamic-align
opened="{{opened}}"
hover="{{hover}}"
no-cancel-on-outside-click="{{preventCloseOnOutsideClick}}"
allow-outside-scroll="{{allowOutsideScroll}}"
disabled$="{{disabled}}">
<div class="dropdown-content shadow-temporary">
<template is="dom-if" if="{{searchMode}}" value="{{searchTerm::input}}">
<div class="u-p-">
<input id="searchbox" class="text-input input--search" type="text" value="{{searchTerm::input}}" on-input="_notifyResize">
</div>
</template>
<iron-selector
id="selector"
multi="{{multi}}"
selected={{selected}}
selected-values={{selectedValues}}
selected-items={{selectedItems}}
attr-for-selected="{{selectBy}}">
<template is="dom-repeat" id="dropdownItems" items="{{items}}" filter="{{_computeFilter(searchTerm)}}" delay="100" strip-whitespace>
<div class="dropdown-option" key="{{item.key}}" val="{{item.val}}" disabled$="{{item.disabled}}" on-mouseover="_hoverOn" on-mouseout="_hoverOff" title="{{item.val}}">
<template is="dom-if" if="{{multi}}">
<iron-icon icon="px:check"></iron-icon>
<span class="dropdown-option__item truncate">{{item.val}}</span>
</template>
<template is="dom-if" if="{{!multi}}"><span class="dropdown-option__item truncate">{{item.val}}</span></template>
</div>
</template>
</iron-selector>
</div>
</iron-dropdown>
</template>
</dom-module>
<script>
Polymer({
is: 'px-dropdown',
properties: {
/**
* A flag which reflects if the dropdown trigger has been clicked or not.
*/
opened: {
type: Boolean,
notify: true,
value: false
},
/**
* A flag which reflects whether the dropdown is being hovered over.
*/
hover: {
type: Boolean,
notify: true,
value: false
},
/**
* Returns the currently focused item in the dropdown list.
*/
focusedItem: {
observer: '_focusedItemChanged',
readOnly: true,
type: Object
},
/**
* Whether or not to hide the chevron icon from the dropdown.
*/
hideChevron: {
type: Boolean,
value: false
},
/**
* A CSS selector which specifies the bounding target the dropdown will be
* displayed within. Defaults to `window`.
*/
boundTarget: {
type: String
},
/**
* Whether the dropdown will close when a user clicks
* outside of it. Set to true to prevent dropdown from closing.
*/
preventCloseOnOutsideClick: {
type: Boolean,
value: false
},
/**
* The placeholder text to display in the dropdown. If the
* selected value(s) are cleared out, the displayValue will be
* replaced in the dropdown.
*/
displayValue: {
type: String,
notify: true,
value: 'Select',
observer: '_displayValueChanged'
},
/**
* The text that is displayed in the label of the dropdown.
* Updated when the selections change.
*/
_displayValueSelected: {
type: String
},
/**
* An array that contains the list of items which show up in the dropdown.
* Each item can either be a simple string, or an object consisting of:
* * 'key' - a unique identifier (number or string)
* * 'val' - the actual text that is displayed
* * 'disabled' - whether the item should be disabled for selection (optional)
* * 'selected' - whether the item should be selected at instantiation (optional)
*/
items: {
type: Array,
notify: true,
value: function () {
return [];
},
observer: '_itemsChanged'
},
/**
* If set to true, multiple values can be selected in the dropdown.
* Selected values are reflected in the `selectedValues` property.
* If set to false, a single selected value is reflected in `selected`.
*/
multi: {
type: Boolean,
value: false
},
/**
* Which property of each dropdown item will be used to get/set
* the selected items - should be one of "key" or "val".
*/
selectBy: {
type: String,
value: 'key',
observer: '_updateSelection'
},
/**
* Gets or sets the selected item when `multi` is false.
* Will either be a single key or value based on `selectBy`.
*/
selected: {
type: String,
value: null,
notify: true
},
/**
* Gets or sets the selected items when `multi` is true.
* Will either be an array of keys or values based on `selectBy`.
*/
selectedValues: {
type: Array,
value: function() {
return [];
},
notify: true
},
/**
* A read-only array of the selected `<div>` elements in the dropdown.
*/
selectedItems: {
type: Array,
value: function() {
return [];
},
readOnly: true
},
/**
* By default, the dropdown will constrain scrolling on the page to
* itself when opened. Set to true in order to allow scrolling of
* the page while the dropdown is open.
*/
allowOutsideScroll: {
type: Boolean,
value: false
},
/**
* Style for the button that invokes the dropdown.
* One of 'default','bare','bare--primary', or 'tertiary'.
*/
buttonStyle: {
type: String,
value: 'default'
},
/**
* Whether the dropdown should be disabled and non-interactive.
*/
disabled: {
type: Boolean,
value: false
},
/**
* If true, the dropdown will include a search box, whereby the
* dropdown items can be filtered with a search term.
*/
searchMode: {
type: Boolean,
value: false
},
/**
* The value of the search box, used for filtering the dropdown
* items when searchMode is true.
*/
searchTerm: {
type: String,
value: ''
},
/**
* What to sort the dropdown items by - one of "key" or "val".
* By default, the items will be displayed in the order they are
* passed into the component.
*/
sortMode: {
type: String
},
/**
* If set to true, the display-value will always show up in the
* invoking button of the dropdown. Useful in cases like the
* px-data-table, where "Show/Hide Columns" should always appear.
*/
hideSelected: {
type: Boolean,
value: false
},
/**
* Binding target for iron-a11y-keys
*/
_keyBindingsTarget: {
type: Object,
value: function () {
return this;
}
},
/**
* The currently "focused" option in the dropdown list.
* Used for handling of keyboard events.
*/
_focusedOption: {
type: HTMLElement
},
/**
* Used to capture if the user is using the keyboard to interact with the dropdown.
* Used to disable all mouse events.
*/
_keyboardBeingUsed: {
type: Boolean,
value: false
}
},
listeners: {
'iron-activate' : '_ignoreDisabled',
'iron-select' : '_handleSelection',
'iron-deselect' : '_handleDeselection'
},
observers: [
'_initSort(sortMode, items)'
],
/**
* Opens the dropdown when the button is pressed.
*/
toggle: function() {
this.$.dropdown.toggle();
this.$.dropdown.style.minWidth = window.getComputedStyle(this.$.button).width;
},
/**
* Clears all of the selections when the clear button is pressed.
*/
_clear: function(evt) {
evt.stopPropagation();
this.set('selected', null);
this.set('selectedValues', []);
if(this.multi) {
Polymer.dom(this.$.dropdown).querySelectorAll('input#option:checked').forEach(function(item) {
item.checked = false;
});
}
this.$.dropdown.close();
},
/**
* Forces the width of the dropdown to be at least as wide as the button.
*/
attached: function() {
this.$.dropdown.style.minWidth = window.getComputedStyle(this.$.button).width;
this._updateSelection();
},
/**
* Calculates the class for a disabled dropdown.
*/
_getDisabledClass: function() {
return this.disabled ? 'btn--disabled' : '';
},
/**
* Calculates the class for a bare dropdown.
*/
_getClass: function() {
if(this.buttonStyle === 'bare') return 'btn--bare u-pr0';
else if(this.buttonStyle === 'bare--primary') return 'btn--bare--primary u-pr0';
else if(this.buttonStyle === 'tertiary') return 'btn--tertiary';
else return ''
},
/**
* Searches the DOM for the `boundTarget` element.
*/
_getElement: function(target) {
return Polymer.dom(document).querySelector(target);
},
/**
* When `displayValue` update `_displayValueSelected`
*/
_displayValueChanged: function(){
this._displayValueSelected = this.displayValue;
},
/**
* Any time that `items` changes, this method will convert an array
* of simple strings to an array of objects.
*/
_itemsChanged: function(items) {
if(items[0] && typeof items[0] === 'string') {
var computedItems = [];
items.forEach(function(item, idx) {
computedItems.push({"key":idx, "val":item});
})
this.items = computedItems;
}
this._updateSelection();
},
/**
* Iterates over the `items` array and adds items with the
* `selected` property to the `selectedValues` array. Overridden
* by any existing selections in `selectedValues`.
*/
_updateSelection: function() {
if(this.multi && this.items && this.items.length > 0 && this.selectedValues && this.selectedValues.length === 0) {
var length = this.items.length,
selected = [],
i;
for(i=0; i<length; i++) {
if(this.items[i].selected !== undefined && this.items[i].selected.toString() === 'true') {
selected.push(this.items[i][this.selectBy]);
}
}
this.set('selectedValues', selected);
if(!this.hideSelected && this.selectedValues.length > 0) {
this._displayValueSelected = this.selectedValues.length + ' selected';
}
else {
this._displayValueSelected = this.displayValue;
}
}
},
/**
* When iron-activate is fired, this method checks whether the item is disabled.
* If so, it cancels the event so that iron-select is not called.
*/
_ignoreDisabled: function(evt) {
if(evt.detail.item.hasAttribute('disabled')) {
evt.preventDefault();
}
},
/**
* Handles the selection event from iron-selector to update
* the label displayed inside the dropdown.
*/
_handleSelection: function(evt) {
if(this.multi && this.selectedValues.length === 1 && !this.hideSelected) {
this._displayValueSelected = this.$.selector.selectedItems[0].innerText.trim();
}
else if(this.multi && this.selectedValues.length > 1 && !this.hideSelected) {
this._displayValueSelected = this.selectedValues.length + ' selected';
}
else if(!this.hideSelected) {
this._displayValueSelected = this.$.selector.selectedItem ? this.$.selector.selectedItem.val : this.displayValue;
this.$.dropdown.close();
}
this.$.dropdown.notifyResize();
/**
* Event fired when any given element is selected or deselected in the list.
* `evt.detail` contains:
* ```
* { val: "text of the changed element",
* key: "key of the changed element",
* selected: true/false }
* ```
* @event px-dropdown-selection-changed
*/
this.fire('px-dropdown-selection-changed', {
val: evt.detail.item.val,
key: evt.detail.item.key,
selected: true
});
},
/**
* Handles the de-selection event from iron-selector to update
* the label displayed inside the dropdown.
*/
_handleDeselection: function(evt) {
if(this.multi && this.$.selector.selectedItems.length === 1 && !this.hideSelected) {
this._displayValueSelected = this.$.selector.selectedItems[0].innerText.trim();
}
else if(this.multi && this.selectedValues.length > 1 && !this.hideSelected) {
this._displayValueSelected = this.selectedValues.length + ' selected';
}
else {
this._displayValueSelected = this.displayValue;
}
this.$.dropdown.notifyResize();
/**
* Event fired when any given element is selected or deselected in the list.
* `evt.detail` contains:
* ```
* { val: "text of the changed element",
* key: "key of the changed element",
* selected: true/false }
* ```
* @event px-dropdown-selection-changed
*/
this.fire('px-dropdown-selection-changed', {
val: evt.detail.item.val,
key: evt.detail.item.key,
selected: false
});
},
/**
* Resizes the dropdown when the search term is changed.
*/
_notifyResize: function() {
this.$.dropdown.notifyResize();
},
/**
* Filter function used by the dom-repeat inside the iron-selector,
* based on the searchTerm entered in the search box.
*/
_computeFilter: function (searchTerm) {
if (!this.searchMode || !searchTerm.length) {
return null;
} else {
searchTerm = searchTerm.toLowerCase();
return function (entry) {
return entry.val.toString().toLowerCase().indexOf(searchTerm) != -1 || entry.key.toString().toLowerCase().indexOf(searchTerm) != -1;
};
}
},
/**
* Determines whether to display the clear button inside the dropdown.
*/
_showClearButton: function(opened, selected, selectedValues) {
return (opened && (typeof selected === 'string' || typeof selected === 'number' || selectedValues.length > 0));
},
/**
* Determines whether to display the chevron button inside the dropdown.
*/
_showChevron: function(hideChevron, opened, selected, selectedValues) {
return !hideChevron && (!opened || (opened && !selected && selectedValues.length === 0));
},
/**
* Initializes the sort function for the dom-repeat inside of iron-selector.
*/
_initSort: function () {
this.$.dropdownItems.sort = '_computeSort';
this.$.dropdownItems.render();
},
/**
* Event handler for mouse move event. We enable mouse events when user moves the mouse.
* Mouse events are disabled when user uses the keyboard to interact with the dropdown.
* @private
*/
_bindMouse: function () {
this._keyboardBeingUsed = false;
this.$.dropdown.classList.remove('no-mouse-event');
this.removeEventListener('mousemove', this._bindMouse);
},
/**
* The sort function used by the dom-repeat inside of iron-selector to
* sort the items by either 'key' or 'val' based on `sortMode`.
*/
_computeSort: function (a, b) {
var sortValue = 0;
if (!this.sortMode) {
return -1;
}
if (this.sortMode && sortValue === 0) {
if (this.sortMode === 'key') {
sortValue = a.key - b.key;
}
if (this.sortMode === 'val') {
var nameA = a.val.toUpperCase(),
nameB = b.val.toUpperCase();
if (nameA < nameB) {
sortValue--;
}
if (nameA > nameB) {
sortValue++;
}
}
}
return sortValue;
},
/**
* Adds or removes the focused class for keyboard navigation.
*/
_setFocusedOption: function(newOption, oldOption) {
this._focusedOption = newOption;
if(newOption) {
this.toggleClass('focused',true,newOption);
}
if(oldOption) {
this.toggleClass('focused',false,oldOption);
}
},
/**
* Keypress event handler for iron-a11y-keys.
*/
_handleKeyPress: function (event) {
this._keyboardBeingUsed = true;
var keyPressed = event.detail.combo,
options = this.$.selector.getEffectiveChildren().filter(function(node) {
return (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'DIV'
&& !node.hasAttribute('disabled'));
}),
focused = options.indexOf(this._focusedOption),
searchFocused = this.searchMode && Polymer.dom(this.$.dropdown).querySelector(':focus') === Polymer.dom(this.$.dropdown).querySelector('#searchbox');
switch (keyPressed) {
case 'space':
case 'enter':
if(searchFocused) break;
// If closed, open it
if(!this.opened) {
this.toggle();
}
// If opened, select currently focused item
else if(focused !== -1) {
options[focused].click();
}
event.detail.keyboardEvent.preventDefault();
break;
case 'esc':
this.$.button.focus();
this.$.dropdown.close();
break;
case 'tab':
// Close dropdown and (default behavior) move to next item
if(this.opened) {
this.$.dropdown.close();
}
break;
case 'down':
// If closed, open it
if(!this.opened) {
this.toggle();
}
// If something is focused, move to the next sibling
if(focused > -1 && focused < options.length - 1) {
this._setFocusedOption(options[focused + 1], options[focused]);
this.$.dropdown.querySelector('.dropdown-content').scrollTop += options[focused+1].offsetHeight;
}
// If last element is focused, do nothing
else if (focused === options.length - 1) {
break;
}
// If nothing is focused and search-mode is true, move to the search box
else if (focused === -1 && this.searchMode && !searchFocused) {
Polymer.dom(this.$.dropdown).querySelector('#searchbox').focus();
}
// If searchbox is focused, move to the first option
else if (searchFocused) {
Polymer.dom(this.$.dropdown).querySelector('#searchbox').blur();
this.$.button.focus();
this._setFocusedOption(options[0]);
}
// Else focus the first item in the list
else {
this._setFocusedOption(options[0]);
}
event.detail.keyboardEvent.preventDefault();
break;
case 'up':
// If closed, open it
if(!this.opened) {
this.toggle();
}
// If something is focused, move to the previous sibling
if(focused > 0) {
this._setFocusedOption(options[focused - 1], options[focused]);
Polymer.dom(this.$.dropdown).querySelector('.dropdown-content').scrollTop -= options[focused].offsetHeight;
}
// If the first item is focused and search-mode is true, move to the search box
else if (focused === 0 && this.searchMode && !searchFocused) {
Polymer.dom(this.$.dropdown).querySelector('#searchbox').focus();
this._setFocusedOption(null, options[0]);
}
// Else focus the last item in the list
else if (focused === -1 && !searchFocused) {
this._setFocusedOption(options[options.length - 1]);
}
event.detail.keyboardEvent.preventDefault();
break;
}
},
/**
* Event handler when the mouse hovers over a dropdown list item.
*/
_hoverOn: function (event) {
if (!this._keyboardBeingUsed) {
var currHighlightedItem = this.querySelector('.dropdown-option.focused');
if (currHighlightedItem) {
this.toggleClass('focused',false,currHighlightedItem);
}
this.toggleClass('focused',true,Polymer.dom(event).localTarget);
}
},
/**
* Event handler when the mouse hovers out of a dropdown list item.
*/
_hoverOff: function (event) {
this.toggleClass('focused',false,Polymer.dom(event).localTarget);
}
});
</script>