@drecchia/tom-select 2.5.2-virtual-scroll.0 → 2.5.2-virtual-scroll.1

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 (248) hide show
  1. package/dist/cjs/constants.js +16 -0
  2. package/dist/cjs/constants.js.map +1 -0
  3. package/dist/cjs/contrib/highlight.js +69 -0
  4. package/dist/cjs/contrib/highlight.js.map +1 -0
  5. package/dist/cjs/contrib/microevent.js +64 -0
  6. package/dist/cjs/contrib/microevent.js.map +1 -0
  7. package/dist/cjs/contrib/microplugin.js +112 -0
  8. package/dist/cjs/contrib/microplugin.js.map +1 -0
  9. package/dist/cjs/defaults.js +85 -0
  10. package/dist/cjs/defaults.js.map +1 -0
  11. package/dist/cjs/getSettings.js +146 -0
  12. package/dist/cjs/getSettings.js.map +1 -0
  13. package/dist/cjs/package.json +1 -0
  14. package/dist/cjs/plugins/caret_position/plugin.js +66 -0
  15. package/dist/cjs/plugins/caret_position/plugin.js.map +1 -0
  16. package/dist/cjs/plugins/change_listener/plugin.js +25 -0
  17. package/dist/cjs/plugins/change_listener/plugin.js.map +1 -0
  18. package/dist/cjs/plugins/checkbox_options/plugin.js +108 -0
  19. package/dist/cjs/plugins/checkbox_options/plugin.js.map +1 -0
  20. package/dist/cjs/plugins/checkbox_options/types.js +3 -0
  21. package/dist/cjs/plugins/checkbox_options/types.js.map +1 -0
  22. package/dist/cjs/plugins/clear_button/plugin.js +47 -0
  23. package/dist/cjs/plugins/clear_button/plugin.js.map +1 -0
  24. package/dist/cjs/plugins/clear_button/types.js +3 -0
  25. package/dist/cjs/plugins/clear_button/types.js.map +1 -0
  26. package/dist/cjs/plugins/drag_drop/plugin.js +117 -0
  27. package/dist/cjs/plugins/drag_drop/plugin.js.map +1 -0
  28. package/dist/cjs/plugins/dropdown_header/plugin.js +50 -0
  29. package/dist/cjs/plugins/dropdown_header/plugin.js.map +1 -0
  30. package/dist/cjs/plugins/dropdown_header/types.js +3 -0
  31. package/dist/cjs/plugins/dropdown_header/types.js.map +1 -0
  32. package/dist/cjs/plugins/dropdown_input/plugin.js +88 -0
  33. package/dist/cjs/plugins/dropdown_input/plugin.js.map +1 -0
  34. package/dist/cjs/plugins/input_autogrow/plugin.js +47 -0
  35. package/dist/cjs/plugins/input_autogrow/plugin.js.map +1 -0
  36. package/dist/cjs/plugins/local_virtual_scroll/plugin.js +293 -0
  37. package/dist/cjs/plugins/local_virtual_scroll/plugin.js.map +1 -0
  38. package/dist/cjs/plugins/local_virtual_scroll/types.js +3 -0
  39. package/dist/cjs/plugins/local_virtual_scroll/types.js.map +1 -0
  40. package/dist/cjs/plugins/no_active_items/plugin.js +22 -0
  41. package/dist/cjs/plugins/no_active_items/plugin.js.map +1 -0
  42. package/dist/cjs/plugins/no_backspace_delete/plugin.js +28 -0
  43. package/dist/cjs/plugins/no_backspace_delete/plugin.js.map +1 -0
  44. package/dist/cjs/plugins/optgroup_columns/plugin.js +51 -0
  45. package/dist/cjs/plugins/optgroup_columns/plugin.js.map +1 -0
  46. package/dist/cjs/plugins/remove_button/plugin.js +61 -0
  47. package/dist/cjs/plugins/remove_button/plugin.js.map +1 -0
  48. package/dist/cjs/plugins/remove_button/types.js +3 -0
  49. package/dist/cjs/plugins/remove_button/types.js.map +1 -0
  50. package/dist/cjs/plugins/restore_on_backspace/plugin.js +24 -0
  51. package/dist/cjs/plugins/restore_on_backspace/plugin.js.map +1 -0
  52. package/dist/cjs/plugins/virtual_scroll/plugin.js +170 -0
  53. package/dist/cjs/plugins/virtual_scroll/plugin.js.map +1 -0
  54. package/dist/cjs/tom-select.complete.js +35 -0
  55. package/dist/cjs/tom-select.complete.js.map +1 -0
  56. package/dist/cjs/tom-select.js +2303 -0
  57. package/dist/cjs/tom-select.js.map +1 -0
  58. package/dist/cjs/tom-select.popular.js +15 -0
  59. package/dist/cjs/tom-select.popular.js.map +1 -0
  60. package/dist/cjs/types/core.js +3 -0
  61. package/dist/cjs/types/core.js.map +1 -0
  62. package/dist/cjs/types/index.js +19 -0
  63. package/dist/cjs/types/index.js.map +1 -0
  64. package/dist/cjs/types/settings.js +3 -0
  65. package/dist/cjs/types/settings.js.map +1 -0
  66. package/dist/cjs/utils.js +212 -0
  67. package/dist/cjs/utils.js.map +1 -0
  68. package/dist/cjs/vanilla.js +190 -0
  69. package/dist/cjs/vanilla.js.map +1 -0
  70. package/dist/css/tom-select.bootstrap4.css +16 -4
  71. package/dist/css/tom-select.bootstrap4.css.map +1 -0
  72. package/dist/css/tom-select.bootstrap4.min.css +2 -0
  73. package/dist/css/tom-select.bootstrap4.min.css.map +1 -0
  74. package/dist/css/tom-select.bootstrap5.css +16 -4
  75. package/dist/css/tom-select.bootstrap5.css.map +1 -0
  76. package/dist/css/tom-select.bootstrap5.min.css +2 -0
  77. package/dist/css/tom-select.bootstrap5.min.css.map +1 -0
  78. package/dist/css/tom-select.css +12 -4
  79. package/dist/css/tom-select.css.map +1 -0
  80. package/dist/css/tom-select.default.css +11 -5
  81. package/dist/css/tom-select.default.css.map +1 -1
  82. package/dist/css/tom-select.default.min.css +2 -0
  83. package/dist/css/tom-select.default.min.css.map +1 -0
  84. package/dist/css/tom-select.min.css +2 -0
  85. package/dist/css/tom-select.min.css.map +1 -0
  86. package/dist/esm/constants.d.ts +12 -0
  87. package/dist/esm/constants.js +13 -0
  88. package/dist/esm/constants.js.map +1 -0
  89. package/dist/esm/contrib/highlight.d.ts +13 -0
  90. package/dist/esm/contrib/highlight.js +64 -0
  91. package/dist/esm/contrib/highlight.js.map +1 -0
  92. package/dist/esm/contrib/microevent.d.ts +20 -0
  93. package/dist/esm/contrib/microevent.js +61 -0
  94. package/dist/esm/contrib/microevent.js.map +1 -0
  95. package/dist/esm/contrib/microplugin.d.ts +71 -0
  96. package/dist/esm/contrib/microplugin.js +109 -0
  97. package/dist/esm/contrib/microplugin.js.map +1 -0
  98. package/dist/esm/defaults.d.ts +53 -0
  99. package/dist/esm/defaults.js +83 -0
  100. package/dist/esm/defaults.js.map +1 -0
  101. package/dist/esm/getSettings.d.ts +3 -0
  102. package/dist/esm/getSettings.js +143 -0
  103. package/dist/esm/getSettings.js.map +1 -0
  104. package/dist/esm/plugins/caret_position/plugin.d.ts +16 -0
  105. package/dist/esm/plugins/caret_position/plugin.js +1 -1
  106. package/dist/esm/plugins/change_listener/plugin.d.ts +16 -0
  107. package/dist/esm/plugins/change_listener/plugin.js +1 -1
  108. package/dist/esm/plugins/checkbox_options/plugin.d.ts +17 -0
  109. package/dist/esm/plugins/checkbox_options/plugin.js +1 -1
  110. package/dist/esm/plugins/checkbox_options/types.d.ts +14 -0
  111. package/dist/esm/plugins/checkbox_options/types.js +2 -0
  112. package/dist/esm/plugins/checkbox_options/types.js.map +1 -0
  113. package/dist/esm/plugins/clear_button/plugin.d.ts +17 -0
  114. package/dist/esm/plugins/clear_button/plugin.js +1 -1
  115. package/dist/esm/plugins/clear_button/types.d.ts +7 -0
  116. package/dist/esm/plugins/clear_button/types.js +2 -0
  117. package/dist/esm/plugins/clear_button/types.js.map +1 -0
  118. package/dist/esm/plugins/drag_drop/plugin.d.ts +16 -0
  119. package/dist/esm/plugins/drag_drop/plugin.js +1 -1
  120. package/dist/esm/plugins/dropdown_header/plugin.d.ts +17 -0
  121. package/dist/esm/plugins/dropdown_header/plugin.js +1 -1
  122. package/dist/esm/plugins/dropdown_header/types.d.ts +8 -0
  123. package/dist/esm/plugins/dropdown_header/types.js +2 -0
  124. package/dist/esm/plugins/dropdown_header/types.js.map +1 -0
  125. package/dist/esm/plugins/dropdown_input/plugin.d.ts +16 -0
  126. package/dist/esm/plugins/dropdown_input/plugin.js +1 -1
  127. package/dist/esm/plugins/input_autogrow/plugin.d.ts +15 -0
  128. package/dist/esm/plugins/input_autogrow/plugin.js +1 -1
  129. package/dist/esm/plugins/local_virtual_scroll/plugin.d.ts +19 -0
  130. package/dist/esm/plugins/local_virtual_scroll/plugin.js +92 -1
  131. package/dist/esm/plugins/local_virtual_scroll/plugin.js.map +1 -1
  132. package/dist/esm/plugins/local_virtual_scroll/types.d.ts +14 -0
  133. package/dist/esm/plugins/local_virtual_scroll/types.js +2 -0
  134. package/dist/esm/plugins/local_virtual_scroll/types.js.map +1 -0
  135. package/dist/esm/plugins/no_active_items/plugin.d.ts +15 -0
  136. package/dist/esm/plugins/no_active_items/plugin.js +1 -1
  137. package/dist/esm/plugins/no_backspace_delete/plugin.d.ts +15 -0
  138. package/dist/esm/plugins/no_backspace_delete/plugin.js +1 -1
  139. package/dist/esm/plugins/optgroup_columns/plugin.d.ts +16 -0
  140. package/dist/esm/plugins/optgroup_columns/plugin.js +1 -1
  141. package/dist/esm/plugins/remove_button/plugin.d.ts +17 -0
  142. package/dist/esm/plugins/remove_button/plugin.js +1 -1
  143. package/dist/esm/plugins/remove_button/types.d.ts +6 -0
  144. package/dist/esm/plugins/remove_button/types.js +2 -0
  145. package/dist/esm/plugins/remove_button/types.js.map +1 -0
  146. package/dist/esm/plugins/restore_on_backspace/plugin.d.ts +21 -0
  147. package/dist/esm/plugins/restore_on_backspace/plugin.js +1 -1
  148. package/dist/esm/plugins/virtual_scroll/plugin.d.ts +16 -0
  149. package/dist/esm/plugins/virtual_scroll/plugin.js +1 -1
  150. package/dist/esm/tom-select.complete.d.ts +2 -0
  151. package/dist/esm/tom-select.complete.js +33 -0
  152. package/dist/esm/tom-select.complete.js.map +1 -0
  153. package/dist/esm/tom-select.d.ts +594 -0
  154. package/dist/esm/tom-select.js +2300 -0
  155. package/dist/esm/tom-select.js.map +1 -0
  156. package/dist/esm/tom-select.popular.d.ts +2 -0
  157. package/dist/esm/tom-select.popular.js +13 -0
  158. package/dist/esm/tom-select.popular.js.map +1 -0
  159. package/dist/esm/types/core.d.ts +50 -0
  160. package/dist/esm/types/core.js +2 -0
  161. package/dist/esm/types/core.js.map +1 -0
  162. package/dist/esm/types/index.d.ts +2 -0
  163. package/dist/esm/types/index.js +3 -0
  164. package/dist/esm/types/index.js.map +1 -0
  165. package/dist/esm/types/settings.d.ts +81 -0
  166. package/dist/esm/types/settings.js +2 -0
  167. package/dist/esm/types/settings.js.map +1 -0
  168. package/dist/esm/utils.d.ts +95 -0
  169. package/dist/esm/utils.js +195 -0
  170. package/dist/esm/utils.js.map +1 -0
  171. package/dist/esm/vanilla.d.ts +76 -0
  172. package/dist/esm/vanilla.js +172 -0
  173. package/dist/esm/vanilla.js.map +1 -0
  174. package/dist/js/package.json +1 -0
  175. package/dist/js/plugins/caret_position.js +1 -1
  176. package/dist/js/plugins/change_listener.js +1 -1
  177. package/dist/js/plugins/checkbox_options.js +1 -1
  178. package/dist/js/plugins/clear_button.js +1 -1
  179. package/dist/js/plugins/drag_drop.js +1 -1
  180. package/dist/js/plugins/dropdown_header.js +1 -1
  181. package/dist/js/plugins/dropdown_input.js +1 -1
  182. package/dist/js/plugins/input_autogrow.js +1 -1
  183. package/dist/js/plugins/local_virtual_scroll.js +92 -1
  184. package/dist/js/plugins/local_virtual_scroll.js.map +1 -1
  185. package/dist/js/plugins/no_active_items.js +1 -1
  186. package/dist/js/plugins/no_backspace_delete.js +1 -1
  187. package/dist/js/plugins/optgroup_columns.js +1 -1
  188. package/dist/js/plugins/remove_button.js +1 -1
  189. package/dist/js/plugins/restore_on_backspace.js +1 -1
  190. package/dist/js/plugins/virtual_scroll.js +1 -1
  191. package/dist/js/tom-select.base.js +1 -1
  192. package/dist/js/tom-select.base.min.js +1 -1
  193. package/dist/js/tom-select.complete.js +19 -1
  194. package/dist/js/tom-select.complete.js.map +1 -1
  195. package/dist/js/tom-select.complete.min.js +51 -45
  196. package/dist/js/tom-select.complete.min.js.map +1 -1
  197. package/dist/js/tom-select.popular.js +1 -1
  198. package/dist/js/tom-select.popular.min.js +1 -1
  199. package/dist/scss/_dropdown.scss +99 -0
  200. package/dist/scss/_items.scss +114 -0
  201. package/dist/scss/plugins/checkbox_options.scss +11 -0
  202. package/dist/scss/plugins/clear_button.scss +33 -0
  203. package/dist/scss/plugins/drag_drop.scss +10 -0
  204. package/dist/scss/plugins/dropdown_header.scss +24 -0
  205. package/dist/scss/plugins/dropdown_input.scss +43 -0
  206. package/dist/scss/plugins/input_autogrow.scss +15 -0
  207. package/dist/scss/plugins/optgroup_columns.scss +25 -0
  208. package/dist/scss/plugins/remove_button.scss +70 -0
  209. package/dist/scss/tom-select.bootstrap4.scss +218 -0
  210. package/dist/scss/tom-select.bootstrap5.scss +270 -0
  211. package/dist/scss/tom-select.default.scss +89 -0
  212. package/dist/scss/tom-select.scss +179 -0
  213. package/package.json +2 -2
  214. package/src/plugins/local_virtual_scroll/plugin.ts +19 -0
  215. /package/dist/{types → cjs}/constants.d.ts +0 -0
  216. /package/dist/{types → cjs}/contrib/highlight.d.ts +0 -0
  217. /package/dist/{types → cjs}/contrib/microevent.d.ts +0 -0
  218. /package/dist/{types → cjs}/contrib/microplugin.d.ts +0 -0
  219. /package/dist/{types → cjs}/defaults.d.ts +0 -0
  220. /package/dist/{types → cjs}/getSettings.d.ts +0 -0
  221. /package/dist/{types → cjs}/plugins/caret_position/plugin.d.ts +0 -0
  222. /package/dist/{types → cjs}/plugins/change_listener/plugin.d.ts +0 -0
  223. /package/dist/{types → cjs}/plugins/checkbox_options/plugin.d.ts +0 -0
  224. /package/dist/{types → cjs}/plugins/checkbox_options/types.d.ts +0 -0
  225. /package/dist/{types → cjs}/plugins/clear_button/plugin.d.ts +0 -0
  226. /package/dist/{types → cjs}/plugins/clear_button/types.d.ts +0 -0
  227. /package/dist/{types → cjs}/plugins/drag_drop/plugin.d.ts +0 -0
  228. /package/dist/{types → cjs}/plugins/dropdown_header/plugin.d.ts +0 -0
  229. /package/dist/{types → cjs}/plugins/dropdown_header/types.d.ts +0 -0
  230. /package/dist/{types → cjs}/plugins/dropdown_input/plugin.d.ts +0 -0
  231. /package/dist/{types → cjs}/plugins/input_autogrow/plugin.d.ts +0 -0
  232. /package/dist/{types → cjs}/plugins/local_virtual_scroll/plugin.d.ts +0 -0
  233. /package/dist/{types → cjs}/plugins/local_virtual_scroll/types.d.ts +0 -0
  234. /package/dist/{types → cjs}/plugins/no_active_items/plugin.d.ts +0 -0
  235. /package/dist/{types → cjs}/plugins/no_backspace_delete/plugin.d.ts +0 -0
  236. /package/dist/{types → cjs}/plugins/optgroup_columns/plugin.d.ts +0 -0
  237. /package/dist/{types → cjs}/plugins/remove_button/plugin.d.ts +0 -0
  238. /package/dist/{types → cjs}/plugins/remove_button/types.d.ts +0 -0
  239. /package/dist/{types → cjs}/plugins/restore_on_backspace/plugin.d.ts +0 -0
  240. /package/dist/{types → cjs}/plugins/virtual_scroll/plugin.d.ts +0 -0
  241. /package/dist/{types → cjs}/tom-select.complete.d.ts +0 -0
  242. /package/dist/{types → cjs}/tom-select.d.ts +0 -0
  243. /package/dist/{types → cjs}/tom-select.popular.d.ts +0 -0
  244. /package/dist/{types → cjs}/types/core.d.ts +0 -0
  245. /package/dist/{types → cjs}/types/index.d.ts +0 -0
  246. /package/dist/{types → cjs}/types/settings.d.ts +0 -0
  247. /package/dist/{types → cjs}/utils.d.ts +0 -0
  248. /package/dist/{types → cjs}/vanilla.d.ts +0 -0
