@drecchia/tom-select 2.5.2-virtual-scroll.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.
Files changed (164) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +104 -0
  3. package/dist/css/tom-select.bootstrap4.css +573 -0
  4. package/dist/css/tom-select.bootstrap5.css +612 -0
  5. package/dist/css/tom-select.css +405 -0
  6. package/dist/css/tom-select.default.css +497 -0
  7. package/dist/css/tom-select.default.css.map +1 -0
  8. package/dist/esm/plugins/caret_position/plugin.js +163 -0
  9. package/dist/esm/plugins/caret_position/plugin.js.map +1 -0
  10. package/dist/esm/plugins/change_listener/plugin.js +51 -0
  11. package/dist/esm/plugins/change_listener/plugin.js.map +1 -0
  12. package/dist/esm/plugins/checkbox_options/plugin.js +179 -0
  13. package/dist/esm/plugins/checkbox_options/plugin.js.map +1 -0
  14. package/dist/esm/plugins/clear_button/plugin.js +76 -0
  15. package/dist/esm/plugins/clear_button/plugin.js.map +1 -0
  16. package/dist/esm/plugins/drag_drop/plugin.js +220 -0
  17. package/dist/esm/plugins/drag_drop/plugin.js.map +1 -0
  18. package/dist/esm/plugins/dropdown_header/plugin.js +102 -0
  19. package/dist/esm/plugins/dropdown_header/plugin.js.map +1 -0
  20. package/dist/esm/plugins/dropdown_input/plugin.js +224 -0
  21. package/dist/esm/plugins/dropdown_input/plugin.js.map +1 -0
  22. package/dist/esm/plugins/input_autogrow/plugin.js +74 -0
  23. package/dist/esm/plugins/input_autogrow/plugin.js.map +1 -0
  24. package/dist/esm/plugins/local_virtual_scroll/plugin.js +305 -0
  25. package/dist/esm/plugins/local_virtual_scroll/plugin.js.map +1 -0
  26. package/dist/esm/plugins/no_active_items/plugin.js +26 -0
  27. package/dist/esm/plugins/no_active_items/plugin.js.map +1 -0
  28. package/dist/esm/plugins/no_backspace_delete/plugin.js +32 -0
  29. package/dist/esm/plugins/no_backspace_delete/plugin.js.map +1 -0
  30. package/dist/esm/plugins/optgroup_columns/plugin.js +86 -0
  31. package/dist/esm/plugins/optgroup_columns/plugin.js.map +1 -0
  32. package/dist/esm/plugins/remove_button/plugin.js +134 -0
  33. package/dist/esm/plugins/remove_button/plugin.js.map +1 -0
  34. package/dist/esm/plugins/restore_on_backspace/plugin.js +42 -0
  35. package/dist/esm/plugins/restore_on_backspace/plugin.js.map +1 -0
  36. package/dist/esm/plugins/virtual_scroll/plugin.js +272 -0
  37. package/dist/esm/plugins/virtual_scroll/plugin.js.map +1 -0
  38. package/dist/js/plugins/caret_position.js +171 -0
  39. package/dist/js/plugins/caret_position.js.map +1 -0
  40. package/dist/js/plugins/change_listener.js +59 -0
  41. package/dist/js/plugins/change_listener.js.map +1 -0
  42. package/dist/js/plugins/checkbox_options.js +187 -0
  43. package/dist/js/plugins/checkbox_options.js.map +1 -0
  44. package/dist/js/plugins/clear_button.js +84 -0
  45. package/dist/js/plugins/clear_button.js.map +1 -0
  46. package/dist/js/plugins/drag_drop.js +228 -0
  47. package/dist/js/plugins/drag_drop.js.map +1 -0
  48. package/dist/js/plugins/dropdown_header.js +110 -0
  49. package/dist/js/plugins/dropdown_header.js.map +1 -0
  50. package/dist/js/plugins/dropdown_input.js +232 -0
  51. package/dist/js/plugins/dropdown_input.js.map +1 -0
  52. package/dist/js/plugins/input_autogrow.js +82 -0
  53. package/dist/js/plugins/input_autogrow.js.map +1 -0
  54. package/dist/js/plugins/local_virtual_scroll.js +313 -0
  55. package/dist/js/plugins/local_virtual_scroll.js.map +1 -0
  56. package/dist/js/plugins/no_active_items.js +34 -0
  57. package/dist/js/plugins/no_active_items.js.map +1 -0
  58. package/dist/js/plugins/no_backspace_delete.js +40 -0
  59. package/dist/js/plugins/no_backspace_delete.js.map +1 -0
  60. package/dist/js/plugins/optgroup_columns.js +94 -0
  61. package/dist/js/plugins/optgroup_columns.js.map +1 -0
  62. package/dist/js/plugins/remove_button.js +142 -0
  63. package/dist/js/plugins/remove_button.js.map +1 -0
  64. package/dist/js/plugins/restore_on_backspace.js +50 -0
  65. package/dist/js/plugins/restore_on_backspace.js.map +1 -0
  66. package/dist/js/plugins/virtual_scroll.js +280 -0
  67. package/dist/js/plugins/virtual_scroll.js.map +1 -0
  68. package/dist/js/tom-select.base.js +4167 -0
  69. package/dist/js/tom-select.base.js.map +1 -0
  70. package/dist/js/tom-select.base.min.js +373 -0
  71. package/dist/js/tom-select.base.min.js.map +1 -0
  72. package/dist/js/tom-select.complete.js +5364 -0
  73. package/dist/js/tom-select.complete.js.map +1 -0
  74. package/dist/js/tom-select.complete.min.js +489 -0
  75. package/dist/js/tom-select.complete.min.js.map +1 -0
  76. package/dist/js/tom-select.popular.js +4436 -0
  77. package/dist/js/tom-select.popular.js.map +1 -0
  78. package/dist/js/tom-select.popular.min.js +396 -0
  79. package/dist/js/tom-select.popular.min.js.map +1 -0
  80. package/dist/types/constants.d.ts +12 -0
  81. package/dist/types/contrib/highlight.d.ts +13 -0
  82. package/dist/types/contrib/microevent.d.ts +20 -0
  83. package/dist/types/contrib/microplugin.d.ts +71 -0
  84. package/dist/types/defaults.d.ts +53 -0
  85. package/dist/types/getSettings.d.ts +3 -0
  86. package/dist/types/plugins/caret_position/plugin.d.ts +16 -0
  87. package/dist/types/plugins/change_listener/plugin.d.ts +16 -0
  88. package/dist/types/plugins/checkbox_options/plugin.d.ts +17 -0
  89. package/dist/types/plugins/checkbox_options/types.d.ts +14 -0
  90. package/dist/types/plugins/clear_button/plugin.d.ts +17 -0
  91. package/dist/types/plugins/clear_button/types.d.ts +7 -0
  92. package/dist/types/plugins/drag_drop/plugin.d.ts +16 -0
  93. package/dist/types/plugins/dropdown_header/plugin.d.ts +17 -0
  94. package/dist/types/plugins/dropdown_header/types.d.ts +8 -0
  95. package/dist/types/plugins/dropdown_input/plugin.d.ts +16 -0
  96. package/dist/types/plugins/input_autogrow/plugin.d.ts +15 -0
  97. package/dist/types/plugins/local_virtual_scroll/plugin.d.ts +19 -0
  98. package/dist/types/plugins/local_virtual_scroll/types.d.ts +14 -0
  99. package/dist/types/plugins/no_active_items/plugin.d.ts +15 -0
  100. package/dist/types/plugins/no_backspace_delete/plugin.d.ts +15 -0
  101. package/dist/types/plugins/optgroup_columns/plugin.d.ts +16 -0
  102. package/dist/types/plugins/remove_button/plugin.d.ts +17 -0
  103. package/dist/types/plugins/remove_button/types.d.ts +6 -0
  104. package/dist/types/plugins/restore_on_backspace/plugin.d.ts +21 -0
  105. package/dist/types/plugins/virtual_scroll/plugin.d.ts +16 -0
  106. package/dist/types/tom-select.complete.d.ts +2 -0
  107. package/dist/types/tom-select.d.ts +594 -0
  108. package/dist/types/tom-select.popular.d.ts +2 -0
  109. package/dist/types/types/core.d.ts +50 -0
  110. package/dist/types/types/index.d.ts +2 -0
  111. package/dist/types/types/settings.d.ts +81 -0
  112. package/dist/types/utils.d.ts +95 -0
  113. package/dist/types/vanilla.d.ts +76 -0
  114. package/package.json +156 -0
  115. package/src/constants.ts +13 -0
  116. package/src/contrib/highlight.ts +81 -0
  117. package/src/contrib/microevent.ts +73 -0
  118. package/src/contrib/microplugin.ts +137 -0
  119. package/src/defaults.ts +95 -0
  120. package/src/getSettings.ts +176 -0
  121. package/src/plugins/caret_position/plugin.ts +73 -0
  122. package/src/plugins/change_listener/plugin.ts +23 -0
  123. package/src/plugins/checkbox_options/plugin.scss +11 -0
  124. package/src/plugins/checkbox_options/plugin.ts +130 -0
  125. package/src/plugins/checkbox_options/types.ts +15 -0
  126. package/src/plugins/clear_button/plugin.scss +33 -0
  127. package/src/plugins/clear_button/plugin.ts +54 -0
  128. package/src/plugins/clear_button/types.ts +8 -0
  129. package/src/plugins/drag_drop/plugin.scss +10 -0
  130. package/src/plugins/drag_drop/plugin.ts +143 -0
  131. package/src/plugins/dropdown_header/plugin.scss +24 -0
  132. package/src/plugins/dropdown_header/plugin.ts +57 -0
  133. package/src/plugins/dropdown_header/types.ts +9 -0
  134. package/src/plugins/dropdown_input/plugin.scss +43 -0
  135. package/src/plugins/dropdown_input/plugin.ts +97 -0
  136. package/src/plugins/input_autogrow/plugin.scss +15 -0
  137. package/src/plugins/input_autogrow/plugin.ts +56 -0
  138. package/src/plugins/local_virtual_scroll/plugin.ts +309 -0
  139. package/src/plugins/local_virtual_scroll/types.ts +9 -0
  140. package/src/plugins/no_active_items/plugin.ts +20 -0
  141. package/src/plugins/no_backspace_delete/plugin.ts +30 -0
  142. package/src/plugins/optgroup_columns/plugin.scss +25 -0
  143. package/src/plugins/optgroup_columns/plugin.ts +59 -0
  144. package/src/plugins/remove_button/plugin.scss +70 -0
  145. package/src/plugins/remove_button/plugin.ts +78 -0
  146. package/src/plugins/remove_button/types.ts +7 -0
  147. package/src/plugins/restore_on_backspace/plugin.ts +44 -0
  148. package/src/plugins/virtual_scroll/plugin.ts +219 -0
  149. package/src/scss/-tom-select.bootstrap4.scss +4 -0
  150. package/src/scss/-tom-select.bootstrap5.scss +4 -0
  151. package/src/scss/_dropdown.scss +99 -0
  152. package/src/scss/_items.scss +114 -0
  153. package/src/scss/tom-select.bootstrap4.scss +218 -0
  154. package/src/scss/tom-select.bootstrap5.scss +270 -0
  155. package/src/scss/tom-select.default.scss +89 -0
  156. package/src/scss/tom-select.scss +179 -0
  157. package/src/tom-select.complete.ts +35 -0
  158. package/src/tom-select.popular.ts +15 -0
  159. package/src/tom-select.ts +2807 -0
  160. package/src/types/core.ts +68 -0
  161. package/src/types/index.ts +3 -0
  162. package/src/types/settings.ts +98 -0
  163. package/src/utils.ts +230 -0
  164. package/src/vanilla.ts +210 -0
