kmaterialize 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/js/select.js ADDED
@@ -0,0 +1,450 @@
1
+ (function($) {
2
+ 'use strict';
3
+
4
+ let _defaults = {
5
+ classes: '',
6
+ dropdownOptions: {}
7
+ };
8
+
9
+ /**
10
+ * @class
11
+ *
12
+ */
13
+ class FormSelect extends Component {
14
+ /**
15
+ * Construct FormSelect instance
16
+ * @constructor
17
+ * @param {Element} el
18
+ * @param {Object} options
19
+ */
20
+ constructor(el, options) {
21
+ super(FormSelect, el, options);
22
+
23
+ // Don't init if browser default version
24
+ if (this.$el.hasClass('browser-default')) {
25
+ return;
26
+ }
27
+
28
+ this.el.M_FormSelect = this;
29
+
30
+ /**
31
+ * Options for the select
32
+ * @member FormSelect#options
33
+ */
34
+ this.options = $.extend({}, FormSelect.defaults, options);
35
+
36
+ this.isMultiple = this.$el.prop('multiple');
37
+
38
+ // Setup
39
+ this.el.tabIndex = -1;
40
+ this._keysSelected = {};
41
+ this._valueDict = {}; // Maps key to original and generated option element.
42
+ this._setupDropdown();
43
+
44
+ this._setupEventHandlers();
45
+ }
46
+
47
+ static get defaults() {
48
+ return _defaults;
49
+ }
50
+
51
+ static init(els, options) {
52
+ return super.init(this, els, options);
53
+ }
54
+
55
+ /**
56
+ * Get Instance
57
+ */
58
+ static getInstance(el) {
59
+ let domElem = !!el.jquery ? el[0] : el;
60
+ return domElem.M_FormSelect;
61
+ }
62
+
63
+ /**
64
+ * Teardown component
65
+ */
66
+ destroy() {
67
+ this._removeEventHandlers();
68
+ this._removeDropdown();
69
+ this.el.M_FormSelect = undefined;
70
+ }
71
+
72
+ /**
73
+ * Setup Event Handlers
74
+ */
75
+ _setupEventHandlers() {
76
+ this._handleSelectChangeBound = this._handleSelectChange.bind(this);
77
+ this._handleOptionClickBound = this._handleOptionClick.bind(this);
78
+ this._handleInputClickBound = this._handleInputClick.bind(this);
79
+
80
+ $(this.dropdownOptions)
81
+ .find('li:not(.optgroup)')
82
+ .each((el) => {
83
+ el.addEventListener('click', this._handleOptionClickBound);
84
+ });
85
+ this.el.addEventListener('change', this._handleSelectChangeBound);
86
+ this.input.addEventListener('click', this._handleInputClickBound);
87
+ }
88
+
89
+ /**
90
+ * Remove Event Handlers
91
+ */
92
+ _removeEventHandlers() {
93
+ $(this.dropdownOptions)
94
+ .find('li:not(.optgroup)')
95
+ .each((el) => {
96
+ el.removeEventListener('click', this._handleOptionClickBound);
97
+ });
98
+ this.el.removeEventListener('change', this._handleSelectChangeBound);
99
+ this.input.removeEventListener('click', this._handleInputClickBound);
100
+ }
101
+
102
+ /**
103
+ * Handle Select Change
104
+ * @param {Event} e
105
+ */
106
+ _handleSelectChange(e) {
107
+ this._setValueToInput();
108
+ }
109
+
110
+ /**
111
+ * Handle Option Click
112
+ * @param {Event} e
113
+ */
114
+ _handleOptionClick(e) {
115
+ e.preventDefault();
116
+ let optionEl = $(e.target).closest('li')[0];
117
+ this._selectOption(optionEl);
118
+ e.stopPropagation();
119
+ }
120
+
121
+ _selectOption(optionEl) {
122
+ let key = optionEl.id;
123
+ if (!$(optionEl).hasClass('disabled') && !$(optionEl).hasClass('optgroup') && key.length) {
124
+ let selected = true;
125
+
126
+ if (this.isMultiple) {
127
+ // Deselect placeholder option if still selected.
128
+ let placeholderOption = $(this.dropdownOptions).find('li.disabled.selected');
129
+ if (placeholderOption.length) {
130
+ placeholderOption.removeClass('selected');
131
+ placeholderOption.find('input[type="checkbox"]').prop('checked', false);
132
+ this._toggleEntryFromArray(placeholderOption[0].id);
133
+ }
134
+ selected = this._toggleEntryFromArray(key);
135
+ } else {
136
+ $(this.dropdownOptions)
137
+ .find('li')
138
+ .removeClass('selected');
139
+ $(optionEl).toggleClass('selected', selected);
140
+ this._keysSelected = {};
141
+ this._keysSelected[optionEl.id] = true;
142
+ }
143
+
144
+ // Set selected on original select option
145
+ // Only trigger if selected state changed
146
+ let prevSelected = $(this._valueDict[key].el).prop('selected');
147
+ if (prevSelected !== selected) {
148
+ $(this._valueDict[key].el).prop('selected', selected);
149
+ this.$el.trigger('change');
150
+ }
151
+ }
152
+
153
+ if (!this.isMultiple) {
154
+ this.dropdown.close();
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Handle Input Click
160
+ */
161
+ _handleInputClick() {
162
+ if (this.dropdown && this.dropdown.isOpen) {
163
+ this._setValueToInput();
164
+ this._setSelectedStates();
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Setup dropdown
170
+ */
171
+ _setupDropdown() {
172
+ this.wrapper = document.createElement('div');
173
+ $(this.wrapper).addClass('select-wrapper ' + this.options.classes);
174
+ this.$el.before($(this.wrapper));
175
+ // Move actual select element into overflow hidden wrapper
176
+ let $hideSelect = $('<div class="hide-select"></div>');
177
+ $(this.wrapper).append($hideSelect);
178
+ $hideSelect[0].appendChild(this.el);
179
+
180
+ if (this.el.disabled) {
181
+ this.wrapper.classList.add('disabled');
182
+ }
183
+
184
+ // Create dropdown
185
+ this.$selectOptions = this.$el.children('option, optgroup');
186
+ this.dropdownOptions = document.createElement('ul');
187
+ this.dropdownOptions.id = `select-options-${M.guid()}`;
188
+ $(this.dropdownOptions).addClass(
189
+ 'dropdown-content select-dropdown ' + (this.isMultiple ? 'multiple-select-dropdown' : '')
190
+ );
191
+
192
+ // Create dropdown structure.
193
+ if (this.$selectOptions.length) {
194
+ this.$selectOptions.each((el) => {
195
+ if ($(el).is('option')) {
196
+ // Direct descendant option.
197
+ let optionEl;
198
+ if (this.isMultiple) {
199
+ optionEl = this._appendOptionWithIcon(this.$el, el, 'multiple');
200
+ } else {
201
+ optionEl = this._appendOptionWithIcon(this.$el, el);
202
+ }
203
+
204
+ this._addOptionToValueDict(el, optionEl);
205
+ } else if ($(el).is('optgroup')) {
206
+ // Optgroup.
207
+ let selectOptions = $(el).children('option');
208
+ $(this.dropdownOptions).append(
209
+ $('<li class="optgroup"><span>' + el.getAttribute('label') + '</span></li>')[0]
210
+ );
211
+
212
+ selectOptions.each((el) => {
213
+ let optionEl = this._appendOptionWithIcon(this.$el, el, 'optgroup-option');
214
+ this._addOptionToValueDict(el, optionEl);
215
+ });
216
+ }
217
+ });
218
+ }
219
+
220
+ $(this.wrapper).append(this.dropdownOptions);
221
+
222
+ // Add input dropdown
223
+ this.input = document.createElement('input');
224
+ $(this.input).addClass('select-dropdown dropdown-trigger');
225
+ this.input.setAttribute('type', 'text');
226
+ this.input.setAttribute('readonly', 'true');
227
+ this.input.setAttribute('data-target', this.dropdownOptions.id);
228
+ if (this.el.disabled) {
229
+ $(this.input).prop('disabled', 'true');
230
+ }
231
+
232
+ $(this.wrapper).prepend(this.input);
233
+ this._setValueToInput();
234
+
235
+ // Add caret
236
+ let dropdownIcon = $(
237
+ '<svg class="caret" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"/><path d="M0 0h24v24H0z" fill="none"/></svg>'
238
+ );
239
+ $(this.wrapper).prepend(dropdownIcon[0]);
240
+
241
+ // Initialize dropdown
242
+ if (!this.el.disabled) {
243
+ let dropdownOptions = $.extend({}, this.options.dropdownOptions);
244
+ let userOnOpenEnd = dropdownOptions.onOpenEnd;
245
+
246
+ // Add callback for centering selected option when dropdown content is scrollable
247
+ dropdownOptions.onOpenEnd = (el) => {
248
+ let selectedOption = $(this.dropdownOptions)
249
+ .find('.selected')
250
+ .first();
251
+
252
+ if (selectedOption.length) {
253
+ // Focus selected option in dropdown
254
+ M.keyDown = true;
255
+ this.dropdown.focusedIndex = selectedOption.index();
256
+ this.dropdown._focusFocusedItem();
257
+ M.keyDown = false;
258
+
259
+ // Handle scrolling to selected option
260
+ if (this.dropdown.isScrollable) {
261
+ let scrollOffset =
262
+ selectedOption[0].getBoundingClientRect().top -
263
+ this.dropdownOptions.getBoundingClientRect().top; // scroll to selected option
264
+ scrollOffset -= this.dropdownOptions.clientHeight / 2; // center in dropdown
265
+ this.dropdownOptions.scrollTop = scrollOffset;
266
+ }
267
+ }
268
+
269
+ // Handle user declared onOpenEnd if needed
270
+ if (userOnOpenEnd && typeof userOnOpenEnd === 'function') {
271
+ userOnOpenEnd.call(this.dropdown, this.el);
272
+ }
273
+ };
274
+
275
+ // Prevent dropdown from closeing too early
276
+ dropdownOptions.closeOnClick = false;
277
+
278
+ this.dropdown = M.Dropdown.init(this.input, dropdownOptions);
279
+ }
280
+
281
+ // Add initial selections
282
+ this._setSelectedStates();
283
+ }
284
+
285
+ /**
286
+ * Add option to value dict
287
+ * @param {Element} el original option element
288
+ * @param {Element} optionEl generated option element
289
+ */
290
+ _addOptionToValueDict(el, optionEl) {
291
+ let index = Object.keys(this._valueDict).length;
292
+ let key = this.dropdownOptions.id + index;
293
+ let obj = {};
294
+ optionEl.id = key;
295
+
296
+ obj.el = el;
297
+ obj.optionEl = optionEl;
298
+ this._valueDict[key] = obj;
299
+ }
300
+
301
+ /**
302
+ * Remove dropdown
303
+ */
304
+ _removeDropdown() {
305
+ $(this.wrapper)
306
+ .find('.caret')
307
+ .remove();
308
+ $(this.input).remove();
309
+ $(this.dropdownOptions).remove();
310
+ $(this.wrapper).before(this.$el);
311
+ $(this.wrapper).remove();
312
+ }
313
+
314
+ /**
315
+ * Setup dropdown
316
+ * @param {Element} select select element
317
+ * @param {Element} option option element from select
318
+ * @param {String} type
319
+ * @return {Element} option element added
320
+ */
321
+ _appendOptionWithIcon(select, option, type) {
322
+ // Add disabled attr if disabled
323
+ let disabledClass = option.disabled ? 'disabled ' : '';
324
+ let optgroupClass = type === 'optgroup-option' ? 'optgroup-option ' : '';
325
+ let multipleCheckbox = this.isMultiple
326
+ ? `<label><input type="checkbox"${disabledClass}"/><span>${option.innerHTML}</span></label>`
327
+ : option.innerHTML;
328
+ let liEl = $('<li></li>');
329
+ let spanEl = $('<span></span>');
330
+ spanEl.html(multipleCheckbox);
331
+ liEl.addClass(`${disabledClass} ${optgroupClass}`);
332
+ liEl.append(spanEl);
333
+
334
+ // add icons
335
+ let iconUrl = option.getAttribute('data-icon');
336
+ if (!!iconUrl) {
337
+ let imgEl = $(`<img alt="" src="${iconUrl}">`);
338
+ liEl.prepend(imgEl);
339
+ }
340
+
341
+ // Check for multiple type.
342
+ $(this.dropdownOptions).append(liEl[0]);
343
+ return liEl[0];
344
+ }
345
+
346
+ /**
347
+ * Toggle entry from option
348
+ * @param {String} key Option key
349
+ * @return {Boolean} if entry was added or removed
350
+ */
351
+ _toggleEntryFromArray(key) {
352
+ let notAdded = !this._keysSelected.hasOwnProperty(key);
353
+ let $optionLi = $(this._valueDict[key].optionEl);
354
+
355
+ if (notAdded) {
356
+ this._keysSelected[key] = true;
357
+ } else {
358
+ delete this._keysSelected[key];
359
+ }
360
+
361
+ $optionLi.toggleClass('selected', notAdded);
362
+
363
+ // Set checkbox checked value
364
+ $optionLi.find('input[type="checkbox"]').prop('checked', notAdded);
365
+
366
+ // use notAdded instead of true (to detect if the option is selected or not)
367
+ $optionLi.prop('selected', notAdded);
368
+
369
+ return notAdded;
370
+ }
371
+
372
+ /**
373
+ * Set text value to input
374
+ */
375
+ _setValueToInput() {
376
+ let values = [];
377
+ let options = this.$el.find('option');
378
+
379
+ options.each((el) => {
380
+ if ($(el).prop('selected')) {
381
+ let text = $(el).text();
382
+ values.push(text);
383
+ }
384
+ });
385
+
386
+ if (!values.length) {
387
+ let firstDisabled = this.$el.find('option:disabled').eq(0);
388
+ if (firstDisabled.length && firstDisabled[0].value === '') {
389
+ values.push(firstDisabled.text());
390
+ }
391
+ }
392
+
393
+ this.input.value = values.join(', ');
394
+ }
395
+
396
+ /**
397
+ * Set selected state of dropdown to match actual select element
398
+ */
399
+ _setSelectedStates() {
400
+ this._keysSelected = {};
401
+
402
+ for (let key in this._valueDict) {
403
+ let option = this._valueDict[key];
404
+ let optionIsSelected = $(option.el).prop('selected');
405
+ $(option.optionEl)
406
+ .find('input[type="checkbox"]')
407
+ .prop('checked', optionIsSelected);
408
+ if (optionIsSelected) {
409
+ this._activateOption($(this.dropdownOptions), $(option.optionEl));
410
+ this._keysSelected[key] = true;
411
+ } else {
412
+ $(option.optionEl).removeClass('selected');
413
+ }
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Make option as selected and scroll to selected position
419
+ * @param {jQuery} collection Select options jQuery element
420
+ * @param {Element} newOption element of the new option
421
+ */
422
+ _activateOption(collection, newOption) {
423
+ if (newOption) {
424
+ if (!this.isMultiple) {
425
+ collection.find('li.selected').removeClass('selected');
426
+ }
427
+ let option = $(newOption);
428
+ option.addClass('selected');
429
+ }
430
+ }
431
+
432
+ /**
433
+ * Get Selected Values
434
+ * @return {Array} Array of selected values
435
+ */
436
+ getSelectedValues() {
437
+ let selectedValues = [];
438
+ for (let key in this._keysSelected) {
439
+ selectedValues.push(this._valueDict[key].el.value);
440
+ }
441
+ return selectedValues;
442
+ }
443
+ }
444
+
445
+ M.FormSelect = FormSelect;
446
+
447
+ if (M.jQueryLoaded) {
448
+ M.initializeJqueryWrapper(FormSelect, 'formSelect', 'M_FormSelect');
449
+ }
450
+ })(cash);