@@ -0,0 +1,2300 @@
1
+ import MicroEvent from "./contrib/microevent.js";
2
+ import MicroPlugin from "./contrib/microplugin.js";
3
+ import { Sifter } from '@orchidjs/sifter';
4
+ import { escape_regex } from '@orchidjs/unicode-variants';
5
+ import { highlight, removeHighlight } from "./contrib/highlight.js";
6
+ import * as constants from "./constants.js";
7
+ import getSettings from "./getSettings.js";
8
+ import { hash_key, get_hash, escape_html, debounce_events, getSelection, preventDefault, addEvent, loadDebounce, timeout, isKeyDown, getId, addSlashes, append, iterate } from "./utils.js";
9
+ import { getDom, isHtmlString, escapeQuery, triggerEvent, applyCSS, addClasses, removeClasses, parentMatch, getTail, isEmptyObject, nodeIndex, setAttr, replaceNode } from "./vanilla.js";
10
+ var instance_i = 0;
11
+ export default class TomSelect extends MicroPlugin(MicroEvent) {
12
+ constructor(input_arg, user_settings) {
13
+ super();
14
+ this.order = 0;
15
+ this.isOpen = false;
16
+ this.isDisabled = false;
17
+ this.isReadOnly = false;
18
+ this.isInvalid = false; // @deprecated 1.8
19
+ this.isValid = true;
20
+ this.isLocked = false;
21
+ this.isFocused = false;
22
+ this.isInputHidden = false;
23
+ this.isSetup = false;
24
+ this.ignoreFocus = false;
25
+ this.ignoreHover = false;
26
+ this.hasOptions = false;
27
+ this.lastValue = '';
28
+ this.caretPos = 0;
29
+ this.loading = 0;
30
+ this.loadedSearches = {};
31
+ this.activeOption = null;
32
+ this.activeItems = [];
33
+ this.optgroups = {};
34
+ this.options = {};
35
+ this.userOptions = {};
36
+ this.items = [];
37
+ this.refreshTimeout = null;
38
+ instance_i++;
39
+ var dir;
40
+ var input = getDom(input_arg);
41
+ if (input.tomselect) {
42
+ throw new Error('Tom Select already initialized on this element');
43
+ }
44
+ input.tomselect = this;
45
+ // detect rtl environment
46
+ var computedStyle = window.getComputedStyle && window.getComputedStyle(input, null);
47
+ dir = computedStyle.getPropertyValue('direction');
48
+ // setup default state
49
+ const settings = getSettings(input, user_settings);
50
+ this.settings = settings;
51
+ this.input = input;
52
+ this.tabIndex = input.tabIndex || 0;
53
+ this.is_select_tag = input.tagName.toLowerCase() === 'select';
54
+ this.rtl = /rtl/i.test(dir);
55
+ this.inputId = getId(input, 'tomselect-' + instance_i);
56
+ this.isRequired = input.required;
57
+ // search system
58
+ this.sifter = new Sifter(this.options, { diacritics: settings.diacritics });
59
+ // option-dependent defaults
60
+ settings.mode = settings.mode || (settings.maxItems === 1 ? 'single' : 'multi');
61
+ if (typeof settings.hideSelected !== 'boolean') {
62
+ settings.hideSelected = settings.mode === 'multi';
63
+ }
64
+ if (typeof settings.hidePlaceholder !== 'boolean') {
65
+ settings.hidePlaceholder = settings.mode !== 'multi';
66
+ }
67
+ // set up createFilter callback
68
+ var filter = settings.createFilter;
69
+ if (typeof filter !== 'function') {
70
+ if (typeof filter === 'string') {
71
+ filter = new RegExp(filter);
72
+ }
73
+ if (filter instanceof RegExp) {
74
+ settings.createFilter = (input) => filter.test(input);
75
+ }
76
+ else {
77
+ settings.createFilter = (value) => {
78
+ return this.settings.duplicates || !this.options[value];
79
+ };
80
+ }
81
+ }
82
+ this.initializePlugins(settings.plugins);
83
+ this.setupCallbacks();
84
+ this.setupTemplates();
85
+ // Create all elements
86
+ const wrapper = getDom('<div>');
87
+ const control = getDom('<div>');
88
+ const dropdown = this._render('dropdown');
89
+ const dropdown_content = getDom(`<div role="listbox" tabindex="-1">`);
90
+ const classes = this.input.getAttribute('class') || '';
91
+ const inputMode = settings.mode;
92
+ var control_input;
93
+ addClasses(wrapper, settings.wrapperClass, classes, inputMode);
94
+ addClasses(control, settings.controlClass);
95
+ append(wrapper, control);
96
+ addClasses(dropdown, settings.dropdownClass, inputMode);
97
+ if (settings.copyClassesToDropdown) {
98
+ addClasses(dropdown, classes);
99
+ }
100
+ addClasses(dropdown_content, settings.dropdownContentClass);
101
+ append(dropdown, dropdown_content);
102
+ getDom(settings.dropdownParent || wrapper).appendChild(dropdown);
103
+ // default controlInput
104
+ if (isHtmlString(settings.controlInput)) {
105
+ control_input = getDom(settings.controlInput);
106
+ // set attributes
107
+ var attrs = ['autocorrect', 'autocapitalize', 'autocomplete', 'spellcheck', 'aria-label'];
108
+ iterate(attrs, (attr) => {
109
+ if (input.getAttribute(attr)) {
110
+ setAttr(control_input, { [attr]: input.getAttribute(attr) });
111
+ }
112
+ });
113
+ control_input.tabIndex = -1;
114
+ control.appendChild(control_input);
115
+ this.focus_node = control_input;
116
+ // dom element
117
+ }
118
+ else if (settings.controlInput) {
119
+ control_input = getDom(settings.controlInput);
120
+ this.focus_node = control_input;
121
+ }
122
+ else {
123
+ control_input = getDom('<input/>');
124
+ this.focus_node = control;
125
+ }
126
+ this.wrapper = wrapper;
127
+ this.dropdown = dropdown;
128
+ this.dropdown_content = dropdown_content;
129
+ this.control = control;
130
+ this.control_input = control_input;
131
+ this.setup();
132
+ }
133
+ /**
134
+ * set up event bindings.
135
+ *
136
+ */
137
+ setup() {
138
+ const self = this;
139
+ const settings = self.settings;
140
+ const control_input = self.control_input;
141
+ const dropdown = self.dropdown;
142
+ const dropdown_content = self.dropdown_content;
143
+ const wrapper = self.wrapper;
144
+ const control = self.control;
145
+ const input = self.input;
146
+ const focus_node = self.focus_node;
147
+ const passive_event = { passive: true };
148
+ const listboxId = self.inputId + '-ts-dropdown';
149
+ setAttr(dropdown_content, {
150
+ id: listboxId
151
+ });
152
+ setAttr(focus_node, {
153
+ role: 'combobox',
154
+ 'aria-haspopup': 'listbox',
155
+ 'aria-expanded': 'false',
156
+ 'aria-controls': listboxId
157
+ });
158
+ const control_id = getId(focus_node, self.inputId + '-ts-control');
159
+ const query = "label[for='" + escapeQuery(self.inputId) + "']";
160
+ const label = document.querySelector(query);
161
+ const label_click = self.focus.bind(self);
162
+ if (label) {
163
+ addEvent(label, 'click', label_click);
164
+ setAttr(label, { for: control_id });
165
+ const label_id = getId(label, self.inputId + '-ts-label');
166
+ setAttr(focus_node, { 'aria-labelledby': label_id });
167
+ setAttr(dropdown_content, { 'aria-labelledby': label_id });
168
+ }
169
+ wrapper.style.width = input.style.width;
170
+ wrapper.style.minWidth = input.style.minWidth;
171
+ wrapper.style.maxWidth = input.style.maxWidth;
172
+ if (self.plugins.names.length) {
173
+ const classes_plugins = 'plugin-' + self.plugins.names.join(' plugin-');
174
+ addClasses([wrapper, dropdown], classes_plugins);
175
+ }
176
+ if ((settings.maxItems === null || settings.maxItems > 1) && self.is_select_tag) {
177
+ setAttr(input, { multiple: 'multiple' });
178
+ }
179
+ if (settings.placeholder) {
180
+ setAttr(control_input, { placeholder: settings.placeholder });
181
+ }
182
+ // if splitOn was not passed in, construct it from the delimiter to allow pasting universally
183
+ if (!settings.splitOn && settings.delimiter) {
184
+ settings.splitOn = new RegExp('\\s*' + escape_regex(settings.delimiter) + '+\\s*');
185
+ }
186
+ // debounce user defined load() if loadThrottle > 0
187
+ // after initializePlugins() so plugins can create/modify user defined loaders
188
+ if (settings.load && settings.loadThrottle) {
189
+ settings.load = loadDebounce(settings.load, settings.loadThrottle);
190
+ }
191
+ addEvent(dropdown, 'mousemove', () => {
192
+ self.ignoreHover = false;
193
+ });
194
+ addEvent(dropdown, 'mouseenter', (e) => {
195
+ var target_match = parentMatch(e.target, '[data-selectable]', dropdown);
196
+ if (target_match)
197
+ self.onOptionHover(e, target_match);
198
+ }, { capture: true });
199
+ // clicking on an option should select it
200
+ addEvent(dropdown, 'click', (evt) => {
201
+ const option = parentMatch(evt.target, '[data-selectable]');
202
+ if (option) {
203
+ self.onOptionSelect(evt, option);
204
+ preventDefault(evt, true);
205
+ }
206
+ });
207
+ addEvent(control, 'click', (evt) => {
208
+ var target_match = parentMatch(evt.target, '[data-ts-item]', control);
209
+ if (target_match && self.onItemSelect(evt, target_match)) {
210
+ preventDefault(evt, true);
211
+ return;
212
+ }
213
+ // retain focus (see control_input mousedown)
214
+ if (control_input.value != '') {
215
+ return;
216
+ }
217
+ self.onClick();
218
+ preventDefault(evt, true);
219
+ });
220
+ // keydown on focus_node for arrow_down/arrow_up
221
+ addEvent(focus_node, 'keydown', (e) => self.onKeyDown(e));
222
+ // keypress and input/keyup
223
+ addEvent(control_input, 'keypress', (e) => self.onKeyPress(e));
224
+ addEvent(control_input, 'input', (e) => self.onInput(e));
225
+ addEvent(focus_node, 'blur', (e) => self.onBlur(e));
226
+ addEvent(focus_node, 'focus', (e) => self.onFocus(e));
227
+ addEvent(control_input, 'paste', (e) => self.onPaste(e));
228
+ const doc_mousedown = (evt) => {
229
+ // blur if target is outside of this instance
230
+ // dropdown is not always inside wrapper
231
+ const target = evt.composedPath()[0];
232
+ if (!wrapper.contains(target) && !dropdown.contains(target)) {
233
+ if (self.isFocused) {
234
+ self.blur();
235
+ }
236
+ self.inputState();
237
+ return;
238
+ }
239
+ // retain focus by preventing native handling. if the
240
+ // event target is the input it should not be modified.
241
+ // otherwise, text selection within the input won't work.
242
+ // Fixes bug #212 which is no covered by tests
243
+ if (target == control_input && self.isOpen) {
244
+ evt.stopPropagation();
245
+ // clicking anywhere in the control should not blur the control_input (which would close the dropdown)
246
+ }
247
+ else {
248
+ preventDefault(evt, true);
249
+ }
250
+ };
251
+ const win_scroll = () => {
252
+ if (self.isOpen) {
253
+ self.positionDropdown();
254
+ }
255
+ };
256
+ const input_invalid = () => {
257
+ if (self.isValid) {
258
+ self.isValid = false;
259
+ self.isInvalid = true;
260
+ self.refreshState();
261
+ }
262
+ };
263
+ addEvent(input, 'invalid', input_invalid);
264
+ addEvent(document, 'mousedown', doc_mousedown);
265
+ addEvent(window, 'scroll', win_scroll, passive_event);
266
+ addEvent(window, 'resize', win_scroll, passive_event);
267
+ this._destroy = () => {
268
+ input.removeEventListener('invalid', input_invalid);
269
+ document.removeEventListener('mousedown', doc_mousedown);
270
+ window.removeEventListener('scroll', win_scroll);
271
+ window.removeEventListener('resize', win_scroll);
272
+ if (label)
273
+ label.removeEventListener('click', label_click);
274
+ };
275
+ // store original html and tab index so that they can be
276
+ // restored when the destroy() method is called.
277
+ this.revertSettings = {
278
+ innerHTML: input.innerHTML,
279
+ tabIndex: input.tabIndex
280
+ };
281
+ input.tabIndex = -1;
282
+ input.insertAdjacentElement('afterend', self.wrapper);
283
+ self.sync(false);
284
+ settings.items = [];
285
+ delete settings.optgroups;
286
+ delete settings.options;
287
+ self.refreshItems();
288
+ self.close(false);
289
+ self.inputState();
290
+ self.isSetup = true;
291
+ if (input.disabled) {
292
+ self.disable();
293
+ }
294
+ else if (input.readOnly) {
295
+ self.setReadOnly(true);
296
+ }
297
+ else {
298
+ self.enable(); //sets tabIndex
299
+ }
300
+ self.on('change', this.onChange);
301
+ addClasses(input, 'tomselected', 'ts-hidden-accessible');
302
+ self.trigger('initialize');
303
+ // preload options
304
+ if (settings.preload === true) {
305
+ self.preload();
306
+ }
307
+ }
308
+ /**
309
+ * Register options and optgroups
310
+ *
311
+ */
312
+ setupOptions(options = [], optgroups = []) {
313
+ // build options table
314
+ this.addOptions(options);
315
+ // build optgroup table
316
+ iterate(optgroups, (optgroup) => {
317
+ this.registerOptionGroup(optgroup);
318
+ });
319
+ }
320
+ /**
321
+ * Sets up default rendering functions.
322
+ */
323
+ setupTemplates() {
324
+ var self = this;
325
+ var field_label = self.settings.labelField;
326
+ var field_optgroup = self.settings.optgroupLabelField;
327
+ var templates = {
328
+ 'optgroup': (data) => {
329
+ let optgroup = document.createElement('div');
330
+ optgroup.className = 'optgroup';
331
+ optgroup.appendChild(data.options);
332
+ return optgroup;
333
+ },
334
+ 'optgroup_header': (data, escape) => {
335
+ return '<div class="optgroup-header">' + escape(data[field_optgroup]) + '</div>';
336
+ },
337
+ 'option': (data, escape) => {
338
+ return '<div>' + escape(data[field_label]) + '</div>';
339
+ },
340
+ 'item': (data, escape) => {
341
+ return '<div>' + escape(data[field_label]) + '</div>';
342
+ },
343
+ 'option_create': (data, escape) => {
344
+ return '<div class="create">Add <strong>' + escape(data.input) + '</strong>&hellip;</div>';
345
+ },
346
+ 'no_results': () => {
347
+ return '<div class="no-results">No results found</div>';
348
+ },
349
+ 'loading': () => {
350
+ return '<div class="spinner"></div>';
351
+ },
352
+ 'not_loading': () => { },
353
+ 'dropdown': () => {
354
+ return '<div></div>';
355
+ }
356
+ };
357
+ self.settings.render = Object.assign({}, templates, self.settings.render);
358
+ }
359
+ /**
360
+ * Maps fired events to callbacks provided
361
+ * in the settings used when creating the control.
362
+ */
363
+ setupCallbacks() {
364
+ var key, fn;
365
+ var callbacks = {
366
+ 'initialize': 'onInitialize',
367
+ 'change': 'onChange',
368
+ 'item_add': 'onItemAdd',
369
+ 'item_remove': 'onItemRemove',
370
+ 'item_select': 'onItemSelect',
371
+ 'clear': 'onClear',
372
+ 'option_add': 'onOptionAdd',
373
+ 'option_remove': 'onOptionRemove',
374
+ 'option_clear': 'onOptionClear',
375
+ 'optgroup_add': 'onOptionGroupAdd',
376
+ 'optgroup_remove': 'onOptionGroupRemove',
377
+ 'optgroup_clear': 'onOptionGroupClear',
378
+ 'dropdown_open': 'onDropdownOpen',
379
+ 'dropdown_close': 'onDropdownClose',
380
+ 'type': 'onType',
381
+ 'load': 'onLoad',
382
+ 'focus': 'onFocus',
383
+ 'blur': 'onBlur'
384
+ };
385
+ for (key in callbacks) {
386
+ fn = this.settings[callbacks[key]];
387
+ if (fn)
388
+ this.on(key, fn);
389
+ }
390
+ }
391
+ /**
392
+ * Sync the Tom Select instance with the original input or select
393
+ *
394
+ */
395
+ sync(get_settings = true) {
396
+ const self = this;
397
+ const settings = get_settings ? getSettings(self.input, { delimiter: self.settings.delimiter, allowEmptyOption: self.settings.allowEmptyOption }) : self.settings;
398
+ self.setupOptions(settings.options, settings.optgroups);
399
+ self.setValue(settings.items || [], true); // silent prevents recursion
400
+ self.lastQuery = null; // so updated options will be displayed in dropdown
401
+ }
402
+ /**
403
+ * Triggered when the main control element
404
+ * has a click event.
405
+ *
406
+ */
407
+ onClick() {
408
+ var self = this;
409
+ if (self.activeItems.length > 0) {
410
+ self.clearActiveItems();
411
+ self.focus();
412
+ return;
413
+ }
414
+ if (self.isFocused && self.isOpen) {
415
+ self.blur();
416
+ }
417
+ else {
418
+ self.focus();
419
+ }
420
+ }
421
+ /**
422
+ * @deprecated v1.7
423
+ *
424
+ */
425
+ onMouseDown() { }
426
+ /**
427
+ * Triggered when the value of the control has been changed.
428
+ * This should propagate the event to the original DOM
429
+ * input / select element.
430
+ */
431
+ onChange() {
432
+ triggerEvent(this.input, 'input');
433
+ triggerEvent(this.input, 'change');
434
+ }
435
+ /**
436
+ * Triggered on <input> paste.
437
+ *
438
+ */
439
+ onPaste(e) {
440
+ var self = this;
441
+ if (self.isInputHidden || self.isLocked) {
442
+ preventDefault(e);
443
+ return;
444
+ }
445
+ // If a regex or string is included, this will split the pasted
446
+ // input and create Items for each separate value
447
+ if (!self.settings.splitOn) {
448
+ return;
449
+ }
450
+ // Wait for pasted text to be recognized in value
451
+ setTimeout(() => {
452
+ var pastedText = self.inputValue();
453
+ if (!pastedText.match(self.settings.splitOn)) {
454
+ return;
455
+ }
456
+ var splitInput = pastedText.trim().split(self.settings.splitOn);
457
+ iterate(splitInput, (piece) => {
458
+ const hash = hash_key(piece);
459
+ if (hash) {
460
+ if (this.options[piece]) {
461
+ self.addItem(piece);
462
+ }
463
+ else {
464
+ self.createItem(piece);
465
+ }
466
+ }
467
+ });
468
+ }, 0);
469
+ }
470
+ /**
471
+ * Triggered on <input> keypress.
472
+ *
473
+ */
474
+ onKeyPress(e) {
475
+ var self = this;
476
+ if (self.isLocked) {
477
+ preventDefault(e);
478
+ return;
479
+ }
480
+ var character = String.fromCharCode(e.keyCode || e.which);
481
+ if (self.settings.create && self.settings.mode === 'multi' && character === self.settings.delimiter) {
482
+ self.createItem();
483
+ preventDefault(e);
484
+ return;
485
+ }
486
+ }
487
+ /**
488
+ * Triggered on <input> keydown.
489
+ *
490
+ */
491
+ onKeyDown(e) {
492
+ var self = this;
493
+ self.ignoreHover = true;
494
+ if (self.isLocked) {
495
+ if (e.keyCode !== constants.KEY_TAB) {
496
+ preventDefault(e);
497
+ }
498
+ return;
499
+ }
500
+ switch (e.keyCode) {
501
+ // ctrl+A: select all
502
+ case constants.KEY_A:
503
+ if (isKeyDown(constants.KEY_SHORTCUT, e)) {
504
+ if (self.control_input.value == '') {
505
+ preventDefault(e);
506
+ self.selectAll();
507
+ return;
508
+ }
509
+ }
510
+ break;
511
+ // esc: close dropdown
512
+ case constants.KEY_ESC:
513
+ if (self.isOpen) {
514
+ preventDefault(e, true);
515
+ self.close();
516
+ }
517
+ self.clearActiveItems();
518
+ return;
519
+ // down: open dropdown or move selection down
520
+ case constants.KEY_DOWN:
521
+ if (!self.isOpen && self.hasOptions) {
522
+ self.open();
523
+ }
524
+ else if (self.activeOption) {
525
+ let next = self.getAdjacent(self.activeOption, 1);
526
+ if (next)
527
+ self.setActiveOption(next);
528
+ }
529
+ preventDefault(e);
530
+ return;
531
+ // up: move selection up
532
+ case constants.KEY_UP:
533
+ if (self.activeOption) {
534
+ let prev = self.getAdjacent(self.activeOption, -1);
535
+ if (prev)
536
+ self.setActiveOption(prev);
537
+ }
538
+ preventDefault(e);
539
+ return;
540
+ // return: select active option
541
+ case constants.KEY_RETURN:
542
+ if (self.canSelect(self.activeOption)) {
543
+ self.onOptionSelect(e, self.activeOption);
544
+ preventDefault(e);
545
+ // if the option_create=null, the dropdown might be closed
546
+ }
547
+ else if (self.settings.create && self.createItem()) {
548
+ preventDefault(e);
549
+ // don't submit form when searching for a value
550
+ }
551
+ else if (document.activeElement == self.control_input && self.isOpen) {
552
+ preventDefault(e);
553
+ }
554
+ return;
555
+ // left: modifiy item selection to the left
556
+ case constants.KEY_LEFT:
557
+ self.advanceSelection(-1, e);
558
+ return;
559
+ // right: modifiy item selection to the right
560
+ case constants.KEY_RIGHT:
561
+ self.advanceSelection(1, e);
562
+ return;
563
+ // tab: select active option and/or create item
564
+ case constants.KEY_TAB:
565
+ if (self.settings.selectOnTab) {
566
+ if (self.canSelect(self.activeOption)) {
567
+ self.onOptionSelect(e, self.activeOption);
568
+ // prevent default [tab] behaviour of jump to the next field
569
+ // if select isFull, then the dropdown won't be open and [tab] will work normally
570
+ preventDefault(e);
571
+ }
572
+ else if (self.settings.create && self.createItem()) {
573
+ preventDefault(e);
574
+ }
575
+ }
576
+ return;
577
+ // delete|backspace: delete items
578
+ case constants.KEY_BACKSPACE:
579
+ case constants.KEY_DELETE:
580
+ self.deleteSelection(e);
581
+ return;
582
+ }
583
+ // don't enter text in the control_input when active items are selected
584
+ if (self.isInputHidden && !isKeyDown(constants.KEY_SHORTCUT, e)) {
585
+ preventDefault(e);
586
+ }
587
+ }
588
+ /**
589
+ * Triggered on <input> keyup.
590
+ *
591
+ */
592
+ onInput(e) {
593
+ if (this.isLocked) {
594
+ return;
595
+ }
596
+ const value = this.inputValue();
597
+ if (this.lastValue === value)
598
+ return;
599
+ this.lastValue = value;
600
+ if (value == '') {
601
+ this._onInput();
602
+ return;
603
+ }
604
+ if (this.refreshTimeout) {
605
+ window.clearTimeout(this.refreshTimeout);
606
+ }
607
+ this.refreshTimeout = timeout(() => {
608
+ this.refreshTimeout = null;
609
+ this._onInput();
610
+ }, this.settings.refreshThrottle);
611
+ }
612
+ _onInput() {
613
+ const value = this.lastValue;
614
+ if (this.settings.shouldLoad.call(this, value)) {
615
+ this.load(value);
616
+ }
617
+ this.refreshOptions();
618
+ this.trigger('type', value);
619
+ }
620
+ /**
621
+ * Triggered when the user rolls over
622
+ * an option in the autocomplete dropdown menu.
623
+ *
624
+ */
625
+ onOptionHover(evt, option) {
626
+ if (this.ignoreHover)
627
+ return;
628
+ this.setActiveOption(option, false);
629
+ }
630
+ /**
631
+ * Triggered on <input> focus.
632
+ *
633
+ */
634
+ onFocus(e) {
635
+ var self = this;
636
+ var wasFocused = self.isFocused;
637
+ if (self.isDisabled || self.isReadOnly) {
638
+ self.blur();
639
+ preventDefault(e);
640
+ return;
641
+ }
642
+ if (self.ignoreFocus)
643
+ return;
644
+ self.isFocused = true;
645
+ if (self.settings.preload === 'focus')
646
+ self.preload();
647
+ if (!wasFocused)
648
+ self.trigger('focus');
649
+ if (!self.activeItems.length) {
650
+ self.inputState();
651
+ self.refreshOptions(!!self.settings.openOnFocus);
652
+ }
653
+ self.refreshState();
654
+ }
655
+ /**
656
+ * Triggered on <input> blur.
657
+ *
658
+ */
659
+ onBlur(e) {
660
+ if (document.hasFocus() === false)
661
+ return;
662
+ var self = this;
663
+ if (!self.isFocused)
664
+ return;
665
+ self.isFocused = false;
666
+ self.ignoreFocus = false;
667
+ var deactivate = () => {
668
+ self.close();
669
+ self.setActiveItem();
670
+ self.setCaret(self.items.length);
671
+ self.trigger('blur');
672
+ };
673
+ if (self.settings.create && self.settings.createOnBlur) {
674
+ self.createItem(null, deactivate);
675
+ }
676
+ else {
677
+ deactivate();
678
+ }
679
+ }
680
+ /**
681
+ * Triggered when the user clicks on an option
682
+ * in the autocomplete dropdown menu.
683
+ *
684
+ */
685
+ onOptionSelect(evt, option) {
686
+ var value, self = this;
687
+ // should not be possible to trigger a option under a disabled optgroup
688
+ if (option.parentElement && option.parentElement.matches('[data-disabled]')) {
689
+ return;
690
+ }
691
+ if (option.classList.contains('create')) {
692
+ self.createItem(null, () => {
693
+ if (self.settings.closeAfterSelect) {
694
+ self.close();
695
+ }
696
+ else if (self.settings.clearAfterSelect) {
697
+ self.setTextboxValue();
698
+ }
699
+ });
700
+ }
701
+ else {
702
+ value = option.dataset.value;
703
+ if (typeof value !== 'undefined') {
704
+ self.lastQuery = null;
705
+ self.addItem(value);
706
+ if (self.settings.closeAfterSelect) {
707
+ self.close();
708
+ }
709
+ else if (self.settings.clearAfterSelect) {
710
+ self.setTextboxValue();
711
+ }
712
+ if (!self.settings.hideSelected && evt.type && /click/.test(evt.type)) {
713
+ self.setActiveOption(option);
714
+ }
715
+ }
716
+ }
717
+ }
718
+ /**
719
+ * Return true if the given option can be selected
720
+ *
721
+ */
722
+ canSelect(option) {
723
+ if (this.isOpen && option && this.dropdown_content.contains(option)) {
724
+ return true;
725
+ }
726
+ return false;
727
+ }
728
+ /**
729
+ * Triggered when the user clicks on an item
730
+ * that has been selected.
731
+ *
732
+ */
733
+ onItemSelect(evt, item) {
734
+ var self = this;
735
+ if (!self.isLocked && self.settings.mode === 'multi') {
736
+ preventDefault(evt);
737
+ self.setActiveItem(item, evt);
738
+ return true;
739
+ }
740
+ return false;
741
+ }
742
+ /**
743
+ * Determines whether or not to invoke
744
+ * the user-provided option provider / loader
745
+ *
746
+ * Note, there is a subtle difference between
747
+ * this.canLoad() and this.settings.shouldLoad();
748
+ *
749
+ * - settings.shouldLoad() is a user-input validator.
750
+ * When false is returned, the not_loading template
751
+ * will be added to the dropdown
752
+ *
753
+ * - canLoad() is lower level validator that checks
754
+ * the Tom Select instance. There is no inherent user
755
+ * feedback when canLoad returns false
756
+ *
757
+ */
758
+ canLoad(value) {
759
+ if (!this.settings.load)
760
+ return false;
761
+ if (this.loadedSearches.hasOwnProperty(value))
762
+ return false;
763
+ return true;
764
+ }
765
+ /**
766
+ * Invokes the user-provided option provider / loader.
767
+ *
768
+ */
769
+ load(value) {
770
+ const self = this;
771
+ if (!self.canLoad(value))
772
+ return;
773
+ addClasses(self.wrapper, self.settings.loadingClass);
774
+ self.loading++;
775
+ const callback = self.loadCallback.bind(self);
776
+ self.settings.load.call(self, value, callback);
777
+ }
778
+ /**
779
+ * Invoked by the user-provided option provider
780
+ *
781
+ */
782
+ loadCallback(options, optgroups) {
783
+ const self = this;
784
+ self.loading = Math.max(self.loading - 1, 0);
785
+ self.lastQuery = null;
786
+ self.clearActiveOption(); // when new results load, focus should be on first option
787
+ self.setupOptions(options, optgroups);
788
+ self.refreshOptions(self.isFocused && !self.isInputHidden);
789
+ if (!self.loading) {
790
+ removeClasses(self.wrapper, self.settings.loadingClass);
791
+ }
792
+ self.trigger('load', options, optgroups);
793
+ }
794
+ preload() {
795
+ var classList = this.wrapper.classList;
796
+ if (classList.contains('preloaded'))
797
+ return;
798
+ classList.add('preloaded');
799
+ this.load('');
800
+ }
801
+ /**
802
+ * Sets the input field of the control to the specified value.
803
+ *
804
+ */
805
+ setTextboxValue(value = '') {
806
+ var input = this.control_input;
807
+ var changed = input.value !== value;
808
+ if (changed) {
809
+ input.value = value;
810
+ triggerEvent(input, 'update');
811
+ this.lastValue = value;
812
+ }
813
+ }
814
+ /**
815
+ * Returns the value of the control. If multiple items
816
+ * can be selected (e.g. <select multiple>), this returns
817
+ * an array. If only one item can be selected, this
818
+ * returns a string.
819
+ *
820
+ */
821
+ getValue() {
822
+ if (this.is_select_tag && this.input.hasAttribute('multiple')) {
823
+ return this.items;
824
+ }
825
+ return this.items.join(this.settings.delimiter);
826
+ }
827
+ /**
828
+ * Resets the selected items to the given value.
829
+ *
830
+ */
831
+ setValue(value, silent) {
832
+ var events = silent ? [] : ['change'];
833
+ debounce_events(this, events, () => {
834
+ this.clear(silent);
835
+ this.addItems(value, silent);
836
+ });
837
+ }
838
+ /**
839
+ * Resets the number of max items to the given value
840
+ *
841
+ */
842
+ setMaxItems(value) {
843
+ if (value === 0)
844
+ value = null; //reset to unlimited items.
845
+ this.settings.maxItems = value;
846
+ this.refreshState();
847
+ }
848
+ /**
849
+ * Sets the selected item.
850
+ *
851
+ */
852
+ setActiveItem(item, e) {
853
+ var self = this;
854
+ var eventName;
855
+ var i, begin, end, swap;
856
+ var last;
857
+ if (self.settings.mode === 'single')
858
+ return;
859
+ // clear the active selection
860
+ if (!item) {
861
+ self.clearActiveItems();
862
+ if (self.isFocused) {
863
+ self.inputState();
864
+ }
865
+ return;
866
+ }
867
+ // modify selection
868
+ eventName = e && e.type.toLowerCase();
869
+ if (eventName === 'click' && isKeyDown('shiftKey', e) && self.activeItems.length) {
870
+ last = self.getLastActive();
871
+ begin = Array.prototype.indexOf.call(self.control.children, last);
872
+ end = Array.prototype.indexOf.call(self.control.children, item);
873
+ if (begin > end) {
874
+ swap = begin;
875
+ begin = end;
876
+ end = swap;
877
+ }
878
+ for (i = begin; i <= end; i++) {
879
+ item = self.control.children[i];
880
+ if (self.activeItems.indexOf(item) === -1) {
881
+ self.setActiveItemClass(item);
882
+ }
883
+ }
884
+ preventDefault(e);
885
+ }
886
+ else if ((eventName === 'click' && isKeyDown(constants.KEY_SHORTCUT, e)) || (eventName === 'keydown' && isKeyDown('shiftKey', e))) {
887
+ if (item.classList.contains('active')) {
888
+ self.removeActiveItem(item);
889
+ }
890
+ else {
891
+ self.setActiveItemClass(item);
892
+ }
893
+ }
894
+ else {
895
+ self.clearActiveItems();
896
+ self.setActiveItemClass(item);
897
+ }
898
+ // ensure control has focus
899
+ self.inputState();
900
+ if (!self.isFocused) {
901
+ self.focus();
902
+ }
903
+ }
904
+ /**
905
+ * Set the active and last-active classes
906
+ *
907
+ */
908
+ setActiveItemClass(item) {
909
+ const self = this;
910
+ const last_active = self.control.querySelector('.last-active');
911
+ if (last_active)
912
+ removeClasses(last_active, 'last-active');
913
+ addClasses(item, 'active last-active');
914
+ self.trigger('item_select', item);
915
+ if (self.activeItems.indexOf(item) == -1) {
916
+ self.activeItems.push(item);
917
+ }
918
+ }
919
+ /**
920
+ * Remove active item
921
+ *
922
+ */
923
+ removeActiveItem(item) {
924
+ var idx = this.activeItems.indexOf(item);
925
+ this.activeItems.splice(idx, 1);
926
+ removeClasses(item, 'active');
927
+ }
928
+ /**
929
+ * Clears all the active items
930
+ *
931
+ */
932
+ clearActiveItems() {
933
+ removeClasses(this.activeItems, 'active');
934
+ this.activeItems = [];
935
+ }
936
+ /**
937
+ * Sets the selected item in the dropdown menu
938
+ * of available options.
939
+ *
940
+ */
941
+ setActiveOption(option, scroll = true) {
942
+ if (option === this.activeOption) {
943
+ return;
944
+ }
945
+ this.clearActiveOption();
946
+ if (!option)
947
+ return;
948
+ this.activeOption = option;
949
+ setAttr(this.focus_node, { 'aria-activedescendant': option.getAttribute('id') });
950
+ setAttr(option, { 'aria-selected': 'true' });
951
+ addClasses(option, 'active');
952
+ if (scroll)
953
+ this.scrollToOption(option);
954
+ }
955
+ /**
956
+ * Sets the dropdown_content scrollTop to display the option
957
+ *
958
+ */
959
+ scrollToOption(option, behavior) {
960
+ if (!option)
961
+ return;
962
+ const content = this.dropdown_content;
963
+ const height_menu = content.clientHeight;
964
+ const scrollTop = content.scrollTop || 0;
965
+ const height_item = option.offsetHeight;
966
+ const y = option.getBoundingClientRect().top - content.getBoundingClientRect().top + scrollTop;
967
+ if (y + height_item > height_menu + scrollTop) {
968
+ this.scroll(y - height_menu + height_item, behavior);
969
+ }
970
+ else if (y < scrollTop) {
971
+ this.scroll(y, behavior);
972
+ }
973
+ }
974
+ /**
975
+ * Scroll the dropdown to the given position
976
+ *
977
+ */
978
+ scroll(scrollTop, behavior) {
979
+ const content = this.dropdown_content;
980
+ if (behavior) {
981
+ content.style.scrollBehavior = behavior;
982
+ }
983
+ content.scrollTop = scrollTop;
984
+ content.style.scrollBehavior = '';
985
+ }
986
+ /**
987
+ * Clears the active option
988
+ *
989
+ */
990
+ clearActiveOption() {
991
+ if (this.activeOption) {
992
+ removeClasses(this.activeOption, 'active');
993
+ setAttr(this.activeOption, { 'aria-selected': null });
994
+ }
995
+ this.activeOption = null;
996
+ setAttr(this.focus_node, { 'aria-activedescendant': null });
997
+ }
998
+ /**
999
+ * Selects all items (CTRL + A).
1000
+ */
1001
+ selectAll() {
1002
+ const self = this;
1003
+ if (self.settings.mode === 'single')
1004
+ return;
1005
+ const activeItems = self.controlChildren();
1006
+ if (!activeItems.length)
1007
+ return;
1008
+ self.inputState();
1009
+ self.close();
1010
+ self.activeItems = activeItems;
1011
+ iterate(activeItems, (item) => {
1012
+ self.setActiveItemClass(item);
1013
+ });
1014
+ }
1015
+ /**
1016
+ * Determines if the control_input should be in a hidden or visible state
1017
+ *
1018
+ */
1019
+ inputState() {
1020
+ var self = this;
1021
+ if (!self.control.contains(self.control_input))
1022
+ return;
1023
+ setAttr(self.control_input, { placeholder: self.settings.placeholder });
1024
+ if (self.activeItems.length > 0 || (!self.isFocused && self.settings.hidePlaceholder && self.items.length > 0)) {
1025
+ self.setTextboxValue();
1026
+ self.isInputHidden = true;
1027
+ }
1028
+ else {
1029
+ if (self.settings.hidePlaceholder && self.items.length > 0) {
1030
+ setAttr(self.control_input, { placeholder: '' });
1031
+ }
1032
+ self.isInputHidden = false;
1033
+ }
1034
+ self.wrapper.classList.toggle('input-hidden', self.isInputHidden);
1035
+ }
1036
+ /**
1037
+ * Get the input value
1038
+ */
1039
+ inputValue() {
1040
+ return this.control_input.value.trim();
1041
+ }
1042
+ /**
1043
+ * Gives the control focus.
1044
+ */
1045
+ focus() {
1046
+ var self = this;
1047
+ if (self.isDisabled || self.isReadOnly)
1048
+ return;
1049
+ self.ignoreFocus = true;
1050
+ if (self.control_input.offsetWidth) {
1051
+ self.control_input.focus();
1052
+ }
1053
+ else {
1054
+ self.focus_node.focus();
1055
+ }
1056
+ setTimeout(() => {
1057
+ self.ignoreFocus = false;
1058
+ self.onFocus();
1059
+ }, 0);
1060
+ }
1061
+ /**
1062
+ * Forces the control out of focus.
1063
+ *
1064
+ */
1065
+ blur() {
1066
+ this.focus_node.blur();
1067
+ this.onBlur();
1068
+ }
1069
+ /**
1070
+ * Returns a function that scores an object
1071
+ * to show how good of a match it is to the
1072
+ * provided query.
1073
+ *
1074
+ * @return {function}
1075
+ */
1076
+ getScoreFunction(query) {
1077
+ return this.sifter.getScoreFunction(query, this.getSearchOptions());
1078
+ }
1079
+ /**
1080
+ * Returns search options for sifter (the system
1081
+ * for scoring and sorting results).
1082
+ *
1083
+ * @see https://github.com/orchidjs/sifter.js
1084
+ * @return {object}
1085
+ */
1086
+ getSearchOptions() {
1087
+ var settings = this.settings;
1088
+ var sort = settings.sortField;
1089
+ if (typeof settings.sortField === 'string') {
1090
+ sort = [{ field: settings.sortField }];
1091
+ }
1092
+ return {
1093
+ fields: settings.searchField,
1094
+ conjunction: settings.searchConjunction,
1095
+ sort: sort,
1096
+ nesting: settings.nesting
1097
+ };
1098
+ }
1099
+ /**
1100
+ * Searches through available options and returns
1101
+ * a sorted array of matches.
1102
+ *
1103
+ */
1104
+ search(query) {
1105
+ var result, calculateScore;
1106
+ var self = this;
1107
+ var options = this.getSearchOptions();
1108
+ // validate user-provided result scoring function
1109
+ if (self.settings.score) {
1110
+ calculateScore = self.settings.score.call(self, query);
1111
+ if (typeof calculateScore !== 'function') {
1112
+ throw new Error('Tom Select "score" setting must be a function that returns a function');
1113
+ }
1114
+ }
1115
+ // perform search
1116
+ if (query !== self.lastQuery) {
1117
+ self.lastQuery = query;
1118
+ // temp fix for https://github.com/orchidjs/tom-select/issues/987
1119
+ // UI crashed when more than 30 same chars in a row, prevent search and return empt result
1120
+ if (/(.)\1{15,}/.test(query)) {
1121
+ query = '';
1122
+ }
1123
+ result = self.sifter.search(query, Object.assign(options, { score: calculateScore }));
1124
+ self.currentResults = result;
1125
+ }
1126
+ else {
1127
+ result = Object.assign({}, self.currentResults);
1128
+ }
1129
+ // filter out selected items
1130
+ if (self.settings.hideSelected) {
1131
+ result.items = result.items.filter((item) => {
1132
+ let hashed = hash_key(item.id);
1133
+ return !(hashed !== null && self.items.indexOf(hashed) !== -1);
1134
+ });
1135
+ }
1136
+ return result;
1137
+ }
1138
+ /**
1139
+ * Refreshes the list of available options shown
1140
+ * in the autocomplete dropdown menu.
1141
+ *
1142
+ */
1143
+ refreshOptions(triggerDropdown = true) {
1144
+ var i, j, k, n, optgroup, optgroups, html, has_create_option, active_group;
1145
+ var create;
1146
+ const groups = {};
1147
+ const groups_order = [];
1148
+ var self = this;
1149
+ var query = self.inputValue();
1150
+ const same_query = query === self.lastQuery || (query == '' && self.lastQuery == null);
1151
+ var results = self.search(query);
1152
+ var active_option = null;
1153
+ var show_dropdown = self.settings.shouldOpen || false;
1154
+ var dropdown_content = self.dropdown_content;
1155
+ if (same_query) {
1156
+ active_option = self.activeOption;
1157
+ if (active_option) {
1158
+ active_group = active_option.closest('[data-group]');
1159
+ }
1160
+ }
1161
+ // build markup
1162
+ n = results.items.length;
1163
+ if (typeof self.settings.maxOptions === 'number') {
1164
+ n = Math.min(n, self.settings.maxOptions);
1165
+ }
1166
+ if (n > 0) {
1167
+ show_dropdown = true;
1168
+ }
1169
+ // get fragment for group and the position of the group in group_order
1170
+ const getGroupFragment = (optgroup, order) => {
1171
+ let group_order_i = groups[optgroup];
1172
+ if (group_order_i !== undefined) {
1173
+ let order_group = groups_order[group_order_i];
1174
+ if (order_group !== undefined) {
1175
+ return [group_order_i, order_group.fragment];
1176
+ }
1177
+ }
1178
+ let group_fragment = document.createDocumentFragment();
1179
+ group_order_i = groups_order.length;
1180
+ groups_order.push({ fragment: group_fragment, order, optgroup });
1181
+ return [group_order_i, group_fragment];
1182
+ };
1183
+ // render and group available options individually
1184
+ for (i = 0; i < n; i++) {
1185
+ // get option dom element
1186
+ let item = results.items[i];
1187
+ if (!item)
1188
+ continue;
1189
+ let opt_value = item.id;
1190
+ let option = self.options[opt_value];
1191
+ if (option === undefined)
1192
+ continue;
1193
+ let opt_hash = get_hash(opt_value);
1194
+ let option_el = self.getOption(opt_hash, true);
1195
+ // toggle 'selected' class
1196
+ if (!self.settings.hideSelected) {
1197
+ option_el.classList.toggle('selected', self.items.includes(opt_hash));
1198
+ }
1199
+ optgroup = option[self.settings.optgroupField] || '';
1200
+ optgroups = Array.isArray(optgroup) ? optgroup : [optgroup];
1201
+ for (j = 0, k = optgroups && optgroups.length; j < k; j++) {
1202
+ optgroup = optgroups[j];
1203
+ let order = option.$order;
1204
+ let self_optgroup = self.optgroups[optgroup];
1205
+ if (self_optgroup === undefined && typeof self.settings.optionGroupRegister === 'function') {
1206
+ var regGroup;
1207
+ if (regGroup = self.settings.optionGroupRegister.apply(self, [optgroup])) {
1208
+ self.registerOptionGroup(regGroup);
1209
+ }
1210
+ }
1211
+ self_optgroup = self.optgroups[optgroup];
1212
+ if (self_optgroup === undefined) {
1213
+ optgroup = '';
1214
+ }
1215
+ else {
1216
+ order = self_optgroup.$order;
1217
+ }
1218
+ const [group_order_i, group_fragment] = getGroupFragment(optgroup, order);
1219
+ // nodes can only have one parent, so if the option is in mutple groups, we need a clone
1220
+ if (j > 0) {
1221
+ option_el = option_el.cloneNode(true);
1222
+ setAttr(option_el, { id: option.$id + '-clone-' + j, 'aria-selected': null });
1223
+ option_el.classList.add('ts-cloned');
1224
+ removeClasses(option_el, 'active');
1225
+ // make sure we keep the activeOption in the same group
1226
+ if (self.activeOption && self.activeOption.dataset.value == opt_value) {
1227
+ if (active_group && active_group.dataset.group === optgroup.toString()) {
1228
+ active_option = option_el;
1229
+ }
1230
+ }
1231
+ }
1232
+ group_fragment.appendChild(option_el);
1233
+ if (optgroup != '') {
1234
+ groups[optgroup] = group_order_i;
1235
+ }
1236
+ }
1237
+ }
1238
+ // sort optgroups
1239
+ if (self.settings.lockOptgroupOrder) {
1240
+ groups_order.sort((a, b) => {
1241
+ return a.order - b.order;
1242
+ });
1243
+ }
1244
+ // render optgroup headers & join groups
1245
+ html = document.createDocumentFragment();
1246
+ iterate(groups_order, (group_order) => {
1247
+ let group_fragment = group_order.fragment;
1248
+ let optgroup = group_order.optgroup;
1249
+ if (!group_fragment || !group_fragment.children.length)
1250
+ return;
1251
+ let group_heading = self.optgroups[optgroup];
1252
+ if (group_heading !== undefined) {
1253
+ let group_options = document.createDocumentFragment();
1254
+ let header = self.render('optgroup_header', group_heading);
1255
+ append(group_options, header);
1256
+ append(group_options, group_fragment);
1257
+ let group_html = self.render('optgroup', { group: group_heading, options: group_options });
1258
+ append(html, group_html);
1259
+ }
1260
+ else {
1261
+ append(html, group_fragment);
1262
+ }
1263
+ });
1264
+ dropdown_content.innerHTML = '';
1265
+ append(dropdown_content, html);
1266
+ // highlight matching terms inline
1267
+ if (self.settings.highlight) {
1268
+ removeHighlight(dropdown_content);
1269
+ if (results.query.length && results.tokens.length) {
1270
+ iterate(results.tokens, (tok) => {
1271
+ highlight(dropdown_content, tok.regex);
1272
+ });
1273
+ }
1274
+ }
1275
+ // helper method for adding templates to dropdown
1276
+ var add_template = (template) => {
1277
+ let content = self.render(template, { input: query });
1278
+ if (content) {
1279
+ show_dropdown = true;
1280
+ dropdown_content.insertBefore(content, dropdown_content.firstChild);
1281
+ }
1282
+ return content;
1283
+ };
1284
+ // add loading message
1285
+ if (self.loading) {
1286
+ add_template('loading');
1287
+ // invalid query
1288
+ }
1289
+ else if (!self.settings.shouldLoad.call(self, query)) {
1290
+ add_template('not_loading');
1291
+ // add no_results message
1292
+ }
1293
+ else if (results.items.length === 0) {
1294
+ add_template('no_results');
1295
+ }
1296
+ // add create option
1297
+ has_create_option = self.canCreate(query);
1298
+ if (has_create_option) {
1299
+ create = add_template('option_create');
1300
+ }
1301
+ // activate
1302
+ self.hasOptions = results.items.length > 0 || has_create_option;
1303
+ if (show_dropdown) {
1304
+ if (results.items.length > 0) {
1305
+ if (!active_option && self.settings.mode === 'single' && self.items[0] != undefined) {
1306
+ active_option = self.getOption(self.items[0]);
1307
+ }
1308
+ if (!dropdown_content.contains(active_option)) {
1309
+ let active_index = 0;
1310
+ if (create && !self.settings.addPrecedence) {
1311
+ active_index = 1;
1312
+ }
1313
+ active_option = self.selectable()[active_index];
1314
+ }
1315
+ }
1316
+ else if (create) {
1317
+ active_option = create;
1318
+ }
1319
+ if (triggerDropdown && !self.isOpen) {
1320
+ self.open();
1321
+ self.scrollToOption(active_option, 'auto');
1322
+ }
1323
+ self.setActiveOption(active_option);
1324
+ }
1325
+ else {
1326
+ self.clearActiveOption();
1327
+ if (triggerDropdown && self.isOpen) {
1328
+ self.close(false); // if create_option=null, we want the dropdown to close but not reset the textbox value
1329
+ }
1330
+ }
1331
+ }
1332
+ /**
1333
+ * Return list of selectable options
1334
+ *
1335
+ */
1336
+ selectable() {
1337
+ return this.dropdown_content.querySelectorAll('[data-selectable]');
1338
+ }
1339
+ /**
1340
+ * Adds an available option. If it already exists,
1341
+ * nothing will happen. Note: this does not refresh
1342
+ * the options list dropdown (use `refreshOptions`
1343
+ * for that).
1344
+ *
1345
+ * Usage:
1346
+ *
1347
+ * this.addOption(data)
1348
+ *
1349
+ */
1350
+ addOption(data, user_created = false) {
1351
+ const self = this;
1352
+ // @deprecated 1.7.7
1353
+ // use addOptions( array, user_created ) for adding multiple options
1354
+ if (Array.isArray(data)) {
1355
+ self.addOptions(data, user_created);
1356
+ return false;
1357
+ }
1358
+ const key = hash_key(data[self.settings.valueField]);
1359
+ if (key === null || self.options.hasOwnProperty(key)) {
1360
+ return false;
1361
+ }
1362
+ data.$order = data.$order || ++self.order;
1363
+ data.$id = self.inputId + '-opt-' + data.$order;
1364
+ self.options[key] = data;
1365
+ self.lastQuery = null;
1366
+ if (user_created) {
1367
+ self.userOptions[key] = user_created;
1368
+ self.trigger('option_add', key, data);
1369
+ }
1370
+ return key;
1371
+ }
1372
+ /**
1373
+ * Add multiple options
1374
+ *
1375
+ */
1376
+ addOptions(data, user_created = false) {
1377
+ iterate(data, (dat) => {
1378
+ this.addOption(dat, user_created);
1379
+ });
1380
+ }
1381
+ /**
1382
+ * @deprecated 1.7.7
1383
+ */
1384
+ registerOption(data) {
1385
+ return this.addOption(data);
1386
+ }
1387
+ /**
1388
+ * Registers an option group to the pool of option groups.
1389
+ *
1390
+ * @return {boolean|string}
1391
+ */
1392
+ registerOptionGroup(data) {
1393
+ var key = hash_key(data[this.settings.optgroupValueField]);
1394
+ if (key === null)
1395
+ return false;
1396
+ data.$order = data.$order || ++this.order;
1397
+ this.optgroups[key] = data;
1398
+ return key;
1399
+ }
1400
+ /**
1401
+ * Registers a new optgroup for options
1402
+ * to be bucketed into.
1403
+ *
1404
+ */
1405
+ addOptionGroup(id, data) {
1406
+ var hashed_id;
1407
+ data[this.settings.optgroupValueField] = id;
1408
+ if (hashed_id = this.registerOptionGroup(data)) {
1409
+ this.trigger('optgroup_add', hashed_id, data);
1410
+ }
1411
+ }
1412
+ /**
1413
+ * Removes an existing option group.
1414
+ *
1415
+ */
1416
+ removeOptionGroup(id) {
1417
+ if (this.optgroups.hasOwnProperty(id)) {
1418
+ delete this.optgroups[id];
1419
+ this.clearCache();
1420
+ this.trigger('optgroup_remove', id);
1421
+ }
1422
+ }
1423
+ /**
1424
+ * Clears all existing option groups.
1425
+ */
1426
+ clearOptionGroups() {
1427
+ this.optgroups = {};
1428
+ this.clearCache();
1429
+ this.trigger('optgroup_clear');
1430
+ }
1431
+ /**
1432
+ * Updates an option available for selection. If
1433
+ * it is visible in the selected items or options
1434
+ * dropdown, it will be re-rendered automatically.
1435
+ *
1436
+ */
1437
+ updateOption(value, data) {
1438
+ const self = this;
1439
+ var item_new;
1440
+ var index_item;
1441
+ const value_old = hash_key(value);
1442
+ const value_new = hash_key(data[self.settings.valueField]);
1443
+ // sanity checks
1444
+ if (value_old === null)
1445
+ return;
1446
+ const data_old = self.options[value_old];
1447
+ if (data_old == undefined)
1448
+ return;
1449
+ if (typeof value_new !== 'string')
1450
+ throw new Error('Value must be set in option data');
1451
+ const option = self.getOption(value_old);
1452
+ const item = self.getItem(value_old);
1453
+ data.$order = data.$order || data_old.$order;
1454
+ delete self.options[value_old];
1455
+ // invalidate render cache
1456
+ // don't remove existing node yet, we'll remove it after replacing it
1457
+ self.uncacheValue(value_new);
1458
+ self.options[value_new] = data;
1459
+ // update the option if it's in the dropdown
1460
+ if (option) {
1461
+ if (self.dropdown_content.contains(option)) {
1462
+ const option_new = self._render('option', data);
1463
+ replaceNode(option, option_new);
1464
+ if (self.activeOption === option) {
1465
+ self.setActiveOption(option_new);
1466
+ }
1467
+ }
1468
+ option.remove();
1469
+ }
1470
+ // update the item if we have one
1471
+ if (item) {
1472
+ index_item = self.items.indexOf(value_old);
1473
+ if (index_item !== -1) {
1474
+ self.items.splice(index_item, 1, value_new);
1475
+ }
1476
+ item_new = self._render('item', data);
1477
+ if (item.classList.contains('active'))
1478
+ addClasses(item_new, 'active');
1479
+ replaceNode(item, item_new);
1480
+ }
1481
+ // invalidate last query because we might have updated the sortField
1482
+ self.lastQuery = null;
1483
+ }
1484
+ /**
1485
+ * Removes a single option.
1486
+ *
1487
+ */
1488
+ removeOption(value, silent) {
1489
+ const self = this;
1490
+ value = get_hash(value);
1491
+ self.uncacheValue(value);
1492
+ delete self.userOptions[value];
1493
+ delete self.options[value];
1494
+ self.lastQuery = null;
1495
+ self.trigger('option_remove', value);
1496
+ self.removeItem(value, silent);
1497
+ }
1498
+ /**
1499
+ * Clears all options.
1500
+ */
1501
+ clearOptions(filter) {
1502
+ const boundFilter = (filter || this.clearFilter).bind(this);
1503
+ this.loadedSearches = {};
1504
+ this.userOptions = {};
1505
+ this.clearCache();
1506
+ const selected = {};
1507
+ iterate(this.options, (option, key) => {
1508
+ if (boundFilter(option, key)) {
1509
+ selected[key] = option;
1510
+ }
1511
+ });
1512
+ this.options = this.sifter.items = selected;
1513
+ this.lastQuery = null;
1514
+ this.trigger('option_clear');
1515
+ }
1516
+ /**
1517
+ * Used by clearOptions() to decide whether or not an option should be removed
1518
+ * Return true to keep an option, false to remove
1519
+ *
1520
+ */
1521
+ clearFilter(option, value) {
1522
+ if (this.items.indexOf(value) >= 0) {
1523
+ return true;
1524
+ }
1525
+ return false;
1526
+ }
1527
+ /**
1528
+ * Returns the dom element of the option
1529
+ * matching the given value.
1530
+ *
1531
+ */
1532
+ getOption(value, create = false) {
1533
+ const hashed = hash_key(value);
1534
+ if (hashed === null)
1535
+ return null;
1536
+ const option = this.options[hashed];
1537
+ if (option != undefined) {
1538
+ if (option.$div) {
1539
+ return option.$div;
1540
+ }
1541
+ if (create) {
1542
+ return this._render('option', option);
1543
+ }
1544
+ }
1545
+ return null;
1546
+ }
1547
+ /**
1548
+ * Returns the dom element of the next or previous dom element of the same type
1549
+ * Note: adjacent options may not be adjacent DOM elements (optgroups)
1550
+ *
1551
+ */
1552
+ getAdjacent(option, direction, type = 'option') {
1553
+ var self = this, all;
1554
+ if (!option) {
1555
+ return null;
1556
+ }
1557
+ if (type == 'item') {
1558
+ all = self.controlChildren();
1559
+ }
1560
+ else {
1561
+ all = self.dropdown_content.querySelectorAll('[data-selectable]');
1562
+ }
1563
+ for (let i = 0; i < all.length; i++) {
1564
+ if (all[i] != option) {
1565
+ continue;
1566
+ }
1567
+ if (direction > 0) {
1568
+ return all[i + 1];
1569
+ }
1570
+ return all[i - 1];
1571
+ }
1572
+ return null;
1573
+ }
1574
+ /**
1575
+ * Returns the dom element of the item
1576
+ * matching the given value.
1577
+ *
1578
+ */
1579
+ getItem(item) {
1580
+ if (typeof item == 'object') {
1581
+ return item;
1582
+ }
1583
+ var value = hash_key(item);
1584
+ return value !== null
1585
+ ? this.control.querySelector(`[data-value="${addSlashes(value)}"]`)
1586
+ : null;
1587
+ }
1588
+ /**
1589
+ * "Selects" multiple items at once. Adds them to the list
1590
+ * at the current caret position.
1591
+ *
1592
+ */
1593
+ addItems(values, silent) {
1594
+ var self = this;
1595
+ var items = Array.isArray(values) ? values : [values];
1596
+ items = items.filter(x => self.items.indexOf(x) === -1);
1597
+ const last_item = items[items.length - 1];
1598
+ items.forEach(item => {
1599
+ self.isPending = (item !== last_item);
1600
+ self.addItem(item, silent);
1601
+ });
1602
+ }
1603
+ /**
1604
+ * "Selects" an item. Adds it to the list
1605
+ * at the current caret position.
1606
+ *
1607
+ */
1608
+ addItem(value, silent) {
1609
+ var events = silent ? [] : ['change', 'dropdown_close'];
1610
+ debounce_events(this, events, () => {
1611
+ var item, wasFull;
1612
+ const self = this;
1613
+ const inputMode = self.settings.mode;
1614
+ const hashed = hash_key(value);
1615
+ if (hashed && self.items.indexOf(hashed) !== -1) {
1616
+ if (inputMode === 'single') {
1617
+ self.close();
1618
+ }
1619
+ if (inputMode === 'single' || !self.settings.duplicates) {
1620
+ return;
1621
+ }
1622
+ }
1623
+ if (hashed === null || !self.options.hasOwnProperty(hashed))
1624
+ return;
1625
+ if (inputMode === 'single')
1626
+ self.clear(silent);
1627
+ if (inputMode === 'multi' && self.isFull())
1628
+ return;
1629
+ item = self._render('item', self.options[hashed]);
1630
+ if (self.control.contains(item)) { // duplicates
1631
+ item = item.cloneNode(true);
1632
+ }
1633
+ wasFull = self.isFull();
1634
+ self.items.splice(self.caretPos, 0, hashed);
1635
+ self.insertAtCaret(item);
1636
+ if (self.isSetup) {
1637
+ // update menu / remove the option (if this is not one item being added as part of series)
1638
+ if (!self.isPending && self.settings.hideSelected) {
1639
+ let option = self.getOption(hashed);
1640
+ let next = self.getAdjacent(option, 1);
1641
+ if (next) {
1642
+ self.setActiveOption(next);
1643
+ }
1644
+ }
1645
+ //remove input value when enabled
1646
+ if (self.settings.clearAfterSelect) {
1647
+ self.setTextboxValue();
1648
+ }
1649
+ // refreshOptions after setActiveOption(),
1650
+ // otherwise setActiveOption() will be called by refreshOptions() with the wrong value
1651
+ if (!self.isPending && !self.settings.closeAfterSelect) {
1652
+ self.refreshOptions(self.isFocused && inputMode !== 'single');
1653
+ }
1654
+ // hide the menu if the maximum number of items have been selected or no options are left
1655
+ if (self.settings.closeAfterSelect != false && self.isFull()) {
1656
+ self.close();
1657
+ }
1658
+ else if (!self.isPending) {
1659
+ self.positionDropdown();
1660
+ }
1661
+ self.trigger('item_add', hashed, item);
1662
+ if (!self.isPending) {
1663
+ self.updateOriginalInput({ silent: silent });
1664
+ }
1665
+ }
1666
+ if (!self.isPending || (!wasFull && self.isFull())) {
1667
+ self.inputState();
1668
+ self.refreshState();
1669
+ }
1670
+ });
1671
+ }
1672
+ /**
1673
+ * Removes the selected item matching
1674
+ * the provided value.
1675
+ *
1676
+ */
1677
+ removeItem(item = null, silent) {
1678
+ const self = this;
1679
+ item = self.getItem(item);
1680
+ if (!item)
1681
+ return;
1682
+ var i, idx;
1683
+ const value = item.dataset.value;
1684
+ i = nodeIndex(item);
1685
+ item.remove();
1686
+ if (item.classList.contains('active')) {
1687
+ idx = self.activeItems.indexOf(item);
1688
+ self.activeItems.splice(idx, 1);
1689
+ removeClasses(item, 'active');
1690
+ }
1691
+ self.items.splice(i, 1);
1692
+ self.lastQuery = null;
1693
+ if (!self.settings.persist && self.userOptions.hasOwnProperty(value)) {
1694
+ self.removeOption(value, silent);
1695
+ }
1696
+ if (i < self.caretPos) {
1697
+ self.setCaret(self.caretPos - 1);
1698
+ }
1699
+ self.updateOriginalInput({ silent: silent });
1700
+ self.refreshState();
1701
+ self.positionDropdown();
1702
+ self.trigger('item_remove', value, item);
1703
+ }
1704
+ /**
1705
+ * Invokes the `create` method provided in the
1706
+ * TomSelect options that should provide the data
1707
+ * for the new item, given the user input.
1708
+ *
1709
+ * Once this completes, it will be added
1710
+ * to the item list.
1711
+ *
1712
+ */
1713
+ createItem(input = null, callback = () => { }) {
1714
+ // triggerDropdown parameter @deprecated 2.1.1
1715
+ if (arguments.length === 3) {
1716
+ callback = arguments[2];
1717
+ }
1718
+ if (typeof callback != 'function') {
1719
+ callback = () => { };
1720
+ }
1721
+ var self = this;
1722
+ var caret = self.caretPos;
1723
+ var output;
1724
+ input = input || self.inputValue();
1725
+ if (!self.canCreate(input)) {
1726
+ const hash = hash_key(input);
1727
+ if (hash) {
1728
+ if (this.options[input]) {
1729
+ self.addItem(input);
1730
+ }
1731
+ }
1732
+ callback();
1733
+ return false;
1734
+ }
1735
+ self.lock();
1736
+ var created = false;
1737
+ var create = (data) => {
1738
+ self.unlock();
1739
+ if (!data || typeof data !== 'object')
1740
+ return callback();
1741
+ var value = hash_key(data[self.settings.valueField]);
1742
+ if (typeof value !== 'string') {
1743
+ return callback();
1744
+ }
1745
+ self.setTextboxValue();
1746
+ self.addOption(data, true);
1747
+ self.setCaret(caret);
1748
+ self.addItem(value);
1749
+ callback(data);
1750
+ created = true;
1751
+ };
1752
+ if (typeof self.settings.create === 'function') {
1753
+ output = self.settings.create.call(this, input, create);
1754
+ }
1755
+ else {
1756
+ output = {
1757
+ [self.settings.labelField]: input,
1758
+ [self.settings.valueField]: input,
1759
+ };
1760
+ }
1761
+ if (!created) {
1762
+ create(output);
1763
+ }
1764
+ return true;
1765
+ }
1766
+ /**
1767
+ * Re-renders the selected item lists.
1768
+ */
1769
+ refreshItems() {
1770
+ var self = this;
1771
+ self.lastQuery = null;
1772
+ if (self.isSetup) {
1773
+ self.addItems(self.items);
1774
+ }
1775
+ self.updateOriginalInput();
1776
+ self.refreshState();
1777
+ }
1778
+ /**
1779
+ * Updates all state-dependent attributes
1780
+ * and CSS classes.
1781
+ */
1782
+ refreshState() {
1783
+ const self = this;
1784
+ self.refreshValidityState();
1785
+ const isFull = self.isFull();
1786
+ const isLocked = self.isLocked;
1787
+ self.wrapper.classList.toggle('rtl', self.rtl);
1788
+ const wrap_classList = self.wrapper.classList;
1789
+ wrap_classList.toggle('focus', self.isFocused);
1790
+ wrap_classList.toggle('disabled', self.isDisabled);
1791
+ wrap_classList.toggle('readonly', self.isReadOnly);
1792
+ wrap_classList.toggle('required', self.isRequired);
1793
+ wrap_classList.toggle('invalid', !self.isValid);
1794
+ wrap_classList.toggle('locked', isLocked);
1795
+ wrap_classList.toggle('full', isFull);
1796
+ wrap_classList.toggle('input-active', self.isFocused && !self.isInputHidden);
1797
+ wrap_classList.toggle('dropdown-active', self.isOpen);
1798
+ wrap_classList.toggle('has-options', isEmptyObject(self.options));
1799
+ wrap_classList.toggle('has-items', self.items.length > 0);
1800
+ }
1801
+ /**
1802
+ * Update the `required` attribute of both input and control input.
1803
+ *
1804
+ * The `required` property needs to be activated on the control input
1805
+ * for the error to be displayed at the right place. `required` also
1806
+ * needs to be temporarily deactivated on the input since the input is
1807
+ * hidden and can't show errors.
1808
+ */
1809
+ refreshValidityState() {
1810
+ var self = this;
1811
+ if (!self.input.validity) {
1812
+ return;
1813
+ }
1814
+ self.isValid = self.input.validity.valid;
1815
+ self.isInvalid = !self.isValid;
1816
+ }
1817
+ /**
1818
+ * Determines whether or not more items can be added
1819
+ * to the control without exceeding the user-defined maximum.
1820
+ *
1821
+ * @returns {boolean}
1822
+ */
1823
+ isFull() {
1824
+ return this.settings.maxItems !== null && this.items.length >= this.settings.maxItems;
1825
+ }
1826
+ /**
1827
+ * Refreshes the original <select> or <input>
1828
+ * element to reflect the current state.
1829
+ *
1830
+ */
1831
+ updateOriginalInput(opts = {}) {
1832
+ const self = this;
1833
+ var option, label;
1834
+ const empty_option = self.input.querySelector('option[value=""]');
1835
+ if (self.is_select_tag) {
1836
+ const selected = [];
1837
+ const has_selected = self.input.querySelectorAll('option:checked').length;
1838
+ function AddSelected(option_el, value, label) {
1839
+ if (!option_el) {
1840
+ option_el = getDom('<option value="' + escape_html(value) + '">' + escape_html(label) + '</option>');
1841
+ }
1842
+ // don't move empty option from top of list
1843
+ // fixes bug in firefox https://bugzilla.mozilla.org/show_bug.cgi?id=1725293
1844
+ if (option_el != empty_option) {
1845
+ self.input.append(option_el);
1846
+ }
1847
+ selected.push(option_el);
1848
+ // marking empty option as selected can break validation
1849
+ // fixes https://github.com/orchidjs/tom-select/issues/303
1850
+ if (option_el != empty_option || has_selected > 0) {
1851
+ option_el.selected = true;
1852
+ }
1853
+ return option_el;
1854
+ }
1855
+ // unselect all selected options
1856
+ self.input.querySelectorAll('option:checked').forEach((option_el) => {
1857
+ option_el.selected = false;
1858
+ });
1859
+ // nothing selected?
1860
+ if (self.items.length == 0 && self.settings.mode == 'single') {
1861
+ AddSelected(empty_option, "", "");
1862
+ // order selected <option> tags for values in self.items
1863
+ }
1864
+ else {
1865
+ self.items.forEach((value) => {
1866
+ option = self.options[value];
1867
+ label = option[self.settings.labelField] || '';
1868
+ if (selected.includes(option.$option)) {
1869
+ const reuse_opt = self.input.querySelector(`option[value="${addSlashes(value)}"]:not(:checked)`);
1870
+ AddSelected(reuse_opt, value, label);
1871
+ }
1872
+ else {
1873
+ option.$option = AddSelected(option.$option, value, label);
1874
+ }
1875
+ });
1876
+ }
1877
+ }
1878
+ else {
1879
+ self.input.value = self.getValue();
1880
+ }
1881
+ if (self.isSetup) {
1882
+ if (!opts.silent) {
1883
+ self.trigger('change', self.getValue());
1884
+ }
1885
+ }
1886
+ }
1887
+ /**
1888
+ * Shows the autocomplete dropdown containing
1889
+ * the available options.
1890
+ */
1891
+ open() {
1892
+ var self = this;
1893
+ if (self.isLocked || self.isOpen || (self.settings.mode === 'multi' && self.isFull()))
1894
+ return;
1895
+ self.isOpen = true;
1896
+ setAttr(self.focus_node, { 'aria-expanded': 'true' });
1897
+ self.refreshState();
1898
+ applyCSS(self.dropdown, { visibility: 'hidden', display: 'block' });
1899
+ self.positionDropdown();
1900
+ applyCSS(self.dropdown, { visibility: 'visible', display: 'block' });
1901
+ self.focus();
1902
+ self.trigger('dropdown_open', self.dropdown);
1903
+ }
1904
+ /**
1905
+ * Closes the autocomplete dropdown menu.
1906
+ */
1907
+ close(setTextboxValue = true) {
1908
+ var self = this;
1909
+ var trigger = self.isOpen;
1910
+ if (setTextboxValue) {
1911
+ // before blur() to prevent form onchange event
1912
+ self.setTextboxValue();
1913
+ if (self.settings.mode === 'single' && self.items.length) {
1914
+ self.inputState();
1915
+ }
1916
+ }
1917
+ self.isOpen = false;
1918
+ setAttr(self.focus_node, { 'aria-expanded': 'false' });
1919
+ applyCSS(self.dropdown, { display: 'none' });
1920
+ if (self.settings.hideSelected) {
1921
+ self.clearActiveOption();
1922
+ }
1923
+ self.refreshState();
1924
+ if (trigger)
1925
+ self.trigger('dropdown_close', self.dropdown);
1926
+ }
1927
+ /**
1928
+ * Calculates and applies the appropriate
1929
+ * position of the dropdown if dropdownParent = 'body'.
1930
+ * Otherwise, position is determined by css
1931
+ */
1932
+ positionDropdown() {
1933
+ if (this.settings.dropdownParent !== 'body') {
1934
+ return;
1935
+ }
1936
+ var context = this.control;
1937
+ var rect = context.getBoundingClientRect();
1938
+ var top = context.offsetHeight + rect.top + window.scrollY;
1939
+ var left = rect.left + window.scrollX;
1940
+ applyCSS(this.dropdown, {
1941
+ width: rect.width + 'px',
1942
+ top: top + 'px',
1943
+ left: left + 'px'
1944
+ });
1945
+ }
1946
+ /**
1947
+ * Resets / clears all selected items
1948
+ * from the control.
1949
+ *
1950
+ */
1951
+ clear(silent) {
1952
+ var self = this;
1953
+ if (!self.items.length)
1954
+ return;
1955
+ var items = self.controlChildren();
1956
+ iterate(items, (item) => {
1957
+ self.removeItem(item, true);
1958
+ });
1959
+ self.inputState();
1960
+ if (!silent)
1961
+ self.updateOriginalInput();
1962
+ self.trigger('clear');
1963
+ }
1964
+ /**
1965
+ * A helper method for inserting an element
1966
+ * at the current caret position.
1967
+ *
1968
+ */
1969
+ insertAtCaret(el) {
1970
+ const self = this;
1971
+ const caret = self.caretPos;
1972
+ const target = self.control;
1973
+ target.insertBefore(el, target.children[caret] || null);
1974
+ self.setCaret(caret + 1);
1975
+ }
1976
+ /**
1977
+ * Removes the current selected item(s).
1978
+ *
1979
+ */
1980
+ deleteSelection(e) {
1981
+ var direction, selection, caret, tail;
1982
+ var self = this;
1983
+ direction = (e && e.keyCode === constants.KEY_BACKSPACE) ? -1 : 1;
1984
+ selection = getSelection(self.control_input);
1985
+ // determine items that will be removed
1986
+ const rm_items = [];
1987
+ if (self.activeItems.length) {
1988
+ tail = getTail(self.activeItems, direction);
1989
+ caret = nodeIndex(tail);
1990
+ if (direction > 0) {
1991
+ caret++;
1992
+ }
1993
+ iterate(self.activeItems, (item) => rm_items.push(item));
1994
+ }
1995
+ else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) {
1996
+ const items = self.controlChildren();
1997
+ let rm_item;
1998
+ if (direction < 0 && selection.start === 0 && selection.length === 0) {
1999
+ rm_item = items[self.caretPos - 1];
2000
+ }
2001
+ else if (direction > 0 && selection.start === self.inputValue().length) {
2002
+ rm_item = items[self.caretPos];
2003
+ }
2004
+ if (rm_item !== undefined) {
2005
+ rm_items.push(rm_item);
2006
+ }
2007
+ }
2008
+ if (!self.shouldDelete(rm_items, e)) {
2009
+ return false;
2010
+ }
2011
+ preventDefault(e, true);
2012
+ // perform removal
2013
+ if (typeof caret !== 'undefined') {
2014
+ self.setCaret(caret);
2015
+ }
2016
+ while (rm_items.length) {
2017
+ self.removeItem(rm_items.pop());
2018
+ }
2019
+ self.inputState();
2020
+ self.positionDropdown();
2021
+ self.refreshOptions(false);
2022
+ return true;
2023
+ }
2024
+ /**
2025
+ * Return true if the items should be deleted
2026
+ */
2027
+ shouldDelete(items, evt) {
2028
+ const values = items.map(item => item.dataset.value);
2029
+ // allow the callback to abort
2030
+ if (!values.length || (typeof this.settings.onDelete === 'function' && this.settings.onDelete.call(this, values, evt) === false)) {
2031
+ return false;
2032
+ }
2033
+ return true;
2034
+ }
2035
+ /**
2036
+ * Selects the previous / next item (depending on the `direction` argument).
2037
+ *
2038
+ * > 0 - right
2039
+ * < 0 - left
2040
+ *
2041
+ */
2042
+ advanceSelection(direction, e) {
2043
+ var last_active, adjacent, self = this;
2044
+ if (self.rtl)
2045
+ direction *= -1;
2046
+ if (self.inputValue().length)
2047
+ return;
2048
+ // add or remove to active items
2049
+ if (isKeyDown(constants.KEY_SHORTCUT, e) || isKeyDown('shiftKey', e)) {
2050
+ last_active = self.getLastActive(direction);
2051
+ if (last_active) {
2052
+ if (!last_active.classList.contains('active')) {
2053
+ adjacent = last_active;
2054
+ }
2055
+ else {
2056
+ adjacent = self.getAdjacent(last_active, direction, 'item');
2057
+ }
2058
+ // if no active item, get items adjacent to the control input
2059
+ }
2060
+ else if (direction > 0) {
2061
+ adjacent = self.control_input.nextElementSibling;
2062
+ }
2063
+ else {
2064
+ adjacent = self.control_input.previousElementSibling;
2065
+ }
2066
+ if (adjacent) {
2067
+ if (adjacent.classList.contains('active')) {
2068
+ self.removeActiveItem(last_active);
2069
+ }
2070
+ self.setActiveItemClass(adjacent); // mark as last_active !! after removeActiveItem() on last_active
2071
+ }
2072
+ // move caret to the left or right
2073
+ }
2074
+ else {
2075
+ self.moveCaret(direction);
2076
+ }
2077
+ }
2078
+ moveCaret(direction) { }
2079
+ /**
2080
+ * Get the last active item
2081
+ *
2082
+ */
2083
+ getLastActive(direction) {
2084
+ let last_active = this.control.querySelector('.last-active');
2085
+ if (last_active) {
2086
+ return last_active;
2087
+ }
2088
+ var result = this.control.querySelectorAll('.active');
2089
+ if (result) {
2090
+ return getTail(result, direction);
2091
+ }
2092
+ }
2093
+ /**
2094
+ * Moves the caret to the specified index.
2095
+ *
2096
+ * The input must be moved by leaving it in place and moving the
2097
+ * siblings, due to the fact that focus cannot be restored once lost
2098
+ * on mobile webkit devices
2099
+ *
2100
+ */
2101
+ setCaret(new_pos) {
2102
+ this.caretPos = this.items.length;
2103
+ }
2104
+ /**
2105
+ * Return list of item dom elements
2106
+ *
2107
+ */
2108
+ controlChildren() {
2109
+ return Array.from(this.control.querySelectorAll('[data-ts-item]'));
2110
+ }
2111
+ /**
2112
+ * Disables user input on the control. Used while
2113
+ * items are being asynchronously created.
2114
+ */
2115
+ lock() {
2116
+ this.setLocked(true);
2117
+ }
2118
+ /**
2119
+ * Re-enables user input on the control.
2120
+ */
2121
+ unlock() {
2122
+ this.setLocked(false);
2123
+ }
2124
+ /**
2125
+ * Disable or enable user input on the control
2126
+ */
2127
+ setLocked(lock = this.isReadOnly || this.isDisabled) {
2128
+ this.isLocked = lock;
2129
+ this.refreshState();
2130
+ }
2131
+ /**
2132
+ * Disables user input on the control completely.
2133
+ * While disabled, it cannot receive focus.
2134
+ */
2135
+ disable() {
2136
+ this.setDisabled(true);
2137
+ this.close();
2138
+ }
2139
+ /**
2140
+ * Enables the control so that it can respond
2141
+ * to focus and user input.
2142
+ */
2143
+ enable() {
2144
+ this.setDisabled(false);
2145
+ }
2146
+ setDisabled(disabled) {
2147
+ this.focus_node.tabIndex = disabled ? -1 : this.tabIndex;
2148
+ this.isDisabled = disabled;
2149
+ this.input.disabled = disabled;
2150
+ this.control_input.disabled = disabled;
2151
+ this.setLocked();
2152
+ }
2153
+ setReadOnly(isReadOnly) {
2154
+ this.isReadOnly = isReadOnly;
2155
+ this.input.readOnly = isReadOnly;
2156
+ this.control_input.readOnly = isReadOnly;
2157
+ this.setLocked();
2158
+ }
2159
+ /**
2160
+ * Completely destroys the control and
2161
+ * unbinds all event listeners so that it can
2162
+ * be garbage collected.
2163
+ */
2164
+ destroy() {
2165
+ var self = this;
2166
+ var revertSettings = self.revertSettings;
2167
+ self.trigger('destroy');
2168
+ self.off();
2169
+ self.wrapper.remove();
2170
+ self.dropdown.remove();
2171
+ self.input.innerHTML = revertSettings.innerHTML;
2172
+ self.input.tabIndex = revertSettings.tabIndex;
2173
+ removeClasses(self.input, 'tomselected', 'ts-hidden-accessible');
2174
+ self._destroy();
2175
+ delete self.input.tomselect;
2176
+ }
2177
+ /**
2178
+ * A helper method for rendering "item" and
2179
+ * "option" templates, given the data.
2180
+ *
2181
+ */
2182
+ render(templateName, data) {
2183
+ var id, html;
2184
+ const self = this;
2185
+ if (typeof this.settings.render[templateName] !== 'function') {
2186
+ return null;
2187
+ }
2188
+ // render markup
2189
+ html = self.settings.render[templateName].call(this, data, escape_html);
2190
+ if (!html) {
2191
+ return null;
2192
+ }
2193
+ html = getDom(html);
2194
+ // add mandatory attributes
2195
+ if (templateName === 'option' || templateName === 'option_create') {
2196
+ if (data[self.settings.disabledField]) {
2197
+ setAttr(html, { 'aria-disabled': 'true' });
2198
+ }
2199
+ else {
2200
+ setAttr(html, { 'data-selectable': '' });
2201
+ }
2202
+ }
2203
+ else if (templateName === 'optgroup') {
2204
+ id = data.group[self.settings.optgroupValueField];
2205
+ setAttr(html, { 'data-group': id });
2206
+ if (data.group[self.settings.disabledField]) {
2207
+ setAttr(html, { 'data-disabled': '' });
2208
+ }
2209
+ }
2210
+ if (templateName === 'option' || templateName === 'item') {
2211
+ const value = get_hash(data[self.settings.valueField]);
2212
+ setAttr(html, { 'data-value': value });
2213
+ // make sure we have some classes if a template is overwritten
2214
+ if (templateName === 'item') {
2215
+ addClasses(html, self.settings.itemClass);
2216
+ setAttr(html, { 'data-ts-item': '' });
2217
+ }
2218
+ else {
2219
+ addClasses(html, self.settings.optionClass);
2220
+ setAttr(html, {
2221
+ role: 'option',
2222
+ id: data.$id
2223
+ });
2224
+ // update cache
2225
+ data.$div = html;
2226
+ self.options[value] = data;
2227
+ }
2228
+ }
2229
+ return html;
2230
+ }
2231
+ /**
2232
+ * Type guarded rendering
2233
+ *
2234
+ */
2235
+ _render(templateName, data) {
2236
+ const html = this.render(templateName, data);
2237
+ if (html == null) {
2238
+ throw 'HTMLElement expected';
2239
+ }
2240
+ return html;
2241
+ }
2242
+ /**
2243
+ * Clears the render cache for a template. If
2244
+ * no template is given, clears all render
2245
+ * caches.
2246
+ *
2247
+ */
2248
+ clearCache() {
2249
+ iterate(this.options, (option) => {
2250
+ if (option.$div) {
2251
+ option.$div.remove();
2252
+ delete option.$div;
2253
+ }
2254
+ });
2255
+ }
2256
+ /**
2257
+ * Removes a value from item and option caches
2258
+ *
2259
+ */
2260
+ uncacheValue(value) {
2261
+ const option_el = this.getOption(value);
2262
+ if (option_el)
2263
+ option_el.remove();
2264
+ }
2265
+ /**
2266
+ * Determines whether or not to display the
2267
+ * create item prompt, given a user input.
2268
+ *
2269
+ */
2270
+ canCreate(input) {
2271
+ return this.settings.create && (input.length > 0) && this.settings.createFilter.call(this, input);
2272
+ }
2273
+ /**
2274
+ * Wraps this.`method` so that `new_fn` can be invoked 'before', 'after', or 'instead' of the original method
2275
+ *
2276
+ * this.hook('instead','onKeyDown',function( arg1, arg2 ...){
2277
+ *
2278
+ * });
2279
+ */
2280
+ hook(when, method, new_fn) {
2281
+ var self = this;
2282
+ var orig_method = self[method];
2283
+ self[method] = function () {
2284
+ var result, result_new;
2285
+ if (when === 'after') {
2286
+ result = orig_method.apply(self, arguments);
2287
+ }
2288
+ result_new = new_fn.apply(self, arguments);
2289
+ if (when === 'instead') {
2290
+ return result_new;
2291
+ }
2292
+ if (when === 'before') {
2293
+ result = orig_method.apply(self, arguments);
2294
+ }
2295
+ return result;
2296
+ };
2297
+ }
2298
+ }
2299
+ ;
2300
+ //# sourceMappingURL=tom-select.js.map