-
Notifications
You must be signed in to change notification settings - Fork 1
/
selectize-wrapper.html
687 lines (614 loc) · 21.5 KB
/
selectize-wrapper.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
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../iron-icons/iron-icons.html">
<link rel="import" href="../paper-input/paper-input.html">
<link rel="import" href="../paper-icon-button/paper-icon-button.html">
<link rel="import" href="../ugo-jquery-deps/ugo-jquery-deps.html">
<link rel="stylesheet" href="../selectize/dist/css/selectize.css" />
<!-- <script src="../selectize/dist/js/standalone/selectize.min.js"></script> -->
<script src="../selectize/dist/js/standalone/selectize.min.js"></script>
<script type="text/javascript" src="../underscore/underscore-min.js"></script>
<link rel="stylesheet" href="selectize.override.css" />
<!--
Forked and extended from [selectize-decorator](https://github.com/display-interactive/selectize-decorator).
Wrapper around [Selectize.js](https://github.com/brianreavis/selectize.js), using
a `paper-input-container` as the main input element to give it a more 'Polymerish' look.
Please find the usage scenarios in the demo/index.html file. It also contains comments.
Examples:
<selectize-wrapper id="ajax1"
ajax-options-url="cities.json"
ajax-result-transformer="{{cityResultTransformer}}">
</selectize-wrapper>
<selectize-wrapper id="ajax2"
value-field="url"
label-field="name"
search-fields="{{searchFields}}"
load-fn="{{loadFn}}"
render="{{renderObjGithub}}"
max-items="100"
load-throttle="200">
</selectize-wrapper>
@element selectize-wrapper
@demo demo/index.html
-->
<!--
Fired when the user selects (via mouse or keyboard) a particular suggestion from the dropdown list.
@event selectize-wrapper-add
-->
<!--
Fired when the user removes a particular item from previously selected items.
<p>
The event will be turned into a Polymer
@event selectize-wrapper-remove
-->
<dom-module name="selectize-wrapper">
<template>
<paper-input-container id='input'>
<label>
<span hidden$='{{_hideLabel}}'>{{label}}</span>
<span hidden$='{{_hidePlaceholder}}'>{{placeholder}}</span>
</label>
<input id='rawInput' is="iron-input" class='spinner'>
<content select='paper-icon-button'></content>
<paper-input-error id='errorMessage'>Please select a value</paper-input-error>
</paper-input-container>
</template>
</dom-module>
<script>
Polymer({
is: 'selectize-wrapper',
behaviors: [
Polymer.IronFormElementBehavior,
Polymer.IronValidatableBehavior
],
/**
* Fired when an option has been added to the selected items.
*
* @event selectize-wrapper-add
*/
/**
* Fired when a selected item is being removed.
*
* @event selectize-wrapper-remove
*/
/** @see https://github.com/brianreavis/selectize.js/blob/master/docs/usage.md */
properties: {
delimiter: {
type: String,
value: ','
},
diacritics: {
type: Boolean,
value: true
},
createOpt: {
type: Boolean,
value: false
},
createOnBlur: {
type: Boolean,
value: false
},
createFilter: {
type: String,
value: null
},
highlight: {
type: Boolean,
value: true
},
persist: {
type: Boolean,
value: true
},
openOnFocus: {
type: Boolean,
value: true
},
maxOptions: {
type: Number,
value: 1000
},
maxItems: {
type: Number,
value: 1
},
hideSelected: {
type: Boolean,
value: false
},
closeAfterSelect: {
type: Boolean,
value: false
},
allowEmptyOption: {
type: Boolean,
value: false
},
scrollDuration: {
type: Number,
value: 60
},
loadThrottle: {
type: Number,
value: 300
},
loadingClass: {
type: String,
value: 'loading'
},
preload: {
type: Boolean, //check if it works
value: false
},
dropdownParent: {
type: String,
value: null
},
addPrecedence: {
type: Boolean,
value: false
},
selectOnTab: {
type: Boolean,
value: false
},
options: {
type: Array,
value: function() { return []; }
},
items: {
type: Array,
notify: true,
value: function() { return []; }
},
optgroups: {
type: Array,
value: function() { return []; }
},
dataAttr: {
type: String,
value: 'data-data'
},
valueField: {
type: String,
value: 'value'
},
optgroupValueField: {
type: String,
value: 'value'
},
labelField: {
type: String,
value: 'text'
},
optgroupLabelField: {
type: String,
value: 'label'
},
optgroupField: {
type: String,
value: 'optgroup'
},
sortField: {
type: String,
value: '$order'
},
searchFields: {
type: Array,
value: function() { return ['text']; }
},
searchConjunction: {
type: String,
value: 'and'
},
lockOptgroupOrder: {
type: Boolean,
value: false
},
copyClassesToDropdown: {
type: Boolean,
value: true
},
ajaxOptionsUrl: {
type: String,
value: null
},
ajaxOptionsRoot: {
type: String,
value: null
},
ajaxOptionsDataType: {
type: String,
value: null
},
/**
* [plugins description]
* @type {Object}
*/
plugins: {
type: Array,
value: function() { return [ 'remove_button' ]; }
},
/**
* The body of the ajax request.
* Allows POST requests to send additional data.
*/
ajaxBodyObj: {
type: String
},
/**
* Ajax method to use for the request.
*/
ajaxMethod: {
type: String,
value: 'GET'
},
/**
* Function invoked whenever the user types into the input field.
* See https://github.com/brianreavis/selectize.js/blob/master/docs/usage.md#callbacks
* for more information on how to implement a score function.
*
* @attribute loadFn
* @type Function
*/
loadFn: {
type: Function
},
/**
* Function invoked to score the input.
* See https://github.com/brianreavis/selectize.js/blob/master/docs/usage.md#callbacks
* for more information on how to implement a score function.
*
* @type Function
*/
scoreFn: {
type: Function
},
/**
* Object which usually includes 2 functions (`item` and `option`) which
* determine how the options are rendered in the dropdown as well as
* how they appear when selected.
*
* See the demo/index.html on how to use this.
* See also https://github.com/brianreavis/selectize.js/blob/master/docs/usage.md#rendering
*/
render: {
type: Object,
value: undefined
},
/**
* Function defining how the received ajax results are transformed to
* the expected format by Selectize of `[{value: <value>, text: <label>}, ...]`.
*
* See the demo/index.html on how to use this.
* @attribute ajaxResultTransformer
* @type Function
*/
ajaxResultTransformer: {
type: Function
},
defaultResultTransformer: {
type: Function,
value: function() {
return function(data) {
var resultList = data.map(function(obj) {
return {value: obj, text: obj};
});
return resultList;
};
}
},
/**
* The label being displayed if no items have been selected yet.
* @attribute placeholder
* @type String
* @default ""
*/
placeholder: {
type: String,
value: ""
},
/**
* The label being displayed when items have been selected.
* @attribute label
* @type String
* @default ""
*/
label: {
type: String,
value: ""
},
/**
* Specifies whether the label is shown or not.
* Needed so that it looks decent while the dropdown is open.
* @attribute _hideLabel
* @type Boolean
* @default false
* @access private
*/
_hideLabel: {
type: Boolean,
value: false
},
/**
* Promise indicating whether this wrapper instance has been initialised.
* @attribute isInitialised
* @type Promise
*/
isInitialised: {
type: Promise
},
/**
* The value for this element.
*/
value: {
notify: true,
type: String
},
selectizeInstance: {
type: Object
}
},
/**
* Initializes the component. The easiest way to do this is to call this method
* from the hosting parent element's `ready` method. This is done in this particular
* way because binding values to non-primitive, i.e. functions for example, won't work
* as one might expect. The demo shows this more clearly.
*
* @method initialize
*/
initialize: function() {
var self = this;
var field = this.$.rawInput;
var userOptions = {
delimiter: this.delimiter
,diacritics: this.diacritics
,create: this.createOpt
,createOnBlur: this.createOnBlur
,createFilter: this.createFilter
,highlight: this.highlight
,persist: this.persist
,openOnFocus: this.openOnFocus
,maxOptions: this.maxOptions
,maxItems: this.maxItems
,hideSelected: this.hideSelected
,closeAfterSelect: this.closeAfterSelect
,alglowEmptyOption: this.allowEmptyOption
,scrollDuration: this.scrollDuration
,loadThrottle: this.loadThrottle
,loadingClass: this.loadingClass
,preload: this.preload
,dropdownParent: this.dropdownParent
,addPrecedence: this.addPrecedence
,score: this.scoreFn
,selectOnTab: this.selectOnTab
,load: this.loadFn
,options: this.options
,items: this.items
,optgroups: this.optgroups
,dataAttr: this.dataAttr
,valueField: this.valueField
,optgroupValueField: this.optgroupValueField
,labelField: this.labelField
,optgroupLabelField: this.optgroupLabelField
,optgroupField: this.optgroupField
,sortField: this.sortField
,searchField: this.searchFields
,searchConjunction: this.searchConjunction
,lockOptgroupOrder: this.lockOptgroupOrder
,copyClassesToDropdown: this.copyClassesToDropdown
,plugins: this.plugins
,render: this.render
};
this.isInitialised = new Promise(function(resolve, reject) {
if (null !== self.ajaxOptionsUrl) {
self._buildAjaxOptions(field, userOptions, arguments[0], arguments[1]);
} else {
self._createSelectizeInstance(field, userOptions, arguments[0]);
}
});
return this.isInitialised;
},
/**
* Builds the selectize instance based on the result from an ajax request.
*
* @param field The DOM input instance the selectize instance will be attached to
* @param userOptions The current selectize configuration options
* @access private
* @ method _buildAjaxOptions
*/
_buildAjaxOptions: function(field, userOptions, resolveFunction, rejectFunction) {
var self = this;
if (this.ajaxOptionsDataType) {
config.dataType = this.ajaxOptionsDataType;
}
var ajax = document.createElement('iron-ajax');
ajax.contentType = 'application/json';
ajax.url = this.ajaxOptionsUrl;
if (this.ajaxMethod) {
ajax.method = this.ajaxMethod.toUpperCase();
}
if (this.ajaxBody) {
ajax.body = this.ajaxBody;
}
ajax.generateRequest().completes.then(function success(resp) {
var dataValues = null;
if (self.ajaxOptionsRoot) {
dataValues = resp.response[self.ajaxOptionsRoot];
} else {
dataValues = resp.response;
}
if (self.ajaxResultTransformer) {
self.options = self.ajaxResultTransformer(dataValues);
userOptions.options = self.options;
} else {
self.options = self.defaultResultTransformer(dataValues);
userOptions.options = self.options;
}
self._createSelectizeInstance(field, userOptions, resolveFunction);
}, function error(err) {
rejectFunction(err);
});
},
/**
* Allows this instance to be initialised with values.
*/
initializeFromObject: function(obj) {
var self = this;
var config = obj.selectizeWrapper;
if (config) {
if (config.ajaxOptionsUrl) {
this.ajaxOptionsUrl = config.ajaxOptionsUrl;
}
if (config.ajaxMethod) {
this.ajaxMethod = config.ajaxMethod;
}
if (config.ajaxBody) {
this.ajaxBody = config.ajaxBody;
}
return this.initialize().then(function() {
if (config.items && _.keys(config.items).length > 0) {
// select the values in the 'select' list
_.forEach(config.items, function(item) {
self.addItem(item);
});
}
});
} else {
// console.log('Initialization using an object was invoked but no configuration was provided.');
// console.log('Will invoke simple initialization.');
return this.initialize();
}
},
/**
* Creates the selectize instance on the given field element.
* Also installs the needed event handlers.
* @method _createSelectizeInstance
* @access private
*/
_createSelectizeInstance: function(field, userOptions, resolveFunction) {
var instanceObj = jQuery(field).selectize(userOptions);
var selectizeInstance = instanceObj[0].selectize;
this._setSelectizeInstance(selectizeInstance);
this._showHideLabelAndPlaceholder(this.getSelectizeInstance().items.length);
this._installEventHandlers(this.getSelectizeInstance());
this._fireBlurIfNecessary();
// resolve this Promise
resolveFunction();
},
/**
* Adds an item to the currently selected items.
* @method addItem
* @param {String} value The value to add
*/
addItem: function(value) {
this.getSelectizeInstance().addItem(value, false);
this._setCurrentValue();
},
/**
* Removes an item from the currently selected items.
* @method removeItem
* @param {String} value The value to remove
*/
removeItem: function(value) {
this.getSelectizeInstance().removeItem(value, false);
this._setCurrentValue();
},
/**
*
*/
_setCurrentValue: function() {
// reference items from underlying selectize instance
this.items = this.getSelectizeInstance().items;
this.value = this.getSelectizeInstance().getValue();
},
// Overidden from Polymer.IronValidatableBehavior. Will set the `invalid`
// attribute automatically, which should be used for styling.
_getValidity: function() {
this._setCurrentValue();
var currentValue = this.value;
// indicates that it's an array because it has the join method
if (currentValue.join) {
this.value = currentValue.join();
} else {
this.value = currentValue;
}
var valid = !_.isUndefined(this.value) && !_.isEmpty(this.value);
this.$.errorMessage.update({invalid: !valid});
return valid;
},
/**
* @access private
*/
_setSelectizeInstance: function(instance) {
this.selectizeInstance = instance;
this._setCurrentValue();
},
getSelectizeInstance: function() {
return this.selectizeInstance;
},
_showHideLabelAndPlaceholder: function(propertyToCheck) {
// this._hideLabel = this.getSelectizeInstance().items.length === 0;
this._hideLabel = propertyToCheck === 0;
this._hidePlaceholder = !this._hideLabel
},
/**
* Installs the necessary event handlers. They convert the events thrown from
* the selectize instance into Polymer elements which then can be used
* in the normal declarative Polymer fashion. See the demo for an example.
* @method _installEventHandlers
* @access private
*/
_installEventHandlers: function(selectize) {
var self = this;
selectize.on('change', function(value) {
self._showHideLabelAndPlaceholder(self.getSelectizeInstance().items.length);
var numOfElements = self.getSelectizeInstance().items.length;
if (numOfElements === 1) {
// workaround if shadow-dom is enabled: if so, the above query
// for .input-content returns null because you can't 'see' inside
// of the shadow dom
self.$.input.alwaysFloatLabel = true;
} else if (numOfElements === 0) {
self.$.input.alwaysFloatLabel = false;
}
self._setCurrentValue();
self.fire('change-selectize-wrapper');
});
selectize.on('type', function(value) {
if (value) {
self._showHideLabelAndPlaceholder(value.length);
if (value.length > 0) {
// workaround if shadow-dom is enabled: if so, the above query
// for .input-content returns null because you can't 'see' inside
// of the shadow dom
self.$.input.alwaysFloatLabel = true;
} else if (!value || value.length === 0) {
self.$.input.alwaysFloatLabel = false;
}
self._setCurrentValue();
}
});
selectize.on('item_add', function(value, item) {
self._setCurrentValue();
self.fire('selectize-wrapper-add', {value: value});
});
selectize.on('item_remove', function(value, item) {
self._setCurrentValue();
self.fire('selectize-wrapper-remove', {value: value});
});
},
/**
* Will fire the blur event on the input element if items have been preselected.
* This is necessary so that the label transitions into the floating state (above the selected value).
*
* @method _fireBlurIfNecessary
* @access private
*/
_fireBlurIfNecessary: function() {
if (this.items && this.items.length > 0) {
this.$.input.fire('blur');
}
}
});
</script>