@@ -0,0 +1,4167 @@
1
+ /**
2
+ * Tom Select v2.5.2
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ */
5
+
6
+ (function (global, factory) {
7
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
8
+ typeof define === 'function' && define.amd ? define(factory) :
9
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.TomSelect = factory());
10
+ })(this, (function () { 'use strict';
11
+
12
+ /**
13
+ * MicroEvent - to make any js object an event emitter
14
+ *
15
+ * - pure javascript - server compatible, browser compatible
16
+ * - dont rely on the browser doms
17
+ * - super simple - you get it immediatly, no mistery, no magic involved
18
+ *
19
+ * @author Jerome Etienne (https://github.com/jeromeetienne)
20
+ */
21
+
22
+ /**
23
+ * Execute callback for each event in space separated list of event names
24
+ *
25
+ */
26
+ function forEvents(events, callback) {
27
+ events.split(/\s+/).forEach(event => {
28
+ callback(event);
29
+ });
30
+ }
31
+ class MicroEvent {
32
+ constructor() {
33
+ this._events = {};
34
+ }
35
+ on(events, fct) {
36
+ forEvents(events, event => {
37
+ const event_array = this._events[event] || [];
38
+ event_array.push(fct);
39
+ this._events[event] = event_array;
40
+ });
41
+ }
42
+ off(events, fct) {
43
+ var n = arguments.length;
44
+ if (n === 0) {
45
+ this._events = {};
46
+ return;
47
+ }
48
+ forEvents(events, event => {
49
+ if (n === 1) {
50
+ delete this._events[event];
51
+ return;
52
+ }
53
+ const event_array = this._events[event];
54
+ if (event_array === undefined) return;
55
+ event_array.splice(event_array.indexOf(fct), 1);
56
+ this._events[event] = event_array;
57
+ });
58
+ }
59
+ trigger(events, ...args) {
60
+ var self = this;
61
+ forEvents(events, event => {
62
+ const event_array = self._events[event];
63
+ if (event_array === undefined) return;
64
+ event_array.forEach(fct => {
65
+ fct.apply(self, args);
66
+ });
67
+ });
68
+ }
69
+ }
70
+
71
+ /**
72
+ * microplugin.js
73
+ * Copyright (c) 2013 Brian Reavis & contributors
74
+ *
75
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
76
+ * file except in compliance with the License. You may obtain a copy of the License at:
77
+ * http://www.apache.org/licenses/LICENSE-2.0
78
+ *
79
+ * Unless required by applicable law or agreed to in writing, software distributed under
80
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
81
+ * ANY KIND, either express or implied. See the License for the specific language
82
+ * governing permissions and limitations under the License.
83
+ *
84
+ * @author Brian Reavis <brian@thirdroute.com>
85
+ */
86
+
87
+ function MicroPlugin(Interface) {
88
+ Interface.plugins = {};
89
+ return class extends Interface {
90
+ constructor(...args) {
91
+ super(...args);
92
+ this.plugins = {
93
+ names: [],
94
+ settings: {},
95
+ requested: {},
96
+ loaded: {}
97
+ };
98
+ }
99
+ /**
100
+ * Registers a plugin.
101
+ *
102
+ * @param {function} fn
103
+ */
104
+ static define(name, fn) {
105
+ Interface.plugins[name] = {
106
+ 'name': name,
107
+ 'fn': fn
108
+ };
109
+ }
110
+
111
+ /**
112
+ * Initializes the listed plugins (with options).
113
+ * Acceptable formats:
114
+ *
115
+ * List (without options):
116
+ * ['a', 'b', 'c']
117
+ *
118
+ * List (with options):
119
+ * [{'name': 'a', options: {}}, {'name': 'b', options: {}}]
120
+ *
121
+ * Hash (with options):
122
+ * {'a': { ... }, 'b': { ... }, 'c': { ... }}
123
+ *
124
+ * @param {array|object} plugins
125
+ */
126
+ initializePlugins(plugins) {
127
+ var key, name;
128
+ const self = this;
129
+ const queue = [];
130
+ if (Array.isArray(plugins)) {
131
+ plugins.forEach(plugin => {
132
+ if (typeof plugin === 'string') {
133
+ queue.push(plugin);
134
+ } else {
135
+ self.plugins.settings[plugin.name] = plugin.options;
136
+ queue.push(plugin.name);
137
+ }
138
+ });
139
+ } else if (plugins) {
140
+ for (key in plugins) {
141
+ if (plugins.hasOwnProperty(key)) {
142
+ self.plugins.settings[key] = plugins[key];
143
+ queue.push(key);
144
+ }
145
+ }
146
+ }
147
+ while (name = queue.shift()) {
148
+ self.require(name);
149
+ }
150
+ }
151
+ loadPlugin(name) {
152
+ var self = this;
153
+ var plugins = self.plugins;
154
+ var plugin = Interface.plugins[name];
155
+ if (!Interface.plugins.hasOwnProperty(name)) {
156
+ throw new Error('Unable to find "' + name + '" plugin');
157
+ }
158
+ plugins.requested[name] = true;
159
+ plugins.loaded[name] = plugin.fn.apply(self, [self.plugins.settings[name] || {}]);
160
+ plugins.names.push(name);
161
+ }
162
+
163
+ /**
164
+ * Initializes a plugin.
165
+ *
166
+ */
167
+ require(name) {
168
+ var self = this;
169
+ var plugins = self.plugins;
170
+ if (!self.plugins.loaded.hasOwnProperty(name)) {
171
+ if (plugins.requested[name]) {
172
+ throw new Error('Plugin has circular dependency ("' + name + '")');
173
+ }
174
+ self.loadPlugin(name);
175
+ }
176
+ return plugins.loaded[name];
177
+ }
178
+ };
179
+ }
180
+
181
+ /**
182
+ * Convert array of strings to a regular expression
183
+ * ex ['ab','a'] => (?:ab|a)
184
+ * ex ['a','b'] => [ab]
185
+ */
186
+ const arrayToPattern = (chars) => {
187
+ chars = chars.filter(Boolean);
188
+ if (chars.length < 2) {
189
+ return chars[0] || '';
190
+ }
191
+ return (maxValueLength(chars) == 1) ? '[' + chars.join('') + ']' : '(?:' + chars.join('|') + ')';
192
+ };
193
+ const sequencePattern = (array) => {
194
+ if (!hasDuplicates(array)) {
195
+ return array.join('');
196
+ }
197
+ let pattern = '';
198
+ let prev_char_count = 0;
199
+ const prev_pattern = () => {
200
+ if (prev_char_count > 1) {
201
+ pattern += '{' + prev_char_count + '}';
202
+ }
203
+ };
204
+ array.forEach((char, i) => {
205
+ if (char === array[i - 1]) {
206
+ prev_char_count++;
207
+ return;
208
+ }
209
+ prev_pattern();
210
+ pattern += char;
211
+ prev_char_count = 1;
212
+ });
213
+ prev_pattern();
214
+ return pattern;
215
+ };
216
+ /**
217
+ * Convert array of strings to a regular expression
218
+ * ex ['ab','a'] => (?:ab|a)
219
+ * ex ['a','b'] => [ab]
220
+ */
221
+ const setToPattern = (chars) => {
222
+ let array = Array.from(chars);
223
+ return arrayToPattern(array);
224
+ };
225
+ /**
226
+ * https://stackoverflow.com/questions/7376598/in-javascript-how-do-i-check-if-an-array-has-duplicate-values
227
+ */
228
+ const hasDuplicates = (array) => {
229
+ return (new Set(array)).size !== array.length;
230
+ };
231
+ /**
232
+ * https://stackoverflow.com/questions/63006601/why-does-u-throw-an-invalid-escape-error
233
+ */
234
+ const escape_regex = (str) => {
235
+ return (str + '').replace(/([\$\(\)\*\+\.\?\[\]\^\{\|\}\\])/gu, '\\$1');
236
+ };
237
+ /**
238
+ * Return the max length of array values
239
+ */
240
+ const maxValueLength = (array) => {
241
+ return array.reduce((longest, value) => Math.max(longest, unicodeLength(value)), 0);
242
+ };
243
+ const unicodeLength = (str) => {
244
+ return Array.from(str).length;
245
+ };
246
+
247
+ /**
248
+ * Get all possible combinations of substrings that add up to the given string
249
+ * https://stackoverflow.com/questions/30169587/find-all-the-combination-of-substrings-that-add-up-to-the-given-string
250
+ */
251
+ const allSubstrings = (input) => {
252
+ if (input.length === 1)
253
+ return [[input]];
254
+ let result = [];
255
+ const start = input.substring(1);
256
+ const suba = allSubstrings(start);
257
+ suba.forEach(function (subresult) {
258
+ let tmp = subresult.slice(0);
259
+ tmp[0] = input.charAt(0) + tmp[0];
260
+ result.push(tmp);
261
+ tmp = subresult.slice(0);
262
+ tmp.unshift(input.charAt(0));
263
+ result.push(tmp);
264
+ });
265
+ return result;
266
+ };
267
+
268
+ const code_points = [[0, 65535]];
269
+ const accent_pat = '[\u0300-\u036F\u{b7}\u{2be}\u{2bc}]';
270
+ let unicode_map;
271
+ let multi_char_reg;
272
+ const max_char_length = 3;
273
+ const latin_convert = {};
274
+ const latin_condensed = {
275
+ '/': '⁄∕',
276
+ '0': '߀',
277
+ "a": "ⱥɐɑ",
278
+ "aa": "ꜳ",
279
+ "ae": "æǽǣ",
280
+ "ao": "ꜵ",
281
+ "au": "ꜷ",
282
+ "av": "ꜹꜻ",
283
+ "ay": "ꜽ",
284
+ "b": "ƀɓƃ",
285
+ "c": "ꜿƈȼↄ",
286
+ "d": "đɗɖᴅƌꮷԁɦ",
287
+ "e": "ɛǝᴇɇ",
288
+ "f": "ꝼƒ",
289
+ "g": "ǥɠꞡᵹꝿɢ",
290
+ "h": "ħⱨⱶɥ",
291
+ "i": "ɨı",
292
+ "j": "ɉȷ",
293
+ "k": "ƙⱪꝁꝃꝅꞣ",
294
+ "l": "łƚɫⱡꝉꝇꞁɭ",
295
+ "m": "ɱɯϻ",
296
+ "n": "ꞥƞɲꞑᴎлԉ",
297
+ "o": "øǿɔɵꝋꝍᴑ",
298
+ "oe": "œ",
299
+ "oi": "ƣ",
300
+ "oo": "ꝏ",
301
+ "ou": "ȣ",
302
+ "p": "ƥᵽꝑꝓꝕρ",
303
+ "q": "ꝗꝙɋ",
304
+ "r": "ɍɽꝛꞧꞃ",
305
+ "s": "ßȿꞩꞅʂ",
306
+ "t": "ŧƭʈⱦꞇ",
307
+ "th": "þ",
308
+ "tz": "ꜩ",
309
+ "u": "ʉ",
310
+ "v": "ʋꝟʌ",
311
+ "vy": "ꝡ",
312
+ "w": "ⱳ",
313
+ "y": "ƴɏỿ",
314
+ "z": "ƶȥɀⱬꝣ",
315
+ "hv": "ƕ"
316
+ };
317
+ for (let latin in latin_condensed) {
318
+ let unicode = latin_condensed[latin] || '';
319
+ for (let i = 0; i < unicode.length; i++) {
320
+ let char = unicode.substring(i, i + 1);
321
+ latin_convert[char] = latin;
322
+ }
323
+ }
324
+ const convert_pat = new RegExp(Object.keys(latin_convert).join('|') + '|' + accent_pat, 'gu');
325
+ /**
326
+ * Initialize the unicode_map from the give code point ranges
327
+ */
328
+ const initialize = (_code_points) => {
329
+ if (unicode_map !== undefined)
330
+ return;
331
+ unicode_map = generateMap(code_points);
332
+ };
333
+ /**
334
+ * Helper method for normalize a string
335
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
336
+ */
337
+ const normalize = (str, form = 'NFKD') => str.normalize(form);
338
+ /**
339
+ * Remove accents without reordering string
340
+ * calling str.normalize('NFKD') on \u{594}\u{595}\u{596} becomes \u{596}\u{594}\u{595}
341
+ * via https://github.com/krisk/Fuse/issues/133#issuecomment-318692703
342
+ */
343
+ const asciifold = (str) => {
344
+ return Array.from(str).reduce(
345
+ /**
346
+ * @param {string} result
347
+ * @param {string} char
348
+ */
349
+ (result, char) => {
350
+ return result + _asciifold(char);
351
+ }, '');
352
+ };
353
+ const _asciifold = (str) => {
354
+ str = normalize(str)
355
+ .toLowerCase()
356
+ .replace(convert_pat, (/** @type {string} */ char) => {
357
+ return latin_convert[char] || '';
358
+ });
359
+ //return str;
360
+ return normalize(str, 'NFC');
361
+ };
362
+ /**
363
+ * Generate a list of unicode variants from the list of code points
364
+ */
365
+ function* generator(code_points) {
366
+ for (const [code_point_min, code_point_max] of code_points) {
367
+ for (let i = code_point_min; i <= code_point_max; i++) {
368
+ let composed = String.fromCharCode(i);
369
+ let folded = asciifold(composed);
370
+ if (folded == composed.toLowerCase()) {
371
+ continue;
372
+ }
373
+ // skip when folded is a string longer than 3 characters long
374
+ // bc the resulting regex patterns will be long
375
+ // eg:
376
+ // folded صلى الله عليه وسلم length 18 code point 65018
377
+ // folded جل جلاله length 8 code point 65019
378
+ if (folded.length > max_char_length) {
379
+ continue;
380
+ }
381
+ if (folded.length == 0) {
382
+ continue;
383
+ }
384
+ yield { folded: folded, composed: composed, code_point: i };
385
+ }
386
+ }
387
+ }
388
+ /**
389
+ * Generate a unicode map from the list of code points
390
+ */
391
+ const generateSets = (code_points) => {
392
+ const unicode_sets = {};
393
+ const addMatching = (folded, to_add) => {
394
+ /** @type {Set<string>} */
395
+ const folded_set = unicode_sets[folded] || new Set();
396
+ const patt = new RegExp('^' + setToPattern(folded_set) + '$', 'iu');
397
+ if (to_add.match(patt)) {
398
+ return;
399
+ }
400
+ folded_set.add(escape_regex(to_add));
401
+ unicode_sets[folded] = folded_set;
402
+ };
403
+ for (let value of generator(code_points)) {
404
+ addMatching(value.folded, value.folded);
405
+ addMatching(value.folded, value.composed);
406
+ }
407
+ return unicode_sets;
408
+ };
409
+ /**
410
+ * Generate a unicode map from the list of code points
411
+ * ae => (?:(?:ae|Æ|Ǽ|Ǣ)|(?:A|Ⓐ|A...)(?:E|ɛ|Ⓔ...))
412
+ */
413
+ const generateMap = (code_points) => {
414
+ const unicode_sets = generateSets(code_points);
415
+ const unicode_map = {};
416
+ let multi_char = [];
417
+ for (let folded in unicode_sets) {
418
+ let set = unicode_sets[folded];
419
+ if (set) {
420
+ unicode_map[folded] = setToPattern(set);
421
+ }
422
+ if (folded.length > 1) {
423
+ multi_char.push(escape_regex(folded));
424
+ }
425
+ }
426
+ multi_char.sort((a, b) => b.length - a.length);
427
+ const multi_char_patt = arrayToPattern(multi_char);
428
+ multi_char_reg = new RegExp('^' + multi_char_patt, 'u');
429
+ return unicode_map;
430
+ };
431
+ /**
432
+ * Map each element of an array from its folded value to all possible unicode matches
433
+ */
434
+ const mapSequence = (strings, min_replacement = 1) => {
435
+ let chars_replaced = 0;
436
+ strings = strings.map((str) => {
437
+ if (unicode_map[str]) {
438
+ chars_replaced += str.length;
439
+ }
440
+ return unicode_map[str] || str;
441
+ });
442
+ if (chars_replaced >= min_replacement) {
443
+ return sequencePattern(strings);
444
+ }
445
+ return '';
446
+ };
447
+ /**
448
+ * Convert a short string and split it into all possible patterns
449
+ * Keep a pattern only if min_replacement is met
450
+ *
451
+ * 'abc'
452
+ * => [['abc'],['ab','c'],['a','bc'],['a','b','c']]
453
+ * => ['abc-pattern','ab-c-pattern'...]
454
+ */
455
+ const substringsToPattern = (str, min_replacement = 1) => {
456
+ min_replacement = Math.max(min_replacement, str.length - 1);
457
+ return arrayToPattern(allSubstrings(str).map((sub_pat) => {
458
+ return mapSequence(sub_pat, min_replacement);
459
+ }));
460
+ };
461
+ /**
462
+ * Convert an array of sequences into a pattern
463
+ * [{start:0,end:3,length:3,substr:'iii'}...] => (?:iii...)
464
+ */
465
+ const sequencesToPattern = (sequences, all = true) => {
466
+ let min_replacement = sequences.length > 1 ? 1 : 0;
467
+ return arrayToPattern(sequences.map((sequence) => {
468
+ let seq = [];
469
+ const len = all ? sequence.length() : sequence.length() - 1;
470
+ for (let j = 0; j < len; j++) {
471
+ seq.push(substringsToPattern(sequence.substrs[j] || '', min_replacement));
472
+ }
473
+ return sequencePattern(seq);
474
+ }));
475
+ };
476
+ /**
477
+ * Return true if the sequence is already in the sequences
478
+ */
479
+ const inSequences = (needle_seq, sequences) => {
480
+ for (const seq of sequences) {
481
+ if (seq.start != needle_seq.start || seq.end != needle_seq.end) {
482
+ continue;
483
+ }
484
+ if (seq.substrs.join('') !== needle_seq.substrs.join('')) {
485
+ continue;
486
+ }
487
+ let needle_parts = needle_seq.parts;
488
+ const filter = (part) => {
489
+ for (const needle_part of needle_parts) {
490
+ if (needle_part.start === part.start && needle_part.substr === part.substr) {
491
+ return false;
492
+ }
493
+ if (part.length == 1 || needle_part.length == 1) {
494
+ continue;
495
+ }
496
+ // check for overlapping parts
497
+ // a = ['::=','==']
498
+ // b = ['::','===']
499
+ // a = ['r','sm']
500
+ // b = ['rs','m']
501
+ if (part.start < needle_part.start && part.end > needle_part.start) {
502
+ return true;
503
+ }
504
+ if (needle_part.start < part.start && needle_part.end > part.start) {
505
+ return true;
506
+ }
507
+ }
508
+ return false;
509
+ };
510
+ let filtered = seq.parts.filter(filter);
511
+ if (filtered.length > 0) {
512
+ continue;
513
+ }
514
+ return true;
515
+ }
516
+ return false;
517
+ };
518
+ class Sequence {
519
+ parts;
520
+ substrs;
521
+ start;
522
+ end;
523
+ constructor() {
524
+ this.parts = [];
525
+ this.substrs = [];
526
+ this.start = 0;
527
+ this.end = 0;
528
+ }
529
+ add(part) {
530
+ if (part) {
531
+ this.parts.push(part);
532
+ this.substrs.push(part.substr);
533
+ this.start = Math.min(part.start, this.start);
534
+ this.end = Math.max(part.end, this.end);
535
+ }
536
+ }
537
+ last() {
538
+ return this.parts[this.parts.length - 1];
539
+ }
540
+ length() {
541
+ return this.parts.length;
542
+ }
543
+ clone(position, last_piece) {
544
+ let clone = new Sequence();
545
+ let parts = JSON.parse(JSON.stringify(this.parts));
546
+ let last_part = parts.pop();
547
+ for (const part of parts) {
548
+ clone.add(part);
549
+ }
550
+ let last_substr = last_piece.substr.substring(0, position - last_part.start);
551
+ let clone_last_len = last_substr.length;
552
+ clone.add({ start: last_part.start, end: last_part.start + clone_last_len, length: clone_last_len, substr: last_substr });
553
+ return clone;
554
+ }
555
+ }
556
+ /**
557
+ * Expand a regular expression pattern to include unicode variants
558
+ * eg /a/ becomes /aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐɑAⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ/
559
+ *
560
+ * Issue:
561
+ * ﺊﺋ [ 'ﺊ = \\u{fe8a}', 'ﺋ = \\u{fe8b}' ]
562
+ * becomes: ئئ [ 'ي = \\u{64a}', 'ٔ = \\u{654}', 'ي = \\u{64a}', 'ٔ = \\u{654}' ]
563
+ *
564
+ * İIJ = IIJ = ⅡJ
565
+ *
566
+ * 1/2/4
567
+ */
568
+ const getPattern = (str) => {
569
+ initialize();
570
+ str = asciifold(str);
571
+ let pattern = '';
572
+ let sequences = [new Sequence()];
573
+ for (let i = 0; i < str.length; i++) {
574
+ let substr = str.substring(i);
575
+ let match = substr.match(multi_char_reg);
576
+ const char = str.substring(i, i + 1);
577
+ const match_str = match ? match[0] : null;
578
+ // loop through sequences
579
+ // add either the char or multi_match
580
+ let overlapping = [];
581
+ let added_types = new Set();
582
+ for (const sequence of sequences) {
583
+ const last_piece = sequence.last();
584
+ if (!last_piece || last_piece.length == 1 || last_piece.end <= i) {
585
+ // if we have a multi match
586
+ if (match_str) {
587
+ const len = match_str.length;
588
+ sequence.add({ start: i, end: i + len, length: len, substr: match_str });
589
+ added_types.add('1');
590
+ }
591
+ else {
592
+ sequence.add({ start: i, end: i + 1, length: 1, substr: char });
593
+ added_types.add('2');
594
+ }
595
+ }
596
+ else if (match_str) {
597
+ let clone = sequence.clone(i, last_piece);
598
+ const len = match_str.length;
599
+ clone.add({ start: i, end: i + len, length: len, substr: match_str });
600
+ overlapping.push(clone);
601
+ }
602
+ else {
603
+ // don't add char
604
+ // adding would create invalid patterns: 234 => [2,34,4]
605
+ added_types.add('3');
606
+ }
607
+ }
608
+ // if we have overlapping
609
+ if (overlapping.length > 0) {
610
+ // ['ii','iii'] before ['i','i','iii']
611
+ overlapping = overlapping.sort((a, b) => {
612
+ return a.length() - b.length();
613
+ });
614
+ for (let clone of overlapping) {
615
+ // don't add if we already have an equivalent sequence
616
+ if (inSequences(clone, sequences)) {
617
+ continue;
618
+ }
619
+ sequences.push(clone);
620
+ }
621
+ continue;
622
+ }
623
+ // if we haven't done anything unique
624
+ // clean up the patterns
625
+ // helps keep patterns smaller
626
+ // if str = 'r₨㎧aarss', pattern will be 446 instead of 655
627
+ if (i > 0 && added_types.size == 1 && !added_types.has('3')) {
628
+ pattern += sequencesToPattern(sequences, false);
629
+ let new_seq = new Sequence();
630
+ const old_seq = sequences[0];
631
+ if (old_seq) {
632
+ new_seq.add(old_seq.last());
633
+ }
634
+ sequences = [new_seq];
635
+ }
636
+ }
637
+ pattern += sequencesToPattern(sequences, true);
638
+ return pattern;
639
+ };
640
+
641
+ /**
642
+ * A property getter resolving dot-notation
643
+ * @param {Object} obj The root object to fetch property on
644
+ * @param {String} name The optionally dotted property name to fetch
645
+ * @return {Object} The resolved property value
646
+ */
647
+ const getAttr = (obj, name) => {
648
+ if (!obj)
649
+ return;
650
+ return obj[name];
651
+ };
652
+ /**
653
+ * A property getter resolving dot-notation
654
+ * @param {Object} obj The root object to fetch property on
655
+ * @param {String} name The optionally dotted property name to fetch
656
+ * @return {Object} The resolved property value
657
+ */
658
+ const getAttrNesting = (obj, name) => {
659
+ if (!obj)
660
+ return;
661
+ var part, names = name.split(".");
662
+ while ((part = names.shift()) && (obj = obj[part]))
663
+ ;
664
+ return obj;
665
+ };
666
+ /**
667
+ * Calculates how close of a match the
668
+ * given value is against a search token.
669
+ *
670
+ */
671
+ const scoreValue = (value, token, weight) => {
672
+ var score, pos;
673
+ if (!value)
674
+ return 0;
675
+ value = value + '';
676
+ if (token.regex == null)
677
+ return 0;
678
+ pos = value.search(token.regex);
679
+ if (pos === -1)
680
+ return 0;
681
+ score = token.string.length / value.length;
682
+ if (pos === 0)
683
+ score += 0.5;
684
+ return score * weight;
685
+ };
686
+ /**
687
+ * Cast object property to an array if it exists and has a value
688
+ *
689
+ */
690
+ const propToArray = (obj, key) => {
691
+ var value = obj[key];
692
+ if (typeof value == 'function')
693
+ return value;
694
+ if (value && !Array.isArray(value)) {
695
+ obj[key] = [value];
696
+ }
697
+ };
698
+ /**
699
+ * Iterates over arrays and hashes.
700
+ *
701
+ * ```
702
+ * iterate(this.items, function(item, id) {
703
+ * // invoked for each item
704
+ * });
705
+ * ```
706
+ *
707
+ */
708
+ const iterate$1 = (object, callback) => {
709
+ if (Array.isArray(object)) {
710
+ object.forEach(callback);
711
+ }
712
+ else {
713
+ for (var key in object) {
714
+ if (object.hasOwnProperty(key)) {
715
+ callback(object[key], key);
716
+ }
717
+ }
718
+ }
719
+ };
720
+ const cmp = (a, b) => {
721
+ if (typeof a === 'number' && typeof b === 'number') {
722
+ return a > b ? 1 : (a < b ? -1 : 0);
723
+ }
724
+ a = asciifold(a + '').toLowerCase();
725
+ b = asciifold(b + '').toLowerCase();
726
+ if (a > b)
727
+ return 1;
728
+ if (b > a)
729
+ return -1;
730
+ return 0;
731
+ };
732
+
733
+ /**
734
+ * sifter.js
735
+ * Copyright (c) 2013–2020 Brian Reavis & contributors
736
+ *
737
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
738
+ * file except in compliance with the License. You may obtain a copy of the License at:
739
+ * http://www.apache.org/licenses/LICENSE-2.0
740
+ *
741
+ * Unless required by applicable law or agreed to in writing, software distributed under
742
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
743
+ * ANY KIND, either express or implied. See the License for the specific language
744
+ * governing permissions and limitations under the License.
745
+ *
746
+ * @author Brian Reavis <brian@thirdroute.com>
747
+ */
748
+ class Sifter {
749
+ items; // []|{};
750
+ settings;
751
+ /**
752
+ * Textually searches arrays and hashes of objects
753
+ * by property (or multiple properties). Designed
754
+ * specifically for autocomplete.
755
+ *
756
+ */
757
+ constructor(items, settings) {
758
+ this.items = items;
759
+ this.settings = settings || { diacritics: true };
760
+ }
761
+ ;
762
+ /**
763
+ * Splits a search string into an array of individual
764
+ * regexps to be used to match results.
765
+ *
766
+ */
767
+ tokenize(query, respect_word_boundaries, weights) {
768
+ if (!query || !query.length)
769
+ return [];
770
+ const tokens = [];
771
+ const words = query.split(/\s+/);
772
+ var field_regex;
773
+ if (weights) {
774
+ field_regex = new RegExp('^(' + Object.keys(weights).map(escape_regex).join('|') + ')\:(.*)$');
775
+ }
776
+ words.forEach((word) => {
777
+ let field_match;
778
+ let field = null;
779
+ let regex = null;
780
+ // look for "field:query" tokens
781
+ if (field_regex && (field_match = word.match(field_regex))) {
782
+ field = field_match[1];
783
+ word = field_match[2];
784
+ }
785
+ if (word.length > 0) {
786
+ if (this.settings.diacritics) {
787
+ regex = getPattern(word) || null;
788
+ }
789
+ else {
790
+ regex = escape_regex(word);
791
+ }
792
+ if (regex && respect_word_boundaries)
793
+ regex = "\\b" + regex;
794
+ }
795
+ tokens.push({
796
+ string: word,
797
+ regex: regex ? new RegExp(regex, 'iu') : null,
798
+ field: field,
799
+ });
800
+ });
801
+ return tokens;
802
+ }
803
+ ;
804
+ /**
805
+ * Returns a function to be used to score individual results.
806
+ *
807
+ * Good matches will have a higher score than poor matches.
808
+ * If an item is not a match, 0 will be returned by the function.
809
+ *
810
+ * @returns {T.ScoreFn}
811
+ */
812
+ getScoreFunction(query, options) {
813
+ var search = this.prepareSearch(query, options);
814
+ return this._getScoreFunction(search);
815
+ }
816
+ /**
817
+ * @returns {T.ScoreFn}
818
+ *
819
+ */
820
+ _getScoreFunction(search) {
821
+ const tokens = search.tokens, token_count = tokens.length;
822
+ if (!token_count) {
823
+ return function () { return 0; };
824
+ }
825
+ const fields = search.options.fields, weights = search.weights, field_count = fields.length, getAttrFn = search.getAttrFn;
826
+ if (!field_count) {
827
+ return function () { return 1; };
828
+ }
829
+ /**
830
+ * Calculates the score of an object
831
+ * against the search query.
832
+ *
833
+ */
834
+ const scoreObject = (function () {
835
+ if (field_count === 1) {
836
+ return function (token, data) {
837
+ const field = fields[0].field;
838
+ return scoreValue(getAttrFn(data, field), token, weights[field] || 1);
839
+ };
840
+ }
841
+ return function (token, data) {
842
+ var sum = 0;
843
+ // is the token specific to a field?
844
+ if (token.field) {
845
+ const value = getAttrFn(data, token.field);
846
+ if (!token.regex && value) {
847
+ sum += (1 / field_count);
848
+ }
849
+ else {
850
+ sum += scoreValue(value, token, 1);
851
+ }
852
+ }
853
+ else {
854
+ iterate$1(weights, (weight, field) => {
855
+ sum += scoreValue(getAttrFn(data, field), token, weight);
856
+ });
857
+ }
858
+ return sum / field_count;
859
+ };
860
+ })();
861
+ if (token_count === 1) {
862
+ return function (data) {
863
+ return scoreObject(tokens[0], data);
864
+ };
865
+ }
866
+ if (search.options.conjunction === 'and') {
867
+ return function (data) {
868
+ var score, sum = 0;
869
+ for (let token of tokens) {
870
+ score = scoreObject(token, data);
871
+ if (score <= 0)
872
+ return 0;
873
+ sum += score;
874
+ }
875
+ return sum / token_count;
876
+ };
877
+ }
878
+ else {
879
+ return function (data) {
880
+ var sum = 0;
881
+ iterate$1(tokens, (token) => {
882
+ sum += scoreObject(token, data);
883
+ });
884
+ return sum / token_count;
885
+ };
886
+ }
887
+ }
888
+ ;
889
+ /**
890
+ * Returns a function that can be used to compare two
891
+ * results, for sorting purposes. If no sorting should
892
+ * be performed, `null` will be returned.
893
+ *
894
+ * @return function(a,b)
895
+ */
896
+ getSortFunction(query, options) {
897
+ var search = this.prepareSearch(query, options);
898
+ return this._getSortFunction(search);
899
+ }
900
+ _getSortFunction(search) {
901
+ var implicit_score, sort_flds = [];
902
+ const self = this, options = search.options, sort = (!search.query && options.sort_empty) ? options.sort_empty : options.sort;
903
+ if (typeof sort == 'function') {
904
+ return sort.bind(this);
905
+ }
906
+ /**
907
+ * Fetches the specified sort field value
908
+ * from a search result item.
909
+ *
910
+ */
911
+ const get_field = function (name, result) {
912
+ if (name === '$score')
913
+ return result.score;
914
+ return search.getAttrFn(self.items[result.id], name);
915
+ };
916
+ // parse options
917
+ if (sort) {
918
+ for (let s of sort) {
919
+ if (search.query || s.field !== '$score') {
920
+ sort_flds.push(s);
921
+ }
922
+ }
923
+ }
924
+ // the "$score" field is implied to be the primary
925
+ // sort field, unless it's manually specified
926
+ if (search.query) {
927
+ implicit_score = true;
928
+ for (let fld of sort_flds) {
929
+ if (fld.field === '$score') {
930
+ implicit_score = false;
931
+ break;
932
+ }
933
+ }
934
+ if (implicit_score) {
935
+ sort_flds.unshift({ field: '$score', direction: 'desc' });
936
+ }
937
+ // without a search.query, all items will have the same score
938
+ }
939
+ else {
940
+ sort_flds = sort_flds.filter((fld) => fld.field !== '$score');
941
+ }
942
+ // build function
943
+ const sort_flds_count = sort_flds.length;
944
+ if (!sort_flds_count) {
945
+ return null;
946
+ }
947
+ return function (a, b) {
948
+ var result, field;
949
+ for (let sort_fld of sort_flds) {
950
+ field = sort_fld.field;
951
+ let multiplier = sort_fld.direction === 'desc' ? -1 : 1;
952
+ result = multiplier * cmp(get_field(field, a), get_field(field, b));
953
+ if (result)
954
+ return result;
955
+ }
956
+ return 0;
957
+ };
958
+ }
959
+ ;
960
+ /**
961
+ * Parses a search query and returns an object
962
+ * with tokens and fields ready to be populated
963
+ * with results.
964
+ *
965
+ */
966
+ prepareSearch(query, optsUser) {
967
+ const weights = {};
968
+ var options = Object.assign({}, optsUser);
969
+ propToArray(options, 'sort');
970
+ propToArray(options, 'sort_empty');
971
+ // convert fields to new format
972
+ if (options.fields) {
973
+ propToArray(options, 'fields');
974
+ const fields = [];
975
+ options.fields.forEach((field) => {
976
+ if (typeof field == 'string') {
977
+ field = { field: field, weight: 1 };
978
+ }
979
+ fields.push(field);
980
+ weights[field.field] = ('weight' in field) ? field.weight : 1;
981
+ });
982
+ options.fields = fields;
983
+ }
984
+ return {
985
+ options: options,
986
+ query: query.toLowerCase().trim(),
987
+ tokens: this.tokenize(query, options.respect_word_boundaries, weights),
988
+ total: 0,
989
+ items: [],
990
+ weights: weights,
991
+ getAttrFn: (options.nesting) ? getAttrNesting : getAttr,
992
+ };
993
+ }
994
+ ;
995
+ /**
996
+ * Searches through all items and returns a sorted array of matches.
997
+ *
998
+ */
999
+ search(query, options) {
1000
+ var self = this, score, search;
1001
+ search = this.prepareSearch(query, options);
1002
+ options = search.options;
1003
+ query = search.query;
1004
+ // generate result scoring function
1005
+ const fn_score = options.score || self._getScoreFunction(search);
1006
+ // perform search and sort
1007
+ if (query.length) {
1008
+ iterate$1(self.items, (item, id) => {
1009
+ score = fn_score(item);
1010
+ if (options.filter === false || score > 0) {
1011
+ search.items.push({ 'score': score, 'id': id });
1012
+ }
1013
+ });
1014
+ }
1015
+ else {
1016
+ iterate$1(self.items, (_, id) => {
1017
+ search.items.push({ 'score': 1, 'id': id });
1018
+ });
1019
+ }
1020
+ const fn_sort = self._getSortFunction(search);
1021
+ if (fn_sort)
1022
+ search.items.sort(fn_sort);
1023
+ // apply limits
1024
+ search.total = search.items.length;
1025
+ if (typeof options.limit === 'number') {
1026
+ search.items = search.items.slice(0, options.limit);
1027
+ }
1028
+ return search;
1029
+ }
1030
+ ;
1031
+ }
1032
+
1033
+ /**
1034
+ * Converts a scalar to its best string representation
1035
+ * for hash keys and HTML attribute values.
1036
+ *
1037
+ * Transformations:
1038
+ * 'str' -> 'str'
1039
+ * null -> ''
1040
+ * undefined -> ''
1041
+ * true -> '1'
1042
+ * false -> '0'
1043
+ * 0 -> '0'
1044
+ * 1 -> '1'
1045
+ *
1046
+ */
1047
+ const hash_key = value => {
1048
+ if (typeof value === 'undefined' || value === null) return null;
1049
+ return get_hash(value);
1050
+ };
1051
+ const get_hash = value => {
1052
+ if (typeof value === 'boolean') return value ? '1' : '0';
1053
+ return value + '';
1054
+ };
1055
+
1056
+ /**
1057
+ * Escapes a string for use within HTML.
1058
+ *
1059
+ */
1060
+ const escape_html = str => {
1061
+ return (str + '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
1062
+ };
1063
+
1064
+ /**
1065
+ * use setTimeout if timeout > 0
1066
+ */
1067
+ const timeout = (fn, timeout) => {
1068
+ if (timeout > 0) {
1069
+ return window.setTimeout(fn, timeout);
1070
+ }
1071
+ fn.call(null);
1072
+ return null;
1073
+ };
1074
+
1075
+ /**
1076
+ * Debounce the user provided load function
1077
+ *
1078
+ */
1079
+ const loadDebounce = (fn, delay) => {
1080
+ var timeout;
1081
+ return function (value, callback) {
1082
+ var self = this;
1083
+ if (timeout) {
1084
+ self.loading = Math.max(self.loading - 1, 0);
1085
+ clearTimeout(timeout);
1086
+ }
1087
+ timeout = setTimeout(function () {
1088
+ timeout = null;
1089
+ self.loadedSearches[value] = true;
1090
+ fn.call(self, value, callback);
1091
+ }, delay);
1092
+ };
1093
+ };
1094
+
1095
+ /**
1096
+ * Debounce all fired events types listed in `types`
1097
+ * while executing the provided `fn`.
1098
+ *
1099
+ */
1100
+ const debounce_events = (self, types, fn) => {
1101
+ var type;
1102
+ var trigger = self.trigger;
1103
+ var event_args = {};
1104
+
1105
+ // override trigger method
1106
+ self.trigger = function () {
1107
+ var type = arguments[0];
1108
+ if (types.indexOf(type) !== -1) {
1109
+ event_args[type] = arguments;
1110
+ } else {
1111
+ return trigger.apply(self, arguments);
1112
+ }
1113
+ };
1114
+
1115
+ // invoke provided function
1116
+ fn.apply(self, []);
1117
+ self.trigger = trigger;
1118
+
1119
+ // trigger queued events
1120
+ for (type of types) {
1121
+ if (type in event_args) {
1122
+ trigger.apply(self, event_args[type]);
1123
+ }
1124
+ }
1125
+ };
1126
+
1127
+ /**
1128
+ * Determines the current selection within a text input control.
1129
+ * Returns an object containing:
1130
+ * - start
1131
+ * - length
1132
+ *
1133
+ * Note: "selectionStart, selectionEnd ... apply only to inputs of types text, search, URL, tel and password"
1134
+ * - https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
1135
+ */
1136
+ const getSelection = input => {
1137
+ return {
1138
+ start: input.selectionStart || 0,
1139
+ length: (input.selectionEnd || 0) - (input.selectionStart || 0)
1140
+ };
1141
+ };
1142
+
1143
+ /**
1144
+ * Prevent default
1145
+ *
1146
+ */
1147
+ const preventDefault = (evt, stop = false) => {
1148
+ if (evt) {
1149
+ evt.preventDefault();
1150
+ if (stop) {
1151
+ evt.stopPropagation();
1152
+ }
1153
+ }
1154
+ };
1155
+
1156
+ /**
1157
+ * Add event helper
1158
+ *
1159
+ */
1160
+ const addEvent = (target, type, callback, options) => {
1161
+ target.addEventListener(type, callback, options);
1162
+ };
1163
+
1164
+ /**
1165
+ * Return true if the requested key is down
1166
+ * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )
1167
+ * The current evt may not always set ( eg calling advanceSelection() )
1168
+ *
1169
+ */
1170
+ const isKeyDown = (key_name, evt) => {
1171
+ if (!evt) {
1172
+ return false;
1173
+ }
1174
+ if (!evt[key_name]) {
1175
+ return false;
1176
+ }
1177
+ var count = (evt.altKey ? 1 : 0) + (evt.ctrlKey ? 1 : 0) + (evt.shiftKey ? 1 : 0) + (evt.metaKey ? 1 : 0);
1178
+ if (count === 1) {
1179
+ return true;
1180
+ }
1181
+ return false;
1182
+ };
1183
+
1184
+ /**
1185
+ * Get the id of an element
1186
+ * If the id attribute is not set, set the attribute with the given id
1187
+ *
1188
+ */
1189
+ const getId = (el, id) => {
1190
+ const existing_id = el.getAttribute('id');
1191
+ if (existing_id) {
1192
+ return existing_id;
1193
+ }
1194
+ el.setAttribute('id', id);
1195
+ return id;
1196
+ };
1197
+
1198
+ /**
1199
+ * Returns a string with backslashes added before characters that need to be escaped.
1200
+ */
1201
+ const addSlashes = str => {
1202
+ return str.replace(/[\\"']/g, '\\$&');
1203
+ };
1204
+
1205
+ /**
1206
+ *
1207
+ */
1208
+ const append = (parent, node) => {
1209
+ if (node) parent.append(node);
1210
+ };
1211
+
1212
+ /**
1213
+ * Iterates over arrays and hashes.
1214
+ *
1215
+ * ```
1216
+ * iterate(this.items, function(item, id) {
1217
+ * // invoked for each item
1218
+ * });
1219
+ * ```
1220
+ *
1221
+ */
1222
+ const iterate = (object, callback) => {
1223
+ if (Array.isArray(object)) {
1224
+ object.forEach(callback);
1225
+ } else {
1226
+ for (var key in object) {
1227
+ if (object.hasOwnProperty(key)) {
1228
+ callback(object[key], key);
1229
+ }
1230
+ }
1231
+ }
1232
+ };
1233
+
1234
+ /**
1235
+ * Return a dom element from either a dom query string, jQuery object, a dom element or html string
1236
+ * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518
1237
+ *
1238
+ * param query should be {}
1239
+ */
1240
+ const getDom = query => {
1241
+ if (query.jquery) {
1242
+ return query[0];
1243
+ }
1244
+ if (query instanceof HTMLElement) {
1245
+ return query;
1246
+ }
1247
+ if (isHtmlString(query)) {
1248
+ var tpl = document.createElement('template');
1249
+ tpl.innerHTML = query.trim(); // Never return a text node of whitespace as the result
1250
+ return tpl.content.firstChild;
1251
+ }
1252
+ return document.querySelector(query);
1253
+ };
1254
+ const isHtmlString = arg => {
1255
+ if (typeof arg === 'string' && arg.indexOf('<') > -1) {
1256
+ return true;
1257
+ }
1258
+ return false;
1259
+ };
1260
+ const escapeQuery = query => {
1261
+ return query.replace(/['"\\]/g, '\\$&');
1262
+ };
1263
+
1264
+ /**
1265
+ * Dispatch an event
1266
+ *
1267
+ */
1268
+ const triggerEvent = (dom_el, event_name) => {
1269
+ var event = document.createEvent('HTMLEvents');
1270
+ event.initEvent(event_name, true, false);
1271
+ dom_el.dispatchEvent(event);
1272
+ };
1273
+
1274
+ /**
1275
+ * Apply CSS rules to a dom element
1276
+ *
1277
+ */
1278
+ const applyCSS = (dom_el, css) => {
1279
+ Object.assign(dom_el.style, css);
1280
+ };
1281
+
1282
+ /**
1283
+ * Add css classes
1284
+ *
1285
+ */
1286
+ const addClasses = (elmts, ...classes) => {
1287
+ var norm_classes = classesArray(classes);
1288
+ elmts = castAsArray(elmts);
1289
+ elmts.map(el => {
1290
+ norm_classes.map(cls => {
1291
+ el.classList.add(cls);
1292
+ });
1293
+ });
1294
+ };
1295
+
1296
+ /**
1297
+ * Remove css classes
1298
+ *
1299
+ */
1300
+ const removeClasses = (elmts, ...classes) => {
1301
+ var norm_classes = classesArray(classes);
1302
+ elmts = castAsArray(elmts);
1303
+ elmts.map(el => {
1304
+ norm_classes.map(cls => {
1305
+ el.classList.remove(cls);
1306
+ });
1307
+ });
1308
+ };
1309
+
1310
+ /**
1311
+ * Return arguments
1312
+ *
1313
+ */
1314
+ const classesArray = args => {
1315
+ var classes = [];
1316
+ iterate(args, _classes => {
1317
+ if (typeof _classes === 'string') {
1318
+ _classes = _classes.trim().split(/[\t\n\f\r\s]/);
1319
+ }
1320
+ if (Array.isArray(_classes)) {
1321
+ classes = classes.concat(_classes);
1322
+ }
1323
+ });
1324
+ return classes.filter(Boolean);
1325
+ };
1326
+
1327
+ /**
1328
+ * Create an array from arg if it's not already an array
1329
+ *
1330
+ */
1331
+ const castAsArray = arg => {
1332
+ if (!Array.isArray(arg)) {
1333
+ arg = [arg];
1334
+ }
1335
+ return arg;
1336
+ };
1337
+
1338
+ /**
1339
+ * Get the closest node to the evt.target matching the selector
1340
+ * Stops at wrapper
1341
+ *
1342
+ */
1343
+ const parentMatch = (target, selector, wrapper) => {
1344
+ if (wrapper && !wrapper.contains(target)) {
1345
+ return;
1346
+ }
1347
+ while (target && target.matches) {
1348
+ if (target.matches(selector)) {
1349
+ return target;
1350
+ }
1351
+ target = target.parentNode;
1352
+ }
1353
+ };
1354
+
1355
+ /**
1356
+ * Get the first or last item from an array
1357
+ *
1358
+ * > 0 - right (last)
1359
+ * <= 0 - left (first)
1360
+ *
1361
+ */
1362
+ const getTail = (list, direction = 0) => {
1363
+ if (direction > 0) {
1364
+ return list[list.length - 1];
1365
+ }
1366
+ return list[0];
1367
+ };
1368
+
1369
+ /**
1370
+ * Return true if an object is empty
1371
+ *
1372
+ */
1373
+ const isEmptyObject = obj => {
1374
+ return Object.keys(obj).length === 0;
1375
+ };
1376
+
1377
+ /**
1378
+ * Get the index of an element amongst sibling nodes of the same type
1379
+ *
1380
+ */
1381
+ const nodeIndex = (el, amongst) => {
1382
+ if (!el) return -1;
1383
+ amongst = amongst || el.nodeName;
1384
+ var i = 0;
1385
+ while (el = el.previousElementSibling) {
1386
+ if (el.matches(amongst)) {
1387
+ i++;
1388
+ }
1389
+ }
1390
+ return i;
1391
+ };
1392
+
1393
+ /**
1394
+ * Set attributes of an element
1395
+ *
1396
+ */
1397
+ const setAttr = (el, attrs) => {
1398
+ iterate(attrs, (val, attr) => {
1399
+ if (val == null) {
1400
+ el.removeAttribute(attr);
1401
+ } else {
1402
+ el.setAttribute(attr, '' + val);
1403
+ }
1404
+ });
1405
+ };
1406
+
1407
+ /**
1408
+ * Replace a node
1409
+ */
1410
+ const replaceNode = (existing, replacement) => {
1411
+ if (existing.parentNode) existing.parentNode.replaceChild(replacement, existing);
1412
+ };
1413
+
1414
+ /**
1415
+ * highlight v3 | MIT license | Johann Burkard <jb@eaio.com>
1416
+ * Highlights arbitrary terms in a node.
1417
+ *
1418
+ * - Modified by Marshal <beatgates@gmail.com> 2011-6-24 (added regex)
1419
+ * - Modified by Brian Reavis <brian@thirdroute.com> 2012-8-27 (cleanup)
1420
+ */
1421
+
1422
+ const highlight = (element, regex) => {
1423
+ if (regex === null) return;
1424
+
1425
+ // convet string to regex
1426
+ if (typeof regex === 'string') {
1427
+ if (!regex.length) return;
1428
+ regex = new RegExp(regex, 'i');
1429
+ }
1430
+
1431
+ // Wrap matching part of text node with highlighting <span>, e.g.
1432
+ // Soccer -> <span class="highlight">Soc</span>cer for regex = /soc/i
1433
+ const highlightText = node => {
1434
+ var match = node.data.match(regex);
1435
+ if (match && node.data.length > 0) {
1436
+ var spannode = document.createElement('span');
1437
+ spannode.className = 'highlight';
1438
+ var middlebit = node.splitText(match.index);
1439
+ middlebit.splitText(match[0].length);
1440
+ var middleclone = middlebit.cloneNode(true);
1441
+ spannode.appendChild(middleclone);
1442
+ replaceNode(middlebit, spannode);
1443
+ return 1;
1444
+ }
1445
+ return 0;
1446
+ };
1447
+
1448
+ // Recurse element node, looking for child text nodes to highlight, unless element
1449
+ // is childless, <script>, <style>, or already highlighted: <span class="hightlight">
1450
+ const highlightChildren = node => {
1451
+ if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName) && (node.className !== 'highlight' || node.tagName !== 'SPAN')) {
1452
+ Array.from(node.childNodes).forEach(element => {
1453
+ highlightRecursive(element);
1454
+ });
1455
+ }
1456
+ };
1457
+ const highlightRecursive = node => {
1458
+ if (node.nodeType === 3) {
1459
+ return highlightText(node);
1460
+ }
1461
+ highlightChildren(node);
1462
+ return 0;
1463
+ };
1464
+ highlightRecursive(element);
1465
+ };
1466
+
1467
+ /**
1468
+ * removeHighlight fn copied from highlight v5 and
1469
+ * edited to remove with(), pass js strict mode, and use without jquery
1470
+ */
1471
+ const removeHighlight = el => {
1472
+ var elements = el.querySelectorAll("span.highlight");
1473
+ Array.prototype.forEach.call(elements, function (el) {
1474
+ var parent = el.parentNode;
1475
+ parent.replaceChild(el.firstChild, el);
1476
+ parent.normalize();
1477
+ });
1478
+ };
1479
+
1480
+ const KEY_A = 65;
1481
+ const KEY_RETURN = 13;
1482
+ const KEY_ESC = 27;
1483
+ const KEY_LEFT = 37;
1484
+ const KEY_UP = 38;
1485
+ const KEY_RIGHT = 39;
1486
+ const KEY_DOWN = 40;
1487
+ const KEY_BACKSPACE = 8;
1488
+ const KEY_DELETE = 46;
1489
+ const KEY_TAB = 9;
1490
+ const IS_MAC = typeof navigator === 'undefined' ? false : /Mac/.test(navigator.userAgent);
1491
+ const KEY_SHORTCUT = IS_MAC ? 'metaKey' : 'ctrlKey'; // ctrl key or apple key for ma
1492
+
1493
+ var defaults = {
1494
+ options: [],
1495
+ optgroups: [],
1496
+ plugins: [],
1497
+ delimiter: ',',
1498
+ splitOn: null,
1499
+ // regexp or string for splitting up values from a paste command
1500
+ persist: true,
1501
+ diacritics: true,
1502
+ create: null,
1503
+ createOnBlur: false,
1504
+ createFilter: null,
1505
+ clearAfterSelect: false,
1506
+ highlight: true,
1507
+ openOnFocus: true,
1508
+ shouldOpen: null,
1509
+ maxOptions: 50,
1510
+ maxItems: null,
1511
+ hideSelected: null,
1512
+ duplicates: false,
1513
+ addPrecedence: false,
1514
+ selectOnTab: false,
1515
+ preload: null,
1516
+ allowEmptyOption: false,
1517
+ //closeAfterSelect: false,
1518
+ refreshThrottle: 300,
1519
+ loadThrottle: 300,
1520
+ loadingClass: 'loading',
1521
+ dataAttr: null,
1522
+ //'data-data',
1523
+ optgroupField: 'optgroup',
1524
+ valueField: 'value',
1525
+ labelField: 'text',
1526
+ disabledField: 'disabled',
1527
+ optgroupLabelField: 'label',
1528
+ optgroupValueField: 'value',
1529
+ lockOptgroupOrder: false,
1530
+ sortField: '$order',
1531
+ searchField: ['text'],
1532
+ searchConjunction: 'and',
1533
+ mode: null,
1534
+ wrapperClass: 'ts-wrapper',
1535
+ controlClass: 'ts-control',
1536
+ dropdownClass: 'ts-dropdown',
1537
+ dropdownContentClass: 'ts-dropdown-content',
1538
+ itemClass: 'item',
1539
+ optionClass: 'option',
1540
+ dropdownParent: null,
1541
+ controlInput: '<input type="text" autocomplete="off" size="1" />',
1542
+ copyClassesToDropdown: false,
1543
+ placeholder: null,
1544
+ hidePlaceholder: null,
1545
+ shouldLoad: function (query) {
1546
+ return query.length > 0;
1547
+ },
1548
+ /*
1549
+ load : null, // function(query, callback) { ... }
1550
+ score : null, // function(search) { ... }
1551
+ onInitialize : null, // function() { ... }
1552
+ onChange : null, // function(value) { ... }
1553
+ onItemAdd : null, // function(value, $item) { ... }
1554
+ onItemRemove : null, // function(value) { ... }
1555
+ onClear : null, // function() { ... }
1556
+ onOptionAdd : null, // function(value, data) { ... }
1557
+ onOptionRemove : null, // function(value) { ... }
1558
+ onOptionClear : null, // function() { ... }
1559
+ onOptionGroupAdd : null, // function(id, data) { ... }
1560
+ onOptionGroupRemove : null, // function(id) { ... }
1561
+ onOptionGroupClear : null, // function() { ... }
1562
+ onDropdownOpen : null, // function(dropdown) { ... }
1563
+ onDropdownClose : null, // function(dropdown) { ... }
1564
+ onType : null, // function(str) { ... }
1565
+ onDelete : null, // function(values) { ... }
1566
+ */
1567
+
1568
+ render: {
1569
+ /*
1570
+ item: null,
1571
+ optgroup: null,
1572
+ optgroup_header: null,
1573
+ option: null,
1574
+ option_create: null
1575
+ */
1576
+ }
1577
+ };
1578
+
1579
+ function getSettings(input, settings_user) {
1580
+ var settings = Object.assign({}, defaults, settings_user);
1581
+ var attr_data = settings.dataAttr;
1582
+ var field_label = settings.labelField;
1583
+ var field_value = settings.valueField;
1584
+ var field_disabled = settings.disabledField;
1585
+ var field_optgroup = settings.optgroupField;
1586
+ var field_optgroup_label = settings.optgroupLabelField;
1587
+ var field_optgroup_value = settings.optgroupValueField;
1588
+ var tag_name = input.tagName.toLowerCase();
1589
+ var placeholder = input.getAttribute('placeholder') || input.getAttribute('data-placeholder');
1590
+ if (!placeholder && !settings.allowEmptyOption) {
1591
+ let option = input.querySelector('option[value=""]');
1592
+ if (option) {
1593
+ placeholder = option.textContent;
1594
+ }
1595
+ }
1596
+ var settings_element = {
1597
+ placeholder: placeholder,
1598
+ options: [],
1599
+ optgroups: [],
1600
+ items: [],
1601
+ maxItems: null
1602
+ };
1603
+
1604
+ /**
1605
+ * Initialize from a <select> element.
1606
+ *
1607
+ */
1608
+ var init_select = () => {
1609
+ var tagName;
1610
+ var options = settings_element.options;
1611
+ var optionsMap = {};
1612
+ var group_count = 1;
1613
+ let $order = 0;
1614
+ var readData = el => {
1615
+ var data = Object.assign({}, el.dataset); // get plain object from DOMStringMap
1616
+ var json = attr_data && data[attr_data];
1617
+ if (typeof json === 'string' && json.length) {
1618
+ data = Object.assign(data, JSON.parse(json));
1619
+ }
1620
+ return data;
1621
+ };
1622
+ var addOption = (option, group) => {
1623
+ var value = hash_key(option.value);
1624
+ if (value == null) return;
1625
+ if (!value && !settings.allowEmptyOption) return;
1626
+
1627
+ // if the option already exists, it's probably been
1628
+ // duplicated in another optgroup. in this case, push
1629
+ // the current group to the "optgroup" property on the
1630
+ // existing option so that it's rendered in both places.
1631
+ if (optionsMap.hasOwnProperty(value)) {
1632
+ if (group) {
1633
+ var arr = optionsMap[value][field_optgroup];
1634
+ if (!arr) {
1635
+ optionsMap[value][field_optgroup] = group;
1636
+ } else if (!Array.isArray(arr)) {
1637
+ optionsMap[value][field_optgroup] = [arr, group];
1638
+ } else {
1639
+ arr.push(group);
1640
+ }
1641
+ }
1642
+ } else {
1643
+ var option_data = readData(option);
1644
+ option_data[field_label] = option_data[field_label] || option.textContent;
1645
+ option_data[field_value] = option_data[field_value] || value;
1646
+ option_data[field_disabled] = option_data[field_disabled] || option.disabled;
1647
+ option_data[field_optgroup] = option_data[field_optgroup] || group;
1648
+ option_data.$option = option;
1649
+ option_data.$order = option_data.$order || ++$order;
1650
+ optionsMap[value] = option_data;
1651
+ options.push(option_data);
1652
+ }
1653
+ if (option.selected) {
1654
+ settings_element.items.push(value);
1655
+ }
1656
+ };
1657
+ var addGroup = optgroup => {
1658
+ var id, optgroup_data;
1659
+ optgroup_data = readData(optgroup);
1660
+ optgroup_data[field_optgroup_label] = optgroup_data[field_optgroup_label] || optgroup.getAttribute('label') || '';
1661
+ optgroup_data[field_optgroup_value] = optgroup_data[field_optgroup_value] || group_count++;
1662
+ optgroup_data[field_disabled] = optgroup_data[field_disabled] || optgroup.disabled;
1663
+ optgroup_data.$order = optgroup_data.$order || ++$order;
1664
+ settings_element.optgroups.push(optgroup_data);
1665
+ id = optgroup_data[field_optgroup_value];
1666
+ iterate(optgroup.children, option => {
1667
+ addOption(option, id);
1668
+ });
1669
+ };
1670
+ settings_element.maxItems = input.hasAttribute('multiple') ? null : 1;
1671
+ iterate(input.children, child => {
1672
+ tagName = child.tagName.toLowerCase();
1673
+ if (tagName === 'optgroup') {
1674
+ addGroup(child);
1675
+ } else if (tagName === 'option') {
1676
+ addOption(child);
1677
+ }
1678
+ });
1679
+ };
1680
+
1681
+ /**
1682
+ * Initialize from a <input type="text"> element.
1683
+ *
1684
+ */
1685
+ var init_textbox = () => {
1686
+ const data_raw = input.getAttribute(attr_data);
1687
+ if (!data_raw) {
1688
+ var value = input.value.trim() || '';
1689
+ if (!settings.allowEmptyOption && !value.length) return;
1690
+ const values = value.split(settings.delimiter);
1691
+ iterate(values, value => {
1692
+ const option = {};
1693
+ option[field_label] = value;
1694
+ option[field_value] = value;
1695
+ settings_element.options.push(option);
1696
+ });
1697
+ settings_element.items = values;
1698
+ } else {
1699
+ settings_element.options = JSON.parse(data_raw);
1700
+ iterate(settings_element.options, opt => {
1701
+ settings_element.items.push(opt[field_value]);
1702
+ });
1703
+ }
1704
+ };
1705
+ if (tag_name === 'select') {
1706
+ init_select();
1707
+ } else {
1708
+ init_textbox();
1709
+ }
1710
+ return Object.assign({}, defaults, settings_element, settings_user);
1711
+ }
1712
+
1713
+ var instance_i = 0;
1714
+ class TomSelect extends MicroPlugin(MicroEvent) {
1715
+ constructor(input_arg, user_settings) {
1716
+ super();
1717
+ this.order = 0;
1718
+ this.isOpen = false;
1719
+ this.isDisabled = false;
1720
+ this.isReadOnly = false;
1721
+ this.isInvalid = false;
1722
+ // @deprecated 1.8
1723
+ this.isValid = true;
1724
+ this.isLocked = false;
1725
+ this.isFocused = false;
1726
+ this.isInputHidden = false;
1727
+ this.isSetup = false;
1728
+ this.ignoreFocus = false;
1729
+ this.ignoreHover = false;
1730
+ this.hasOptions = false;
1731
+ this.lastValue = '';
1732
+ this.caretPos = 0;
1733
+ this.loading = 0;
1734
+ this.loadedSearches = {};
1735
+ this.activeOption = null;
1736
+ this.activeItems = [];
1737
+ this.optgroups = {};
1738
+ this.options = {};
1739
+ this.userOptions = {};
1740
+ this.items = [];
1741
+ this.refreshTimeout = null;
1742
+ instance_i++;
1743
+ var dir;
1744
+ var input = getDom(input_arg);
1745
+ if (input.tomselect) {
1746
+ throw new Error('Tom Select already initialized on this element');
1747
+ }
1748
+ input.tomselect = this;
1749
+
1750
+ // detect rtl environment
1751
+ var computedStyle = window.getComputedStyle && window.getComputedStyle(input, null);
1752
+ dir = computedStyle.getPropertyValue('direction');
1753
+
1754
+ // setup default state
1755
+ const settings = getSettings(input, user_settings);
1756
+ this.settings = settings;
1757
+ this.input = input;
1758
+ this.tabIndex = input.tabIndex || 0;
1759
+ this.is_select_tag = input.tagName.toLowerCase() === 'select';
1760
+ this.rtl = /rtl/i.test(dir);
1761
+ this.inputId = getId(input, 'tomselect-' + instance_i);
1762
+ this.isRequired = input.required;
1763
+
1764
+ // search system
1765
+ this.sifter = new Sifter(this.options, {
1766
+ diacritics: settings.diacritics
1767
+ });
1768
+
1769
+ // option-dependent defaults
1770
+ settings.mode = settings.mode || (settings.maxItems === 1 ? 'single' : 'multi');
1771
+ if (typeof settings.hideSelected !== 'boolean') {
1772
+ settings.hideSelected = settings.mode === 'multi';
1773
+ }
1774
+ if (typeof settings.hidePlaceholder !== 'boolean') {
1775
+ settings.hidePlaceholder = settings.mode !== 'multi';
1776
+ }
1777
+
1778
+ // set up createFilter callback
1779
+ var filter = settings.createFilter;
1780
+ if (typeof filter !== 'function') {
1781
+ if (typeof filter === 'string') {
1782
+ filter = new RegExp(filter);
1783
+ }
1784
+ if (filter instanceof RegExp) {
1785
+ settings.createFilter = input => filter.test(input);
1786
+ } else {
1787
+ settings.createFilter = value => {
1788
+ return this.settings.duplicates || !this.options[value];
1789
+ };
1790
+ }
1791
+ }
1792
+ this.initializePlugins(settings.plugins);
1793
+ this.setupCallbacks();
1794
+ this.setupTemplates();
1795
+
1796
+ // Create all elements
1797
+ const wrapper = getDom('<div>');
1798
+ const control = getDom('<div>');
1799
+ const dropdown = this._render('dropdown');
1800
+ const dropdown_content = getDom(`<div role="listbox" tabindex="-1">`);
1801
+ const classes = this.input.getAttribute('class') || '';
1802
+ const inputMode = settings.mode;
1803
+ var control_input;
1804
+ addClasses(wrapper, settings.wrapperClass, classes, inputMode);
1805
+ addClasses(control, settings.controlClass);
1806
+ append(wrapper, control);
1807
+ addClasses(dropdown, settings.dropdownClass, inputMode);
1808
+ if (settings.copyClassesToDropdown) {
1809
+ addClasses(dropdown, classes);
1810
+ }
1811
+ addClasses(dropdown_content, settings.dropdownContentClass);
1812
+ append(dropdown, dropdown_content);
1813
+ getDom(settings.dropdownParent || wrapper).appendChild(dropdown);
1814
+
1815
+ // default controlInput
1816
+ if (isHtmlString(settings.controlInput)) {
1817
+ control_input = getDom(settings.controlInput);
1818
+
1819
+ // set attributes
1820
+ var attrs = ['autocorrect', 'autocapitalize', 'autocomplete', 'spellcheck', 'aria-label'];
1821
+ iterate(attrs, attr => {
1822
+ if (input.getAttribute(attr)) {
1823
+ setAttr(control_input, {
1824
+ [attr]: input.getAttribute(attr)
1825
+ });
1826
+ }
1827
+ });
1828
+ control_input.tabIndex = -1;
1829
+ control.appendChild(control_input);
1830
+ this.focus_node = control_input;
1831
+
1832
+ // dom element
1833
+ } else if (settings.controlInput) {
1834
+ control_input = getDom(settings.controlInput);
1835
+ this.focus_node = control_input;
1836
+ } else {
1837
+ control_input = getDom('<input/>');
1838
+ this.focus_node = control;
1839
+ }
1840
+ this.wrapper = wrapper;
1841
+ this.dropdown = dropdown;
1842
+ this.dropdown_content = dropdown_content;
1843
+ this.control = control;
1844
+ this.control_input = control_input;
1845
+ this.setup();
1846
+ }
1847
+
1848
+ /**
1849
+ * set up event bindings.
1850
+ *
1851
+ */
1852
+ setup() {
1853
+ const self = this;
1854
+ const settings = self.settings;
1855
+ const control_input = self.control_input;
1856
+ const dropdown = self.dropdown;
1857
+ const dropdown_content = self.dropdown_content;
1858
+ const wrapper = self.wrapper;
1859
+ const control = self.control;
1860
+ const input = self.input;
1861
+ const focus_node = self.focus_node;
1862
+ const passive_event = {
1863
+ passive: true
1864
+ };
1865
+ const listboxId = self.inputId + '-ts-dropdown';
1866
+ setAttr(dropdown_content, {
1867
+ id: listboxId
1868
+ });
1869
+ setAttr(focus_node, {
1870
+ role: 'combobox',
1871
+ 'aria-haspopup': 'listbox',
1872
+ 'aria-expanded': 'false',
1873
+ 'aria-controls': listboxId
1874
+ });
1875
+ const control_id = getId(focus_node, self.inputId + '-ts-control');
1876
+ const query = "label[for='" + escapeQuery(self.inputId) + "']";
1877
+ const label = document.querySelector(query);
1878
+ const label_click = self.focus.bind(self);
1879
+ if (label) {
1880
+ addEvent(label, 'click', label_click);
1881
+ setAttr(label, {
1882
+ for: control_id
1883
+ });
1884
+ const label_id = getId(label, self.inputId + '-ts-label');
1885
+ setAttr(focus_node, {
1886
+ 'aria-labelledby': label_id
1887
+ });
1888
+ setAttr(dropdown_content, {
1889
+ 'aria-labelledby': label_id
1890
+ });
1891
+ }
1892
+ wrapper.style.width = input.style.width;
1893
+ wrapper.style.minWidth = input.style.minWidth;
1894
+ wrapper.style.maxWidth = input.style.maxWidth;
1895
+ if (self.plugins.names.length) {
1896
+ const classes_plugins = 'plugin-' + self.plugins.names.join(' plugin-');
1897
+ addClasses([wrapper, dropdown], classes_plugins);
1898
+ }
1899
+ if ((settings.maxItems === null || settings.maxItems > 1) && self.is_select_tag) {
1900
+ setAttr(input, {
1901
+ multiple: 'multiple'
1902
+ });
1903
+ }
1904
+ if (settings.placeholder) {
1905
+ setAttr(control_input, {
1906
+ placeholder: settings.placeholder
1907
+ });
1908
+ }
1909
+
1910
+ // if splitOn was not passed in, construct it from the delimiter to allow pasting universally
1911
+ if (!settings.splitOn && settings.delimiter) {
1912
+ settings.splitOn = new RegExp('\\s*' + escape_regex(settings.delimiter) + '+\\s*');
1913
+ }
1914
+
1915
+ // debounce user defined load() if loadThrottle > 0
1916
+ // after initializePlugins() so plugins can create/modify user defined loaders
1917
+ if (settings.load && settings.loadThrottle) {
1918
+ settings.load = loadDebounce(settings.load, settings.loadThrottle);
1919
+ }
1920
+ addEvent(dropdown, 'mousemove', () => {
1921
+ self.ignoreHover = false;
1922
+ });
1923
+ addEvent(dropdown, 'mouseenter', e => {
1924
+ var target_match = parentMatch(e.target, '[data-selectable]', dropdown);
1925
+ if (target_match) self.onOptionHover(e, target_match);
1926
+ }, {
1927
+ capture: true
1928
+ });
1929
+
1930
+ // clicking on an option should select it
1931
+ addEvent(dropdown, 'click', evt => {
1932
+ const option = parentMatch(evt.target, '[data-selectable]');
1933
+ if (option) {
1934
+ self.onOptionSelect(evt, option);
1935
+ preventDefault(evt, true);
1936
+ }
1937
+ });
1938
+ addEvent(control, 'click', evt => {
1939
+ var target_match = parentMatch(evt.target, '[data-ts-item]', control);
1940
+ if (target_match && self.onItemSelect(evt, target_match)) {
1941
+ preventDefault(evt, true);
1942
+ return;
1943
+ }
1944
+
1945
+ // retain focus (see control_input mousedown)
1946
+ if (control_input.value != '') {
1947
+ return;
1948
+ }
1949
+ self.onClick();
1950
+ preventDefault(evt, true);
1951
+ });
1952
+
1953
+ // keydown on focus_node for arrow_down/arrow_up
1954
+ addEvent(focus_node, 'keydown', e => self.onKeyDown(e));
1955
+
1956
+ // keypress and input/keyup
1957
+ addEvent(control_input, 'keypress', e => self.onKeyPress(e));
1958
+ addEvent(control_input, 'input', e => self.onInput(e));
1959
+ addEvent(focus_node, 'blur', e => self.onBlur(e));
1960
+ addEvent(focus_node, 'focus', e => self.onFocus(e));
1961
+ addEvent(control_input, 'paste', e => self.onPaste(e));
1962
+ const doc_mousedown = evt => {
1963
+ // blur if target is outside of this instance
1964
+ // dropdown is not always inside wrapper
1965
+ const target = evt.composedPath()[0];
1966
+ if (!wrapper.contains(target) && !dropdown.contains(target)) {
1967
+ if (self.isFocused) {
1968
+ self.blur();
1969
+ }
1970
+ self.inputState();
1971
+ return;
1972
+ }
1973
+
1974
+ // retain focus by preventing native handling. if the
1975
+ // event target is the input it should not be modified.
1976
+ // otherwise, text selection within the input won't work.
1977
+ // Fixes bug #212 which is no covered by tests
1978
+ if (target == control_input && self.isOpen) {
1979
+ evt.stopPropagation();
1980
+
1981
+ // clicking anywhere in the control should not blur the control_input (which would close the dropdown)
1982
+ } else {
1983
+ preventDefault(evt, true);
1984
+ }
1985
+ };
1986
+ const win_scroll = () => {
1987
+ if (self.isOpen) {
1988
+ self.positionDropdown();
1989
+ }
1990
+ };
1991
+ const input_invalid = () => {
1992
+ if (self.isValid) {
1993
+ self.isValid = false;
1994
+ self.isInvalid = true;
1995
+ self.refreshState();
1996
+ }
1997
+ };
1998
+ addEvent(input, 'invalid', input_invalid);
1999
+ addEvent(document, 'mousedown', doc_mousedown);
2000
+ addEvent(window, 'scroll', win_scroll, passive_event);
2001
+ addEvent(window, 'resize', win_scroll, passive_event);
2002
+ this._destroy = () => {
2003
+ input.removeEventListener('invalid', input_invalid);
2004
+ document.removeEventListener('mousedown', doc_mousedown);
2005
+ window.removeEventListener('scroll', win_scroll);
2006
+ window.removeEventListener('resize', win_scroll);
2007
+ if (label) label.removeEventListener('click', label_click);
2008
+ };
2009
+
2010
+ // store original html and tab index so that they can be
2011
+ // restored when the destroy() method is called.
2012
+ this.revertSettings = {
2013
+ innerHTML: input.innerHTML,
2014
+ tabIndex: input.tabIndex
2015
+ };
2016
+ input.tabIndex = -1;
2017
+ input.insertAdjacentElement('afterend', self.wrapper);
2018
+ self.sync(false);
2019
+ settings.items = [];
2020
+ delete settings.optgroups;
2021
+ delete settings.options;
2022
+ self.refreshItems();
2023
+ self.close(false);
2024
+ self.inputState();
2025
+ self.isSetup = true;
2026
+ if (input.disabled) {
2027
+ self.disable();
2028
+ } else if (input.readOnly) {
2029
+ self.setReadOnly(true);
2030
+ } else {
2031
+ self.enable(); //sets tabIndex
2032
+ }
2033
+ self.on('change', this.onChange);
2034
+ addClasses(input, 'tomselected', 'ts-hidden-accessible');
2035
+ self.trigger('initialize');
2036
+
2037
+ // preload options
2038
+ if (settings.preload === true) {
2039
+ self.preload();
2040
+ }
2041
+ }
2042
+
2043
+ /**
2044
+ * Register options and optgroups
2045
+ *
2046
+ */
2047
+ setupOptions(options = [], optgroups = []) {
2048
+ // build options table
2049
+ this.addOptions(options);
2050
+
2051
+ // build optgroup table
2052
+ iterate(optgroups, optgroup => {
2053
+ this.registerOptionGroup(optgroup);
2054
+ });
2055
+ }
2056
+
2057
+ /**
2058
+ * Sets up default rendering functions.
2059
+ */
2060
+ setupTemplates() {
2061
+ var self = this;
2062
+ var field_label = self.settings.labelField;
2063
+ var field_optgroup = self.settings.optgroupLabelField;
2064
+ var templates = {
2065
+ 'optgroup': data => {
2066
+ let optgroup = document.createElement('div');
2067
+ optgroup.className = 'optgroup';
2068
+ optgroup.appendChild(data.options);
2069
+ return optgroup;
2070
+ },
2071
+ 'optgroup_header': (data, escape) => {
2072
+ return '<div class="optgroup-header">' + escape(data[field_optgroup]) + '</div>';
2073
+ },
2074
+ 'option': (data, escape) => {
2075
+ return '<div>' + escape(data[field_label]) + '</div>';
2076
+ },
2077
+ 'item': (data, escape) => {
2078
+ return '<div>' + escape(data[field_label]) + '</div>';
2079
+ },
2080
+ 'option_create': (data, escape) => {
2081
+ return '<div class="create">Add <strong>' + escape(data.input) + '</strong>&hellip;</div>';
2082
+ },
2083
+ 'no_results': () => {
2084
+ return '<div class="no-results">No results found</div>';
2085
+ },
2086
+ 'loading': () => {
2087
+ return '<div class="spinner"></div>';
2088
+ },
2089
+ 'not_loading': () => {},
2090
+ 'dropdown': () => {
2091
+ return '<div></div>';
2092
+ }
2093
+ };
2094
+ self.settings.render = Object.assign({}, templates, self.settings.render);
2095
+ }
2096
+
2097
+ /**
2098
+ * Maps fired events to callbacks provided
2099
+ * in the settings used when creating the control.
2100
+ */
2101
+ setupCallbacks() {
2102
+ var key, fn;
2103
+ var callbacks = {
2104
+ 'initialize': 'onInitialize',
2105
+ 'change': 'onChange',
2106
+ 'item_add': 'onItemAdd',
2107
+ 'item_remove': 'onItemRemove',
2108
+ 'item_select': 'onItemSelect',
2109
+ 'clear': 'onClear',
2110
+ 'option_add': 'onOptionAdd',
2111
+ 'option_remove': 'onOptionRemove',
2112
+ 'option_clear': 'onOptionClear',
2113
+ 'optgroup_add': 'onOptionGroupAdd',
2114
+ 'optgroup_remove': 'onOptionGroupRemove',
2115
+ 'optgroup_clear': 'onOptionGroupClear',
2116
+ 'dropdown_open': 'onDropdownOpen',
2117
+ 'dropdown_close': 'onDropdownClose',
2118
+ 'type': 'onType',
2119
+ 'load': 'onLoad',
2120
+ 'focus': 'onFocus',
2121
+ 'blur': 'onBlur'
2122
+ };
2123
+ for (key in callbacks) {
2124
+ fn = this.settings[callbacks[key]];
2125
+ if (fn) this.on(key, fn);
2126
+ }
2127
+ }
2128
+
2129
+ /**
2130
+ * Sync the Tom Select instance with the original input or select
2131
+ *
2132
+ */
2133
+ sync(get_settings = true) {
2134
+ const self = this;
2135
+ const settings = get_settings ? getSettings(self.input, {
2136
+ delimiter: self.settings.delimiter,
2137
+ allowEmptyOption: self.settings.allowEmptyOption
2138
+ }) : self.settings;
2139
+ self.setupOptions(settings.options, settings.optgroups);
2140
+ self.setValue(settings.items || [], true); // silent prevents recursion
2141
+
2142
+ self.lastQuery = null; // so updated options will be displayed in dropdown
2143
+ }
2144
+
2145
+ /**
2146
+ * Triggered when the main control element
2147
+ * has a click event.
2148
+ *
2149
+ */
2150
+ onClick() {
2151
+ var self = this;
2152
+ if (self.activeItems.length > 0) {
2153
+ self.clearActiveItems();
2154
+ self.focus();
2155
+ return;
2156
+ }
2157
+ if (self.isFocused && self.isOpen) {
2158
+ self.blur();
2159
+ } else {
2160
+ self.focus();
2161
+ }
2162
+ }
2163
+
2164
+ /**
2165
+ * @deprecated v1.7
2166
+ *
2167
+ */
2168
+ onMouseDown() {}
2169
+
2170
+ /**
2171
+ * Triggered when the value of the control has been changed.
2172
+ * This should propagate the event to the original DOM
2173
+ * input / select element.
2174
+ */
2175
+ onChange() {
2176
+ triggerEvent(this.input, 'input');
2177
+ triggerEvent(this.input, 'change');
2178
+ }
2179
+
2180
+ /**
2181
+ * Triggered on <input> paste.
2182
+ *
2183
+ */
2184
+ onPaste(e) {
2185
+ var self = this;
2186
+ if (self.isInputHidden || self.isLocked) {
2187
+ preventDefault(e);
2188
+ return;
2189
+ }
2190
+
2191
+ // If a regex or string is included, this will split the pasted
2192
+ // input and create Items for each separate value
2193
+ if (!self.settings.splitOn) {
2194
+ return;
2195
+ }
2196
+
2197
+ // Wait for pasted text to be recognized in value
2198
+ setTimeout(() => {
2199
+ var pastedText = self.inputValue();
2200
+ if (!pastedText.match(self.settings.splitOn)) {
2201
+ return;
2202
+ }
2203
+ var splitInput = pastedText.trim().split(self.settings.splitOn);
2204
+ iterate(splitInput, piece => {
2205
+ const hash = hash_key(piece);
2206
+ if (hash) {
2207
+ if (this.options[piece]) {
2208
+ self.addItem(piece);
2209
+ } else {
2210
+ self.createItem(piece);
2211
+ }
2212
+ }
2213
+ });
2214
+ }, 0);
2215
+ }
2216
+
2217
+ /**
2218
+ * Triggered on <input> keypress.
2219
+ *
2220
+ */
2221
+ onKeyPress(e) {
2222
+ var self = this;
2223
+ if (self.isLocked) {
2224
+ preventDefault(e);
2225
+ return;
2226
+ }
2227
+ var character = String.fromCharCode(e.keyCode || e.which);
2228
+ if (self.settings.create && self.settings.mode === 'multi' && character === self.settings.delimiter) {
2229
+ self.createItem();
2230
+ preventDefault(e);
2231
+ return;
2232
+ }
2233
+ }
2234
+
2235
+ /**
2236
+ * Triggered on <input> keydown.
2237
+ *
2238
+ */
2239
+ onKeyDown(e) {
2240
+ var self = this;
2241
+ self.ignoreHover = true;
2242
+ if (self.isLocked) {
2243
+ if (e.keyCode !== KEY_TAB) {
2244
+ preventDefault(e);
2245
+ }
2246
+ return;
2247
+ }
2248
+ switch (e.keyCode) {
2249
+ // ctrl+A: select all
2250
+ case KEY_A:
2251
+ if (isKeyDown(KEY_SHORTCUT, e)) {
2252
+ if (self.control_input.value == '') {
2253
+ preventDefault(e);
2254
+ self.selectAll();
2255
+ return;
2256
+ }
2257
+ }
2258
+ break;
2259
+
2260
+ // esc: close dropdown
2261
+ case KEY_ESC:
2262
+ if (self.isOpen) {
2263
+ preventDefault(e, true);
2264
+ self.close();
2265
+ }
2266
+ self.clearActiveItems();
2267
+ return;
2268
+
2269
+ // down: open dropdown or move selection down
2270
+ case KEY_DOWN:
2271
+ if (!self.isOpen && self.hasOptions) {
2272
+ self.open();
2273
+ } else if (self.activeOption) {
2274
+ let next = self.getAdjacent(self.activeOption, 1);
2275
+ if (next) self.setActiveOption(next);
2276
+ }
2277
+ preventDefault(e);
2278
+ return;
2279
+
2280
+ // up: move selection up
2281
+ case KEY_UP:
2282
+ if (self.activeOption) {
2283
+ let prev = self.getAdjacent(self.activeOption, -1);
2284
+ if (prev) self.setActiveOption(prev);
2285
+ }
2286
+ preventDefault(e);
2287
+ return;
2288
+
2289
+ // return: select active option
2290
+ case KEY_RETURN:
2291
+ if (self.canSelect(self.activeOption)) {
2292
+ self.onOptionSelect(e, self.activeOption);
2293
+ preventDefault(e);
2294
+
2295
+ // if the option_create=null, the dropdown might be closed
2296
+ } else if (self.settings.create && self.createItem()) {
2297
+ preventDefault(e);
2298
+
2299
+ // don't submit form when searching for a value
2300
+ } else if (document.activeElement == self.control_input && self.isOpen) {
2301
+ preventDefault(e);
2302
+ }
2303
+ return;
2304
+
2305
+ // left: modifiy item selection to the left
2306
+ case KEY_LEFT:
2307
+ self.advanceSelection(-1, e);
2308
+ return;
2309
+
2310
+ // right: modifiy item selection to the right
2311
+ case KEY_RIGHT:
2312
+ self.advanceSelection(1, e);
2313
+ return;
2314
+
2315
+ // tab: select active option and/or create item
2316
+ case KEY_TAB:
2317
+ if (self.settings.selectOnTab) {
2318
+ if (self.canSelect(self.activeOption)) {
2319
+ self.onOptionSelect(e, self.activeOption);
2320
+
2321
+ // prevent default [tab] behaviour of jump to the next field
2322
+ // if select isFull, then the dropdown won't be open and [tab] will work normally
2323
+ preventDefault(e);
2324
+ } else if (self.settings.create && self.createItem()) {
2325
+ preventDefault(e);
2326
+ }
2327
+ }
2328
+ return;
2329
+
2330
+ // delete|backspace: delete items
2331
+ case KEY_BACKSPACE:
2332
+ case KEY_DELETE:
2333
+ self.deleteSelection(e);
2334
+ return;
2335
+ }
2336
+
2337
+ // don't enter text in the control_input when active items are selected
2338
+ if (self.isInputHidden && !isKeyDown(KEY_SHORTCUT, e)) {
2339
+ preventDefault(e);
2340
+ }
2341
+ }
2342
+
2343
+ /**
2344
+ * Triggered on <input> keyup.
2345
+ *
2346
+ */
2347
+ onInput(e) {
2348
+ if (this.isLocked) {
2349
+ return;
2350
+ }
2351
+ const value = this.inputValue();
2352
+ if (this.lastValue === value) return;
2353
+ this.lastValue = value;
2354
+ if (value == '') {
2355
+ this._onInput();
2356
+ return;
2357
+ }
2358
+ if (this.refreshTimeout) {
2359
+ window.clearTimeout(this.refreshTimeout);
2360
+ }
2361
+ this.refreshTimeout = timeout(() => {
2362
+ this.refreshTimeout = null;
2363
+ this._onInput();
2364
+ }, this.settings.refreshThrottle);
2365
+ }
2366
+ _onInput() {
2367
+ const value = this.lastValue;
2368
+ if (this.settings.shouldLoad.call(this, value)) {
2369
+ this.load(value);
2370
+ }
2371
+ this.refreshOptions();
2372
+ this.trigger('type', value);
2373
+ }
2374
+
2375
+ /**
2376
+ * Triggered when the user rolls over
2377
+ * an option in the autocomplete dropdown menu.
2378
+ *
2379
+ */
2380
+ onOptionHover(evt, option) {
2381
+ if (this.ignoreHover) return;
2382
+ this.setActiveOption(option, false);
2383
+ }
2384
+
2385
+ /**
2386
+ * Triggered on <input> focus.
2387
+ *
2388
+ */
2389
+ onFocus(e) {
2390
+ var self = this;
2391
+ var wasFocused = self.isFocused;
2392
+ if (self.isDisabled || self.isReadOnly) {
2393
+ self.blur();
2394
+ preventDefault(e);
2395
+ return;
2396
+ }
2397
+ if (self.ignoreFocus) return;
2398
+ self.isFocused = true;
2399
+ if (self.settings.preload === 'focus') self.preload();
2400
+ if (!wasFocused) self.trigger('focus');
2401
+ if (!self.activeItems.length) {
2402
+ self.inputState();
2403
+ self.refreshOptions(!!self.settings.openOnFocus);
2404
+ }
2405
+ self.refreshState();
2406
+ }
2407
+
2408
+ /**
2409
+ * Triggered on <input> blur.
2410
+ *
2411
+ */
2412
+ onBlur(e) {
2413
+ if (document.hasFocus() === false) return;
2414
+ var self = this;
2415
+ if (!self.isFocused) return;
2416
+ self.isFocused = false;
2417
+ self.ignoreFocus = false;
2418
+ var deactivate = () => {
2419
+ self.close();
2420
+ self.setActiveItem();
2421
+ self.setCaret(self.items.length);
2422
+ self.trigger('blur');
2423
+ };
2424
+ if (self.settings.create && self.settings.createOnBlur) {
2425
+ self.createItem(null, deactivate);
2426
+ } else {
2427
+ deactivate();
2428
+ }
2429
+ }
2430
+
2431
+ /**
2432
+ * Triggered when the user clicks on an option
2433
+ * in the autocomplete dropdown menu.
2434
+ *
2435
+ */
2436
+ onOptionSelect(evt, option) {
2437
+ var value,
2438
+ self = this;
2439
+
2440
+ // should not be possible to trigger a option under a disabled optgroup
2441
+ if (option.parentElement && option.parentElement.matches('[data-disabled]')) {
2442
+ return;
2443
+ }
2444
+ if (option.classList.contains('create')) {
2445
+ self.createItem(null, () => {
2446
+ if (self.settings.closeAfterSelect) {
2447
+ self.close();
2448
+ } else if (self.settings.clearAfterSelect) {
2449
+ self.setTextboxValue();
2450
+ }
2451
+ });
2452
+ } else {
2453
+ value = option.dataset.value;
2454
+ if (typeof value !== 'undefined') {
2455
+ self.lastQuery = null;
2456
+ self.addItem(value);
2457
+ if (self.settings.closeAfterSelect) {
2458
+ self.close();
2459
+ } else if (self.settings.clearAfterSelect) {
2460
+ self.setTextboxValue();
2461
+ }
2462
+ if (!self.settings.hideSelected && evt.type && /click/.test(evt.type)) {
2463
+ self.setActiveOption(option);
2464
+ }
2465
+ }
2466
+ }
2467
+ }
2468
+
2469
+ /**
2470
+ * Return true if the given option can be selected
2471
+ *
2472
+ */
2473
+ canSelect(option) {
2474
+ if (this.isOpen && option && this.dropdown_content.contains(option)) {
2475
+ return true;
2476
+ }
2477
+ return false;
2478
+ }
2479
+
2480
+ /**
2481
+ * Triggered when the user clicks on an item
2482
+ * that has been selected.
2483
+ *
2484
+ */
2485
+ onItemSelect(evt, item) {
2486
+ var self = this;
2487
+ if (!self.isLocked && self.settings.mode === 'multi') {
2488
+ preventDefault(evt);
2489
+ self.setActiveItem(item, evt);
2490
+ return true;
2491
+ }
2492
+ return false;
2493
+ }
2494
+
2495
+ /**
2496
+ * Determines whether or not to invoke
2497
+ * the user-provided option provider / loader
2498
+ *
2499
+ * Note, there is a subtle difference between
2500
+ * this.canLoad() and this.settings.shouldLoad();
2501
+ *
2502
+ * - settings.shouldLoad() is a user-input validator.
2503
+ * When false is returned, the not_loading template
2504
+ * will be added to the dropdown
2505
+ *
2506
+ * - canLoad() is lower level validator that checks
2507
+ * the Tom Select instance. There is no inherent user
2508
+ * feedback when canLoad returns false
2509
+ *
2510
+ */
2511
+ canLoad(value) {
2512
+ if (!this.settings.load) return false;
2513
+ if (this.loadedSearches.hasOwnProperty(value)) return false;
2514
+ return true;
2515
+ }
2516
+
2517
+ /**
2518
+ * Invokes the user-provided option provider / loader.
2519
+ *
2520
+ */
2521
+ load(value) {
2522
+ const self = this;
2523
+ if (!self.canLoad(value)) return;
2524
+ addClasses(self.wrapper, self.settings.loadingClass);
2525
+ self.loading++;
2526
+ const callback = self.loadCallback.bind(self);
2527
+ self.settings.load.call(self, value, callback);
2528
+ }
2529
+
2530
+ /**
2531
+ * Invoked by the user-provided option provider
2532
+ *
2533
+ */
2534
+ loadCallback(options, optgroups) {
2535
+ const self = this;
2536
+ self.loading = Math.max(self.loading - 1, 0);
2537
+ self.lastQuery = null;
2538
+ self.clearActiveOption(); // when new results load, focus should be on first option
2539
+ self.setupOptions(options, optgroups);
2540
+ self.refreshOptions(self.isFocused && !self.isInputHidden);
2541
+ if (!self.loading) {
2542
+ removeClasses(self.wrapper, self.settings.loadingClass);
2543
+ }
2544
+ self.trigger('load', options, optgroups);
2545
+ }
2546
+ preload() {
2547
+ var classList = this.wrapper.classList;
2548
+ if (classList.contains('preloaded')) return;
2549
+ classList.add('preloaded');
2550
+ this.load('');
2551
+ }
2552
+
2553
+ /**
2554
+ * Sets the input field of the control to the specified value.
2555
+ *
2556
+ */
2557
+ setTextboxValue(value = '') {
2558
+ var input = this.control_input;
2559
+ var changed = input.value !== value;
2560
+ if (changed) {
2561
+ input.value = value;
2562
+ triggerEvent(input, 'update');
2563
+ this.lastValue = value;
2564
+ }
2565
+ }
2566
+
2567
+ /**
2568
+ * Returns the value of the control. If multiple items
2569
+ * can be selected (e.g. <select multiple>), this returns
2570
+ * an array. If only one item can be selected, this
2571
+ * returns a string.
2572
+ *
2573
+ */
2574
+ getValue() {
2575
+ if (this.is_select_tag && this.input.hasAttribute('multiple')) {
2576
+ return this.items;
2577
+ }
2578
+ return this.items.join(this.settings.delimiter);
2579
+ }
2580
+
2581
+ /**
2582
+ * Resets the selected items to the given value.
2583
+ *
2584
+ */
2585
+ setValue(value, silent) {
2586
+ var events = silent ? [] : ['change'];
2587
+ debounce_events(this, events, () => {
2588
+ this.clear(silent);
2589
+ this.addItems(value, silent);
2590
+ });
2591
+ }
2592
+
2593
+ /**
2594
+ * Resets the number of max items to the given value
2595
+ *
2596
+ */
2597
+ setMaxItems(value) {
2598
+ if (value === 0) value = null; //reset to unlimited items.
2599
+ this.settings.maxItems = value;
2600
+ this.refreshState();
2601
+ }
2602
+
2603
+ /**
2604
+ * Sets the selected item.
2605
+ *
2606
+ */
2607
+ setActiveItem(item, e) {
2608
+ var self = this;
2609
+ var eventName;
2610
+ var i, begin, end, swap;
2611
+ var last;
2612
+ if (self.settings.mode === 'single') return;
2613
+
2614
+ // clear the active selection
2615
+ if (!item) {
2616
+ self.clearActiveItems();
2617
+ if (self.isFocused) {
2618
+ self.inputState();
2619
+ }
2620
+ return;
2621
+ }
2622
+
2623
+ // modify selection
2624
+ eventName = e && e.type.toLowerCase();
2625
+ if (eventName === 'click' && isKeyDown('shiftKey', e) && self.activeItems.length) {
2626
+ last = self.getLastActive();
2627
+ begin = Array.prototype.indexOf.call(self.control.children, last);
2628
+ end = Array.prototype.indexOf.call(self.control.children, item);
2629
+ if (begin > end) {
2630
+ swap = begin;
2631
+ begin = end;
2632
+ end = swap;
2633
+ }
2634
+ for (i = begin; i <= end; i++) {
2635
+ item = self.control.children[i];
2636
+ if (self.activeItems.indexOf(item) === -1) {
2637
+ self.setActiveItemClass(item);
2638
+ }
2639
+ }
2640
+ preventDefault(e);
2641
+ } else if (eventName === 'click' && isKeyDown(KEY_SHORTCUT, e) || eventName === 'keydown' && isKeyDown('shiftKey', e)) {
2642
+ if (item.classList.contains('active')) {
2643
+ self.removeActiveItem(item);
2644
+ } else {
2645
+ self.setActiveItemClass(item);
2646
+ }
2647
+ } else {
2648
+ self.clearActiveItems();
2649
+ self.setActiveItemClass(item);
2650
+ }
2651
+
2652
+ // ensure control has focus
2653
+ self.inputState();
2654
+ if (!self.isFocused) {
2655
+ self.focus();
2656
+ }
2657
+ }
2658
+
2659
+ /**
2660
+ * Set the active and last-active classes
2661
+ *
2662
+ */
2663
+ setActiveItemClass(item) {
2664
+ const self = this;
2665
+ const last_active = self.control.querySelector('.last-active');
2666
+ if (last_active) removeClasses(last_active, 'last-active');
2667
+ addClasses(item, 'active last-active');
2668
+ self.trigger('item_select', item);
2669
+ if (self.activeItems.indexOf(item) == -1) {
2670
+ self.activeItems.push(item);
2671
+ }
2672
+ }
2673
+
2674
+ /**
2675
+ * Remove active item
2676
+ *
2677
+ */
2678
+ removeActiveItem(item) {
2679
+ var idx = this.activeItems.indexOf(item);
2680
+ this.activeItems.splice(idx, 1);
2681
+ removeClasses(item, 'active');
2682
+ }
2683
+
2684
+ /**
2685
+ * Clears all the active items
2686
+ *
2687
+ */
2688
+ clearActiveItems() {
2689
+ removeClasses(this.activeItems, 'active');
2690
+ this.activeItems = [];
2691
+ }
2692
+
2693
+ /**
2694
+ * Sets the selected item in the dropdown menu
2695
+ * of available options.
2696
+ *
2697
+ */
2698
+ setActiveOption(option, scroll = true) {
2699
+ if (option === this.activeOption) {
2700
+ return;
2701
+ }
2702
+ this.clearActiveOption();
2703
+ if (!option) return;
2704
+ this.activeOption = option;
2705
+ setAttr(this.focus_node, {
2706
+ 'aria-activedescendant': option.getAttribute('id')
2707
+ });
2708
+ setAttr(option, {
2709
+ 'aria-selected': 'true'
2710
+ });
2711
+ addClasses(option, 'active');
2712
+ if (scroll) this.scrollToOption(option);
2713
+ }
2714
+
2715
+ /**
2716
+ * Sets the dropdown_content scrollTop to display the option
2717
+ *
2718
+ */
2719
+ scrollToOption(option, behavior) {
2720
+ if (!option) return;
2721
+ const content = this.dropdown_content;
2722
+ const height_menu = content.clientHeight;
2723
+ const scrollTop = content.scrollTop || 0;
2724
+ const height_item = option.offsetHeight;
2725
+ const y = option.getBoundingClientRect().top - content.getBoundingClientRect().top + scrollTop;
2726
+ if (y + height_item > height_menu + scrollTop) {
2727
+ this.scroll(y - height_menu + height_item, behavior);
2728
+ } else if (y < scrollTop) {
2729
+ this.scroll(y, behavior);
2730
+ }
2731
+ }
2732
+
2733
+ /**
2734
+ * Scroll the dropdown to the given position
2735
+ *
2736
+ */
2737
+ scroll(scrollTop, behavior) {
2738
+ const content = this.dropdown_content;
2739
+ if (behavior) {
2740
+ content.style.scrollBehavior = behavior;
2741
+ }
2742
+ content.scrollTop = scrollTop;
2743
+ content.style.scrollBehavior = '';
2744
+ }
2745
+
2746
+ /**
2747
+ * Clears the active option
2748
+ *
2749
+ */
2750
+ clearActiveOption() {
2751
+ if (this.activeOption) {
2752
+ removeClasses(this.activeOption, 'active');
2753
+ setAttr(this.activeOption, {
2754
+ 'aria-selected': null
2755
+ });
2756
+ }
2757
+ this.activeOption = null;
2758
+ setAttr(this.focus_node, {
2759
+ 'aria-activedescendant': null
2760
+ });
2761
+ }
2762
+
2763
+ /**
2764
+ * Selects all items (CTRL + A).
2765
+ */
2766
+ selectAll() {
2767
+ const self = this;
2768
+ if (self.settings.mode === 'single') return;
2769
+ const activeItems = self.controlChildren();
2770
+ if (!activeItems.length) return;
2771
+ self.inputState();
2772
+ self.close();
2773
+ self.activeItems = activeItems;
2774
+ iterate(activeItems, item => {
2775
+ self.setActiveItemClass(item);
2776
+ });
2777
+ }
2778
+
2779
+ /**
2780
+ * Determines if the control_input should be in a hidden or visible state
2781
+ *
2782
+ */
2783
+ inputState() {
2784
+ var self = this;
2785
+ if (!self.control.contains(self.control_input)) return;
2786
+ setAttr(self.control_input, {
2787
+ placeholder: self.settings.placeholder
2788
+ });
2789
+ if (self.activeItems.length > 0 || !self.isFocused && self.settings.hidePlaceholder && self.items.length > 0) {
2790
+ self.setTextboxValue();
2791
+ self.isInputHidden = true;
2792
+ } else {
2793
+ if (self.settings.hidePlaceholder && self.items.length > 0) {
2794
+ setAttr(self.control_input, {
2795
+ placeholder: ''
2796
+ });
2797
+ }
2798
+ self.isInputHidden = false;
2799
+ }
2800
+ self.wrapper.classList.toggle('input-hidden', self.isInputHidden);
2801
+ }
2802
+
2803
+ /**
2804
+ * Get the input value
2805
+ */
2806
+ inputValue() {
2807
+ return this.control_input.value.trim();
2808
+ }
2809
+
2810
+ /**
2811
+ * Gives the control focus.
2812
+ */
2813
+ focus() {
2814
+ var self = this;
2815
+ if (self.isDisabled || self.isReadOnly) return;
2816
+ self.ignoreFocus = true;
2817
+ if (self.control_input.offsetWidth) {
2818
+ self.control_input.focus();
2819
+ } else {
2820
+ self.focus_node.focus();
2821
+ }
2822
+ setTimeout(() => {
2823
+ self.ignoreFocus = false;
2824
+ self.onFocus();
2825
+ }, 0);
2826
+ }
2827
+
2828
+ /**
2829
+ * Forces the control out of focus.
2830
+ *
2831
+ */
2832
+ blur() {
2833
+ this.focus_node.blur();
2834
+ this.onBlur();
2835
+ }
2836
+
2837
+ /**
2838
+ * Returns a function that scores an object
2839
+ * to show how good of a match it is to the
2840
+ * provided query.
2841
+ *
2842
+ * @return {function}
2843
+ */
2844
+ getScoreFunction(query) {
2845
+ return this.sifter.getScoreFunction(query, this.getSearchOptions());
2846
+ }
2847
+
2848
+ /**
2849
+ * Returns search options for sifter (the system
2850
+ * for scoring and sorting results).
2851
+ *
2852
+ * @see https://github.com/orchidjs/sifter.js
2853
+ * @return {object}
2854
+ */
2855
+ getSearchOptions() {
2856
+ var settings = this.settings;
2857
+ var sort = settings.sortField;
2858
+ if (typeof settings.sortField === 'string') {
2859
+ sort = [{
2860
+ field: settings.sortField
2861
+ }];
2862
+ }
2863
+ return {
2864
+ fields: settings.searchField,
2865
+ conjunction: settings.searchConjunction,
2866
+ sort: sort,
2867
+ nesting: settings.nesting
2868
+ };
2869
+ }
2870
+
2871
+ /**
2872
+ * Searches through available options and returns
2873
+ * a sorted array of matches.
2874
+ *
2875
+ */
2876
+ search(query) {
2877
+ var result, calculateScore;
2878
+ var self = this;
2879
+ var options = this.getSearchOptions();
2880
+
2881
+ // validate user-provided result scoring function
2882
+ if (self.settings.score) {
2883
+ calculateScore = self.settings.score.call(self, query);
2884
+ if (typeof calculateScore !== 'function') {
2885
+ throw new Error('Tom Select "score" setting must be a function that returns a function');
2886
+ }
2887
+ }
2888
+
2889
+ // perform search
2890
+ if (query !== self.lastQuery) {
2891
+ self.lastQuery = query;
2892
+ // temp fix for https://github.com/orchidjs/tom-select/issues/987
2893
+ // UI crashed when more than 30 same chars in a row, prevent search and return empt result
2894
+ if (/(.)\1{15,}/.test(query)) {
2895
+ query = '';
2896
+ }
2897
+ result = self.sifter.search(query, Object.assign(options, {
2898
+ score: calculateScore
2899
+ }));
2900
+ self.currentResults = result;
2901
+ } else {
2902
+ result = Object.assign({}, self.currentResults);
2903
+ }
2904
+
2905
+ // filter out selected items
2906
+ if (self.settings.hideSelected) {
2907
+ result.items = result.items.filter(item => {
2908
+ let hashed = hash_key(item.id);
2909
+ return !(hashed !== null && self.items.indexOf(hashed) !== -1);
2910
+ });
2911
+ }
2912
+ return result;
2913
+ }
2914
+
2915
+ /**
2916
+ * Refreshes the list of available options shown
2917
+ * in the autocomplete dropdown menu.
2918
+ *
2919
+ */
2920
+ refreshOptions(triggerDropdown = true) {
2921
+ var i, j, k, n, optgroup, optgroups, html, has_create_option, active_group;
2922
+ var create;
2923
+ const groups = {};
2924
+ const groups_order = [];
2925
+ var self = this;
2926
+ var query = self.inputValue();
2927
+ const same_query = query === self.lastQuery || query == '' && self.lastQuery == null;
2928
+ var results = self.search(query);
2929
+ var active_option = null;
2930
+ var show_dropdown = self.settings.shouldOpen || false;
2931
+ var dropdown_content = self.dropdown_content;
2932
+ if (same_query) {
2933
+ active_option = self.activeOption;
2934
+ if (active_option) {
2935
+ active_group = active_option.closest('[data-group]');
2936
+ }
2937
+ }
2938
+
2939
+ // build markup
2940
+ n = results.items.length;
2941
+ if (typeof self.settings.maxOptions === 'number') {
2942
+ n = Math.min(n, self.settings.maxOptions);
2943
+ }
2944
+ if (n > 0) {
2945
+ show_dropdown = true;
2946
+ }
2947
+
2948
+ // get fragment for group and the position of the group in group_order
2949
+ const getGroupFragment = (optgroup, order) => {
2950
+ let group_order_i = groups[optgroup];
2951
+ if (group_order_i !== undefined) {
2952
+ let order_group = groups_order[group_order_i];
2953
+ if (order_group !== undefined) {
2954
+ return [group_order_i, order_group.fragment];
2955
+ }
2956
+ }
2957
+ let group_fragment = document.createDocumentFragment();
2958
+ group_order_i = groups_order.length;
2959
+ groups_order.push({
2960
+ fragment: group_fragment,
2961
+ order,
2962
+ optgroup
2963
+ });
2964
+ return [group_order_i, group_fragment];
2965
+ };
2966
+
2967
+ // render and group available options individually
2968
+ for (i = 0; i < n; i++) {
2969
+ // get option dom element
2970
+ let item = results.items[i];
2971
+ if (!item) continue;
2972
+ let opt_value = item.id;
2973
+ let option = self.options[opt_value];
2974
+ if (option === undefined) continue;
2975
+ let opt_hash = get_hash(opt_value);
2976
+ let option_el = self.getOption(opt_hash, true);
2977
+
2978
+ // toggle 'selected' class
2979
+ if (!self.settings.hideSelected) {
2980
+ option_el.classList.toggle('selected', self.items.includes(opt_hash));
2981
+ }
2982
+ optgroup = option[self.settings.optgroupField] || '';
2983
+ optgroups = Array.isArray(optgroup) ? optgroup : [optgroup];
2984
+ for (j = 0, k = optgroups && optgroups.length; j < k; j++) {
2985
+ optgroup = optgroups[j];
2986
+ let order = option.$order;
2987
+ let self_optgroup = self.optgroups[optgroup];
2988
+ if (self_optgroup === undefined && typeof self.settings.optionGroupRegister === 'function') {
2989
+ var regGroup;
2990
+ if (regGroup = self.settings.optionGroupRegister.apply(self, [optgroup])) {
2991
+ self.registerOptionGroup(regGroup);
2992
+ }
2993
+ }
2994
+ self_optgroup = self.optgroups[optgroup];
2995
+ if (self_optgroup === undefined) {
2996
+ optgroup = '';
2997
+ } else {
2998
+ order = self_optgroup.$order;
2999
+ }
3000
+ const [group_order_i, group_fragment] = getGroupFragment(optgroup, order);
3001
+
3002
+ // nodes can only have one parent, so if the option is in mutple groups, we need a clone
3003
+ if (j > 0) {
3004
+ option_el = option_el.cloneNode(true);
3005
+ setAttr(option_el, {
3006
+ id: option.$id + '-clone-' + j,
3007
+ 'aria-selected': null
3008
+ });
3009
+ option_el.classList.add('ts-cloned');
3010
+ removeClasses(option_el, 'active');
3011
+
3012
+ // make sure we keep the activeOption in the same group
3013
+ if (self.activeOption && self.activeOption.dataset.value == opt_value) {
3014
+ if (active_group && active_group.dataset.group === optgroup.toString()) {
3015
+ active_option = option_el;
3016
+ }
3017
+ }
3018
+ }
3019
+ group_fragment.appendChild(option_el);
3020
+ if (optgroup != '') {
3021
+ groups[optgroup] = group_order_i;
3022
+ }
3023
+ }
3024
+ }
3025
+
3026
+ // sort optgroups
3027
+ if (self.settings.lockOptgroupOrder) {
3028
+ groups_order.sort((a, b) => {
3029
+ return a.order - b.order;
3030
+ });
3031
+ }
3032
+
3033
+ // render optgroup headers & join groups
3034
+ html = document.createDocumentFragment();
3035
+ iterate(groups_order, group_order => {
3036
+ let group_fragment = group_order.fragment;
3037
+ let optgroup = group_order.optgroup;
3038
+ if (!group_fragment || !group_fragment.children.length) return;
3039
+ let group_heading = self.optgroups[optgroup];
3040
+ if (group_heading !== undefined) {
3041
+ let group_options = document.createDocumentFragment();
3042
+ let header = self.render('optgroup_header', group_heading);
3043
+ append(group_options, header);
3044
+ append(group_options, group_fragment);
3045
+ let group_html = self.render('optgroup', {
3046
+ group: group_heading,
3047
+ options: group_options
3048
+ });
3049
+ append(html, group_html);
3050
+ } else {
3051
+ append(html, group_fragment);
3052
+ }
3053
+ });
3054
+ dropdown_content.innerHTML = '';
3055
+ append(dropdown_content, html);
3056
+
3057
+ // highlight matching terms inline
3058
+ if (self.settings.highlight) {
3059
+ removeHighlight(dropdown_content);
3060
+ if (results.query.length && results.tokens.length) {
3061
+ iterate(results.tokens, tok => {
3062
+ highlight(dropdown_content, tok.regex);
3063
+ });
3064
+ }
3065
+ }
3066
+
3067
+ // helper method for adding templates to dropdown
3068
+ var add_template = template => {
3069
+ let content = self.render(template, {
3070
+ input: query
3071
+ });
3072
+ if (content) {
3073
+ show_dropdown = true;
3074
+ dropdown_content.insertBefore(content, dropdown_content.firstChild);
3075
+ }
3076
+ return content;
3077
+ };
3078
+
3079
+ // add loading message
3080
+ if (self.loading) {
3081
+ add_template('loading');
3082
+
3083
+ // invalid query
3084
+ } else if (!self.settings.shouldLoad.call(self, query)) {
3085
+ add_template('not_loading');
3086
+
3087
+ // add no_results message
3088
+ } else if (results.items.length === 0) {
3089
+ add_template('no_results');
3090
+ }
3091
+
3092
+ // add create option
3093
+ has_create_option = self.canCreate(query);
3094
+ if (has_create_option) {
3095
+ create = add_template('option_create');
3096
+ }
3097
+
3098
+ // activate
3099
+ self.hasOptions = results.items.length > 0 || has_create_option;
3100
+ if (show_dropdown) {
3101
+ if (results.items.length > 0) {
3102
+ if (!active_option && self.settings.mode === 'single' && self.items[0] != undefined) {
3103
+ active_option = self.getOption(self.items[0]);
3104
+ }
3105
+ if (!dropdown_content.contains(active_option)) {
3106
+ let active_index = 0;
3107
+ if (create && !self.settings.addPrecedence) {
3108
+ active_index = 1;
3109
+ }
3110
+ active_option = self.selectable()[active_index];
3111
+ }
3112
+ } else if (create) {
3113
+ active_option = create;
3114
+ }
3115
+ if (triggerDropdown && !self.isOpen) {
3116
+ self.open();
3117
+ self.scrollToOption(active_option, 'auto');
3118
+ }
3119
+ self.setActiveOption(active_option);
3120
+ } else {
3121
+ self.clearActiveOption();
3122
+ if (triggerDropdown && self.isOpen) {
3123
+ self.close(false); // if create_option=null, we want the dropdown to close but not reset the textbox value
3124
+ }
3125
+ }
3126
+ }
3127
+
3128
+ /**
3129
+ * Return list of selectable options
3130
+ *
3131
+ */
3132
+ selectable() {
3133
+ return this.dropdown_content.querySelectorAll('[data-selectable]');
3134
+ }
3135
+
3136
+ /**
3137
+ * Adds an available option. If it already exists,
3138
+ * nothing will happen. Note: this does not refresh
3139
+ * the options list dropdown (use `refreshOptions`
3140
+ * for that).
3141
+ *
3142
+ * Usage:
3143
+ *
3144
+ * this.addOption(data)
3145
+ *
3146
+ */
3147
+ addOption(data, user_created = false) {
3148
+ const self = this;
3149
+
3150
+ // @deprecated 1.7.7
3151
+ // use addOptions( array, user_created ) for adding multiple options
3152
+ if (Array.isArray(data)) {
3153
+ self.addOptions(data, user_created);
3154
+ return false;
3155
+ }
3156
+ const key = hash_key(data[self.settings.valueField]);
3157
+ if (key === null || self.options.hasOwnProperty(key)) {
3158
+ return false;
3159
+ }
3160
+ data.$order = data.$order || ++self.order;
3161
+ data.$id = self.inputId + '-opt-' + data.$order;
3162
+ self.options[key] = data;
3163
+ self.lastQuery = null;
3164
+ if (user_created) {
3165
+ self.userOptions[key] = user_created;
3166
+ self.trigger('option_add', key, data);
3167
+ }
3168
+ return key;
3169
+ }
3170
+
3171
+ /**
3172
+ * Add multiple options
3173
+ *
3174
+ */
3175
+ addOptions(data, user_created = false) {
3176
+ iterate(data, dat => {
3177
+ this.addOption(dat, user_created);
3178
+ });
3179
+ }
3180
+
3181
+ /**
3182
+ * @deprecated 1.7.7
3183
+ */
3184
+ registerOption(data) {
3185
+ return this.addOption(data);
3186
+ }
3187
+
3188
+ /**
3189
+ * Registers an option group to the pool of option groups.
3190
+ *
3191
+ * @return {boolean|string}
3192
+ */
3193
+ registerOptionGroup(data) {
3194
+ var key = hash_key(data[this.settings.optgroupValueField]);
3195
+ if (key === null) return false;
3196
+ data.$order = data.$order || ++this.order;
3197
+ this.optgroups[key] = data;
3198
+ return key;
3199
+ }
3200
+
3201
+ /**
3202
+ * Registers a new optgroup for options
3203
+ * to be bucketed into.
3204
+ *
3205
+ */
3206
+ addOptionGroup(id, data) {
3207
+ var hashed_id;
3208
+ data[this.settings.optgroupValueField] = id;
3209
+ if (hashed_id = this.registerOptionGroup(data)) {
3210
+ this.trigger('optgroup_add', hashed_id, data);
3211
+ }
3212
+ }
3213
+
3214
+ /**
3215
+ * Removes an existing option group.
3216
+ *
3217
+ */
3218
+ removeOptionGroup(id) {
3219
+ if (this.optgroups.hasOwnProperty(id)) {
3220
+ delete this.optgroups[id];
3221
+ this.clearCache();
3222
+ this.trigger('optgroup_remove', id);
3223
+ }
3224
+ }
3225
+
3226
+ /**
3227
+ * Clears all existing option groups.
3228
+ */
3229
+ clearOptionGroups() {
3230
+ this.optgroups = {};
3231
+ this.clearCache();
3232
+ this.trigger('optgroup_clear');
3233
+ }
3234
+
3235
+ /**
3236
+ * Updates an option available for selection. If
3237
+ * it is visible in the selected items or options
3238
+ * dropdown, it will be re-rendered automatically.
3239
+ *
3240
+ */
3241
+ updateOption(value, data) {
3242
+ const self = this;
3243
+ var item_new;
3244
+ var index_item;
3245
+ const value_old = hash_key(value);
3246
+ const value_new = hash_key(data[self.settings.valueField]);
3247
+
3248
+ // sanity checks
3249
+ if (value_old === null) return;
3250
+ const data_old = self.options[value_old];
3251
+ if (data_old == undefined) return;
3252
+ if (typeof value_new !== 'string') throw new Error('Value must be set in option data');
3253
+ const option = self.getOption(value_old);
3254
+ const item = self.getItem(value_old);
3255
+ data.$order = data.$order || data_old.$order;
3256
+ delete self.options[value_old];
3257
+
3258
+ // invalidate render cache
3259
+ // don't remove existing node yet, we'll remove it after replacing it
3260
+ self.uncacheValue(value_new);
3261
+ self.options[value_new] = data;
3262
+
3263
+ // update the option if it's in the dropdown
3264
+ if (option) {
3265
+ if (self.dropdown_content.contains(option)) {
3266
+ const option_new = self._render('option', data);
3267
+ replaceNode(option, option_new);
3268
+ if (self.activeOption === option) {
3269
+ self.setActiveOption(option_new);
3270
+ }
3271
+ }
3272
+ option.remove();
3273
+ }
3274
+
3275
+ // update the item if we have one
3276
+ if (item) {
3277
+ index_item = self.items.indexOf(value_old);
3278
+ if (index_item !== -1) {
3279
+ self.items.splice(index_item, 1, value_new);
3280
+ }
3281
+ item_new = self._render('item', data);
3282
+ if (item.classList.contains('active')) addClasses(item_new, 'active');
3283
+ replaceNode(item, item_new);
3284
+ }
3285
+
3286
+ // invalidate last query because we might have updated the sortField
3287
+ self.lastQuery = null;
3288
+ }
3289
+
3290
+ /**
3291
+ * Removes a single option.
3292
+ *
3293
+ */
3294
+ removeOption(value, silent) {
3295
+ const self = this;
3296
+ value = get_hash(value);
3297
+ self.uncacheValue(value);
3298
+ delete self.userOptions[value];
3299
+ delete self.options[value];
3300
+ self.lastQuery = null;
3301
+ self.trigger('option_remove', value);
3302
+ self.removeItem(value, silent);
3303
+ }
3304
+
3305
+ /**
3306
+ * Clears all options.
3307
+ */
3308
+ clearOptions(filter) {
3309
+ const boundFilter = (filter || this.clearFilter).bind(this);
3310
+ this.loadedSearches = {};
3311
+ this.userOptions = {};
3312
+ this.clearCache();
3313
+ const selected = {};
3314
+ iterate(this.options, (option, key) => {
3315
+ if (boundFilter(option, key)) {
3316
+ selected[key] = option;
3317
+ }
3318
+ });
3319
+ this.options = this.sifter.items = selected;
3320
+ this.lastQuery = null;
3321
+ this.trigger('option_clear');
3322
+ }
3323
+
3324
+ /**
3325
+ * Used by clearOptions() to decide whether or not an option should be removed
3326
+ * Return true to keep an option, false to remove
3327
+ *
3328
+ */
3329
+ clearFilter(option, value) {
3330
+ if (this.items.indexOf(value) >= 0) {
3331
+ return true;
3332
+ }
3333
+ return false;
3334
+ }
3335
+
3336
+ /**
3337
+ * Returns the dom element of the option
3338
+ * matching the given value.
3339
+ *
3340
+ */
3341
+ getOption(value, create = false) {
3342
+ const hashed = hash_key(value);
3343
+ if (hashed === null) return null;
3344
+ const option = this.options[hashed];
3345
+ if (option != undefined) {
3346
+ if (option.$div) {
3347
+ return option.$div;
3348
+ }
3349
+ if (create) {
3350
+ return this._render('option', option);
3351
+ }
3352
+ }
3353
+ return null;
3354
+ }
3355
+
3356
+ /**
3357
+ * Returns the dom element of the next or previous dom element of the same type
3358
+ * Note: adjacent options may not be adjacent DOM elements (optgroups)
3359
+ *
3360
+ */
3361
+ getAdjacent(option, direction, type = 'option') {
3362
+ var self = this,
3363
+ all;
3364
+ if (!option) {
3365
+ return null;
3366
+ }
3367
+ if (type == 'item') {
3368
+ all = self.controlChildren();
3369
+ } else {
3370
+ all = self.dropdown_content.querySelectorAll('[data-selectable]');
3371
+ }
3372
+ for (let i = 0; i < all.length; i++) {
3373
+ if (all[i] != option) {
3374
+ continue;
3375
+ }
3376
+ if (direction > 0) {
3377
+ return all[i + 1];
3378
+ }
3379
+ return all[i - 1];
3380
+ }
3381
+ return null;
3382
+ }
3383
+
3384
+ /**
3385
+ * Returns the dom element of the item
3386
+ * matching the given value.
3387
+ *
3388
+ */
3389
+ getItem(item) {
3390
+ if (typeof item == 'object') {
3391
+ return item;
3392
+ }
3393
+ var value = hash_key(item);
3394
+ return value !== null ? this.control.querySelector(`[data-value="${addSlashes(value)}"]`) : null;
3395
+ }
3396
+
3397
+ /**
3398
+ * "Selects" multiple items at once. Adds them to the list
3399
+ * at the current caret position.
3400
+ *
3401
+ */
3402
+ addItems(values, silent) {
3403
+ var self = this;
3404
+ var items = Array.isArray(values) ? values : [values];
3405
+ items = items.filter(x => self.items.indexOf(x) === -1);
3406
+ const last_item = items[items.length - 1];
3407
+ items.forEach(item => {
3408
+ self.isPending = item !== last_item;
3409
+ self.addItem(item, silent);
3410
+ });
3411
+ }
3412
+
3413
+ /**
3414
+ * "Selects" an item. Adds it to the list
3415
+ * at the current caret position.
3416
+ *
3417
+ */
3418
+ addItem(value, silent) {
3419
+ var events = silent ? [] : ['change', 'dropdown_close'];
3420
+ debounce_events(this, events, () => {
3421
+ var item, wasFull;
3422
+ const self = this;
3423
+ const inputMode = self.settings.mode;
3424
+ const hashed = hash_key(value);
3425
+ if (hashed && self.items.indexOf(hashed) !== -1) {
3426
+ if (inputMode === 'single') {
3427
+ self.close();
3428
+ }
3429
+ if (inputMode === 'single' || !self.settings.duplicates) {
3430
+ return;
3431
+ }
3432
+ }
3433
+ if (hashed === null || !self.options.hasOwnProperty(hashed)) return;
3434
+ if (inputMode === 'single') self.clear(silent);
3435
+ if (inputMode === 'multi' && self.isFull()) return;
3436
+ item = self._render('item', self.options[hashed]);
3437
+ if (self.control.contains(item)) {
3438
+ // duplicates
3439
+ item = item.cloneNode(true);
3440
+ }
3441
+ wasFull = self.isFull();
3442
+ self.items.splice(self.caretPos, 0, hashed);
3443
+ self.insertAtCaret(item);
3444
+ if (self.isSetup) {
3445
+ // update menu / remove the option (if this is not one item being added as part of series)
3446
+ if (!self.isPending && self.settings.hideSelected) {
3447
+ let option = self.getOption(hashed);
3448
+ let next = self.getAdjacent(option, 1);
3449
+ if (next) {
3450
+ self.setActiveOption(next);
3451
+ }
3452
+ }
3453
+
3454
+ //remove input value when enabled
3455
+ if (self.settings.clearAfterSelect) {
3456
+ self.setTextboxValue();
3457
+ }
3458
+
3459
+ // refreshOptions after setActiveOption(),
3460
+ // otherwise setActiveOption() will be called by refreshOptions() with the wrong value
3461
+ if (!self.isPending && !self.settings.closeAfterSelect) {
3462
+ self.refreshOptions(self.isFocused && inputMode !== 'single');
3463
+ }
3464
+
3465
+ // hide the menu if the maximum number of items have been selected or no options are left
3466
+ if (self.settings.closeAfterSelect != false && self.isFull()) {
3467
+ self.close();
3468
+ } else if (!self.isPending) {
3469
+ self.positionDropdown();
3470
+ }
3471
+ self.trigger('item_add', hashed, item);
3472
+ if (!self.isPending) {
3473
+ self.updateOriginalInput({
3474
+ silent: silent
3475
+ });
3476
+ }
3477
+ }
3478
+ if (!self.isPending || !wasFull && self.isFull()) {
3479
+ self.inputState();
3480
+ self.refreshState();
3481
+ }
3482
+ });
3483
+ }
3484
+
3485
+ /**
3486
+ * Removes the selected item matching
3487
+ * the provided value.
3488
+ *
3489
+ */
3490
+ removeItem(item = null, silent) {
3491
+ const self = this;
3492
+ item = self.getItem(item);
3493
+ if (!item) return;
3494
+ var i, idx;
3495
+ const value = item.dataset.value;
3496
+ i = nodeIndex(item);
3497
+ item.remove();
3498
+ if (item.classList.contains('active')) {
3499
+ idx = self.activeItems.indexOf(item);
3500
+ self.activeItems.splice(idx, 1);
3501
+ removeClasses(item, 'active');
3502
+ }
3503
+ self.items.splice(i, 1);
3504
+ self.lastQuery = null;
3505
+ if (!self.settings.persist && self.userOptions.hasOwnProperty(value)) {
3506
+ self.removeOption(value, silent);
3507
+ }
3508
+ if (i < self.caretPos) {
3509
+ self.setCaret(self.caretPos - 1);
3510
+ }
3511
+ self.updateOriginalInput({
3512
+ silent: silent
3513
+ });
3514
+ self.refreshState();
3515
+ self.positionDropdown();
3516
+ self.trigger('item_remove', value, item);
3517
+ }
3518
+
3519
+ /**
3520
+ * Invokes the `create` method provided in the
3521
+ * TomSelect options that should provide the data
3522
+ * for the new item, given the user input.
3523
+ *
3524
+ * Once this completes, it will be added
3525
+ * to the item list.
3526
+ *
3527
+ */
3528
+ createItem(input = null, callback = () => {}) {
3529
+ // triggerDropdown parameter @deprecated 2.1.1
3530
+ if (arguments.length === 3) {
3531
+ callback = arguments[2];
3532
+ }
3533
+ if (typeof callback != 'function') {
3534
+ callback = () => {};
3535
+ }
3536
+ var self = this;
3537
+ var caret = self.caretPos;
3538
+ var output;
3539
+ input = input || self.inputValue();
3540
+ if (!self.canCreate(input)) {
3541
+ const hash = hash_key(input);
3542
+ if (hash) {
3543
+ if (this.options[input]) {
3544
+ self.addItem(input);
3545
+ }
3546
+ }
3547
+ callback();
3548
+ return false;
3549
+ }
3550
+ self.lock();
3551
+ var created = false;
3552
+ var create = data => {
3553
+ self.unlock();
3554
+ if (!data || typeof data !== 'object') return callback();
3555
+ var value = hash_key(data[self.settings.valueField]);
3556
+ if (typeof value !== 'string') {
3557
+ return callback();
3558
+ }
3559
+ self.setTextboxValue();
3560
+ self.addOption(data, true);
3561
+ self.setCaret(caret);
3562
+ self.addItem(value);
3563
+ callback(data);
3564
+ created = true;
3565
+ };
3566
+ if (typeof self.settings.create === 'function') {
3567
+ output = self.settings.create.call(this, input, create);
3568
+ } else {
3569
+ output = {
3570
+ [self.settings.labelField]: input,
3571
+ [self.settings.valueField]: input
3572
+ };
3573
+ }
3574
+ if (!created) {
3575
+ create(output);
3576
+ }
3577
+ return true;
3578
+ }
3579
+
3580
+ /**
3581
+ * Re-renders the selected item lists.
3582
+ */
3583
+ refreshItems() {
3584
+ var self = this;
3585
+ self.lastQuery = null;
3586
+ if (self.isSetup) {
3587
+ self.addItems(self.items);
3588
+ }
3589
+ self.updateOriginalInput();
3590
+ self.refreshState();
3591
+ }
3592
+
3593
+ /**
3594
+ * Updates all state-dependent attributes
3595
+ * and CSS classes.
3596
+ */
3597
+ refreshState() {
3598
+ const self = this;
3599
+ self.refreshValidityState();
3600
+ const isFull = self.isFull();
3601
+ const isLocked = self.isLocked;
3602
+ self.wrapper.classList.toggle('rtl', self.rtl);
3603
+ const wrap_classList = self.wrapper.classList;
3604
+ wrap_classList.toggle('focus', self.isFocused);
3605
+ wrap_classList.toggle('disabled', self.isDisabled);
3606
+ wrap_classList.toggle('readonly', self.isReadOnly);
3607
+ wrap_classList.toggle('required', self.isRequired);
3608
+ wrap_classList.toggle('invalid', !self.isValid);
3609
+ wrap_classList.toggle('locked', isLocked);
3610
+ wrap_classList.toggle('full', isFull);
3611
+ wrap_classList.toggle('input-active', self.isFocused && !self.isInputHidden);
3612
+ wrap_classList.toggle('dropdown-active', self.isOpen);
3613
+ wrap_classList.toggle('has-options', isEmptyObject(self.options));
3614
+ wrap_classList.toggle('has-items', self.items.length > 0);
3615
+ }
3616
+
3617
+ /**
3618
+ * Update the `required` attribute of both input and control input.
3619
+ *
3620
+ * The `required` property needs to be activated on the control input
3621
+ * for the error to be displayed at the right place. `required` also
3622
+ * needs to be temporarily deactivated on the input since the input is
3623
+ * hidden and can't show errors.
3624
+ */
3625
+ refreshValidityState() {
3626
+ var self = this;
3627
+ if (!self.input.validity) {
3628
+ return;
3629
+ }
3630
+ self.isValid = self.input.validity.valid;
3631
+ self.isInvalid = !self.isValid;
3632
+ }
3633
+
3634
+ /**
3635
+ * Determines whether or not more items can be added
3636
+ * to the control without exceeding the user-defined maximum.
3637
+ *
3638
+ * @returns {boolean}
3639
+ */
3640
+ isFull() {
3641
+ return this.settings.maxItems !== null && this.items.length >= this.settings.maxItems;
3642
+ }
3643
+
3644
+ /**
3645
+ * Refreshes the original <select> or <input>
3646
+ * element to reflect the current state.
3647
+ *
3648
+ */
3649
+ updateOriginalInput(opts = {}) {
3650
+ const self = this;
3651
+ var option, label;
3652
+ const empty_option = self.input.querySelector('option[value=""]');
3653
+ if (self.is_select_tag) {
3654
+ const selected = [];
3655
+ const has_selected = self.input.querySelectorAll('option:checked').length;
3656
+ function AddSelected(option_el, value, label) {
3657
+ if (!option_el) {
3658
+ option_el = getDom('<option value="' + escape_html(value) + '">' + escape_html(label) + '</option>');
3659
+ }
3660
+
3661
+ // don't move empty option from top of list
3662
+ // fixes bug in firefox https://bugzilla.mozilla.org/show_bug.cgi?id=1725293
3663
+ if (option_el != empty_option) {
3664
+ self.input.append(option_el);
3665
+ }
3666
+ selected.push(option_el);
3667
+
3668
+ // marking empty option as selected can break validation
3669
+ // fixes https://github.com/orchidjs/tom-select/issues/303
3670
+ if (option_el != empty_option || has_selected > 0) {
3671
+ option_el.selected = true;
3672
+ }
3673
+ return option_el;
3674
+ }
3675
+
3676
+ // unselect all selected options
3677
+ self.input.querySelectorAll('option:checked').forEach(option_el => {
3678
+ option_el.selected = false;
3679
+ });
3680
+
3681
+ // nothing selected?
3682
+ if (self.items.length == 0 && self.settings.mode == 'single') {
3683
+ AddSelected(empty_option, "", "");
3684
+
3685
+ // order selected <option> tags for values in self.items
3686
+ } else {
3687
+ self.items.forEach(value => {
3688
+ option = self.options[value];
3689
+ label = option[self.settings.labelField] || '';
3690
+ if (selected.includes(option.$option)) {
3691
+ const reuse_opt = self.input.querySelector(`option[value="${addSlashes(value)}"]:not(:checked)`);
3692
+ AddSelected(reuse_opt, value, label);
3693
+ } else {
3694
+ option.$option = AddSelected(option.$option, value, label);
3695
+ }
3696
+ });
3697
+ }
3698
+ } else {
3699
+ self.input.value = self.getValue();
3700
+ }
3701
+ if (self.isSetup) {
3702
+ if (!opts.silent) {
3703
+ self.trigger('change', self.getValue());
3704
+ }
3705
+ }
3706
+ }
3707
+
3708
+ /**
3709
+ * Shows the autocomplete dropdown containing
3710
+ * the available options.
3711
+ */
3712
+ open() {
3713
+ var self = this;
3714
+ if (self.isLocked || self.isOpen || self.settings.mode === 'multi' && self.isFull()) return;
3715
+ self.isOpen = true;
3716
+ setAttr(self.focus_node, {
3717
+ 'aria-expanded': 'true'
3718
+ });
3719
+ self.refreshState();
3720
+ applyCSS(self.dropdown, {
3721
+ visibility: 'hidden',
3722
+ display: 'block'
3723
+ });
3724
+ self.positionDropdown();
3725
+ applyCSS(self.dropdown, {
3726
+ visibility: 'visible',
3727
+ display: 'block'
3728
+ });
3729
+ self.focus();
3730
+ self.trigger('dropdown_open', self.dropdown);
3731
+ }
3732
+
3733
+ /**
3734
+ * Closes the autocomplete dropdown menu.
3735
+ */
3736
+ close(setTextboxValue = true) {
3737
+ var self = this;
3738
+ var trigger = self.isOpen;
3739
+ if (setTextboxValue) {
3740
+ // before blur() to prevent form onchange event
3741
+ self.setTextboxValue();
3742
+ if (self.settings.mode === 'single' && self.items.length) {
3743
+ self.inputState();
3744
+ }
3745
+ }
3746
+ self.isOpen = false;
3747
+ setAttr(self.focus_node, {
3748
+ 'aria-expanded': 'false'
3749
+ });
3750
+ applyCSS(self.dropdown, {
3751
+ display: 'none'
3752
+ });
3753
+ if (self.settings.hideSelected) {
3754
+ self.clearActiveOption();
3755
+ }
3756
+ self.refreshState();
3757
+ if (trigger) self.trigger('dropdown_close', self.dropdown);
3758
+ }
3759
+
3760
+ /**
3761
+ * Calculates and applies the appropriate
3762
+ * position of the dropdown if dropdownParent = 'body'.
3763
+ * Otherwise, position is determined by css
3764
+ */
3765
+ positionDropdown() {
3766
+ if (this.settings.dropdownParent !== 'body') {
3767
+ return;
3768
+ }
3769
+ var context = this.control;
3770
+ var rect = context.getBoundingClientRect();
3771
+ var top = context.offsetHeight + rect.top + window.scrollY;
3772
+ var left = rect.left + window.scrollX;
3773
+ applyCSS(this.dropdown, {
3774
+ width: rect.width + 'px',
3775
+ top: top + 'px',
3776
+ left: left + 'px'
3777
+ });
3778
+ }
3779
+
3780
+ /**
3781
+ * Resets / clears all selected items
3782
+ * from the control.
3783
+ *
3784
+ */
3785
+ clear(silent) {
3786
+ var self = this;
3787
+ if (!self.items.length) return;
3788
+ var items = self.controlChildren();
3789
+ iterate(items, item => {
3790
+ self.removeItem(item, true);
3791
+ });
3792
+ self.inputState();
3793
+ if (!silent) self.updateOriginalInput();
3794
+ self.trigger('clear');
3795
+ }
3796
+
3797
+ /**
3798
+ * A helper method for inserting an element
3799
+ * at the current caret position.
3800
+ *
3801
+ */
3802
+ insertAtCaret(el) {
3803
+ const self = this;
3804
+ const caret = self.caretPos;
3805
+ const target = self.control;
3806
+ target.insertBefore(el, target.children[caret] || null);
3807
+ self.setCaret(caret + 1);
3808
+ }
3809
+
3810
+ /**
3811
+ * Removes the current selected item(s).
3812
+ *
3813
+ */
3814
+ deleteSelection(e) {
3815
+ var direction, selection, caret, tail;
3816
+ var self = this;
3817
+ direction = e && e.keyCode === KEY_BACKSPACE ? -1 : 1;
3818
+ selection = getSelection(self.control_input);
3819
+
3820
+ // determine items that will be removed
3821
+ const rm_items = [];
3822
+ if (self.activeItems.length) {
3823
+ tail = getTail(self.activeItems, direction);
3824
+ caret = nodeIndex(tail);
3825
+ if (direction > 0) {
3826
+ caret++;
3827
+ }
3828
+ iterate(self.activeItems, item => rm_items.push(item));
3829
+ } else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) {
3830
+ const items = self.controlChildren();
3831
+ let rm_item;
3832
+ if (direction < 0 && selection.start === 0 && selection.length === 0) {
3833
+ rm_item = items[self.caretPos - 1];
3834
+ } else if (direction > 0 && selection.start === self.inputValue().length) {
3835
+ rm_item = items[self.caretPos];
3836
+ }
3837
+ if (rm_item !== undefined) {
3838
+ rm_items.push(rm_item);
3839
+ }
3840
+ }
3841
+ if (!self.shouldDelete(rm_items, e)) {
3842
+ return false;
3843
+ }
3844
+ preventDefault(e, true);
3845
+
3846
+ // perform removal
3847
+ if (typeof caret !== 'undefined') {
3848
+ self.setCaret(caret);
3849
+ }
3850
+ while (rm_items.length) {
3851
+ self.removeItem(rm_items.pop());
3852
+ }
3853
+ self.inputState();
3854
+ self.positionDropdown();
3855
+ self.refreshOptions(false);
3856
+ return true;
3857
+ }
3858
+
3859
+ /**
3860
+ * Return true if the items should be deleted
3861
+ */
3862
+ shouldDelete(items, evt) {
3863
+ const values = items.map(item => item.dataset.value);
3864
+
3865
+ // allow the callback to abort
3866
+ if (!values.length || typeof this.settings.onDelete === 'function' && this.settings.onDelete.call(this, values, evt) === false) {
3867
+ return false;
3868
+ }
3869
+ return true;
3870
+ }
3871
+
3872
+ /**
3873
+ * Selects the previous / next item (depending on the `direction` argument).
3874
+ *
3875
+ * > 0 - right
3876
+ * < 0 - left
3877
+ *
3878
+ */
3879
+ advanceSelection(direction, e) {
3880
+ var last_active,
3881
+ adjacent,
3882
+ self = this;
3883
+ if (self.rtl) direction *= -1;
3884
+ if (self.inputValue().length) return;
3885
+
3886
+ // add or remove to active items
3887
+ if (isKeyDown(KEY_SHORTCUT, e) || isKeyDown('shiftKey', e)) {
3888
+ last_active = self.getLastActive(direction);
3889
+ if (last_active) {
3890
+ if (!last_active.classList.contains('active')) {
3891
+ adjacent = last_active;
3892
+ } else {
3893
+ adjacent = self.getAdjacent(last_active, direction, 'item');
3894
+ }
3895
+
3896
+ // if no active item, get items adjacent to the control input
3897
+ } else if (direction > 0) {
3898
+ adjacent = self.control_input.nextElementSibling;
3899
+ } else {
3900
+ adjacent = self.control_input.previousElementSibling;
3901
+ }
3902
+ if (adjacent) {
3903
+ if (adjacent.classList.contains('active')) {
3904
+ self.removeActiveItem(last_active);
3905
+ }
3906
+ self.setActiveItemClass(adjacent); // mark as last_active !! after removeActiveItem() on last_active
3907
+ }
3908
+
3909
+ // move caret to the left or right
3910
+ } else {
3911
+ self.moveCaret(direction);
3912
+ }
3913
+ }
3914
+ moveCaret(direction) {}
3915
+
3916
+ /**
3917
+ * Get the last active item
3918
+ *
3919
+ */
3920
+ getLastActive(direction) {
3921
+ let last_active = this.control.querySelector('.last-active');
3922
+ if (last_active) {
3923
+ return last_active;
3924
+ }
3925
+ var result = this.control.querySelectorAll('.active');
3926
+ if (result) {
3927
+ return getTail(result, direction);
3928
+ }
3929
+ }
3930
+
3931
+ /**
3932
+ * Moves the caret to the specified index.
3933
+ *
3934
+ * The input must be moved by leaving it in place and moving the
3935
+ * siblings, due to the fact that focus cannot be restored once lost
3936
+ * on mobile webkit devices
3937
+ *
3938
+ */
3939
+ setCaret(new_pos) {
3940
+ this.caretPos = this.items.length;
3941
+ }
3942
+
3943
+ /**
3944
+ * Return list of item dom elements
3945
+ *
3946
+ */
3947
+ controlChildren() {
3948
+ return Array.from(this.control.querySelectorAll('[data-ts-item]'));
3949
+ }
3950
+
3951
+ /**
3952
+ * Disables user input on the control. Used while
3953
+ * items are being asynchronously created.
3954
+ */
3955
+ lock() {
3956
+ this.setLocked(true);
3957
+ }
3958
+
3959
+ /**
3960
+ * Re-enables user input on the control.
3961
+ */
3962
+ unlock() {
3963
+ this.setLocked(false);
3964
+ }
3965
+
3966
+ /**
3967
+ * Disable or enable user input on the control
3968
+ */
3969
+ setLocked(lock = this.isReadOnly || this.isDisabled) {
3970
+ this.isLocked = lock;
3971
+ this.refreshState();
3972
+ }
3973
+
3974
+ /**
3975
+ * Disables user input on the control completely.
3976
+ * While disabled, it cannot receive focus.
3977
+ */
3978
+ disable() {
3979
+ this.setDisabled(true);
3980
+ this.close();
3981
+ }
3982
+
3983
+ /**
3984
+ * Enables the control so that it can respond
3985
+ * to focus and user input.
3986
+ */
3987
+ enable() {
3988
+ this.setDisabled(false);
3989
+ }
3990
+ setDisabled(disabled) {
3991
+ this.focus_node.tabIndex = disabled ? -1 : this.tabIndex;
3992
+ this.isDisabled = disabled;
3993
+ this.input.disabled = disabled;
3994
+ this.control_input.disabled = disabled;
3995
+ this.setLocked();
3996
+ }
3997
+ setReadOnly(isReadOnly) {
3998
+ this.isReadOnly = isReadOnly;
3999
+ this.input.readOnly = isReadOnly;
4000
+ this.control_input.readOnly = isReadOnly;
4001
+ this.setLocked();
4002
+ }
4003
+
4004
+ /**
4005
+ * Completely destroys the control and
4006
+ * unbinds all event listeners so that it can
4007
+ * be garbage collected.
4008
+ */
4009
+ destroy() {
4010
+ var self = this;
4011
+ var revertSettings = self.revertSettings;
4012
+ self.trigger('destroy');
4013
+ self.off();
4014
+ self.wrapper.remove();
4015
+ self.dropdown.remove();
4016
+ self.input.innerHTML = revertSettings.innerHTML;
4017
+ self.input.tabIndex = revertSettings.tabIndex;
4018
+ removeClasses(self.input, 'tomselected', 'ts-hidden-accessible');
4019
+ self._destroy();
4020
+ delete self.input.tomselect;
4021
+ }
4022
+
4023
+ /**
4024
+ * A helper method for rendering "item" and
4025
+ * "option" templates, given the data.
4026
+ *
4027
+ */
4028
+ render(templateName, data) {
4029
+ var id, html;
4030
+ const self = this;
4031
+ if (typeof this.settings.render[templateName] !== 'function') {
4032
+ return null;
4033
+ }
4034
+
4035
+ // render markup
4036
+ html = self.settings.render[templateName].call(this, data, escape_html);
4037
+ if (!html) {
4038
+ return null;
4039
+ }
4040
+ html = getDom(html);
4041
+
4042
+ // add mandatory attributes
4043
+ if (templateName === 'option' || templateName === 'option_create') {
4044
+ if (data[self.settings.disabledField]) {
4045
+ setAttr(html, {
4046
+ 'aria-disabled': 'true'
4047
+ });
4048
+ } else {
4049
+ setAttr(html, {
4050
+ 'data-selectable': ''
4051
+ });
4052
+ }
4053
+ } else if (templateName === 'optgroup') {
4054
+ id = data.group[self.settings.optgroupValueField];
4055
+ setAttr(html, {
4056
+ 'data-group': id
4057
+ });
4058
+ if (data.group[self.settings.disabledField]) {
4059
+ setAttr(html, {
4060
+ 'data-disabled': ''
4061
+ });
4062
+ }
4063
+ }
4064
+ if (templateName === 'option' || templateName === 'item') {
4065
+ const value = get_hash(data[self.settings.valueField]);
4066
+ setAttr(html, {
4067
+ 'data-value': value
4068
+ });
4069
+
4070
+ // make sure we have some classes if a template is overwritten
4071
+ if (templateName === 'item') {
4072
+ addClasses(html, self.settings.itemClass);
4073
+ setAttr(html, {
4074
+ 'data-ts-item': ''
4075
+ });
4076
+ } else {
4077
+ addClasses(html, self.settings.optionClass);
4078
+ setAttr(html, {
4079
+ role: 'option',
4080
+ id: data.$id
4081
+ });
4082
+
4083
+ // update cache
4084
+ data.$div = html;
4085
+ self.options[value] = data;
4086
+ }
4087
+ }
4088
+ return html;
4089
+ }
4090
+
4091
+ /**
4092
+ * Type guarded rendering
4093
+ *
4094
+ */
4095
+ _render(templateName, data) {
4096
+ const html = this.render(templateName, data);
4097
+ if (html == null) {
4098
+ throw 'HTMLElement expected';
4099
+ }
4100
+ return html;
4101
+ }
4102
+
4103
+ /**
4104
+ * Clears the render cache for a template. If
4105
+ * no template is given, clears all render
4106
+ * caches.
4107
+ *
4108
+ */
4109
+ clearCache() {
4110
+ iterate(this.options, option => {
4111
+ if (option.$div) {
4112
+ option.$div.remove();
4113
+ delete option.$div;
4114
+ }
4115
+ });
4116
+ }
4117
+
4118
+ /**
4119
+ * Removes a value from item and option caches
4120
+ *
4121
+ */
4122
+ uncacheValue(value) {
4123
+ const option_el = this.getOption(value);
4124
+ if (option_el) option_el.remove();
4125
+ }
4126
+
4127
+ /**
4128
+ * Determines whether or not to display the
4129
+ * create item prompt, given a user input.
4130
+ *
4131
+ */
4132
+ canCreate(input) {
4133
+ return this.settings.create && input.length > 0 && this.settings.createFilter.call(this, input);
4134
+ }
4135
+
4136
+ /**
4137
+ * Wraps this.`method` so that `new_fn` can be invoked 'before', 'after', or 'instead' of the original method
4138
+ *
4139
+ * this.hook('instead','onKeyDown',function( arg1, arg2 ...){
4140
+ *
4141
+ * });
4142
+ */
4143
+ hook(when, method, new_fn) {
4144
+ var self = this;
4145
+ var orig_method = self[method];
4146
+ self[method] = function () {
4147
+ var result, result_new;
4148
+ if (when === 'after') {
4149
+ result = orig_method.apply(self, arguments);
4150
+ }
4151
+ result_new = new_fn.apply(self, arguments);
4152
+ if (when === 'instead') {
4153
+ return result_new;
4154
+ }
4155
+ if (when === 'before') {
4156
+ result = orig_method.apply(self, arguments);
4157
+ }
4158
+ return result;
4159
+ };
4160
+ }
4161
+ }
4162
+
4163
+ return TomSelect;
4164
+
4165
+ }));
4166
+ var tomSelect=function(el,opts){return new TomSelect(el,opts);}
4167
+ //# sourceMappingURL=tom-select.base.js.map