govuk_publishing_components 58.1.0 → 58.2.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 (148) hide show
  1. checksums.yaml +4 -4
  2. data/app/assets/images/select-with-search/cross-icon.svg +6 -0
  3. data/app/assets/javascripts/govuk_publishing_components/analytics-ga4/ga4-search-tracker.js +4 -0
  4. data/app/assets/javascripts/govuk_publishing_components/components/select-with-search.js +57 -0
  5. data/app/assets/stylesheets/govuk_publishing_components/_all_components.scss +1 -0
  6. data/app/assets/stylesheets/govuk_publishing_components/components/_layout-super-navigation-header.scss +7 -2
  7. data/app/assets/stylesheets/govuk_publishing_components/components/_select-with-search.scss +168 -0
  8. data/app/assets/stylesheets/govuk_publishing_components/components/_select.scss +6 -0
  9. data/app/assets/stylesheets/govuk_publishing_components/components/govspeak/_contact.scss +10 -10
  10. data/app/assets/stylesheets/govuk_publishing_components/components/govspeak/_typography.scss +3 -16
  11. data/app/views/govuk_publishing_components/components/_add_another.html.erb +0 -1
  12. data/app/views/govuk_publishing_components/components/_layout_super_navigation_header.html.erb +1 -1
  13. data/app/views/govuk_publishing_components/components/_select.html.erb +22 -23
  14. data/app/views/govuk_publishing_components/components/_select_with_search.html.erb +14 -0
  15. data/app/views/govuk_publishing_components/components/docs/select.yml +11 -0
  16. data/app/views/govuk_publishing_components/components/docs/select_with_search.yml +196 -0
  17. data/lib/govuk_publishing_components/presenters/select_helper.rb +8 -5
  18. data/lib/govuk_publishing_components/presenters/select_with_search_helper.rb +92 -0
  19. data/lib/govuk_publishing_components/version.rb +1 -1
  20. data/lib/govuk_publishing_components.rb +1 -0
  21. data/node_modules/choices.js/LICENSE +21 -0
  22. data/node_modules/choices.js/README.md +1360 -0
  23. data/node_modules/choices.js/package.json +173 -0
  24. data/node_modules/choices.js/public/assets/scripts/choices.js +5230 -0
  25. data/node_modules/choices.js/public/assets/scripts/choices.min.js +2 -0
  26. data/node_modules/choices.js/public/assets/scripts/choices.mjs +5222 -0
  27. data/node_modules/choices.js/public/assets/scripts/choices.search-basic.js +4748 -0
  28. data/node_modules/choices.js/public/assets/scripts/choices.search-basic.min.js +2 -0
  29. data/node_modules/choices.js/public/assets/scripts/choices.search-basic.mjs +4740 -0
  30. data/node_modules/choices.js/public/assets/scripts/choices.search-kmp.js +3631 -0
  31. data/node_modules/choices.js/public/assets/scripts/choices.search-kmp.min.js +2 -0
  32. data/node_modules/choices.js/public/assets/scripts/choices.search-kmp.mjs +3623 -0
  33. data/node_modules/choices.js/public/assets/scripts/choices.search-prefix.js +3590 -0
  34. data/node_modules/choices.js/public/assets/scripts/choices.search-prefix.min.js +2 -0
  35. data/node_modules/choices.js/public/assets/scripts/choices.search-prefix.mjs +3582 -0
  36. data/node_modules/choices.js/public/assets/styles/base.css +180 -0
  37. data/node_modules/choices.js/public/assets/styles/base.css.map +1 -0
  38. data/node_modules/choices.js/public/assets/styles/base.min.css +1 -0
  39. data/node_modules/choices.js/public/assets/styles/choices.css +338 -0
  40. data/node_modules/choices.js/public/assets/styles/choices.css.map +1 -0
  41. data/node_modules/choices.js/public/assets/styles/choices.min.css +1 -0
  42. data/node_modules/choices.js/public/types/src/index.d.ts +6 -0
  43. data/node_modules/choices.js/public/types/src/scripts/actions/choices.d.ts +30 -0
  44. data/node_modules/choices.js/public/types/src/scripts/actions/groups.d.ts +8 -0
  45. data/node_modules/choices.js/public/types/src/scripts/actions/items.d.ts +17 -0
  46. data/node_modules/choices.js/public/types/src/scripts/choices.d.ts +210 -0
  47. data/node_modules/choices.js/public/types/src/scripts/components/container.d.ts +36 -0
  48. data/node_modules/choices.js/public/types/src/scripts/components/dropdown.d.ts +21 -0
  49. data/node_modules/choices.js/public/types/src/scripts/components/index.d.ts +7 -0
  50. data/node_modules/choices.js/public/types/src/scripts/components/input.d.ts +37 -0
  51. data/node_modules/choices.js/public/types/src/scripts/components/list.d.ts +14 -0
  52. data/node_modules/choices.js/public/types/src/scripts/components/wrapped-element.d.ts +21 -0
  53. data/node_modules/choices.js/public/types/src/scripts/components/wrapped-input.d.ts +3 -0
  54. data/node_modules/choices.js/public/types/src/scripts/components/wrapped-select.d.ts +20 -0
  55. data/node_modules/choices.js/public/types/src/scripts/constants.d.ts +1 -0
  56. data/node_modules/choices.js/public/types/src/scripts/defaults.d.ts +4 -0
  57. data/node_modules/choices.js/public/types/src/scripts/interfaces/action-type.d.ts +13 -0
  58. data/node_modules/choices.js/public/types/src/scripts/interfaces/build-flags.d.ts +11 -0
  59. data/node_modules/choices.js/public/types/src/scripts/interfaces/choice-full.d.ts +23 -0
  60. data/node_modules/choices.js/public/types/src/scripts/interfaces/class-names.d.ts +61 -0
  61. data/node_modules/choices.js/public/types/src/scripts/interfaces/event-choice.d.ts +7 -0
  62. data/node_modules/choices.js/public/types/src/scripts/interfaces/event-type.d.ts +14 -0
  63. data/node_modules/choices.js/public/types/src/scripts/interfaces/group-full.d.ts +10 -0
  64. data/node_modules/choices.js/public/types/src/scripts/interfaces/index.d.ts +14 -0
  65. data/node_modules/choices.js/public/types/src/scripts/interfaces/input-choice.d.ts +15 -0
  66. data/node_modules/choices.js/public/types/src/scripts/interfaces/input-group.d.ts +10 -0
  67. data/node_modules/choices.js/public/types/src/scripts/interfaces/item.d.ts +17 -0
  68. data/node_modules/choices.js/public/types/src/scripts/interfaces/keycode-map.d.ts +13 -0
  69. data/node_modules/choices.js/public/types/src/scripts/interfaces/options.d.ts +566 -0
  70. data/node_modules/choices.js/public/types/src/scripts/interfaces/passed-element-type.d.ts +7 -0
  71. data/node_modules/choices.js/public/types/src/scripts/interfaces/passed-element.d.ts +95 -0
  72. data/node_modules/choices.js/public/types/src/scripts/interfaces/position-options-type.d.ts +1 -0
  73. data/node_modules/choices.js/public/types/src/scripts/interfaces/search.d.ts +11 -0
  74. data/node_modules/choices.js/public/types/src/scripts/interfaces/state.d.ts +10 -0
  75. data/node_modules/choices.js/public/types/src/scripts/interfaces/store.d.ts +64 -0
  76. data/node_modules/choices.js/public/types/src/scripts/interfaces/string-pre-escaped.d.ts +3 -0
  77. data/node_modules/choices.js/public/types/src/scripts/interfaces/string-untrusted.d.ts +4 -0
  78. data/node_modules/choices.js/public/types/src/scripts/interfaces/templates.d.ts +29 -0
  79. data/node_modules/choices.js/public/types/src/scripts/interfaces/types.d.ts +18 -0
  80. data/node_modules/choices.js/public/types/src/scripts/lib/choice-input.d.ts +9 -0
  81. data/node_modules/choices.js/public/types/src/scripts/lib/html-guard-statements.d.ts +4 -0
  82. data/node_modules/choices.js/public/types/src/scripts/lib/utils.d.ts +31 -0
  83. data/node_modules/choices.js/public/types/src/scripts/reducers/choices.d.ts +8 -0
  84. data/node_modules/choices.js/public/types/src/scripts/reducers/groups.d.ts +8 -0
  85. data/node_modules/choices.js/public/types/src/scripts/reducers/items.d.ts +9 -0
  86. data/node_modules/choices.js/public/types/src/scripts/search/fuse.d.ts +14 -0
  87. data/node_modules/choices.js/public/types/src/scripts/search/index.d.ts +3 -0
  88. data/node_modules/choices.js/public/types/src/scripts/search/kmp.d.ts +11 -0
  89. data/node_modules/choices.js/public/types/src/scripts/search/prefix-filter.d.ts +11 -0
  90. data/node_modules/choices.js/public/types/src/scripts/store/store.d.ts +59 -0
  91. data/node_modules/choices.js/public/types/src/scripts/templates.d.ts +8 -0
  92. data/node_modules/choices.js/src/entry.js +3 -0
  93. data/node_modules/choices.js/src/icons/cross-inverse.svg +1 -0
  94. data/node_modules/choices.js/src/icons/cross.svg +1 -0
  95. data/node_modules/choices.js/src/index.ts +8 -0
  96. data/node_modules/choices.js/src/scripts/actions/choices.ts +59 -0
  97. data/node_modules/choices.js/src/scripts/actions/groups.ts +14 -0
  98. data/node_modules/choices.js/src/scripts/actions/items.ts +34 -0
  99. data/node_modules/choices.js/src/scripts/choices.ts +2364 -0
  100. data/node_modules/choices.js/src/scripts/components/container.ts +157 -0
  101. data/node_modules/choices.js/src/scripts/components/dropdown.ts +50 -0
  102. data/node_modules/choices.js/src/scripts/components/index.ts +8 -0
  103. data/node_modules/choices.js/src/scripts/components/input.ts +146 -0
  104. data/node_modules/choices.js/src/scripts/components/list.ts +89 -0
  105. data/node_modules/choices.js/src/scripts/components/wrapped-element.ts +89 -0
  106. data/node_modules/choices.js/src/scripts/components/wrapped-input.ts +3 -0
  107. data/node_modules/choices.js/src/scripts/components/wrapped-select.ts +115 -0
  108. data/node_modules/choices.js/src/scripts/constants.ts +1 -0
  109. data/node_modules/choices.js/src/scripts/defaults.ts +93 -0
  110. data/node_modules/choices.js/src/scripts/interfaces/action-type.ts +15 -0
  111. data/node_modules/choices.js/src/scripts/interfaces/build-flags.ts +17 -0
  112. data/node_modules/choices.js/src/scripts/interfaces/choice-full.ts +30 -0
  113. data/node_modules/choices.js/src/scripts/interfaces/class-names.ts +61 -0
  114. data/node_modules/choices.js/src/scripts/interfaces/event-choice.ts +9 -0
  115. data/node_modules/choices.js/src/scripts/interfaces/event-type.ts +16 -0
  116. data/node_modules/choices.js/src/scripts/interfaces/group-full.ts +12 -0
  117. data/node_modules/choices.js/src/scripts/interfaces/index.ts +14 -0
  118. data/node_modules/choices.js/src/scripts/interfaces/input-choice.ts +17 -0
  119. data/node_modules/choices.js/src/scripts/interfaces/input-group.ts +11 -0
  120. data/node_modules/choices.js/src/scripts/interfaces/item.ts +17 -0
  121. data/node_modules/choices.js/src/scripts/interfaces/keycode-map.ts +13 -0
  122. data/node_modules/choices.js/src/scripts/interfaces/options.ts +619 -0
  123. data/node_modules/choices.js/src/scripts/interfaces/passed-element-type.ts +9 -0
  124. data/node_modules/choices.js/src/scripts/interfaces/passed-element.ts +96 -0
  125. data/node_modules/choices.js/src/scripts/interfaces/position-options-type.ts +1 -0
  126. data/node_modules/choices.js/src/scripts/interfaces/search.ts +12 -0
  127. data/node_modules/choices.js/src/scripts/interfaces/state.ts +12 -0
  128. data/node_modules/choices.js/src/scripts/interfaces/store.ts +84 -0
  129. data/node_modules/choices.js/src/scripts/interfaces/string-pre-escaped.ts +3 -0
  130. data/node_modules/choices.js/src/scripts/interfaces/string-untrusted.ts +5 -0
  131. data/node_modules/choices.js/src/scripts/interfaces/templates.ts +66 -0
  132. data/node_modules/choices.js/src/scripts/interfaces/types.ts +21 -0
  133. data/node_modules/choices.js/src/scripts/lib/choice-input.ts +88 -0
  134. data/node_modules/choices.js/src/scripts/lib/html-guard-statements.ts +7 -0
  135. data/node_modules/choices.js/src/scripts/lib/utils.ts +230 -0
  136. data/node_modules/choices.js/src/scripts/reducers/choices.ts +86 -0
  137. data/node_modules/choices.js/src/scripts/reducers/groups.ts +32 -0
  138. data/node_modules/choices.js/src/scripts/reducers/items.ts +86 -0
  139. data/node_modules/choices.js/src/scripts/search/fuse.ts +59 -0
  140. data/node_modules/choices.js/src/scripts/search/index.ts +17 -0
  141. data/node_modules/choices.js/src/scripts/search/kmp.ts +87 -0
  142. data/node_modules/choices.js/src/scripts/search/prefix-filter.ts +42 -0
  143. data/node_modules/choices.js/src/scripts/store/store.ts +184 -0
  144. data/node_modules/choices.js/src/scripts/templates.ts +409 -0
  145. data/node_modules/choices.js/src/styles/base.scss +189 -0
  146. data/node_modules/choices.js/src/styles/choices.scss +414 -0
  147. data/node_modules/choices.js/src/tsconfig.json +22 -0
  148. metadata +134 -1
@@ -0,0 +1,3631 @@
1
+ /*! choices.js v11.1.0 | © 2025 Josh Johnson | https://github.com/jshjohnson/Choices#readme */
2
+
3
+ (function (global, factory) {
4
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
5
+ typeof define === 'function' && define.amd ? define(factory) :
6
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Choices = factory());
7
+ })(this, (function () { 'use strict';
8
+
9
+ /******************************************************************************
10
+ Copyright (c) Microsoft Corporation.
11
+
12
+ Permission to use, copy, modify, and/or distribute this software for any
13
+ purpose with or without fee is hereby granted.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
16
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
17
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
18
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
19
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
20
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21
+ PERFORMANCE OF THIS SOFTWARE.
22
+ ***************************************************************************** */
23
+ /* global Reflect, Promise, SuppressedError, Symbol */
24
+
25
+ var extendStatics = function (d, b) {
26
+ extendStatics = Object.setPrototypeOf || {
27
+ __proto__: []
28
+ } instanceof Array && function (d, b) {
29
+ d.__proto__ = b;
30
+ } || function (d, b) {
31
+ for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
32
+ };
33
+ return extendStatics(d, b);
34
+ };
35
+ function __extends(d, b) {
36
+ if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
37
+ extendStatics(d, b);
38
+ function __() {
39
+ this.constructor = d;
40
+ }
41
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42
+ }
43
+ var __assign = function () {
44
+ __assign = Object.assign || function __assign(t) {
45
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
46
+ s = arguments[i];
47
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
48
+ }
49
+ return t;
50
+ };
51
+ return __assign.apply(this, arguments);
52
+ };
53
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
54
+ var e = new Error(message);
55
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
56
+ };
57
+
58
+ var ActionType = {
59
+ ADD_CHOICE: 'ADD_CHOICE',
60
+ REMOVE_CHOICE: 'REMOVE_CHOICE',
61
+ FILTER_CHOICES: 'FILTER_CHOICES',
62
+ ACTIVATE_CHOICES: 'ACTIVATE_CHOICES',
63
+ CLEAR_CHOICES: 'CLEAR_CHOICES',
64
+ ADD_GROUP: 'ADD_GROUP',
65
+ ADD_ITEM: 'ADD_ITEM',
66
+ REMOVE_ITEM: 'REMOVE_ITEM',
67
+ HIGHLIGHT_ITEM: 'HIGHLIGHT_ITEM',
68
+ };
69
+
70
+ var EventType = {
71
+ showDropdown: 'showDropdown',
72
+ hideDropdown: 'hideDropdown',
73
+ change: 'change',
74
+ choice: 'choice',
75
+ search: 'search',
76
+ addItem: 'addItem',
77
+ removeItem: 'removeItem',
78
+ highlightItem: 'highlightItem',
79
+ highlightChoice: 'highlightChoice',
80
+ unhighlightItem: 'unhighlightItem',
81
+ };
82
+
83
+ var KeyCodeMap = {
84
+ TAB_KEY: 9,
85
+ SHIFT_KEY: 16,
86
+ BACK_KEY: 46,
87
+ DELETE_KEY: 8,
88
+ ENTER_KEY: 13,
89
+ A_KEY: 65,
90
+ ESC_KEY: 27,
91
+ UP_KEY: 38,
92
+ DOWN_KEY: 40,
93
+ PAGE_UP_KEY: 33,
94
+ PAGE_DOWN_KEY: 34,
95
+ };
96
+
97
+ var ObjectsInConfig = ['fuseOptions', 'classNames'];
98
+
99
+ var PassedElementTypes = {
100
+ Text: 'text',
101
+ SelectOne: 'select-one',
102
+ SelectMultiple: 'select-multiple',
103
+ };
104
+
105
+ var addChoice = function (choice) { return ({
106
+ type: ActionType.ADD_CHOICE,
107
+ choice: choice,
108
+ }); };
109
+ var removeChoice = function (choice) { return ({
110
+ type: ActionType.REMOVE_CHOICE,
111
+ choice: choice,
112
+ }); };
113
+ var filterChoices = function (results) { return ({
114
+ type: ActionType.FILTER_CHOICES,
115
+ results: results,
116
+ }); };
117
+ var activateChoices = function (active) {
118
+ return ({
119
+ type: ActionType.ACTIVATE_CHOICES,
120
+ active: active,
121
+ });
122
+ };
123
+
124
+ var addGroup = function (group) { return ({
125
+ type: ActionType.ADD_GROUP,
126
+ group: group,
127
+ }); };
128
+
129
+ var addItem = function (item) { return ({
130
+ type: ActionType.ADD_ITEM,
131
+ item: item,
132
+ }); };
133
+ var removeItem$1 = function (item) { return ({
134
+ type: ActionType.REMOVE_ITEM,
135
+ item: item,
136
+ }); };
137
+ var highlightItem = function (item, highlighted) { return ({
138
+ type: ActionType.HIGHLIGHT_ITEM,
139
+ item: item,
140
+ highlighted: highlighted,
141
+ }); };
142
+
143
+ var getRandomNumber = function (min, max) { return Math.floor(Math.random() * (max - min) + min); };
144
+ var generateChars = function (length) {
145
+ return Array.from({ length: length }, function () { return getRandomNumber(0, 36).toString(36); }).join('');
146
+ };
147
+ var generateId = function (element, prefix) {
148
+ var id = element.id || (element.name && "".concat(element.name, "-").concat(generateChars(2))) || generateChars(4);
149
+ id = id.replace(/(:|\.|\[|\]|,)/g, '');
150
+ id = "".concat(prefix, "-").concat(id);
151
+ return id;
152
+ };
153
+ var getAdjacentEl = function (startEl, selector, direction) {
154
+ if (direction === void 0) { direction = 1; }
155
+ var prop = "".concat(direction > 0 ? 'next' : 'previous', "ElementSibling");
156
+ var sibling = startEl[prop];
157
+ while (sibling) {
158
+ if (sibling.matches(selector)) {
159
+ return sibling;
160
+ }
161
+ sibling = sibling[prop];
162
+ }
163
+ return null;
164
+ };
165
+ var isScrolledIntoView = function (element, parent, direction) {
166
+ if (direction === void 0) { direction = 1; }
167
+ var isVisible;
168
+ if (direction > 0) {
169
+ // In view from bottom
170
+ isVisible = parent.scrollTop + parent.offsetHeight >= element.offsetTop + element.offsetHeight;
171
+ }
172
+ else {
173
+ // In view from top
174
+ isVisible = element.offsetTop >= parent.scrollTop;
175
+ }
176
+ return isVisible;
177
+ };
178
+ var sanitise = function (value) {
179
+ if (typeof value !== 'string') {
180
+ if (value === null || value === undefined) {
181
+ return '';
182
+ }
183
+ if (typeof value === 'object') {
184
+ if ('raw' in value) {
185
+ return sanitise(value.raw);
186
+ }
187
+ if ('trusted' in value) {
188
+ return value.trusted;
189
+ }
190
+ }
191
+ return value;
192
+ }
193
+ return value
194
+ .replace(/&/g, '&amp;')
195
+ .replace(/>/g, '&gt;')
196
+ .replace(/</g, '&lt;')
197
+ .replace(/'/g, '&#039;')
198
+ .replace(/"/g, '&quot;');
199
+ };
200
+ var strToEl = (function () {
201
+ var tmpEl = document.createElement('div');
202
+ return function (str) {
203
+ tmpEl.innerHTML = str.trim();
204
+ var firstChild = tmpEl.children[0];
205
+ while (tmpEl.firstChild) {
206
+ tmpEl.removeChild(tmpEl.firstChild);
207
+ }
208
+ return firstChild;
209
+ };
210
+ })();
211
+ var resolveNoticeFunction = function (fn, value) {
212
+ return typeof fn === 'function' ? fn(sanitise(value), value) : fn;
213
+ };
214
+ var resolveStringFunction = function (fn) {
215
+ return typeof fn === 'function' ? fn() : fn;
216
+ };
217
+ var unwrapStringForRaw = function (s) {
218
+ if (typeof s === 'string') {
219
+ return s;
220
+ }
221
+ if (typeof s === 'object') {
222
+ if ('trusted' in s) {
223
+ return s.trusted;
224
+ }
225
+ if ('raw' in s) {
226
+ return s.raw;
227
+ }
228
+ }
229
+ return '';
230
+ };
231
+ var unwrapStringForEscaped = function (s) {
232
+ if (typeof s === 'string') {
233
+ return s;
234
+ }
235
+ if (typeof s === 'object') {
236
+ if ('escaped' in s) {
237
+ return s.escaped;
238
+ }
239
+ if ('trusted' in s) {
240
+ return s.trusted;
241
+ }
242
+ }
243
+ return '';
244
+ };
245
+ var escapeForTemplate = function (allowHTML, s) {
246
+ return allowHTML ? unwrapStringForEscaped(s) : sanitise(s);
247
+ };
248
+ var setElementHtml = function (el, allowHtml, html) {
249
+ el.innerHTML = escapeForTemplate(allowHtml, html);
250
+ };
251
+ var sortByAlpha = function (_a, _b) {
252
+ var value = _a.value, _c = _a.label, label = _c === void 0 ? value : _c;
253
+ var value2 = _b.value, _d = _b.label, label2 = _d === void 0 ? value2 : _d;
254
+ return unwrapStringForRaw(label).localeCompare(unwrapStringForRaw(label2), [], {
255
+ sensitivity: 'base',
256
+ ignorePunctuation: true,
257
+ numeric: true,
258
+ });
259
+ };
260
+ var sortByRank = function (a, b) {
261
+ return a.rank - b.rank;
262
+ };
263
+ var dispatchEvent = function (element, type, customArgs) {
264
+ if (customArgs === void 0) { customArgs = null; }
265
+ var event = new CustomEvent(type, {
266
+ detail: customArgs,
267
+ bubbles: true,
268
+ cancelable: true,
269
+ });
270
+ return element.dispatchEvent(event);
271
+ };
272
+ /**
273
+ * Returns an array of keys present on the first but missing on the second object
274
+ */
275
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
276
+ var diff = function (a, b) {
277
+ var aKeys = Object.keys(a).sort();
278
+ var bKeys = Object.keys(b).sort();
279
+ return aKeys.filter(function (i) { return bKeys.indexOf(i) < 0; });
280
+ };
281
+ var getClassNames = function (ClassNames) {
282
+ return Array.isArray(ClassNames) ? ClassNames : [ClassNames];
283
+ };
284
+ var getClassNamesSelector = function (option) {
285
+ if (option && Array.isArray(option)) {
286
+ return option
287
+ .map(function (item) {
288
+ return ".".concat(item);
289
+ })
290
+ .join('');
291
+ }
292
+ return ".".concat(option);
293
+ };
294
+ var addClassesToElement = function (element, className) {
295
+ var _a;
296
+ (_a = element.classList).add.apply(_a, getClassNames(className));
297
+ };
298
+ var removeClassesFromElement = function (element, className) {
299
+ var _a;
300
+ (_a = element.classList).remove.apply(_a, getClassNames(className));
301
+ };
302
+ var parseCustomProperties = function (customProperties) {
303
+ if (typeof customProperties !== 'undefined') {
304
+ try {
305
+ return JSON.parse(customProperties);
306
+ }
307
+ catch (e) {
308
+ return customProperties;
309
+ }
310
+ }
311
+ return {};
312
+ };
313
+ var updateClassList = function (item, add, remove) {
314
+ var itemEl = item.itemEl;
315
+ if (itemEl) {
316
+ removeClassesFromElement(itemEl, remove);
317
+ addClassesToElement(itemEl, add);
318
+ }
319
+ };
320
+
321
+ var Dropdown = /** @class */ (function () {
322
+ function Dropdown(_a) {
323
+ var element = _a.element, type = _a.type, classNames = _a.classNames;
324
+ this.element = element;
325
+ this.classNames = classNames;
326
+ this.type = type;
327
+ this.isActive = false;
328
+ }
329
+ /**
330
+ * Show dropdown to user by adding active state class
331
+ */
332
+ Dropdown.prototype.show = function () {
333
+ addClassesToElement(this.element, this.classNames.activeState);
334
+ this.element.setAttribute('aria-expanded', 'true');
335
+ this.isActive = true;
336
+ return this;
337
+ };
338
+ /**
339
+ * Hide dropdown from user
340
+ */
341
+ Dropdown.prototype.hide = function () {
342
+ removeClassesFromElement(this.element, this.classNames.activeState);
343
+ this.element.setAttribute('aria-expanded', 'false');
344
+ this.isActive = false;
345
+ return this;
346
+ };
347
+ return Dropdown;
348
+ }());
349
+
350
+ var Container = /** @class */ (function () {
351
+ function Container(_a) {
352
+ var element = _a.element, type = _a.type, classNames = _a.classNames, position = _a.position;
353
+ this.element = element;
354
+ this.classNames = classNames;
355
+ this.type = type;
356
+ this.position = position;
357
+ this.isOpen = false;
358
+ this.isFlipped = false;
359
+ this.isDisabled = false;
360
+ this.isLoading = false;
361
+ }
362
+ /**
363
+ * Determine whether container should be flipped based on passed
364
+ * dropdown position
365
+ */
366
+ Container.prototype.shouldFlip = function (dropdownPos, dropdownHeight) {
367
+ // If flip is enabled and the dropdown bottom position is
368
+ // greater than the window height flip the dropdown.
369
+ var shouldFlip = false;
370
+ if (this.position === 'auto') {
371
+ shouldFlip =
372
+ this.element.getBoundingClientRect().top - dropdownHeight >= 0 &&
373
+ !window.matchMedia("(min-height: ".concat(dropdownPos + 1, "px)")).matches;
374
+ }
375
+ else if (this.position === 'top') {
376
+ shouldFlip = true;
377
+ }
378
+ return shouldFlip;
379
+ };
380
+ Container.prototype.setActiveDescendant = function (activeDescendantID) {
381
+ this.element.setAttribute('aria-activedescendant', activeDescendantID);
382
+ };
383
+ Container.prototype.removeActiveDescendant = function () {
384
+ this.element.removeAttribute('aria-activedescendant');
385
+ };
386
+ Container.prototype.open = function (dropdownPos, dropdownHeight) {
387
+ addClassesToElement(this.element, this.classNames.openState);
388
+ this.element.setAttribute('aria-expanded', 'true');
389
+ this.isOpen = true;
390
+ if (this.shouldFlip(dropdownPos, dropdownHeight)) {
391
+ addClassesToElement(this.element, this.classNames.flippedState);
392
+ this.isFlipped = true;
393
+ }
394
+ };
395
+ Container.prototype.close = function () {
396
+ removeClassesFromElement(this.element, this.classNames.openState);
397
+ this.element.setAttribute('aria-expanded', 'false');
398
+ this.removeActiveDescendant();
399
+ this.isOpen = false;
400
+ // A dropdown flips if it does not have space within the page
401
+ if (this.isFlipped) {
402
+ removeClassesFromElement(this.element, this.classNames.flippedState);
403
+ this.isFlipped = false;
404
+ }
405
+ };
406
+ Container.prototype.addFocusState = function () {
407
+ addClassesToElement(this.element, this.classNames.focusState);
408
+ };
409
+ Container.prototype.removeFocusState = function () {
410
+ removeClassesFromElement(this.element, this.classNames.focusState);
411
+ };
412
+ Container.prototype.enable = function () {
413
+ removeClassesFromElement(this.element, this.classNames.disabledState);
414
+ this.element.removeAttribute('aria-disabled');
415
+ if (this.type === PassedElementTypes.SelectOne) {
416
+ this.element.setAttribute('tabindex', '0');
417
+ }
418
+ this.isDisabled = false;
419
+ };
420
+ Container.prototype.disable = function () {
421
+ addClassesToElement(this.element, this.classNames.disabledState);
422
+ this.element.setAttribute('aria-disabled', 'true');
423
+ if (this.type === PassedElementTypes.SelectOne) {
424
+ this.element.setAttribute('tabindex', '-1');
425
+ }
426
+ this.isDisabled = true;
427
+ };
428
+ Container.prototype.wrap = function (element) {
429
+ var el = this.element;
430
+ var parentNode = element.parentNode;
431
+ if (parentNode) {
432
+ if (element.nextSibling) {
433
+ parentNode.insertBefore(el, element.nextSibling);
434
+ }
435
+ else {
436
+ parentNode.appendChild(el);
437
+ }
438
+ }
439
+ el.appendChild(element);
440
+ };
441
+ Container.prototype.unwrap = function (element) {
442
+ var el = this.element;
443
+ var parentNode = el.parentNode;
444
+ if (parentNode) {
445
+ // Move passed element outside this element
446
+ parentNode.insertBefore(element, el);
447
+ // Remove this element
448
+ parentNode.removeChild(el);
449
+ }
450
+ };
451
+ Container.prototype.addLoadingState = function () {
452
+ addClassesToElement(this.element, this.classNames.loadingState);
453
+ this.element.setAttribute('aria-busy', 'true');
454
+ this.isLoading = true;
455
+ };
456
+ Container.prototype.removeLoadingState = function () {
457
+ removeClassesFromElement(this.element, this.classNames.loadingState);
458
+ this.element.removeAttribute('aria-busy');
459
+ this.isLoading = false;
460
+ };
461
+ return Container;
462
+ }());
463
+
464
+ var Input = /** @class */ (function () {
465
+ function Input(_a) {
466
+ var element = _a.element, type = _a.type, classNames = _a.classNames, preventPaste = _a.preventPaste;
467
+ this.element = element;
468
+ this.type = type;
469
+ this.classNames = classNames;
470
+ this.preventPaste = preventPaste;
471
+ this.isFocussed = this.element.isEqualNode(document.activeElement);
472
+ this.isDisabled = element.disabled;
473
+ this._onPaste = this._onPaste.bind(this);
474
+ this._onInput = this._onInput.bind(this);
475
+ this._onFocus = this._onFocus.bind(this);
476
+ this._onBlur = this._onBlur.bind(this);
477
+ }
478
+ Object.defineProperty(Input.prototype, "placeholder", {
479
+ set: function (placeholder) {
480
+ this.element.placeholder = placeholder;
481
+ },
482
+ enumerable: false,
483
+ configurable: true
484
+ });
485
+ Object.defineProperty(Input.prototype, "value", {
486
+ get: function () {
487
+ return this.element.value;
488
+ },
489
+ set: function (value) {
490
+ this.element.value = value;
491
+ },
492
+ enumerable: false,
493
+ configurable: true
494
+ });
495
+ Input.prototype.addEventListeners = function () {
496
+ var el = this.element;
497
+ el.addEventListener('paste', this._onPaste);
498
+ el.addEventListener('input', this._onInput, {
499
+ passive: true,
500
+ });
501
+ el.addEventListener('focus', this._onFocus, {
502
+ passive: true,
503
+ });
504
+ el.addEventListener('blur', this._onBlur, {
505
+ passive: true,
506
+ });
507
+ };
508
+ Input.prototype.removeEventListeners = function () {
509
+ var el = this.element;
510
+ el.removeEventListener('input', this._onInput);
511
+ el.removeEventListener('paste', this._onPaste);
512
+ el.removeEventListener('focus', this._onFocus);
513
+ el.removeEventListener('blur', this._onBlur);
514
+ };
515
+ Input.prototype.enable = function () {
516
+ var el = this.element;
517
+ el.removeAttribute('disabled');
518
+ this.isDisabled = false;
519
+ };
520
+ Input.prototype.disable = function () {
521
+ var el = this.element;
522
+ el.setAttribute('disabled', '');
523
+ this.isDisabled = true;
524
+ };
525
+ Input.prototype.focus = function () {
526
+ if (!this.isFocussed) {
527
+ this.element.focus();
528
+ }
529
+ };
530
+ Input.prototype.blur = function () {
531
+ if (this.isFocussed) {
532
+ this.element.blur();
533
+ }
534
+ };
535
+ Input.prototype.clear = function (setWidth) {
536
+ if (setWidth === void 0) { setWidth = true; }
537
+ this.element.value = '';
538
+ if (setWidth) {
539
+ this.setWidth();
540
+ }
541
+ return this;
542
+ };
543
+ /**
544
+ * Set the correct input width based on placeholder
545
+ * value or input value
546
+ */
547
+ Input.prototype.setWidth = function () {
548
+ // Resize input to contents or placeholder
549
+ var element = this.element;
550
+ element.style.minWidth = "".concat(element.placeholder.length + 1, "ch");
551
+ element.style.width = "".concat(element.value.length + 1, "ch");
552
+ };
553
+ Input.prototype.setActiveDescendant = function (activeDescendantID) {
554
+ this.element.setAttribute('aria-activedescendant', activeDescendantID);
555
+ };
556
+ Input.prototype.removeActiveDescendant = function () {
557
+ this.element.removeAttribute('aria-activedescendant');
558
+ };
559
+ Input.prototype._onInput = function () {
560
+ if (this.type !== PassedElementTypes.SelectOne) {
561
+ this.setWidth();
562
+ }
563
+ };
564
+ Input.prototype._onPaste = function (event) {
565
+ if (this.preventPaste) {
566
+ event.preventDefault();
567
+ }
568
+ };
569
+ Input.prototype._onFocus = function () {
570
+ this.isFocussed = true;
571
+ };
572
+ Input.prototype._onBlur = function () {
573
+ this.isFocussed = false;
574
+ };
575
+ return Input;
576
+ }());
577
+
578
+ var SCROLLING_SPEED = 4;
579
+
580
+ var List = /** @class */ (function () {
581
+ function List(_a) {
582
+ var element = _a.element;
583
+ this.element = element;
584
+ this.scrollPos = this.element.scrollTop;
585
+ this.height = this.element.offsetHeight;
586
+ }
587
+ List.prototype.prepend = function (node) {
588
+ var child = this.element.firstElementChild;
589
+ if (child) {
590
+ this.element.insertBefore(node, child);
591
+ }
592
+ else {
593
+ this.element.append(node);
594
+ }
595
+ };
596
+ List.prototype.scrollToTop = function () {
597
+ this.element.scrollTop = 0;
598
+ };
599
+ List.prototype.scrollToChildElement = function (element, direction) {
600
+ var _this = this;
601
+ if (!element) {
602
+ return;
603
+ }
604
+ var listHeight = this.element.offsetHeight;
605
+ // Scroll position of dropdown
606
+ var listScrollPosition = this.element.scrollTop + listHeight;
607
+ var elementHeight = element.offsetHeight;
608
+ // Distance from bottom of element to top of parent
609
+ var elementPos = element.offsetTop + elementHeight;
610
+ // Difference between the element and scroll position
611
+ var destination = direction > 0 ? this.element.scrollTop + elementPos - listScrollPosition : element.offsetTop;
612
+ requestAnimationFrame(function () {
613
+ _this._animateScroll(destination, direction);
614
+ });
615
+ };
616
+ List.prototype._scrollDown = function (scrollPos, strength, destination) {
617
+ var easing = (destination - scrollPos) / strength;
618
+ var distance = easing > 1 ? easing : 1;
619
+ this.element.scrollTop = scrollPos + distance;
620
+ };
621
+ List.prototype._scrollUp = function (scrollPos, strength, destination) {
622
+ var easing = (scrollPos - destination) / strength;
623
+ var distance = easing > 1 ? easing : 1;
624
+ this.element.scrollTop = scrollPos - distance;
625
+ };
626
+ List.prototype._animateScroll = function (destination, direction) {
627
+ var _this = this;
628
+ var strength = SCROLLING_SPEED;
629
+ var choiceListScrollTop = this.element.scrollTop;
630
+ var continueAnimation = false;
631
+ if (direction > 0) {
632
+ this._scrollDown(choiceListScrollTop, strength, destination);
633
+ if (choiceListScrollTop < destination) {
634
+ continueAnimation = true;
635
+ }
636
+ }
637
+ else {
638
+ this._scrollUp(choiceListScrollTop, strength, destination);
639
+ if (choiceListScrollTop > destination) {
640
+ continueAnimation = true;
641
+ }
642
+ }
643
+ if (continueAnimation) {
644
+ requestAnimationFrame(function () {
645
+ _this._animateScroll(destination, direction);
646
+ });
647
+ }
648
+ };
649
+ return List;
650
+ }());
651
+
652
+ var WrappedElement = /** @class */ (function () {
653
+ function WrappedElement(_a) {
654
+ var element = _a.element, classNames = _a.classNames;
655
+ this.element = element;
656
+ this.classNames = classNames;
657
+ this.isDisabled = false;
658
+ }
659
+ Object.defineProperty(WrappedElement.prototype, "isActive", {
660
+ get: function () {
661
+ return this.element.dataset.choice === 'active';
662
+ },
663
+ enumerable: false,
664
+ configurable: true
665
+ });
666
+ Object.defineProperty(WrappedElement.prototype, "dir", {
667
+ get: function () {
668
+ return this.element.dir;
669
+ },
670
+ enumerable: false,
671
+ configurable: true
672
+ });
673
+ Object.defineProperty(WrappedElement.prototype, "value", {
674
+ get: function () {
675
+ return this.element.value;
676
+ },
677
+ set: function (value) {
678
+ this.element.setAttribute('value', value);
679
+ this.element.value = value;
680
+ },
681
+ enumerable: false,
682
+ configurable: true
683
+ });
684
+ WrappedElement.prototype.conceal = function () {
685
+ var el = this.element;
686
+ // Hide passed input
687
+ addClassesToElement(el, this.classNames.input);
688
+ el.hidden = true;
689
+ // Remove element from tab index
690
+ el.tabIndex = -1;
691
+ // Backup original styles if any
692
+ var origStyle = el.getAttribute('style');
693
+ if (origStyle) {
694
+ el.setAttribute('data-choice-orig-style', origStyle);
695
+ }
696
+ el.setAttribute('data-choice', 'active');
697
+ };
698
+ WrappedElement.prototype.reveal = function () {
699
+ var el = this.element;
700
+ // Reinstate passed element
701
+ removeClassesFromElement(el, this.classNames.input);
702
+ el.hidden = false;
703
+ el.removeAttribute('tabindex');
704
+ // Recover original styles if any
705
+ var origStyle = el.getAttribute('data-choice-orig-style');
706
+ if (origStyle) {
707
+ el.removeAttribute('data-choice-orig-style');
708
+ el.setAttribute('style', origStyle);
709
+ }
710
+ else {
711
+ el.removeAttribute('style');
712
+ }
713
+ el.removeAttribute('data-choice');
714
+ };
715
+ WrappedElement.prototype.enable = function () {
716
+ this.element.removeAttribute('disabled');
717
+ this.element.disabled = false;
718
+ this.isDisabled = false;
719
+ };
720
+ WrappedElement.prototype.disable = function () {
721
+ this.element.setAttribute('disabled', '');
722
+ this.element.disabled = true;
723
+ this.isDisabled = true;
724
+ };
725
+ WrappedElement.prototype.triggerEvent = function (eventType, data) {
726
+ dispatchEvent(this.element, eventType, data || {});
727
+ };
728
+ return WrappedElement;
729
+ }());
730
+
731
+ var WrappedInput = /** @class */ (function (_super) {
732
+ __extends(WrappedInput, _super);
733
+ function WrappedInput() {
734
+ return _super !== null && _super.apply(this, arguments) || this;
735
+ }
736
+ return WrappedInput;
737
+ }(WrappedElement));
738
+
739
+ var coerceBool = function (arg, defaultValue) {
740
+ if (defaultValue === void 0) { defaultValue = true; }
741
+ return typeof arg === 'undefined' ? defaultValue : !!arg;
742
+ };
743
+ var stringToHtmlClass = function (input) {
744
+ if (typeof input === 'string') {
745
+ // eslint-disable-next-line no-param-reassign
746
+ input = input.split(' ').filter(function (s) { return s.length; });
747
+ }
748
+ if (Array.isArray(input) && input.length) {
749
+ return input;
750
+ }
751
+ return undefined;
752
+ };
753
+ var mapInputToChoice = function (value, allowGroup, allowRawString) {
754
+ if (allowRawString === void 0) { allowRawString = true; }
755
+ if (typeof value === 'string') {
756
+ var sanitisedValue = sanitise(value);
757
+ var userValue = allowRawString || sanitisedValue === value ? value : { escaped: sanitisedValue, raw: value };
758
+ var result_1 = mapInputToChoice({
759
+ value: value,
760
+ label: userValue,
761
+ selected: true,
762
+ }, false);
763
+ return result_1;
764
+ }
765
+ var groupOrChoice = value;
766
+ if ('choices' in groupOrChoice) {
767
+ if (!allowGroup) {
768
+ // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup
769
+ throw new TypeError("optGroup is not allowed");
770
+ }
771
+ var group = groupOrChoice;
772
+ var choices = group.choices.map(function (e) { return mapInputToChoice(e, false); });
773
+ var result_2 = {
774
+ id: 0, // actual ID will be assigned during _addGroup
775
+ label: unwrapStringForRaw(group.label) || group.value,
776
+ active: !!choices.length,
777
+ disabled: !!group.disabled,
778
+ choices: choices,
779
+ };
780
+ return result_2;
781
+ }
782
+ var choice = groupOrChoice;
783
+ var result = {
784
+ id: 0, // actual ID will be assigned during _addChoice
785
+ group: null, // actual group will be assigned during _addGroup but before _addChoice
786
+ score: 0, // used in search
787
+ rank: 0, // used in search, stable sort order
788
+ value: choice.value,
789
+ label: choice.label || choice.value,
790
+ active: coerceBool(choice.active),
791
+ selected: coerceBool(choice.selected, false),
792
+ disabled: coerceBool(choice.disabled, false),
793
+ placeholder: coerceBool(choice.placeholder, false),
794
+ highlighted: false,
795
+ labelClass: stringToHtmlClass(choice.labelClass),
796
+ labelDescription: choice.labelDescription,
797
+ customProperties: choice.customProperties,
798
+ };
799
+ return result;
800
+ };
801
+
802
+ var isHtmlInputElement = function (e) { return e.tagName === 'INPUT'; };
803
+ var isHtmlSelectElement = function (e) { return e.tagName === 'SELECT'; };
804
+ var isHtmlOption = function (e) { return e.tagName === 'OPTION'; };
805
+ var isHtmlOptgroup = function (e) { return e.tagName === 'OPTGROUP'; };
806
+
807
+ var WrappedSelect = /** @class */ (function (_super) {
808
+ __extends(WrappedSelect, _super);
809
+ function WrappedSelect(_a) {
810
+ var element = _a.element, classNames = _a.classNames, template = _a.template, extractPlaceholder = _a.extractPlaceholder;
811
+ var _this = _super.call(this, { element: element, classNames: classNames }) || this;
812
+ _this.template = template;
813
+ _this.extractPlaceholder = extractPlaceholder;
814
+ return _this;
815
+ }
816
+ Object.defineProperty(WrappedSelect.prototype, "placeholderOption", {
817
+ get: function () {
818
+ return (this.element.querySelector('option[value=""]') ||
819
+ // Backward compatibility layer for the non-standard placeholder attribute supported in older versions.
820
+ this.element.querySelector('option[placeholder]'));
821
+ },
822
+ enumerable: false,
823
+ configurable: true
824
+ });
825
+ WrappedSelect.prototype.addOptions = function (choices) {
826
+ var _this = this;
827
+ var fragment = document.createDocumentFragment();
828
+ choices.forEach(function (obj) {
829
+ var choice = obj;
830
+ if (choice.element) {
831
+ return;
832
+ }
833
+ var option = _this.template(choice);
834
+ fragment.appendChild(option);
835
+ choice.element = option;
836
+ });
837
+ this.element.appendChild(fragment);
838
+ };
839
+ WrappedSelect.prototype.optionsAsChoices = function () {
840
+ var _this = this;
841
+ var choices = [];
842
+ this.element.querySelectorAll(':scope > option, :scope > optgroup').forEach(function (e) {
843
+ if (isHtmlOption(e)) {
844
+ choices.push(_this._optionToChoice(e));
845
+ }
846
+ else if (isHtmlOptgroup(e)) {
847
+ choices.push(_this._optgroupToChoice(e));
848
+ }
849
+ // todo: hr as empty optgroup, requires displaying empty opt-groups to be useful
850
+ });
851
+ return choices;
852
+ };
853
+ // eslint-disable-next-line class-methods-use-this
854
+ WrappedSelect.prototype._optionToChoice = function (option) {
855
+ // option.value returns the label if there is no value attribute, which can break legacy placeholder attribute support
856
+ if (!option.hasAttribute('value') && option.hasAttribute('placeholder')) {
857
+ option.setAttribute('value', '');
858
+ option.value = '';
859
+ }
860
+ return {
861
+ id: 0,
862
+ group: null,
863
+ score: 0,
864
+ rank: 0,
865
+ value: option.value,
866
+ // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option
867
+ // This attribute is text for the label indicating the meaning of the option. If the `label` attribute isn't defined, its value is that of the element text content (ie `innerText`).
868
+ label: option.label,
869
+ element: option,
870
+ active: true,
871
+ // this returns true if nothing is selected on initial load, which will break placeholder support
872
+ selected: this.extractPlaceholder ? option.selected : option.hasAttribute('selected'),
873
+ disabled: option.disabled,
874
+ highlighted: false,
875
+ placeholder: this.extractPlaceholder && (!option.value || option.hasAttribute('placeholder')),
876
+ labelClass: typeof option.dataset.labelClass !== 'undefined' ? stringToHtmlClass(option.dataset.labelClass) : undefined,
877
+ labelDescription: typeof option.dataset.labelDescription !== 'undefined' ? option.dataset.labelDescription : undefined,
878
+ customProperties: parseCustomProperties(option.dataset.customProperties),
879
+ };
880
+ };
881
+ WrappedSelect.prototype._optgroupToChoice = function (optgroup) {
882
+ var _this = this;
883
+ var options = optgroup.querySelectorAll('option');
884
+ var choices = Array.from(options).map(function (option) { return _this._optionToChoice(option); });
885
+ return {
886
+ id: 0,
887
+ label: optgroup.label || '',
888
+ element: optgroup,
889
+ active: !!choices.length,
890
+ disabled: optgroup.disabled,
891
+ choices: choices,
892
+ };
893
+ };
894
+ return WrappedSelect;
895
+ }(WrappedElement));
896
+
897
+ var DEFAULT_CLASSNAMES = {
898
+ containerOuter: ['choices'],
899
+ containerInner: ['choices__inner'],
900
+ input: ['choices__input'],
901
+ inputCloned: ['choices__input--cloned'],
902
+ list: ['choices__list'],
903
+ listItems: ['choices__list--multiple'],
904
+ listSingle: ['choices__list--single'],
905
+ listDropdown: ['choices__list--dropdown'],
906
+ item: ['choices__item'],
907
+ itemSelectable: ['choices__item--selectable'],
908
+ itemDisabled: ['choices__item--disabled'],
909
+ itemChoice: ['choices__item--choice'],
910
+ description: ['choices__description'],
911
+ placeholder: ['choices__placeholder'],
912
+ group: ['choices__group'],
913
+ groupHeading: ['choices__heading'],
914
+ button: ['choices__button'],
915
+ activeState: ['is-active'],
916
+ focusState: ['is-focused'],
917
+ openState: ['is-open'],
918
+ disabledState: ['is-disabled'],
919
+ highlightedState: ['is-highlighted'],
920
+ selectedState: ['is-selected'],
921
+ flippedState: ['is-flipped'],
922
+ loadingState: ['is-loading'],
923
+ notice: ['choices__notice'],
924
+ addChoice: ['choices__item--selectable', 'add-choice'],
925
+ noResults: ['has-no-results'],
926
+ noChoices: ['has-no-choices'],
927
+ };
928
+ var DEFAULT_CONFIG = {
929
+ items: [],
930
+ choices: [],
931
+ silent: false,
932
+ renderChoiceLimit: -1,
933
+ maxItemCount: -1,
934
+ closeDropdownOnSelect: 'auto',
935
+ singleModeForMultiSelect: false,
936
+ addChoices: false,
937
+ addItems: true,
938
+ addItemFilter: function (value) { return !!value && value !== ''; },
939
+ removeItems: true,
940
+ removeItemButton: false,
941
+ removeItemButtonAlignLeft: false,
942
+ editItems: false,
943
+ allowHTML: false,
944
+ allowHtmlUserInput: false,
945
+ duplicateItemsAllowed: true,
946
+ delimiter: ',',
947
+ paste: true,
948
+ searchEnabled: true,
949
+ searchChoices: true,
950
+ searchFloor: 1,
951
+ searchResultLimit: 4,
952
+ searchFields: ['label', 'value'],
953
+ position: 'auto',
954
+ resetScrollPosition: true,
955
+ shouldSort: true,
956
+ shouldSortItems: false,
957
+ sorter: sortByAlpha,
958
+ shadowRoot: null,
959
+ placeholder: true,
960
+ placeholderValue: null,
961
+ searchPlaceholderValue: null,
962
+ prependValue: null,
963
+ appendValue: null,
964
+ renderSelectedChoices: 'auto',
965
+ loadingText: 'Loading...',
966
+ noResultsText: 'No results found',
967
+ noChoicesText: 'No choices to choose from',
968
+ itemSelectText: 'Press to select',
969
+ uniqueItemText: 'Only unique values can be added',
970
+ customAddItemText: 'Only values matching specific conditions can be added',
971
+ addItemText: function (value) { return "Press Enter to add <b>\"".concat(value, "\"</b>"); },
972
+ removeItemIconText: function () { return "Remove item"; },
973
+ removeItemLabelText: function (value) { return "Remove item: ".concat(value); },
974
+ maxItemText: function (maxItemCount) { return "Only ".concat(maxItemCount, " values can be added"); },
975
+ valueComparer: function (value1, value2) { return value1 === value2; },
976
+ fuseOptions: {
977
+ includeScore: true,
978
+ },
979
+ labelId: '',
980
+ callbackOnInit: null,
981
+ callbackOnCreateTemplates: null,
982
+ classNames: DEFAULT_CLASSNAMES,
983
+ appendGroupInSearch: false,
984
+ };
985
+
986
+ var removeItem = function (item) {
987
+ var itemEl = item.itemEl;
988
+ if (itemEl) {
989
+ itemEl.remove();
990
+ item.itemEl = undefined;
991
+ }
992
+ };
993
+ function items(s, action, context) {
994
+ var state = s;
995
+ var update = true;
996
+ switch (action.type) {
997
+ case ActionType.ADD_ITEM: {
998
+ action.item.selected = true;
999
+ var el = action.item.element;
1000
+ if (el) {
1001
+ el.selected = true;
1002
+ el.setAttribute('selected', '');
1003
+ }
1004
+ state.push(action.item);
1005
+ break;
1006
+ }
1007
+ case ActionType.REMOVE_ITEM: {
1008
+ action.item.selected = false;
1009
+ var el = action.item.element;
1010
+ if (el) {
1011
+ el.selected = false;
1012
+ el.removeAttribute('selected');
1013
+ // For a select-one, if all options are deselected, the first item is selected. To set a black value, select.value needs to be set
1014
+ var select = el.parentElement;
1015
+ if (select && isHtmlSelectElement(select) && select.type === PassedElementTypes.SelectOne) {
1016
+ select.value = '';
1017
+ }
1018
+ }
1019
+ // this is mixing concerns, but this is *so much faster*
1020
+ removeItem(action.item);
1021
+ state = state.filter(function (choice) { return choice.id !== action.item.id; });
1022
+ break;
1023
+ }
1024
+ case ActionType.REMOVE_CHOICE: {
1025
+ removeItem(action.choice);
1026
+ state = state.filter(function (item) { return item.id !== action.choice.id; });
1027
+ break;
1028
+ }
1029
+ case ActionType.HIGHLIGHT_ITEM: {
1030
+ var highlighted = action.highlighted;
1031
+ var item = state.find(function (obj) { return obj.id === action.item.id; });
1032
+ if (item && item.highlighted !== highlighted) {
1033
+ item.highlighted = highlighted;
1034
+ if (context) {
1035
+ updateClassList(item, highlighted ? context.classNames.highlightedState : context.classNames.selectedState, highlighted ? context.classNames.selectedState : context.classNames.highlightedState);
1036
+ }
1037
+ }
1038
+ break;
1039
+ }
1040
+ default: {
1041
+ update = false;
1042
+ break;
1043
+ }
1044
+ }
1045
+ return { state: state, update: update };
1046
+ }
1047
+
1048
+ function groups(s, action) {
1049
+ var state = s;
1050
+ var update = true;
1051
+ switch (action.type) {
1052
+ case ActionType.ADD_GROUP: {
1053
+ state.push(action.group);
1054
+ break;
1055
+ }
1056
+ case ActionType.CLEAR_CHOICES: {
1057
+ state = [];
1058
+ break;
1059
+ }
1060
+ default: {
1061
+ update = false;
1062
+ break;
1063
+ }
1064
+ }
1065
+ return { state: state, update: update };
1066
+ }
1067
+
1068
+ /* eslint-disable */
1069
+ function choices(s, action, context) {
1070
+ var state = s;
1071
+ var update = true;
1072
+ switch (action.type) {
1073
+ case ActionType.ADD_CHOICE: {
1074
+ state.push(action.choice);
1075
+ break;
1076
+ }
1077
+ case ActionType.REMOVE_CHOICE: {
1078
+ action.choice.choiceEl = undefined;
1079
+ if (action.choice.group) {
1080
+ action.choice.group.choices = action.choice.group.choices.filter(function (obj) { return obj.id !== action.choice.id; });
1081
+ }
1082
+ state = state.filter(function (obj) { return obj.id !== action.choice.id; });
1083
+ break;
1084
+ }
1085
+ case ActionType.ADD_ITEM:
1086
+ case ActionType.REMOVE_ITEM: {
1087
+ action.item.choiceEl = undefined;
1088
+ break;
1089
+ }
1090
+ case ActionType.FILTER_CHOICES: {
1091
+ // avoid O(n^2) algorithm complexity when searching/filtering choices
1092
+ var scoreLookup_1 = [];
1093
+ action.results.forEach(function (result) {
1094
+ scoreLookup_1[result.item.id] = result;
1095
+ });
1096
+ state.forEach(function (choice) {
1097
+ var result = scoreLookup_1[choice.id];
1098
+ if (result !== undefined) {
1099
+ choice.score = result.score;
1100
+ choice.rank = result.rank;
1101
+ choice.active = true;
1102
+ }
1103
+ else {
1104
+ choice.score = 0;
1105
+ choice.rank = 0;
1106
+ choice.active = false;
1107
+ }
1108
+ if (context && context.appendGroupInSearch) {
1109
+ choice.choiceEl = undefined;
1110
+ }
1111
+ });
1112
+ break;
1113
+ }
1114
+ case ActionType.ACTIVATE_CHOICES: {
1115
+ state.forEach(function (choice) {
1116
+ choice.active = action.active;
1117
+ if (context && context.appendGroupInSearch) {
1118
+ choice.choiceEl = undefined;
1119
+ }
1120
+ });
1121
+ break;
1122
+ }
1123
+ case ActionType.CLEAR_CHOICES: {
1124
+ state = [];
1125
+ break;
1126
+ }
1127
+ default: {
1128
+ update = false;
1129
+ break;
1130
+ }
1131
+ }
1132
+ return { state: state, update: update };
1133
+ }
1134
+
1135
+ var reducers = {
1136
+ groups: groups,
1137
+ items: items,
1138
+ choices: choices,
1139
+ };
1140
+ var Store = /** @class */ (function () {
1141
+ function Store(context) {
1142
+ this._state = this.defaultState;
1143
+ this._listeners = [];
1144
+ this._txn = 0;
1145
+ this._context = context;
1146
+ }
1147
+ Object.defineProperty(Store.prototype, "defaultState", {
1148
+ // eslint-disable-next-line class-methods-use-this
1149
+ get: function () {
1150
+ return {
1151
+ groups: [],
1152
+ items: [],
1153
+ choices: [],
1154
+ };
1155
+ },
1156
+ enumerable: false,
1157
+ configurable: true
1158
+ });
1159
+ // eslint-disable-next-line class-methods-use-this
1160
+ Store.prototype.changeSet = function (init) {
1161
+ return {
1162
+ groups: init,
1163
+ items: init,
1164
+ choices: init,
1165
+ };
1166
+ };
1167
+ Store.prototype.reset = function () {
1168
+ this._state = this.defaultState;
1169
+ var changes = this.changeSet(true);
1170
+ if (this._txn) {
1171
+ this._changeSet = changes;
1172
+ }
1173
+ else {
1174
+ this._listeners.forEach(function (l) { return l(changes); });
1175
+ }
1176
+ };
1177
+ Store.prototype.subscribe = function (onChange) {
1178
+ this._listeners.push(onChange);
1179
+ return this;
1180
+ };
1181
+ Store.prototype.dispatch = function (action) {
1182
+ var _this = this;
1183
+ var state = this._state;
1184
+ var hasChanges = false;
1185
+ var changes = this._changeSet || this.changeSet(false);
1186
+ Object.keys(reducers).forEach(function (key) {
1187
+ var stateUpdate = reducers[key](state[key], action, _this._context);
1188
+ if (stateUpdate.update) {
1189
+ hasChanges = true;
1190
+ changes[key] = true;
1191
+ state[key] = stateUpdate.state;
1192
+ }
1193
+ });
1194
+ if (hasChanges) {
1195
+ if (this._txn) {
1196
+ this._changeSet = changes;
1197
+ }
1198
+ else {
1199
+ this._listeners.forEach(function (l) { return l(changes); });
1200
+ }
1201
+ }
1202
+ };
1203
+ Store.prototype.withTxn = function (func) {
1204
+ this._txn++;
1205
+ try {
1206
+ func();
1207
+ }
1208
+ finally {
1209
+ this._txn = Math.max(0, this._txn - 1);
1210
+ if (!this._txn) {
1211
+ var changeSet_1 = this._changeSet;
1212
+ if (changeSet_1) {
1213
+ this._changeSet = undefined;
1214
+ this._listeners.forEach(function (l) { return l(changeSet_1); });
1215
+ }
1216
+ }
1217
+ }
1218
+ };
1219
+ Object.defineProperty(Store.prototype, "state", {
1220
+ /**
1221
+ * Get store object
1222
+ */
1223
+ get: function () {
1224
+ return this._state;
1225
+ },
1226
+ enumerable: false,
1227
+ configurable: true
1228
+ });
1229
+ Object.defineProperty(Store.prototype, "items", {
1230
+ /**
1231
+ * Get items from store
1232
+ */
1233
+ get: function () {
1234
+ return this.state.items;
1235
+ },
1236
+ enumerable: false,
1237
+ configurable: true
1238
+ });
1239
+ Object.defineProperty(Store.prototype, "highlightedActiveItems", {
1240
+ /**
1241
+ * Get highlighted items from store
1242
+ */
1243
+ get: function () {
1244
+ return this.items.filter(function (item) { return item.active && item.highlighted; });
1245
+ },
1246
+ enumerable: false,
1247
+ configurable: true
1248
+ });
1249
+ Object.defineProperty(Store.prototype, "choices", {
1250
+ /**
1251
+ * Get choices from store
1252
+ */
1253
+ get: function () {
1254
+ return this.state.choices;
1255
+ },
1256
+ enumerable: false,
1257
+ configurable: true
1258
+ });
1259
+ Object.defineProperty(Store.prototype, "activeChoices", {
1260
+ /**
1261
+ * Get active choices from store
1262
+ */
1263
+ get: function () {
1264
+ return this.choices.filter(function (choice) { return choice.active; });
1265
+ },
1266
+ enumerable: false,
1267
+ configurable: true
1268
+ });
1269
+ Object.defineProperty(Store.prototype, "searchableChoices", {
1270
+ /**
1271
+ * Get choices that can be searched (excluding placeholders or disabled choices)
1272
+ */
1273
+ get: function () {
1274
+ return this.choices.filter(function (choice) { return !choice.disabled && !choice.placeholder; });
1275
+ },
1276
+ enumerable: false,
1277
+ configurable: true
1278
+ });
1279
+ Object.defineProperty(Store.prototype, "groups", {
1280
+ /**
1281
+ * Get groups from store
1282
+ */
1283
+ get: function () {
1284
+ return this.state.groups;
1285
+ },
1286
+ enumerable: false,
1287
+ configurable: true
1288
+ });
1289
+ Object.defineProperty(Store.prototype, "activeGroups", {
1290
+ /**
1291
+ * Get active groups from store
1292
+ */
1293
+ get: function () {
1294
+ var _this = this;
1295
+ return this.state.groups.filter(function (group) {
1296
+ var isActive = group.active && !group.disabled;
1297
+ var hasActiveOptions = _this.state.choices.some(function (choice) { return choice.active && !choice.disabled; });
1298
+ return isActive && hasActiveOptions;
1299
+ }, []);
1300
+ },
1301
+ enumerable: false,
1302
+ configurable: true
1303
+ });
1304
+ Store.prototype.inTxn = function () {
1305
+ return this._txn > 0;
1306
+ };
1307
+ /**
1308
+ * Get single choice by it's ID
1309
+ */
1310
+ Store.prototype.getChoiceById = function (id) {
1311
+ return this.activeChoices.find(function (choice) { return choice.id === id; });
1312
+ };
1313
+ /**
1314
+ * Get group by group id
1315
+ */
1316
+ Store.prototype.getGroupById = function (id) {
1317
+ return this.groups.find(function (group) { return group.id === id; });
1318
+ };
1319
+ return Store;
1320
+ }());
1321
+
1322
+ var NoticeTypes = {
1323
+ noChoices: 'no-choices',
1324
+ noResults: 'no-results',
1325
+ addChoice: 'add-choice',
1326
+ generic: '',
1327
+ };
1328
+
1329
+ function kmpSearch(pattern, text) {
1330
+ if (pattern.length === 0) {
1331
+ return 0; // Immediate match
1332
+ }
1333
+ // Compute longest suffix-prefix table
1334
+ var lsp = [0]; // Base case
1335
+ for (var i = 1; i < pattern.length; i++) {
1336
+ var j_1 = lsp[i - 1]; // Start by assuming we're extending the previous LSP
1337
+ while (j_1 > 0 && pattern.charAt(i) !== pattern.charAt(j_1)) {
1338
+ j_1 = lsp[j_1 - 1];
1339
+ }
1340
+ if (pattern.charAt(i) === pattern.charAt(j_1)) {
1341
+ j_1++;
1342
+ }
1343
+ lsp.push(j_1);
1344
+ }
1345
+ // Walk through text string
1346
+ var j = 0; // Number of chars matched in pattern
1347
+ for (var i = 0; i < text.length; i++) {
1348
+ while (j > 0 && text.charAt(i) !== pattern.charAt(j)) {
1349
+ j = lsp[j - 1]; // Fall back in the pattern
1350
+ }
1351
+ if (text.charAt(i) === pattern.charAt(j)) {
1352
+ j++; // Next char matched, increment position
1353
+ if (j === pattern.length) {
1354
+ return i - (j - 1);
1355
+ }
1356
+ }
1357
+ }
1358
+ return -1; // Not found
1359
+ }
1360
+ var SearchByKMP = /** @class */ (function () {
1361
+ function SearchByKMP(config) {
1362
+ this._haystack = [];
1363
+ this._fields = config.searchFields;
1364
+ }
1365
+ SearchByKMP.prototype.index = function (data) {
1366
+ this._haystack = data;
1367
+ };
1368
+ SearchByKMP.prototype.reset = function () {
1369
+ this._haystack = [];
1370
+ };
1371
+ SearchByKMP.prototype.isEmptyIndex = function () {
1372
+ return !this._haystack.length;
1373
+ };
1374
+ SearchByKMP.prototype.search = function (_needle) {
1375
+ var fields = this._fields;
1376
+ if (!fields || !fields.length || !_needle) {
1377
+ return [];
1378
+ }
1379
+ var needle = _needle.toLowerCase();
1380
+ var results = [];
1381
+ var count = 0;
1382
+ for (var i = 0, j = this._haystack.length; i < j; i++) {
1383
+ var obj = this._haystack[i];
1384
+ for (var k = 0, l = this._fields.length; k < l; k++) {
1385
+ var field = this._fields[k];
1386
+ if (field in obj && kmpSearch(needle, obj[field].toLowerCase()) !== -1) {
1387
+ results.push({
1388
+ item: obj[field],
1389
+ score: count,
1390
+ rank: count + 1,
1391
+ });
1392
+ count++;
1393
+ }
1394
+ }
1395
+ }
1396
+ return results;
1397
+ };
1398
+ return SearchByKMP;
1399
+ }());
1400
+
1401
+ function getSearcher(config) {
1402
+ {
1403
+ return new SearchByKMP(config);
1404
+ }
1405
+ }
1406
+
1407
+ /**
1408
+ * Helpers to create HTML elements used by Choices
1409
+ * Can be overridden by providing `callbackOnCreateTemplates` option.
1410
+ * `Choices.defaults.templates` allows access to the default template methods from `callbackOnCreateTemplates`
1411
+ */
1412
+ var isEmptyObject = function (obj) {
1413
+ // eslint-disable-next-line no-restricted-syntax
1414
+ for (var prop in obj) {
1415
+ if (Object.prototype.hasOwnProperty.call(obj, prop)) {
1416
+ return false;
1417
+ }
1418
+ }
1419
+ return true;
1420
+ };
1421
+ var assignCustomProperties = function (el, choice, withCustomProperties) {
1422
+ var dataset = el.dataset;
1423
+ var customProperties = choice.customProperties, labelClass = choice.labelClass, labelDescription = choice.labelDescription;
1424
+ if (labelClass) {
1425
+ dataset.labelClass = getClassNames(labelClass).join(' ');
1426
+ }
1427
+ if (labelDescription) {
1428
+ dataset.labelDescription = labelDescription;
1429
+ }
1430
+ if (withCustomProperties && customProperties) {
1431
+ if (typeof customProperties === 'string') {
1432
+ dataset.customProperties = customProperties;
1433
+ }
1434
+ else if (typeof customProperties === 'object' && !isEmptyObject(customProperties)) {
1435
+ dataset.customProperties = JSON.stringify(customProperties);
1436
+ }
1437
+ }
1438
+ };
1439
+ var addAriaLabel = function (docRoot, id, element) {
1440
+ var label = id && docRoot.querySelector("label[for='".concat(id, "']"));
1441
+ var text = label && label.innerText;
1442
+ if (text) {
1443
+ element.setAttribute('aria-label', text);
1444
+ }
1445
+ };
1446
+ var templates = {
1447
+ containerOuter: function (_a, dir, isSelectElement, isSelectOneElement, searchEnabled, passedElementType, labelId) {
1448
+ var containerOuter = _a.classNames.containerOuter;
1449
+ var div = document.createElement('div');
1450
+ addClassesToElement(div, containerOuter);
1451
+ div.dataset.type = passedElementType;
1452
+ if (dir) {
1453
+ div.dir = dir;
1454
+ }
1455
+ if (isSelectOneElement) {
1456
+ div.tabIndex = 0;
1457
+ }
1458
+ if (isSelectElement) {
1459
+ div.setAttribute('role', searchEnabled ? 'combobox' : 'listbox');
1460
+ if (searchEnabled) {
1461
+ div.setAttribute('aria-autocomplete', 'list');
1462
+ }
1463
+ else if (!labelId) {
1464
+ addAriaLabel(this._docRoot, this.passedElement.element.id, div);
1465
+ }
1466
+ div.setAttribute('aria-haspopup', 'true');
1467
+ div.setAttribute('aria-expanded', 'false');
1468
+ }
1469
+ if (labelId) {
1470
+ div.setAttribute('aria-labelledby', labelId);
1471
+ }
1472
+ return div;
1473
+ },
1474
+ containerInner: function (_a) {
1475
+ var containerInner = _a.classNames.containerInner;
1476
+ var div = document.createElement('div');
1477
+ addClassesToElement(div, containerInner);
1478
+ return div;
1479
+ },
1480
+ itemList: function (_a, isSelectOneElement) {
1481
+ var searchEnabled = _a.searchEnabled, _b = _a.classNames, list = _b.list, listSingle = _b.listSingle, listItems = _b.listItems;
1482
+ var div = document.createElement('div');
1483
+ addClassesToElement(div, list);
1484
+ addClassesToElement(div, isSelectOneElement ? listSingle : listItems);
1485
+ if (this._isSelectElement && searchEnabled) {
1486
+ div.setAttribute('role', 'listbox');
1487
+ }
1488
+ return div;
1489
+ },
1490
+ placeholder: function (_a, value) {
1491
+ var allowHTML = _a.allowHTML, placeholder = _a.classNames.placeholder;
1492
+ var div = document.createElement('div');
1493
+ addClassesToElement(div, placeholder);
1494
+ setElementHtml(div, allowHTML, value);
1495
+ return div;
1496
+ },
1497
+ item: function (_a, choice, removeItemButton) {
1498
+ var allowHTML = _a.allowHTML, removeItemButtonAlignLeft = _a.removeItemButtonAlignLeft, removeItemIconText = _a.removeItemIconText, removeItemLabelText = _a.removeItemLabelText, _b = _a.classNames, item = _b.item, button = _b.button, highlightedState = _b.highlightedState, itemSelectable = _b.itemSelectable, placeholder = _b.placeholder;
1499
+ var rawValue = unwrapStringForRaw(choice.value);
1500
+ var div = document.createElement('div');
1501
+ addClassesToElement(div, item);
1502
+ if (choice.labelClass) {
1503
+ var spanLabel = document.createElement('span');
1504
+ setElementHtml(spanLabel, allowHTML, choice.label);
1505
+ addClassesToElement(spanLabel, choice.labelClass);
1506
+ div.appendChild(spanLabel);
1507
+ }
1508
+ else {
1509
+ setElementHtml(div, allowHTML, choice.label);
1510
+ }
1511
+ div.dataset.item = '';
1512
+ div.dataset.id = choice.id;
1513
+ div.dataset.value = rawValue;
1514
+ assignCustomProperties(div, choice, true);
1515
+ if (choice.disabled || this.containerOuter.isDisabled) {
1516
+ div.setAttribute('aria-disabled', 'true');
1517
+ }
1518
+ if (this._isSelectElement) {
1519
+ div.setAttribute('aria-selected', 'true');
1520
+ div.setAttribute('role', 'option');
1521
+ }
1522
+ if (choice.placeholder) {
1523
+ addClassesToElement(div, placeholder);
1524
+ div.dataset.placeholder = '';
1525
+ }
1526
+ addClassesToElement(div, choice.highlighted ? highlightedState : itemSelectable);
1527
+ if (removeItemButton) {
1528
+ if (choice.disabled) {
1529
+ removeClassesFromElement(div, itemSelectable);
1530
+ }
1531
+ div.dataset.deletable = '';
1532
+ var removeButton = document.createElement('button');
1533
+ removeButton.type = 'button';
1534
+ addClassesToElement(removeButton, button);
1535
+ setElementHtml(removeButton, true, resolveNoticeFunction(removeItemIconText, choice.value));
1536
+ var REMOVE_ITEM_LABEL = resolveNoticeFunction(removeItemLabelText, choice.value);
1537
+ if (REMOVE_ITEM_LABEL) {
1538
+ removeButton.setAttribute('aria-label', REMOVE_ITEM_LABEL);
1539
+ }
1540
+ removeButton.dataset.button = '';
1541
+ if (removeItemButtonAlignLeft) {
1542
+ div.insertAdjacentElement('afterbegin', removeButton);
1543
+ }
1544
+ else {
1545
+ div.appendChild(removeButton);
1546
+ }
1547
+ }
1548
+ return div;
1549
+ },
1550
+ choiceList: function (_a, isSelectOneElement) {
1551
+ var list = _a.classNames.list;
1552
+ var div = document.createElement('div');
1553
+ addClassesToElement(div, list);
1554
+ if (!isSelectOneElement) {
1555
+ div.setAttribute('aria-multiselectable', 'true');
1556
+ }
1557
+ div.setAttribute('role', 'listbox');
1558
+ return div;
1559
+ },
1560
+ choiceGroup: function (_a, _b) {
1561
+ var allowHTML = _a.allowHTML, _c = _a.classNames, group = _c.group, groupHeading = _c.groupHeading, itemDisabled = _c.itemDisabled;
1562
+ var id = _b.id, label = _b.label, disabled = _b.disabled;
1563
+ var rawLabel = unwrapStringForRaw(label);
1564
+ var div = document.createElement('div');
1565
+ addClassesToElement(div, group);
1566
+ if (disabled) {
1567
+ addClassesToElement(div, itemDisabled);
1568
+ }
1569
+ div.setAttribute('role', 'group');
1570
+ div.dataset.group = '';
1571
+ div.dataset.id = id;
1572
+ div.dataset.value = rawLabel;
1573
+ if (disabled) {
1574
+ div.setAttribute('aria-disabled', 'true');
1575
+ }
1576
+ var heading = document.createElement('div');
1577
+ addClassesToElement(heading, groupHeading);
1578
+ setElementHtml(heading, allowHTML, label || '');
1579
+ div.appendChild(heading);
1580
+ return div;
1581
+ },
1582
+ choice: function (_a, choice, selectText, groupName) {
1583
+ var allowHTML = _a.allowHTML, _b = _a.classNames, item = _b.item, itemChoice = _b.itemChoice, itemSelectable = _b.itemSelectable, selectedState = _b.selectedState, itemDisabled = _b.itemDisabled, description = _b.description, placeholder = _b.placeholder;
1584
+ // eslint-disable-next-line prefer-destructuring
1585
+ var label = choice.label;
1586
+ var rawValue = unwrapStringForRaw(choice.value);
1587
+ var div = document.createElement('div');
1588
+ div.id = choice.elementId;
1589
+ addClassesToElement(div, item);
1590
+ addClassesToElement(div, itemChoice);
1591
+ if (groupName && typeof label === 'string') {
1592
+ label = escapeForTemplate(allowHTML, label);
1593
+ label += " (".concat(groupName, ")");
1594
+ label = { trusted: label };
1595
+ }
1596
+ var describedBy = div;
1597
+ if (choice.labelClass) {
1598
+ var spanLabel = document.createElement('span');
1599
+ setElementHtml(spanLabel, allowHTML, label);
1600
+ addClassesToElement(spanLabel, choice.labelClass);
1601
+ describedBy = spanLabel;
1602
+ div.appendChild(spanLabel);
1603
+ }
1604
+ else {
1605
+ setElementHtml(div, allowHTML, label);
1606
+ }
1607
+ if (choice.labelDescription) {
1608
+ var descId = "".concat(choice.elementId, "-description");
1609
+ describedBy.setAttribute('aria-describedby', descId);
1610
+ var spanDesc = document.createElement('span');
1611
+ setElementHtml(spanDesc, allowHTML, choice.labelDescription);
1612
+ spanDesc.id = descId;
1613
+ addClassesToElement(spanDesc, description);
1614
+ div.appendChild(spanDesc);
1615
+ }
1616
+ if (choice.selected) {
1617
+ addClassesToElement(div, selectedState);
1618
+ }
1619
+ if (choice.placeholder) {
1620
+ addClassesToElement(div, placeholder);
1621
+ }
1622
+ div.setAttribute('role', choice.group ? 'treeitem' : 'option');
1623
+ div.dataset.choice = '';
1624
+ div.dataset.id = choice.id;
1625
+ div.dataset.value = rawValue;
1626
+ if (selectText) {
1627
+ div.dataset.selectText = selectText;
1628
+ }
1629
+ if (choice.group) {
1630
+ div.dataset.groupId = "".concat(choice.group.id);
1631
+ }
1632
+ assignCustomProperties(div, choice, false);
1633
+ if (choice.disabled) {
1634
+ addClassesToElement(div, itemDisabled);
1635
+ div.dataset.choiceDisabled = '';
1636
+ div.setAttribute('aria-disabled', 'true');
1637
+ }
1638
+ else {
1639
+ addClassesToElement(div, itemSelectable);
1640
+ div.dataset.choiceSelectable = '';
1641
+ }
1642
+ return div;
1643
+ },
1644
+ input: function (_a, placeholderValue) {
1645
+ var _b = _a.classNames, input = _b.input, inputCloned = _b.inputCloned, labelId = _a.labelId;
1646
+ var inp = document.createElement('input');
1647
+ inp.type = 'search';
1648
+ addClassesToElement(inp, input);
1649
+ addClassesToElement(inp, inputCloned);
1650
+ inp.autocomplete = 'off';
1651
+ inp.autocapitalize = 'off';
1652
+ inp.spellcheck = false;
1653
+ inp.setAttribute('aria-autocomplete', 'list');
1654
+ if (placeholderValue) {
1655
+ inp.setAttribute('aria-label', placeholderValue);
1656
+ }
1657
+ else if (!labelId) {
1658
+ addAriaLabel(this._docRoot, this.passedElement.element.id, inp);
1659
+ }
1660
+ return inp;
1661
+ },
1662
+ dropdown: function (_a) {
1663
+ var _b = _a.classNames, list = _b.list, listDropdown = _b.listDropdown;
1664
+ var div = document.createElement('div');
1665
+ addClassesToElement(div, list);
1666
+ addClassesToElement(div, listDropdown);
1667
+ div.setAttribute('aria-expanded', 'false');
1668
+ return div;
1669
+ },
1670
+ notice: function (_a, innerHTML, type) {
1671
+ var _b = _a.classNames, item = _b.item, itemChoice = _b.itemChoice, addChoice = _b.addChoice, noResults = _b.noResults, noChoices = _b.noChoices, noticeItem = _b.notice;
1672
+ if (type === void 0) { type = NoticeTypes.generic; }
1673
+ var notice = document.createElement('div');
1674
+ setElementHtml(notice, true, innerHTML);
1675
+ addClassesToElement(notice, item);
1676
+ addClassesToElement(notice, itemChoice);
1677
+ addClassesToElement(notice, noticeItem);
1678
+ // eslint-disable-next-line default-case
1679
+ switch (type) {
1680
+ case NoticeTypes.addChoice:
1681
+ addClassesToElement(notice, addChoice);
1682
+ break;
1683
+ case NoticeTypes.noResults:
1684
+ addClassesToElement(notice, noResults);
1685
+ break;
1686
+ case NoticeTypes.noChoices:
1687
+ addClassesToElement(notice, noChoices);
1688
+ break;
1689
+ }
1690
+ if (type === NoticeTypes.addChoice) {
1691
+ notice.dataset.choiceSelectable = '';
1692
+ notice.dataset.choice = '';
1693
+ }
1694
+ return notice;
1695
+ },
1696
+ option: function (choice) {
1697
+ // HtmlOptionElement's label value does not support HTML, so the avoid double escaping unwrap the untrusted string.
1698
+ var labelValue = unwrapStringForRaw(choice.label);
1699
+ var opt = new Option(labelValue, choice.value, false, choice.selected);
1700
+ assignCustomProperties(opt, choice, true);
1701
+ opt.disabled = choice.disabled;
1702
+ if (choice.selected) {
1703
+ opt.setAttribute('selected', '');
1704
+ }
1705
+ return opt;
1706
+ },
1707
+ };
1708
+
1709
+ /** @see {@link http://browserhacks.com/#hack-acea075d0ac6954f275a70023906050c} */
1710
+ var IS_IE11 = '-ms-scroll-limit' in document.documentElement.style &&
1711
+ '-ms-ime-align' in document.documentElement.style;
1712
+ var USER_DEFAULTS = {};
1713
+ var parseDataSetId = function (element) {
1714
+ if (!element) {
1715
+ return undefined;
1716
+ }
1717
+ return element.dataset.id ? parseInt(element.dataset.id, 10) : undefined;
1718
+ };
1719
+ var selectableChoiceIdentifier = '[data-choice-selectable]';
1720
+ /**
1721
+ * Choices
1722
+ * @author Josh Johnson<josh@joshuajohnson.co.uk>
1723
+ */
1724
+ var Choices = /** @class */ (function () {
1725
+ function Choices(element, userConfig) {
1726
+ if (element === void 0) { element = '[data-choice]'; }
1727
+ if (userConfig === void 0) { userConfig = {}; }
1728
+ var _this = this;
1729
+ this.initialisedOK = undefined;
1730
+ this._hasNonChoicePlaceholder = false;
1731
+ this._lastAddedChoiceId = 0;
1732
+ this._lastAddedGroupId = 0;
1733
+ var defaults = Choices.defaults;
1734
+ this.config = __assign(__assign(__assign({}, defaults.allOptions), defaults.options), userConfig);
1735
+ ObjectsInConfig.forEach(function (key) {
1736
+ _this.config[key] = __assign(__assign(__assign({}, defaults.allOptions[key]), defaults.options[key]), userConfig[key]);
1737
+ });
1738
+ var config = this.config;
1739
+ if (!config.silent) {
1740
+ this._validateConfig();
1741
+ }
1742
+ var docRoot = config.shadowRoot || document.documentElement;
1743
+ this._docRoot = docRoot;
1744
+ var passedElement = typeof element === 'string' ? docRoot.querySelector(element) : element;
1745
+ if (!passedElement ||
1746
+ typeof passedElement !== 'object' ||
1747
+ !(isHtmlInputElement(passedElement) || isHtmlSelectElement(passedElement))) {
1748
+ if (!passedElement && typeof element === 'string') {
1749
+ throw TypeError("Selector ".concat(element, " failed to find an element"));
1750
+ }
1751
+ throw TypeError("Expected one of the following types text|select-one|select-multiple");
1752
+ }
1753
+ var elementType = passedElement.type;
1754
+ var isText = elementType === PassedElementTypes.Text;
1755
+ if (isText || config.maxItemCount !== 1) {
1756
+ config.singleModeForMultiSelect = false;
1757
+ }
1758
+ if (config.singleModeForMultiSelect) {
1759
+ elementType = PassedElementTypes.SelectMultiple;
1760
+ }
1761
+ var isSelectOne = elementType === PassedElementTypes.SelectOne;
1762
+ var isSelectMultiple = elementType === PassedElementTypes.SelectMultiple;
1763
+ var isSelect = isSelectOne || isSelectMultiple;
1764
+ this._elementType = elementType;
1765
+ this._isTextElement = isText;
1766
+ this._isSelectOneElement = isSelectOne;
1767
+ this._isSelectMultipleElement = isSelectMultiple;
1768
+ this._isSelectElement = isSelectOne || isSelectMultiple;
1769
+ this._canAddUserChoices = (isText && config.addItems) || (isSelect && config.addChoices);
1770
+ if (typeof config.renderSelectedChoices !== 'boolean') {
1771
+ config.renderSelectedChoices = config.renderSelectedChoices === 'always' || isSelectOne;
1772
+ }
1773
+ if (config.closeDropdownOnSelect === 'auto') {
1774
+ config.closeDropdownOnSelect = isText || isSelectOne || config.singleModeForMultiSelect;
1775
+ }
1776
+ else {
1777
+ config.closeDropdownOnSelect = coerceBool(config.closeDropdownOnSelect);
1778
+ }
1779
+ if (config.placeholder) {
1780
+ if (config.placeholderValue) {
1781
+ this._hasNonChoicePlaceholder = true;
1782
+ }
1783
+ else if (passedElement.dataset.placeholder) {
1784
+ this._hasNonChoicePlaceholder = true;
1785
+ config.placeholderValue = passedElement.dataset.placeholder;
1786
+ }
1787
+ }
1788
+ if (userConfig.addItemFilter && typeof userConfig.addItemFilter !== 'function') {
1789
+ var re = userConfig.addItemFilter instanceof RegExp ? userConfig.addItemFilter : new RegExp(userConfig.addItemFilter);
1790
+ config.addItemFilter = re.test.bind(re);
1791
+ }
1792
+ if (this._isTextElement) {
1793
+ this.passedElement = new WrappedInput({
1794
+ element: passedElement,
1795
+ classNames: config.classNames,
1796
+ });
1797
+ }
1798
+ else {
1799
+ var selectEl = passedElement;
1800
+ this.passedElement = new WrappedSelect({
1801
+ element: selectEl,
1802
+ classNames: config.classNames,
1803
+ template: function (data) { return _this._templates.option(data); },
1804
+ extractPlaceholder: config.placeholder && !this._hasNonChoicePlaceholder,
1805
+ });
1806
+ }
1807
+ this.initialised = false;
1808
+ this._store = new Store(config);
1809
+ this._currentValue = '';
1810
+ config.searchEnabled = (!isText && config.searchEnabled) || isSelectMultiple;
1811
+ this._canSearch = config.searchEnabled;
1812
+ this._isScrollingOnIe = false;
1813
+ this._highlightPosition = 0;
1814
+ this._wasTap = true;
1815
+ this._placeholderValue = this._generatePlaceholderValue();
1816
+ this._baseId = generateId(passedElement, 'choices-');
1817
+ /**
1818
+ * setting direction in cases where it's explicitly set on passedElement
1819
+ * or when calculated direction is different from the document
1820
+ */
1821
+ this._direction = passedElement.dir;
1822
+ if (!this._direction) {
1823
+ var elementDirection = window.getComputedStyle(passedElement).direction;
1824
+ var documentDirection = window.getComputedStyle(document.documentElement).direction;
1825
+ if (elementDirection !== documentDirection) {
1826
+ this._direction = elementDirection;
1827
+ }
1828
+ }
1829
+ this._idNames = {
1830
+ itemChoice: 'item-choice',
1831
+ };
1832
+ this._templates = defaults.templates;
1833
+ this._render = this._render.bind(this);
1834
+ this._onFocus = this._onFocus.bind(this);
1835
+ this._onBlur = this._onBlur.bind(this);
1836
+ this._onKeyUp = this._onKeyUp.bind(this);
1837
+ this._onKeyDown = this._onKeyDown.bind(this);
1838
+ this._onInput = this._onInput.bind(this);
1839
+ this._onClick = this._onClick.bind(this);
1840
+ this._onTouchMove = this._onTouchMove.bind(this);
1841
+ this._onTouchEnd = this._onTouchEnd.bind(this);
1842
+ this._onMouseDown = this._onMouseDown.bind(this);
1843
+ this._onMouseOver = this._onMouseOver.bind(this);
1844
+ this._onFormReset = this._onFormReset.bind(this);
1845
+ this._onSelectKey = this._onSelectKey.bind(this);
1846
+ this._onEnterKey = this._onEnterKey.bind(this);
1847
+ this._onEscapeKey = this._onEscapeKey.bind(this);
1848
+ this._onDirectionKey = this._onDirectionKey.bind(this);
1849
+ this._onDeleteKey = this._onDeleteKey.bind(this);
1850
+ // If element has already been initialised with Choices, fail silently
1851
+ if (this.passedElement.isActive) {
1852
+ if (!config.silent) {
1853
+ console.warn('Trying to initialise Choices on element already initialised', { element: element });
1854
+ }
1855
+ this.initialised = true;
1856
+ this.initialisedOK = false;
1857
+ return;
1858
+ }
1859
+ // Let's go
1860
+ this.init();
1861
+ // preserve the selected item list after setup for form reset
1862
+ this._initialItems = this._store.items.map(function (choice) { return choice.value; });
1863
+ }
1864
+ Object.defineProperty(Choices, "defaults", {
1865
+ get: function () {
1866
+ return Object.preventExtensions({
1867
+ get options() {
1868
+ return USER_DEFAULTS;
1869
+ },
1870
+ get allOptions() {
1871
+ return DEFAULT_CONFIG;
1872
+ },
1873
+ get templates() {
1874
+ return templates;
1875
+ },
1876
+ });
1877
+ },
1878
+ enumerable: false,
1879
+ configurable: true
1880
+ });
1881
+ Choices.prototype.init = function () {
1882
+ if (this.initialised || this.initialisedOK !== undefined) {
1883
+ return;
1884
+ }
1885
+ this._searcher = getSearcher(this.config);
1886
+ this._loadChoices();
1887
+ this._createTemplates();
1888
+ this._createElements();
1889
+ this._createStructure();
1890
+ if ((this._isTextElement && !this.config.addItems) ||
1891
+ this.passedElement.element.hasAttribute('disabled') ||
1892
+ !!this.passedElement.element.closest('fieldset:disabled')) {
1893
+ this.disable();
1894
+ }
1895
+ else {
1896
+ this.enable();
1897
+ this._addEventListeners();
1898
+ }
1899
+ // should be triggered **after** disabled state to avoid additional re-draws
1900
+ this._initStore();
1901
+ this.initialised = true;
1902
+ this.initialisedOK = true;
1903
+ var callbackOnInit = this.config.callbackOnInit;
1904
+ // Run callback if it is a function
1905
+ if (typeof callbackOnInit === 'function') {
1906
+ callbackOnInit.call(this);
1907
+ }
1908
+ };
1909
+ Choices.prototype.destroy = function () {
1910
+ if (!this.initialised) {
1911
+ return;
1912
+ }
1913
+ this._removeEventListeners();
1914
+ this.passedElement.reveal();
1915
+ this.containerOuter.unwrap(this.passedElement.element);
1916
+ this._store._listeners = []; // prevents select/input value being wiped
1917
+ this.clearStore(false);
1918
+ this._stopSearch();
1919
+ this._templates = Choices.defaults.templates;
1920
+ this.initialised = false;
1921
+ this.initialisedOK = undefined;
1922
+ };
1923
+ Choices.prototype.enable = function () {
1924
+ if (this.passedElement.isDisabled) {
1925
+ this.passedElement.enable();
1926
+ }
1927
+ if (this.containerOuter.isDisabled) {
1928
+ this._addEventListeners();
1929
+ this.input.enable();
1930
+ this.containerOuter.enable();
1931
+ }
1932
+ return this;
1933
+ };
1934
+ Choices.prototype.disable = function () {
1935
+ if (!this.passedElement.isDisabled) {
1936
+ this.passedElement.disable();
1937
+ }
1938
+ if (!this.containerOuter.isDisabled) {
1939
+ this._removeEventListeners();
1940
+ this.input.disable();
1941
+ this.containerOuter.disable();
1942
+ }
1943
+ return this;
1944
+ };
1945
+ Choices.prototype.highlightItem = function (item, runEvent) {
1946
+ if (runEvent === void 0) { runEvent = true; }
1947
+ if (!item || !item.id) {
1948
+ return this;
1949
+ }
1950
+ var choice = this._store.items.find(function (c) { return c.id === item.id; });
1951
+ if (!choice || choice.highlighted) {
1952
+ return this;
1953
+ }
1954
+ this._store.dispatch(highlightItem(choice, true));
1955
+ if (runEvent) {
1956
+ this.passedElement.triggerEvent(EventType.highlightItem, this._getChoiceForOutput(choice));
1957
+ }
1958
+ return this;
1959
+ };
1960
+ Choices.prototype.unhighlightItem = function (item, runEvent) {
1961
+ if (runEvent === void 0) { runEvent = true; }
1962
+ if (!item || !item.id) {
1963
+ return this;
1964
+ }
1965
+ var choice = this._store.items.find(function (c) { return c.id === item.id; });
1966
+ if (!choice || !choice.highlighted) {
1967
+ return this;
1968
+ }
1969
+ this._store.dispatch(highlightItem(choice, false));
1970
+ if (runEvent) {
1971
+ this.passedElement.triggerEvent(EventType.unhighlightItem, this._getChoiceForOutput(choice));
1972
+ }
1973
+ return this;
1974
+ };
1975
+ Choices.prototype.highlightAll = function () {
1976
+ var _this = this;
1977
+ this._store.withTxn(function () {
1978
+ _this._store.items.forEach(function (item) {
1979
+ if (!item.highlighted) {
1980
+ _this._store.dispatch(highlightItem(item, true));
1981
+ _this.passedElement.triggerEvent(EventType.highlightItem, _this._getChoiceForOutput(item));
1982
+ }
1983
+ });
1984
+ });
1985
+ return this;
1986
+ };
1987
+ Choices.prototype.unhighlightAll = function () {
1988
+ var _this = this;
1989
+ this._store.withTxn(function () {
1990
+ _this._store.items.forEach(function (item) {
1991
+ if (item.highlighted) {
1992
+ _this._store.dispatch(highlightItem(item, false));
1993
+ _this.passedElement.triggerEvent(EventType.highlightItem, _this._getChoiceForOutput(item));
1994
+ }
1995
+ });
1996
+ });
1997
+ return this;
1998
+ };
1999
+ Choices.prototype.removeActiveItemsByValue = function (value) {
2000
+ var _this = this;
2001
+ this._store.withTxn(function () {
2002
+ _this._store.items.filter(function (item) { return item.value === value; }).forEach(function (item) { return _this._removeItem(item); });
2003
+ });
2004
+ return this;
2005
+ };
2006
+ Choices.prototype.removeActiveItems = function (excludedId) {
2007
+ var _this = this;
2008
+ this._store.withTxn(function () {
2009
+ _this._store.items.filter(function (_a) {
2010
+ var id = _a.id;
2011
+ return id !== excludedId;
2012
+ }).forEach(function (item) { return _this._removeItem(item); });
2013
+ });
2014
+ return this;
2015
+ };
2016
+ Choices.prototype.removeHighlightedItems = function (runEvent) {
2017
+ var _this = this;
2018
+ if (runEvent === void 0) { runEvent = false; }
2019
+ this._store.withTxn(function () {
2020
+ _this._store.highlightedActiveItems.forEach(function (item) {
2021
+ _this._removeItem(item);
2022
+ // If this action was performed by the user
2023
+ // trigger the event
2024
+ if (runEvent) {
2025
+ _this._triggerChange(item.value);
2026
+ }
2027
+ });
2028
+ });
2029
+ return this;
2030
+ };
2031
+ Choices.prototype.showDropdown = function (preventInputFocus) {
2032
+ var _this = this;
2033
+ if (this.dropdown.isActive) {
2034
+ return this;
2035
+ }
2036
+ if (preventInputFocus === undefined) {
2037
+ // eslint-disable-next-line no-param-reassign
2038
+ preventInputFocus = !this._canSearch;
2039
+ }
2040
+ requestAnimationFrame(function () {
2041
+ _this.dropdown.show();
2042
+ var rect = _this.dropdown.element.getBoundingClientRect();
2043
+ _this.containerOuter.open(rect.bottom, rect.height);
2044
+ if (!preventInputFocus) {
2045
+ _this.input.focus();
2046
+ }
2047
+ _this.passedElement.triggerEvent(EventType.showDropdown);
2048
+ });
2049
+ return this;
2050
+ };
2051
+ Choices.prototype.hideDropdown = function (preventInputBlur) {
2052
+ var _this = this;
2053
+ if (!this.dropdown.isActive) {
2054
+ return this;
2055
+ }
2056
+ requestAnimationFrame(function () {
2057
+ _this.dropdown.hide();
2058
+ _this.containerOuter.close();
2059
+ if (!preventInputBlur && _this._canSearch) {
2060
+ _this.input.removeActiveDescendant();
2061
+ _this.input.blur();
2062
+ }
2063
+ _this.passedElement.triggerEvent(EventType.hideDropdown);
2064
+ });
2065
+ return this;
2066
+ };
2067
+ Choices.prototype.getValue = function (valueOnly) {
2068
+ var _this = this;
2069
+ var values = this._store.items.map(function (item) {
2070
+ return (valueOnly ? item.value : _this._getChoiceForOutput(item));
2071
+ });
2072
+ return this._isSelectOneElement || this.config.singleModeForMultiSelect ? values[0] : values;
2073
+ };
2074
+ Choices.prototype.setValue = function (items) {
2075
+ var _this = this;
2076
+ if (!this.initialisedOK) {
2077
+ this._warnChoicesInitFailed('setValue');
2078
+ return this;
2079
+ }
2080
+ this._store.withTxn(function () {
2081
+ items.forEach(function (value) {
2082
+ if (value) {
2083
+ _this._addChoice(mapInputToChoice(value, false));
2084
+ }
2085
+ });
2086
+ });
2087
+ // @todo integrate with Store
2088
+ this._searcher.reset();
2089
+ return this;
2090
+ };
2091
+ Choices.prototype.setChoiceByValue = function (value) {
2092
+ var _this = this;
2093
+ if (!this.initialisedOK) {
2094
+ this._warnChoicesInitFailed('setChoiceByValue');
2095
+ return this;
2096
+ }
2097
+ if (this._isTextElement) {
2098
+ return this;
2099
+ }
2100
+ this._store.withTxn(function () {
2101
+ // If only one value has been passed, convert to array
2102
+ var choiceValue = Array.isArray(value) ? value : [value];
2103
+ // Loop through each value and
2104
+ choiceValue.forEach(function (val) { return _this._findAndSelectChoiceByValue(val); });
2105
+ _this.unhighlightAll();
2106
+ });
2107
+ // @todo integrate with Store
2108
+ this._searcher.reset();
2109
+ return this;
2110
+ };
2111
+ /**
2112
+ * Set choices of select input via an array of objects (or function that returns array of object or promise of it),
2113
+ * a value field name and a label field name.
2114
+ * This behaves the same as passing items via the choices option but can be called after initialising Choices.
2115
+ * This can also be used to add groups of choices (see example 2); Optionally pass a true `replaceChoices` value to remove any existing choices.
2116
+ * Optionally pass a `customProperties` object to add additional data to your choices (useful when searching/filtering etc).
2117
+ *
2118
+ * **Input types affected:** select-one, select-multiple
2119
+ *
2120
+ * @example
2121
+ * ```js
2122
+ * const example = new Choices(element);
2123
+ *
2124
+ * example.setChoices([
2125
+ * {value: 'One', label: 'Label One', disabled: true},
2126
+ * {value: 'Two', label: 'Label Two', selected: true},
2127
+ * {value: 'Three', label: 'Label Three'},
2128
+ * ], 'value', 'label', false);
2129
+ * ```
2130
+ *
2131
+ * @example
2132
+ * ```js
2133
+ * const example = new Choices(element);
2134
+ *
2135
+ * example.setChoices(async () => {
2136
+ * try {
2137
+ * const items = await fetch('/items');
2138
+ * return items.json()
2139
+ * } catch(err) {
2140
+ * console.error(err)
2141
+ * }
2142
+ * });
2143
+ * ```
2144
+ *
2145
+ * @example
2146
+ * ```js
2147
+ * const example = new Choices(element);
2148
+ *
2149
+ * example.setChoices([{
2150
+ * label: 'Group one',
2151
+ * id: 1,
2152
+ * disabled: false,
2153
+ * choices: [
2154
+ * {value: 'Child One', label: 'Child One', selected: true},
2155
+ * {value: 'Child Two', label: 'Child Two', disabled: true},
2156
+ * {value: 'Child Three', label: 'Child Three'},
2157
+ * ]
2158
+ * },
2159
+ * {
2160
+ * label: 'Group two',
2161
+ * id: 2,
2162
+ * disabled: false,
2163
+ * choices: [
2164
+ * {value: 'Child Four', label: 'Child Four', disabled: true},
2165
+ * {value: 'Child Five', label: 'Child Five'},
2166
+ * {value: 'Child Six', label: 'Child Six', customProperties: {
2167
+ * description: 'Custom description about child six',
2168
+ * random: 'Another random custom property'
2169
+ * }},
2170
+ * ]
2171
+ * }], 'value', 'label', false);
2172
+ * ```
2173
+ */
2174
+ Choices.prototype.setChoices = function (choicesArrayOrFetcher, value, label, replaceChoices, clearSearchFlag, replaceItems) {
2175
+ var _this = this;
2176
+ if (choicesArrayOrFetcher === void 0) { choicesArrayOrFetcher = []; }
2177
+ if (value === void 0) { value = 'value'; }
2178
+ if (label === void 0) { label = 'label'; }
2179
+ if (replaceChoices === void 0) { replaceChoices = false; }
2180
+ if (clearSearchFlag === void 0) { clearSearchFlag = true; }
2181
+ if (replaceItems === void 0) { replaceItems = false; }
2182
+ if (!this.initialisedOK) {
2183
+ this._warnChoicesInitFailed('setChoices');
2184
+ return this;
2185
+ }
2186
+ if (!this._isSelectElement) {
2187
+ throw new TypeError("setChoices can't be used with INPUT based Choices");
2188
+ }
2189
+ if (typeof value !== 'string' || !value) {
2190
+ throw new TypeError("value parameter must be a name of 'value' field in passed objects");
2191
+ }
2192
+ if (typeof choicesArrayOrFetcher === 'function') {
2193
+ // it's a choices fetcher function
2194
+ var fetcher_1 = choicesArrayOrFetcher(this);
2195
+ if (typeof Promise === 'function' && fetcher_1 instanceof Promise) {
2196
+ // that's a promise
2197
+ // eslint-disable-next-line no-promise-executor-return
2198
+ return new Promise(function (resolve) { return requestAnimationFrame(resolve); })
2199
+ .then(function () { return _this._handleLoadingState(true); })
2200
+ .then(function () { return fetcher_1; })
2201
+ .then(function (data) {
2202
+ return _this.setChoices(data, value, label, replaceChoices, clearSearchFlag, replaceItems);
2203
+ })
2204
+ .catch(function (err) {
2205
+ if (!_this.config.silent) {
2206
+ console.error(err);
2207
+ }
2208
+ })
2209
+ .then(function () { return _this._handleLoadingState(false); })
2210
+ .then(function () { return _this; });
2211
+ }
2212
+ // function returned something else than promise, let's check if it's an array of choices
2213
+ if (!Array.isArray(fetcher_1)) {
2214
+ throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: ".concat(typeof fetcher_1));
2215
+ }
2216
+ // recursion with results, it's sync and choices were cleared already
2217
+ return this.setChoices(fetcher_1, value, label, false);
2218
+ }
2219
+ if (!Array.isArray(choicesArrayOrFetcher)) {
2220
+ throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");
2221
+ }
2222
+ this.containerOuter.removeLoadingState();
2223
+ this._store.withTxn(function () {
2224
+ if (clearSearchFlag) {
2225
+ _this._isSearching = false;
2226
+ }
2227
+ // Clear choices if needed
2228
+ if (replaceChoices) {
2229
+ _this.clearChoices(true, replaceItems);
2230
+ }
2231
+ var isDefaultValue = value === 'value';
2232
+ var isDefaultLabel = label === 'label';
2233
+ choicesArrayOrFetcher.forEach(function (groupOrChoice) {
2234
+ if ('choices' in groupOrChoice) {
2235
+ var group = groupOrChoice;
2236
+ if (!isDefaultLabel) {
2237
+ group = __assign(__assign({}, group), { label: group[label] });
2238
+ }
2239
+ _this._addGroup(mapInputToChoice(group, true));
2240
+ }
2241
+ else {
2242
+ var choice = groupOrChoice;
2243
+ if (!isDefaultLabel || !isDefaultValue) {
2244
+ choice = __assign(__assign({}, choice), { value: choice[value], label: choice[label] });
2245
+ }
2246
+ var choiceFull = mapInputToChoice(choice, false);
2247
+ _this._addChoice(choiceFull);
2248
+ if (choiceFull.placeholder && !_this._hasNonChoicePlaceholder) {
2249
+ _this._placeholderValue = unwrapStringForEscaped(choiceFull.label);
2250
+ }
2251
+ }
2252
+ });
2253
+ _this.unhighlightAll();
2254
+ });
2255
+ // @todo integrate with Store
2256
+ this._searcher.reset();
2257
+ return this;
2258
+ };
2259
+ Choices.prototype.refresh = function (withEvents, selectFirstOption, deselectAll) {
2260
+ var _this = this;
2261
+ if (withEvents === void 0) { withEvents = false; }
2262
+ if (selectFirstOption === void 0) { selectFirstOption = false; }
2263
+ if (deselectAll === void 0) { deselectAll = false; }
2264
+ if (!this._isSelectElement) {
2265
+ if (!this.config.silent) {
2266
+ console.warn('refresh method can only be used on choices backed by a <select> element');
2267
+ }
2268
+ return this;
2269
+ }
2270
+ this._store.withTxn(function () {
2271
+ var choicesFromOptions = _this.passedElement.optionsAsChoices();
2272
+ // Build the list of items which require preserving
2273
+ var existingItems = {};
2274
+ if (!deselectAll) {
2275
+ _this._store.items.forEach(function (choice) {
2276
+ if (choice.id && choice.active && choice.selected) {
2277
+ existingItems[choice.value] = true;
2278
+ }
2279
+ });
2280
+ }
2281
+ _this.clearStore(false);
2282
+ var updateChoice = function (choice) {
2283
+ if (deselectAll) {
2284
+ _this._store.dispatch(removeItem$1(choice));
2285
+ }
2286
+ else if (existingItems[choice.value]) {
2287
+ choice.selected = true;
2288
+ }
2289
+ };
2290
+ choicesFromOptions.forEach(function (groupOrChoice) {
2291
+ if ('choices' in groupOrChoice) {
2292
+ groupOrChoice.choices.forEach(updateChoice);
2293
+ return;
2294
+ }
2295
+ updateChoice(groupOrChoice);
2296
+ });
2297
+ /* @todo only generate add events for the added options instead of all
2298
+ if (withEvents) {
2299
+ items.forEach((choice) => {
2300
+ if (existingItems[choice.value]) {
2301
+ this.passedElement.triggerEvent(
2302
+ EventType.removeItem,
2303
+ this._getChoiceForEvent(choice),
2304
+ );
2305
+ }
2306
+ });
2307
+ }
2308
+ */
2309
+ // load new choices & items
2310
+ _this._addPredefinedChoices(choicesFromOptions, selectFirstOption, withEvents);
2311
+ // re-do search if required
2312
+ if (_this._isSearching) {
2313
+ _this._searchChoices(_this.input.value);
2314
+ }
2315
+ });
2316
+ return this;
2317
+ };
2318
+ Choices.prototype.removeChoice = function (value) {
2319
+ var choice = this._store.choices.find(function (c) { return c.value === value; });
2320
+ if (!choice) {
2321
+ return this;
2322
+ }
2323
+ this._clearNotice();
2324
+ this._store.dispatch(removeChoice(choice));
2325
+ // @todo integrate with Store
2326
+ this._searcher.reset();
2327
+ if (choice.selected) {
2328
+ this.passedElement.triggerEvent(EventType.removeItem, this._getChoiceForOutput(choice));
2329
+ }
2330
+ return this;
2331
+ };
2332
+ Choices.prototype.clearChoices = function (clearOptions, clearItems) {
2333
+ var _this = this;
2334
+ if (clearOptions === void 0) { clearOptions = true; }
2335
+ if (clearItems === void 0) { clearItems = false; }
2336
+ if (clearOptions) {
2337
+ if (clearItems) {
2338
+ this.passedElement.element.replaceChildren('');
2339
+ }
2340
+ else {
2341
+ this.passedElement.element.querySelectorAll(':not([selected])').forEach(function (el) {
2342
+ el.remove();
2343
+ });
2344
+ }
2345
+ }
2346
+ this.itemList.element.replaceChildren('');
2347
+ this.choiceList.element.replaceChildren('');
2348
+ this._clearNotice();
2349
+ this._store.withTxn(function () {
2350
+ var items = clearItems ? [] : _this._store.items;
2351
+ _this._store.reset();
2352
+ items.forEach(function (item) {
2353
+ _this._store.dispatch(addChoice(item));
2354
+ _this._store.dispatch(addItem(item));
2355
+ });
2356
+ });
2357
+ // @todo integrate with Store
2358
+ this._searcher.reset();
2359
+ return this;
2360
+ };
2361
+ Choices.prototype.clearStore = function (clearOptions) {
2362
+ if (clearOptions === void 0) { clearOptions = true; }
2363
+ this.clearChoices(clearOptions, true);
2364
+ this._stopSearch();
2365
+ this._lastAddedChoiceId = 0;
2366
+ this._lastAddedGroupId = 0;
2367
+ return this;
2368
+ };
2369
+ Choices.prototype.clearInput = function () {
2370
+ var shouldSetInputWidth = !this._isSelectOneElement;
2371
+ this.input.clear(shouldSetInputWidth);
2372
+ this._stopSearch();
2373
+ return this;
2374
+ };
2375
+ Choices.prototype._validateConfig = function () {
2376
+ var config = this.config;
2377
+ var invalidConfigOptions = diff(config, DEFAULT_CONFIG);
2378
+ if (invalidConfigOptions.length) {
2379
+ console.warn('Unknown config option(s) passed', invalidConfigOptions.join(', '));
2380
+ }
2381
+ if (config.allowHTML && config.allowHtmlUserInput) {
2382
+ if (config.addItems) {
2383
+ console.warn('Warning: allowHTML/allowHtmlUserInput/addItems all being true is strongly not recommended and may lead to XSS attacks');
2384
+ }
2385
+ if (config.addChoices) {
2386
+ console.warn('Warning: allowHTML/allowHtmlUserInput/addChoices all being true is strongly not recommended and may lead to XSS attacks');
2387
+ }
2388
+ }
2389
+ };
2390
+ Choices.prototype._render = function (changes) {
2391
+ if (changes === void 0) { changes = { choices: true, groups: true, items: true }; }
2392
+ if (this._store.inTxn()) {
2393
+ return;
2394
+ }
2395
+ if (this._isSelectElement) {
2396
+ if (changes.choices || changes.groups) {
2397
+ this._renderChoices();
2398
+ }
2399
+ }
2400
+ if (changes.items) {
2401
+ this._renderItems();
2402
+ }
2403
+ };
2404
+ Choices.prototype._renderChoices = function () {
2405
+ var _this = this;
2406
+ if (!this._canAddItems()) {
2407
+ return; // block rendering choices if the input limit is reached.
2408
+ }
2409
+ var _a = this, config = _a.config, isSearching = _a._isSearching;
2410
+ var _b = this._store, activeGroups = _b.activeGroups, activeChoices = _b.activeChoices;
2411
+ var renderLimit = 0;
2412
+ if (isSearching && config.searchResultLimit > 0) {
2413
+ renderLimit = config.searchResultLimit;
2414
+ }
2415
+ else if (config.renderChoiceLimit > 0) {
2416
+ renderLimit = config.renderChoiceLimit;
2417
+ }
2418
+ if (this._isSelectElement) {
2419
+ var backingOptions = activeChoices.filter(function (choice) { return !choice.element; });
2420
+ if (backingOptions.length) {
2421
+ this.passedElement.addOptions(backingOptions);
2422
+ }
2423
+ }
2424
+ var fragment = document.createDocumentFragment();
2425
+ var renderableChoices = function (choices) {
2426
+ return choices.filter(function (choice) {
2427
+ return !choice.placeholder && (isSearching ? !!choice.rank : config.renderSelectedChoices || !choice.selected);
2428
+ });
2429
+ };
2430
+ var selectableChoices = false;
2431
+ var renderChoices = function (choices, withinGroup, groupLabel) {
2432
+ if (isSearching) {
2433
+ // sortByRank is used to ensure stable sorting, as scores are non-unique
2434
+ // this additionally ensures fuseOptions.sortFn is not ignored
2435
+ choices.sort(sortByRank);
2436
+ }
2437
+ else if (config.shouldSort) {
2438
+ choices.sort(config.sorter);
2439
+ }
2440
+ var choiceLimit = choices.length;
2441
+ choiceLimit = !withinGroup && renderLimit && choiceLimit > renderLimit ? renderLimit : choiceLimit;
2442
+ choiceLimit--;
2443
+ choices.every(function (choice, index) {
2444
+ // choiceEl being empty signals the contents has probably significantly changed
2445
+ var dropdownItem = choice.choiceEl || _this._templates.choice(config, choice, config.itemSelectText, groupLabel);
2446
+ choice.choiceEl = dropdownItem;
2447
+ fragment.appendChild(dropdownItem);
2448
+ if (isSearching || !choice.selected) {
2449
+ selectableChoices = true;
2450
+ }
2451
+ return index < choiceLimit;
2452
+ });
2453
+ };
2454
+ if (activeChoices.length) {
2455
+ if (config.resetScrollPosition) {
2456
+ requestAnimationFrame(function () { return _this.choiceList.scrollToTop(); });
2457
+ }
2458
+ if (!this._hasNonChoicePlaceholder && !isSearching && this._isSelectOneElement) {
2459
+ // If we have a placeholder choice along with groups
2460
+ renderChoices(activeChoices.filter(function (choice) { return choice.placeholder && !choice.group; }), false, undefined);
2461
+ }
2462
+ // If we have grouped options
2463
+ if (activeGroups.length && !isSearching) {
2464
+ if (config.shouldSort) {
2465
+ activeGroups.sort(config.sorter);
2466
+ }
2467
+ // render Choices without group first, regardless of sort, otherwise they won't be distinguishable
2468
+ // from the last group
2469
+ renderChoices(activeChoices.filter(function (choice) { return !choice.placeholder && !choice.group; }), false, undefined);
2470
+ activeGroups.forEach(function (group) {
2471
+ var groupChoices = renderableChoices(group.choices);
2472
+ if (groupChoices.length) {
2473
+ if (group.label) {
2474
+ var dropdownGroup = group.groupEl || _this._templates.choiceGroup(_this.config, group);
2475
+ group.groupEl = dropdownGroup;
2476
+ dropdownGroup.remove();
2477
+ fragment.appendChild(dropdownGroup);
2478
+ }
2479
+ renderChoices(groupChoices, true, config.appendGroupInSearch && isSearching ? group.label : undefined);
2480
+ }
2481
+ });
2482
+ }
2483
+ else {
2484
+ renderChoices(renderableChoices(activeChoices), false, undefined);
2485
+ }
2486
+ }
2487
+ if (!selectableChoices && (isSearching || !fragment.children.length || !config.renderSelectedChoices)) {
2488
+ if (!this._notice) {
2489
+ this._notice = {
2490
+ text: resolveStringFunction(isSearching ? config.noResultsText : config.noChoicesText),
2491
+ type: isSearching ? NoticeTypes.noResults : NoticeTypes.noChoices,
2492
+ };
2493
+ }
2494
+ fragment.replaceChildren('');
2495
+ }
2496
+ this._renderNotice(fragment);
2497
+ this.choiceList.element.replaceChildren(fragment);
2498
+ if (selectableChoices) {
2499
+ this._highlightChoice();
2500
+ }
2501
+ };
2502
+ Choices.prototype._renderItems = function () {
2503
+ var _this = this;
2504
+ var items = this._store.items || [];
2505
+ var itemList = this.itemList.element;
2506
+ var config = this.config;
2507
+ var fragment = document.createDocumentFragment();
2508
+ var itemFromList = function (item) {
2509
+ return itemList.querySelector("[data-item][data-id=\"".concat(item.id, "\"]"));
2510
+ };
2511
+ var addItemToFragment = function (item) {
2512
+ var el = item.itemEl;
2513
+ if (el && el.parentElement) {
2514
+ return;
2515
+ }
2516
+ el = itemFromList(item) || _this._templates.item(config, item, config.removeItemButton);
2517
+ item.itemEl = el;
2518
+ fragment.appendChild(el);
2519
+ };
2520
+ // new items
2521
+ items.forEach(addItemToFragment);
2522
+ var addedItems = !!fragment.childNodes.length;
2523
+ if (this._isSelectOneElement) {
2524
+ var existingItems = itemList.children.length;
2525
+ if (addedItems || existingItems > 1) {
2526
+ var placeholder = itemList.querySelector(getClassNamesSelector(config.classNames.placeholder));
2527
+ if (placeholder) {
2528
+ placeholder.remove();
2529
+ }
2530
+ }
2531
+ else if (!addedItems && !existingItems && this._placeholderValue) {
2532
+ addedItems = true;
2533
+ addItemToFragment(mapInputToChoice({
2534
+ selected: true,
2535
+ value: '',
2536
+ label: this._placeholderValue,
2537
+ placeholder: true,
2538
+ }, false));
2539
+ }
2540
+ }
2541
+ if (addedItems) {
2542
+ itemList.append(fragment);
2543
+ if (config.shouldSortItems && !this._isSelectOneElement) {
2544
+ items.sort(config.sorter);
2545
+ // push sorting into the DOM
2546
+ items.forEach(function (item) {
2547
+ var el = itemFromList(item);
2548
+ if (el) {
2549
+ el.remove();
2550
+ fragment.append(el);
2551
+ }
2552
+ });
2553
+ itemList.append(fragment);
2554
+ }
2555
+ }
2556
+ if (this._isTextElement) {
2557
+ // Update the value of the hidden input
2558
+ this.passedElement.value = items.map(function (_a) {
2559
+ var value = _a.value;
2560
+ return value;
2561
+ }).join(config.delimiter);
2562
+ }
2563
+ };
2564
+ Choices.prototype._displayNotice = function (text, type, openDropdown) {
2565
+ if (openDropdown === void 0) { openDropdown = true; }
2566
+ var oldNotice = this._notice;
2567
+ if (oldNotice &&
2568
+ ((oldNotice.type === type && oldNotice.text === text) ||
2569
+ (oldNotice.type === NoticeTypes.addChoice &&
2570
+ (type === NoticeTypes.noResults || type === NoticeTypes.noChoices)))) {
2571
+ if (openDropdown) {
2572
+ this.showDropdown(true);
2573
+ }
2574
+ return;
2575
+ }
2576
+ this._clearNotice();
2577
+ this._notice = text
2578
+ ? {
2579
+ text: text,
2580
+ type: type,
2581
+ }
2582
+ : undefined;
2583
+ this._renderNotice();
2584
+ if (openDropdown && text) {
2585
+ this.showDropdown(true);
2586
+ }
2587
+ };
2588
+ Choices.prototype._clearNotice = function () {
2589
+ if (!this._notice) {
2590
+ return;
2591
+ }
2592
+ var noticeElement = this.choiceList.element.querySelector(getClassNamesSelector(this.config.classNames.notice));
2593
+ if (noticeElement) {
2594
+ noticeElement.remove();
2595
+ }
2596
+ this._notice = undefined;
2597
+ };
2598
+ Choices.prototype._renderNotice = function (fragment) {
2599
+ var noticeConf = this._notice;
2600
+ if (noticeConf) {
2601
+ var notice = this._templates.notice(this.config, noticeConf.text, noticeConf.type);
2602
+ if (fragment) {
2603
+ fragment.append(notice);
2604
+ }
2605
+ else {
2606
+ this.choiceList.prepend(notice);
2607
+ }
2608
+ }
2609
+ };
2610
+ // eslint-disable-next-line class-methods-use-this
2611
+ Choices.prototype._getChoiceForOutput = function (choice, keyCode) {
2612
+ return {
2613
+ id: choice.id,
2614
+ highlighted: choice.highlighted,
2615
+ labelClass: choice.labelClass,
2616
+ labelDescription: choice.labelDescription,
2617
+ customProperties: choice.customProperties,
2618
+ disabled: choice.disabled,
2619
+ active: choice.active,
2620
+ label: choice.label,
2621
+ placeholder: choice.placeholder,
2622
+ value: choice.value,
2623
+ groupValue: choice.group ? choice.group.label : undefined,
2624
+ element: choice.element,
2625
+ keyCode: keyCode,
2626
+ };
2627
+ };
2628
+ Choices.prototype._triggerChange = function (value) {
2629
+ if (value === undefined || value === null) {
2630
+ return;
2631
+ }
2632
+ this.passedElement.triggerEvent(EventType.change, {
2633
+ value: value,
2634
+ });
2635
+ };
2636
+ Choices.prototype._handleButtonAction = function (element) {
2637
+ var _this = this;
2638
+ var items = this._store.items;
2639
+ if (!items.length || !this.config.removeItems || !this.config.removeItemButton) {
2640
+ return;
2641
+ }
2642
+ var id = element && parseDataSetId(element.parentElement);
2643
+ var itemToRemove = id && items.find(function (item) { return item.id === id; });
2644
+ if (!itemToRemove) {
2645
+ return;
2646
+ }
2647
+ this._store.withTxn(function () {
2648
+ // Remove item associated with button
2649
+ _this._removeItem(itemToRemove);
2650
+ _this._triggerChange(itemToRemove.value);
2651
+ if (_this._isSelectOneElement && !_this._hasNonChoicePlaceholder) {
2652
+ var placeholderChoice = (_this.config.shouldSort ? _this._store.choices.reverse() : _this._store.choices).find(function (choice) { return choice.placeholder; });
2653
+ if (placeholderChoice) {
2654
+ _this._addItem(placeholderChoice);
2655
+ _this.unhighlightAll();
2656
+ if (placeholderChoice.value) {
2657
+ _this._triggerChange(placeholderChoice.value);
2658
+ }
2659
+ }
2660
+ }
2661
+ });
2662
+ };
2663
+ Choices.prototype._handleItemAction = function (element, hasShiftKey) {
2664
+ var _this = this;
2665
+ if (hasShiftKey === void 0) { hasShiftKey = false; }
2666
+ var items = this._store.items;
2667
+ if (!items.length || !this.config.removeItems || this._isSelectOneElement) {
2668
+ return;
2669
+ }
2670
+ var id = parseDataSetId(element);
2671
+ if (!id) {
2672
+ return;
2673
+ }
2674
+ // We only want to select one item with a click
2675
+ // so we deselect any items that aren't the target
2676
+ // unless shift is being pressed
2677
+ items.forEach(function (item) {
2678
+ if (item.id === id && !item.highlighted) {
2679
+ _this.highlightItem(item);
2680
+ }
2681
+ else if (!hasShiftKey && item.highlighted) {
2682
+ _this.unhighlightItem(item);
2683
+ }
2684
+ });
2685
+ // Focus input as without focus, a user cannot do anything with a
2686
+ // highlighted item
2687
+ this.input.focus();
2688
+ };
2689
+ Choices.prototype._handleChoiceAction = function (element) {
2690
+ var _this = this;
2691
+ // If we are clicking on an option
2692
+ var id = parseDataSetId(element);
2693
+ var choice = id && this._store.getChoiceById(id);
2694
+ if (!choice || choice.disabled) {
2695
+ return false;
2696
+ }
2697
+ var hasActiveDropdown = this.dropdown.isActive;
2698
+ if (!choice.selected) {
2699
+ if (!this._canAddItems()) {
2700
+ return true; // causes _onEnterKey to early out
2701
+ }
2702
+ this._store.withTxn(function () {
2703
+ _this._addItem(choice, true, true);
2704
+ _this.clearInput();
2705
+ _this.unhighlightAll();
2706
+ });
2707
+ this._triggerChange(choice.value);
2708
+ }
2709
+ // We want to close the dropdown if we are dealing with a single select box
2710
+ if (hasActiveDropdown && this.config.closeDropdownOnSelect) {
2711
+ this.hideDropdown(true);
2712
+ this.containerOuter.element.focus();
2713
+ }
2714
+ return true;
2715
+ };
2716
+ Choices.prototype._handleBackspace = function (items) {
2717
+ var config = this.config;
2718
+ if (!config.removeItems || !items.length) {
2719
+ return;
2720
+ }
2721
+ var lastItem = items[items.length - 1];
2722
+ var hasHighlightedItems = items.some(function (item) { return item.highlighted; });
2723
+ // If editing the last item is allowed and there are not other selected items,
2724
+ // we can edit the item value. Otherwise if we can remove items, remove all selected items
2725
+ if (config.editItems && !hasHighlightedItems && lastItem) {
2726
+ this.input.value = lastItem.value;
2727
+ this.input.setWidth();
2728
+ this._removeItem(lastItem);
2729
+ this._triggerChange(lastItem.value);
2730
+ }
2731
+ else {
2732
+ if (!hasHighlightedItems) {
2733
+ // Highlight last item if none already highlighted
2734
+ this.highlightItem(lastItem, false);
2735
+ }
2736
+ this.removeHighlightedItems(true);
2737
+ }
2738
+ };
2739
+ Choices.prototype._loadChoices = function () {
2740
+ var _a;
2741
+ var _this = this;
2742
+ var config = this.config;
2743
+ if (this._isTextElement) {
2744
+ // Assign preset items from passed object first
2745
+ this._presetChoices = config.items.map(function (e) { return mapInputToChoice(e, false); });
2746
+ // Add any values passed from attribute
2747
+ if (this.passedElement.value) {
2748
+ var elementItems = this.passedElement.value
2749
+ .split(config.delimiter)
2750
+ .map(function (e) { return mapInputToChoice(e, false, _this.config.allowHtmlUserInput); });
2751
+ this._presetChoices = this._presetChoices.concat(elementItems);
2752
+ }
2753
+ this._presetChoices.forEach(function (choice) {
2754
+ choice.selected = true;
2755
+ });
2756
+ }
2757
+ else if (this._isSelectElement) {
2758
+ // Assign preset choices from passed object
2759
+ this._presetChoices = config.choices.map(function (e) { return mapInputToChoice(e, true); });
2760
+ // Create array of choices from option elements
2761
+ var choicesFromOptions = this.passedElement.optionsAsChoices();
2762
+ if (choicesFromOptions) {
2763
+ (_a = this._presetChoices).push.apply(_a, choicesFromOptions);
2764
+ }
2765
+ }
2766
+ };
2767
+ Choices.prototype._handleLoadingState = function (setLoading) {
2768
+ if (setLoading === void 0) { setLoading = true; }
2769
+ var el = this.itemList.element;
2770
+ if (setLoading) {
2771
+ this.disable();
2772
+ this.containerOuter.addLoadingState();
2773
+ if (this._isSelectOneElement) {
2774
+ el.replaceChildren(this._templates.placeholder(this.config, this.config.loadingText));
2775
+ }
2776
+ else {
2777
+ this.input.placeholder = this.config.loadingText;
2778
+ }
2779
+ }
2780
+ else {
2781
+ this.enable();
2782
+ this.containerOuter.removeLoadingState();
2783
+ if (this._isSelectOneElement) {
2784
+ el.replaceChildren('');
2785
+ this._render();
2786
+ }
2787
+ else {
2788
+ this.input.placeholder = this._placeholderValue || '';
2789
+ }
2790
+ }
2791
+ };
2792
+ Choices.prototype._handleSearch = function (value) {
2793
+ if (!this.input.isFocussed) {
2794
+ return;
2795
+ }
2796
+ // Check that we have a value to search and the input was an alphanumeric character
2797
+ if (value !== null && typeof value !== 'undefined' && value.length >= this.config.searchFloor) {
2798
+ var resultCount = this.config.searchChoices ? this._searchChoices(value) : 0;
2799
+ if (resultCount !== null) {
2800
+ // Trigger search event
2801
+ this.passedElement.triggerEvent(EventType.search, {
2802
+ value: value,
2803
+ resultCount: resultCount,
2804
+ });
2805
+ }
2806
+ }
2807
+ else if (this._store.choices.some(function (option) { return !option.active; })) {
2808
+ this._stopSearch();
2809
+ }
2810
+ };
2811
+ Choices.prototype._canAddItems = function () {
2812
+ var config = this.config;
2813
+ var maxItemCount = config.maxItemCount, maxItemText = config.maxItemText;
2814
+ if (!config.singleModeForMultiSelect && maxItemCount > 0 && maxItemCount <= this._store.items.length) {
2815
+ this.choiceList.element.replaceChildren('');
2816
+ this._notice = undefined;
2817
+ this._displayNotice(typeof maxItemText === 'function' ? maxItemText(maxItemCount) : maxItemText, NoticeTypes.addChoice);
2818
+ return false;
2819
+ }
2820
+ if (this._notice && this._notice.type === NoticeTypes.addChoice) {
2821
+ this._clearNotice();
2822
+ }
2823
+ return true;
2824
+ };
2825
+ Choices.prototype._canCreateItem = function (value) {
2826
+ var config = this.config;
2827
+ var canAddItem = true;
2828
+ var notice = '';
2829
+ if (canAddItem && typeof config.addItemFilter === 'function' && !config.addItemFilter(value)) {
2830
+ canAddItem = false;
2831
+ notice = resolveNoticeFunction(config.customAddItemText, value);
2832
+ }
2833
+ if (canAddItem) {
2834
+ var foundChoice = this._store.choices.find(function (choice) { return config.valueComparer(choice.value, value); });
2835
+ if (foundChoice) {
2836
+ if (this._isSelectElement) {
2837
+ // for exact matches, do not prompt to add it as a custom choice
2838
+ this._displayNotice('', NoticeTypes.addChoice);
2839
+ return false;
2840
+ }
2841
+ if (!config.duplicateItemsAllowed) {
2842
+ canAddItem = false;
2843
+ notice = resolveNoticeFunction(config.uniqueItemText, value);
2844
+ }
2845
+ }
2846
+ }
2847
+ if (canAddItem) {
2848
+ notice = resolveNoticeFunction(config.addItemText, value);
2849
+ }
2850
+ if (notice) {
2851
+ this._displayNotice(notice, NoticeTypes.addChoice);
2852
+ }
2853
+ return canAddItem;
2854
+ };
2855
+ Choices.prototype._searchChoices = function (value) {
2856
+ var newValue = value.trim().replace(/\s{2,}/, ' ');
2857
+ // signal input didn't change search
2858
+ if (!newValue.length || newValue === this._currentValue) {
2859
+ return null;
2860
+ }
2861
+ var searcher = this._searcher;
2862
+ if (searcher.isEmptyIndex()) {
2863
+ searcher.index(this._store.searchableChoices);
2864
+ }
2865
+ // If new value matches the desired length and is not the same as the current value with a space
2866
+ var results = searcher.search(newValue);
2867
+ this._currentValue = newValue;
2868
+ this._highlightPosition = 0;
2869
+ this._isSearching = true;
2870
+ var notice = this._notice;
2871
+ var noticeType = notice && notice.type;
2872
+ if (noticeType !== NoticeTypes.addChoice) {
2873
+ if (!results.length) {
2874
+ this._displayNotice(resolveStringFunction(this.config.noResultsText), NoticeTypes.noResults);
2875
+ }
2876
+ else {
2877
+ this._clearNotice();
2878
+ }
2879
+ }
2880
+ this._store.dispatch(filterChoices(results));
2881
+ return results.length;
2882
+ };
2883
+ Choices.prototype._stopSearch = function () {
2884
+ if (this._isSearching) {
2885
+ this._currentValue = '';
2886
+ this._isSearching = false;
2887
+ this._clearNotice();
2888
+ this._store.dispatch(activateChoices(true));
2889
+ this.passedElement.triggerEvent(EventType.search, {
2890
+ value: '',
2891
+ resultCount: 0,
2892
+ });
2893
+ }
2894
+ };
2895
+ Choices.prototype._addEventListeners = function () {
2896
+ var documentElement = this._docRoot;
2897
+ var outerElement = this.containerOuter.element;
2898
+ var inputElement = this.input.element;
2899
+ // capture events - can cancel event processing or propagation
2900
+ documentElement.addEventListener('touchend', this._onTouchEnd, true);
2901
+ outerElement.addEventListener('keydown', this._onKeyDown, true);
2902
+ outerElement.addEventListener('mousedown', this._onMouseDown, true);
2903
+ // passive events - doesn't call `preventDefault` or `stopPropagation`
2904
+ documentElement.addEventListener('click', this._onClick, { passive: true });
2905
+ documentElement.addEventListener('touchmove', this._onTouchMove, {
2906
+ passive: true,
2907
+ });
2908
+ this.dropdown.element.addEventListener('mouseover', this._onMouseOver, {
2909
+ passive: true,
2910
+ });
2911
+ if (this._isSelectOneElement) {
2912
+ outerElement.addEventListener('focus', this._onFocus, {
2913
+ passive: true,
2914
+ });
2915
+ outerElement.addEventListener('blur', this._onBlur, {
2916
+ passive: true,
2917
+ });
2918
+ }
2919
+ inputElement.addEventListener('keyup', this._onKeyUp, {
2920
+ passive: true,
2921
+ });
2922
+ inputElement.addEventListener('input', this._onInput, {
2923
+ passive: true,
2924
+ });
2925
+ inputElement.addEventListener('focus', this._onFocus, {
2926
+ passive: true,
2927
+ });
2928
+ inputElement.addEventListener('blur', this._onBlur, {
2929
+ passive: true,
2930
+ });
2931
+ if (inputElement.form) {
2932
+ inputElement.form.addEventListener('reset', this._onFormReset, {
2933
+ passive: true,
2934
+ });
2935
+ }
2936
+ this.input.addEventListeners();
2937
+ };
2938
+ Choices.prototype._removeEventListeners = function () {
2939
+ var documentElement = this._docRoot;
2940
+ var outerElement = this.containerOuter.element;
2941
+ var inputElement = this.input.element;
2942
+ documentElement.removeEventListener('touchend', this._onTouchEnd, true);
2943
+ outerElement.removeEventListener('keydown', this._onKeyDown, true);
2944
+ outerElement.removeEventListener('mousedown', this._onMouseDown, true);
2945
+ documentElement.removeEventListener('click', this._onClick);
2946
+ documentElement.removeEventListener('touchmove', this._onTouchMove);
2947
+ this.dropdown.element.removeEventListener('mouseover', this._onMouseOver);
2948
+ if (this._isSelectOneElement) {
2949
+ outerElement.removeEventListener('focus', this._onFocus);
2950
+ outerElement.removeEventListener('blur', this._onBlur);
2951
+ }
2952
+ inputElement.removeEventListener('keyup', this._onKeyUp);
2953
+ inputElement.removeEventListener('input', this._onInput);
2954
+ inputElement.removeEventListener('focus', this._onFocus);
2955
+ inputElement.removeEventListener('blur', this._onBlur);
2956
+ if (inputElement.form) {
2957
+ inputElement.form.removeEventListener('reset', this._onFormReset);
2958
+ }
2959
+ this.input.removeEventListeners();
2960
+ };
2961
+ Choices.prototype._onKeyDown = function (event) {
2962
+ var keyCode = event.keyCode;
2963
+ var hasActiveDropdown = this.dropdown.isActive;
2964
+ /*
2965
+ See:
2966
+ https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
2967
+ https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values
2968
+ https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF - UTF-16 surrogate pairs
2969
+ https://stackoverflow.com/a/70866532 - "Unidentified" for mobile
2970
+ http://www.unicode.org/versions/Unicode5.2.0/ch16.pdf#G19635 - U+FFFF is reserved (Section 16.7)
2971
+
2972
+ Logic: when a key event is sent, `event.key` represents its printable value _or_ one
2973
+ of a large list of special values indicating meta keys/functionality. In addition,
2974
+ key events for compose functionality contain a value of `Dead` when mid-composition.
2975
+
2976
+ I can't quite verify it, but non-English IMEs may also be able to generate key codes
2977
+ for code points in the surrogate-pair range, which could potentially be seen as having
2978
+ key.length > 1. Since `Fn` is one of the special keys, we can't distinguish by that
2979
+ alone.
2980
+
2981
+ Here, key.length === 1 means we know for sure the input was printable and not a special
2982
+ `key` value. When the length is greater than 1, it could be either a printable surrogate
2983
+ pair or a special `key` value. We can tell the difference by checking if the _character
2984
+ code_ value (not code point!) is in the "surrogate pair" range or not.
2985
+
2986
+ We don't use .codePointAt because an invalid code point would return 65535, which wouldn't
2987
+ pass the >= 0x10000 check we would otherwise use.
2988
+
2989
+ > ...The Unicode Standard sets aside 66 noncharacter code points. The last two code points
2990
+ > of each plane are noncharacters: U+FFFE and U+FFFF on the BMP...
2991
+ */
2992
+ var wasPrintableChar = event.key.length === 1 ||
2993
+ (event.key.length === 2 && event.key.charCodeAt(0) >= 0xd800) ||
2994
+ event.key === 'Unidentified';
2995
+ /*
2996
+ We do not show the dropdown if focusing out with esc or navigating through input fields.
2997
+ An activated search can still be opened with any other key.
2998
+ */
2999
+ if (!this._isTextElement &&
3000
+ !hasActiveDropdown &&
3001
+ keyCode !== KeyCodeMap.ESC_KEY &&
3002
+ keyCode !== KeyCodeMap.TAB_KEY &&
3003
+ keyCode !== KeyCodeMap.SHIFT_KEY) {
3004
+ this.showDropdown();
3005
+ if (!this.input.isFocussed && wasPrintableChar) {
3006
+ /*
3007
+ We update the input value with the pressed key as
3008
+ the input was not focussed at the time of key press
3009
+ therefore does not have the value of the key.
3010
+ */
3011
+ this.input.value += event.key;
3012
+ // browsers interpret a space as pagedown
3013
+ if (event.key === ' ') {
3014
+ event.preventDefault();
3015
+ }
3016
+ }
3017
+ }
3018
+ switch (keyCode) {
3019
+ case KeyCodeMap.A_KEY:
3020
+ return this._onSelectKey(event, this.itemList.element.hasChildNodes());
3021
+ case KeyCodeMap.ENTER_KEY:
3022
+ return this._onEnterKey(event, hasActiveDropdown);
3023
+ case KeyCodeMap.ESC_KEY:
3024
+ return this._onEscapeKey(event, hasActiveDropdown);
3025
+ case KeyCodeMap.UP_KEY:
3026
+ case KeyCodeMap.PAGE_UP_KEY:
3027
+ case KeyCodeMap.DOWN_KEY:
3028
+ case KeyCodeMap.PAGE_DOWN_KEY:
3029
+ return this._onDirectionKey(event, hasActiveDropdown);
3030
+ case KeyCodeMap.DELETE_KEY:
3031
+ case KeyCodeMap.BACK_KEY:
3032
+ return this._onDeleteKey(event, this._store.items, this.input.isFocussed);
3033
+ }
3034
+ };
3035
+ Choices.prototype._onKeyUp = function ( /* event: KeyboardEvent */) {
3036
+ this._canSearch = this.config.searchEnabled;
3037
+ };
3038
+ Choices.prototype._onInput = function ( /* event: InputEvent */) {
3039
+ var value = this.input.value;
3040
+ if (!value) {
3041
+ if (this._isTextElement) {
3042
+ this.hideDropdown(true);
3043
+ }
3044
+ else {
3045
+ this._stopSearch();
3046
+ }
3047
+ return;
3048
+ }
3049
+ if (!this._canAddItems()) {
3050
+ return;
3051
+ }
3052
+ if (this._canSearch) {
3053
+ // do the search even if the entered text can not be added
3054
+ this._handleSearch(value);
3055
+ }
3056
+ if (!this._canAddUserChoices) {
3057
+ return;
3058
+ }
3059
+ // determine if a notice needs to be displayed for why a search result can't be added
3060
+ this._canCreateItem(value);
3061
+ if (this._isSelectElement) {
3062
+ this._highlightPosition = 0; // reset to select the notice and/or exact match
3063
+ this._highlightChoice();
3064
+ }
3065
+ };
3066
+ Choices.prototype._onSelectKey = function (event, hasItems) {
3067
+ // If CTRL + A or CMD + A have been pressed and there are items to select
3068
+ if ((event.ctrlKey || event.metaKey) && hasItems) {
3069
+ this._canSearch = false;
3070
+ var shouldHightlightAll = this.config.removeItems && !this.input.value && this.input.element === document.activeElement;
3071
+ if (shouldHightlightAll) {
3072
+ this.highlightAll();
3073
+ }
3074
+ }
3075
+ };
3076
+ Choices.prototype._onEnterKey = function (event, hasActiveDropdown) {
3077
+ var _this = this;
3078
+ var value = this.input.value;
3079
+ var target = event.target;
3080
+ event.preventDefault();
3081
+ if (target && target.hasAttribute('data-button')) {
3082
+ this._handleButtonAction(target);
3083
+ return;
3084
+ }
3085
+ if (!hasActiveDropdown) {
3086
+ if (this._isSelectElement || this._notice) {
3087
+ this.showDropdown();
3088
+ }
3089
+ return;
3090
+ }
3091
+ var highlightedChoice = this.dropdown.element.querySelector(getClassNamesSelector(this.config.classNames.highlightedState));
3092
+ if (highlightedChoice && this._handleChoiceAction(highlightedChoice)) {
3093
+ return;
3094
+ }
3095
+ if (!target || !value) {
3096
+ this.hideDropdown(true);
3097
+ return;
3098
+ }
3099
+ if (!this._canAddItems()) {
3100
+ return;
3101
+ }
3102
+ var addedItem = false;
3103
+ this._store.withTxn(function () {
3104
+ addedItem = _this._findAndSelectChoiceByValue(value, true);
3105
+ if (!addedItem) {
3106
+ if (!_this._canAddUserChoices) {
3107
+ return;
3108
+ }
3109
+ if (!_this._canCreateItem(value)) {
3110
+ return;
3111
+ }
3112
+ _this._addChoice(mapInputToChoice(value, false, _this.config.allowHtmlUserInput), true, true);
3113
+ addedItem = true;
3114
+ }
3115
+ _this.clearInput();
3116
+ _this.unhighlightAll();
3117
+ });
3118
+ if (!addedItem) {
3119
+ return;
3120
+ }
3121
+ this._triggerChange(value);
3122
+ if (this.config.closeDropdownOnSelect) {
3123
+ this.hideDropdown(true);
3124
+ }
3125
+ };
3126
+ Choices.prototype._onEscapeKey = function (event, hasActiveDropdown) {
3127
+ if (hasActiveDropdown) {
3128
+ event.stopPropagation();
3129
+ this.hideDropdown(true);
3130
+ this._stopSearch();
3131
+ this.containerOuter.element.focus();
3132
+ }
3133
+ };
3134
+ Choices.prototype._onDirectionKey = function (event, hasActiveDropdown) {
3135
+ var keyCode = event.keyCode;
3136
+ // If up or down key is pressed, traverse through options
3137
+ if (hasActiveDropdown || this._isSelectOneElement) {
3138
+ this.showDropdown();
3139
+ this._canSearch = false;
3140
+ var directionInt = keyCode === KeyCodeMap.DOWN_KEY || keyCode === KeyCodeMap.PAGE_DOWN_KEY ? 1 : -1;
3141
+ var skipKey = event.metaKey || keyCode === KeyCodeMap.PAGE_DOWN_KEY || keyCode === KeyCodeMap.PAGE_UP_KEY;
3142
+ var nextEl = void 0;
3143
+ if (skipKey) {
3144
+ if (directionInt > 0) {
3145
+ nextEl = this.dropdown.element.querySelector("".concat(selectableChoiceIdentifier, ":last-of-type"));
3146
+ }
3147
+ else {
3148
+ nextEl = this.dropdown.element.querySelector(selectableChoiceIdentifier);
3149
+ }
3150
+ }
3151
+ else {
3152
+ var currentEl = this.dropdown.element.querySelector(getClassNamesSelector(this.config.classNames.highlightedState));
3153
+ if (currentEl) {
3154
+ nextEl = getAdjacentEl(currentEl, selectableChoiceIdentifier, directionInt);
3155
+ }
3156
+ else {
3157
+ nextEl = this.dropdown.element.querySelector(selectableChoiceIdentifier);
3158
+ }
3159
+ }
3160
+ if (nextEl) {
3161
+ // We prevent default to stop the cursor moving
3162
+ // when pressing the arrow
3163
+ if (!isScrolledIntoView(nextEl, this.choiceList.element, directionInt)) {
3164
+ this.choiceList.scrollToChildElement(nextEl, directionInt);
3165
+ }
3166
+ this._highlightChoice(nextEl);
3167
+ }
3168
+ // Prevent default to maintain cursor position whilst
3169
+ // traversing dropdown options
3170
+ event.preventDefault();
3171
+ }
3172
+ };
3173
+ Choices.prototype._onDeleteKey = function (event, items, hasFocusedInput) {
3174
+ // If backspace or delete key is pressed and the input has no value
3175
+ if (!this._isSelectOneElement && !event.target.value && hasFocusedInput) {
3176
+ this._handleBackspace(items);
3177
+ event.preventDefault();
3178
+ }
3179
+ };
3180
+ Choices.prototype._onTouchMove = function () {
3181
+ if (this._wasTap) {
3182
+ this._wasTap = false;
3183
+ }
3184
+ };
3185
+ Choices.prototype._onTouchEnd = function (event) {
3186
+ var target = (event || event.touches[0]).target;
3187
+ var touchWasWithinContainer = this._wasTap && this.containerOuter.element.contains(target);
3188
+ if (touchWasWithinContainer) {
3189
+ var containerWasExactTarget = target === this.containerOuter.element || target === this.containerInner.element;
3190
+ if (containerWasExactTarget) {
3191
+ if (this._isTextElement) {
3192
+ this.input.focus();
3193
+ }
3194
+ else if (this._isSelectMultipleElement) {
3195
+ this.showDropdown();
3196
+ }
3197
+ }
3198
+ // Prevents focus event firing
3199
+ event.stopPropagation();
3200
+ }
3201
+ this._wasTap = true;
3202
+ };
3203
+ /**
3204
+ * Handles mousedown event in capture mode for containetOuter.element
3205
+ */
3206
+ Choices.prototype._onMouseDown = function (event) {
3207
+ var target = event.target;
3208
+ if (!(target instanceof HTMLElement)) {
3209
+ return;
3210
+ }
3211
+ // If we have our mouse down on the scrollbar and are on IE11...
3212
+ if (IS_IE11 && this.choiceList.element.contains(target)) {
3213
+ // check if click was on a scrollbar area
3214
+ var firstChoice = this.choiceList.element.firstElementChild;
3215
+ this._isScrollingOnIe =
3216
+ this._direction === 'ltr' ? event.offsetX >= firstChoice.offsetWidth : event.offsetX < firstChoice.offsetLeft;
3217
+ }
3218
+ if (target === this.input.element) {
3219
+ return;
3220
+ }
3221
+ var item = target.closest('[data-button],[data-item],[data-choice]');
3222
+ if (item instanceof HTMLElement) {
3223
+ if ('button' in item.dataset) {
3224
+ this._handleButtonAction(item);
3225
+ }
3226
+ else if ('item' in item.dataset) {
3227
+ this._handleItemAction(item, event.shiftKey);
3228
+ }
3229
+ else if ('choice' in item.dataset) {
3230
+ this._handleChoiceAction(item);
3231
+ }
3232
+ }
3233
+ event.preventDefault();
3234
+ };
3235
+ /**
3236
+ * Handles mouseover event over this.dropdown
3237
+ * @param {MouseEvent} event
3238
+ */
3239
+ Choices.prototype._onMouseOver = function (_a) {
3240
+ var target = _a.target;
3241
+ if (target instanceof HTMLElement && 'choice' in target.dataset) {
3242
+ this._highlightChoice(target);
3243
+ }
3244
+ };
3245
+ Choices.prototype._onClick = function (_a) {
3246
+ var target = _a.target;
3247
+ var containerOuter = this.containerOuter;
3248
+ var clickWasWithinContainer = containerOuter.element.contains(target);
3249
+ if (clickWasWithinContainer) {
3250
+ if (!this.dropdown.isActive && !containerOuter.isDisabled) {
3251
+ if (this._isTextElement) {
3252
+ if (document.activeElement !== this.input.element) {
3253
+ this.input.focus();
3254
+ }
3255
+ }
3256
+ else {
3257
+ this.showDropdown();
3258
+ containerOuter.element.focus();
3259
+ }
3260
+ }
3261
+ else if (this._isSelectOneElement &&
3262
+ target !== this.input.element &&
3263
+ !this.dropdown.element.contains(target)) {
3264
+ this.hideDropdown();
3265
+ }
3266
+ }
3267
+ else {
3268
+ containerOuter.removeFocusState();
3269
+ this.hideDropdown(true);
3270
+ this.unhighlightAll();
3271
+ }
3272
+ };
3273
+ Choices.prototype._onFocus = function (_a) {
3274
+ var target = _a.target;
3275
+ var containerOuter = this.containerOuter;
3276
+ var focusWasWithinContainer = target && containerOuter.element.contains(target);
3277
+ if (!focusWasWithinContainer) {
3278
+ return;
3279
+ }
3280
+ var targetIsInput = target === this.input.element;
3281
+ if (this._isTextElement) {
3282
+ if (targetIsInput) {
3283
+ containerOuter.addFocusState();
3284
+ }
3285
+ }
3286
+ else if (this._isSelectMultipleElement) {
3287
+ if (targetIsInput) {
3288
+ this.showDropdown(true);
3289
+ // If element is a select box, the focused element is the container and the dropdown
3290
+ // isn't already open, focus and show dropdown
3291
+ containerOuter.addFocusState();
3292
+ }
3293
+ }
3294
+ else {
3295
+ containerOuter.addFocusState();
3296
+ if (targetIsInput) {
3297
+ this.showDropdown(true);
3298
+ }
3299
+ }
3300
+ };
3301
+ Choices.prototype._onBlur = function (_a) {
3302
+ var target = _a.target;
3303
+ var containerOuter = this.containerOuter;
3304
+ var blurWasWithinContainer = target && containerOuter.element.contains(target);
3305
+ if (blurWasWithinContainer && !this._isScrollingOnIe) {
3306
+ if (target === this.input.element) {
3307
+ containerOuter.removeFocusState();
3308
+ this.hideDropdown(true);
3309
+ if (this._isTextElement || this._isSelectMultipleElement) {
3310
+ this.unhighlightAll();
3311
+ }
3312
+ }
3313
+ else if (target === this.containerOuter.element) {
3314
+ // Remove the focus state when the past outerContainer was the target
3315
+ containerOuter.removeFocusState();
3316
+ // Also close the dropdown if search is disabled
3317
+ if (!this._canSearch) {
3318
+ this.hideDropdown(true);
3319
+ }
3320
+ }
3321
+ }
3322
+ else {
3323
+ // On IE11, clicking the scollbar blurs our input and thus
3324
+ // closes the dropdown. To stop this, we refocus our input
3325
+ // if we know we are on IE *and* are scrolling.
3326
+ this._isScrollingOnIe = false;
3327
+ this.input.element.focus();
3328
+ }
3329
+ };
3330
+ Choices.prototype._onFormReset = function () {
3331
+ var _this = this;
3332
+ this._store.withTxn(function () {
3333
+ _this.clearInput();
3334
+ _this.hideDropdown();
3335
+ _this.refresh(false, false, true);
3336
+ if (_this._initialItems.length) {
3337
+ _this.setChoiceByValue(_this._initialItems);
3338
+ }
3339
+ });
3340
+ };
3341
+ Choices.prototype._highlightChoice = function (el) {
3342
+ if (el === void 0) { el = null; }
3343
+ var choices = Array.from(this.dropdown.element.querySelectorAll(selectableChoiceIdentifier));
3344
+ if (!choices.length) {
3345
+ return;
3346
+ }
3347
+ var passedEl = el;
3348
+ var highlightedState = this.config.classNames.highlightedState;
3349
+ var highlightedChoices = Array.from(this.dropdown.element.querySelectorAll(getClassNamesSelector(highlightedState)));
3350
+ // Remove any highlighted choices
3351
+ highlightedChoices.forEach(function (choice) {
3352
+ removeClassesFromElement(choice, highlightedState);
3353
+ choice.setAttribute('aria-selected', 'false');
3354
+ });
3355
+ if (passedEl) {
3356
+ this._highlightPosition = choices.indexOf(passedEl);
3357
+ }
3358
+ else {
3359
+ // Highlight choice based on last known highlight location
3360
+ if (choices.length > this._highlightPosition) {
3361
+ // If we have an option to highlight
3362
+ passedEl = choices[this._highlightPosition];
3363
+ }
3364
+ else {
3365
+ // Otherwise highlight the option before
3366
+ passedEl = choices[choices.length - 1];
3367
+ }
3368
+ if (!passedEl) {
3369
+ passedEl = choices[0];
3370
+ }
3371
+ }
3372
+ addClassesToElement(passedEl, highlightedState);
3373
+ passedEl.setAttribute('aria-selected', 'true');
3374
+ this.passedElement.triggerEvent(EventType.highlightChoice, {
3375
+ el: passedEl,
3376
+ });
3377
+ if (this.dropdown.isActive) {
3378
+ // IE11 ignores aria-label and blocks virtual keyboard
3379
+ // if aria-activedescendant is set without a dropdown
3380
+ this.input.setActiveDescendant(passedEl.id);
3381
+ this.containerOuter.setActiveDescendant(passedEl.id);
3382
+ }
3383
+ };
3384
+ Choices.prototype._addItem = function (item, withEvents, userTriggered) {
3385
+ if (withEvents === void 0) { withEvents = true; }
3386
+ if (userTriggered === void 0) { userTriggered = false; }
3387
+ if (!item.id) {
3388
+ throw new TypeError('item.id must be set before _addItem is called for a choice/item');
3389
+ }
3390
+ if (this.config.singleModeForMultiSelect || this._isSelectOneElement) {
3391
+ this.removeActiveItems(item.id);
3392
+ }
3393
+ this._store.dispatch(addItem(item));
3394
+ if (withEvents) {
3395
+ this.passedElement.triggerEvent(EventType.addItem, this._getChoiceForOutput(item));
3396
+ if (userTriggered) {
3397
+ this.passedElement.triggerEvent(EventType.choice, this._getChoiceForOutput(item));
3398
+ }
3399
+ }
3400
+ };
3401
+ Choices.prototype._removeItem = function (item) {
3402
+ if (!item.id) {
3403
+ return;
3404
+ }
3405
+ this._store.dispatch(removeItem$1(item));
3406
+ var notice = this._notice;
3407
+ if (notice && notice.type === NoticeTypes.noChoices) {
3408
+ this._clearNotice();
3409
+ }
3410
+ this.passedElement.triggerEvent(EventType.removeItem, this._getChoiceForOutput(item));
3411
+ };
3412
+ Choices.prototype._addChoice = function (choice, withEvents, userTriggered) {
3413
+ if (withEvents === void 0) { withEvents = true; }
3414
+ if (userTriggered === void 0) { userTriggered = false; }
3415
+ if (choice.id) {
3416
+ throw new TypeError('Can not re-add a choice which has already been added');
3417
+ }
3418
+ var config = this.config;
3419
+ if (!config.duplicateItemsAllowed && this._store.choices.find(function (c) { return config.valueComparer(c.value, choice.value); })) {
3420
+ return;
3421
+ }
3422
+ // Generate unique id, in-place update is required so chaining _addItem works as expected
3423
+ this._lastAddedChoiceId++;
3424
+ choice.id = this._lastAddedChoiceId;
3425
+ choice.elementId = "".concat(this._baseId, "-").concat(this._idNames.itemChoice, "-").concat(choice.id);
3426
+ var prependValue = config.prependValue, appendValue = config.appendValue;
3427
+ if (prependValue) {
3428
+ choice.value = prependValue + choice.value;
3429
+ }
3430
+ if (appendValue) {
3431
+ choice.value += appendValue.toString();
3432
+ }
3433
+ if ((prependValue || appendValue) && choice.element) {
3434
+ choice.element.value = choice.value;
3435
+ }
3436
+ this._clearNotice();
3437
+ this._store.dispatch(addChoice(choice));
3438
+ if (choice.selected) {
3439
+ this._addItem(choice, withEvents, userTriggered);
3440
+ }
3441
+ };
3442
+ Choices.prototype._addGroup = function (group, withEvents) {
3443
+ var _this = this;
3444
+ if (withEvents === void 0) { withEvents = true; }
3445
+ if (group.id) {
3446
+ throw new TypeError('Can not re-add a group which has already been added');
3447
+ }
3448
+ this._store.dispatch(addGroup(group));
3449
+ if (!group.choices) {
3450
+ return;
3451
+ }
3452
+ // add unique id for the group(s), and do not store the full list of choices in this group
3453
+ this._lastAddedGroupId++;
3454
+ group.id = this._lastAddedGroupId;
3455
+ group.choices.forEach(function (item) {
3456
+ item.group = group;
3457
+ if (group.disabled) {
3458
+ item.disabled = true;
3459
+ }
3460
+ _this._addChoice(item, withEvents);
3461
+ });
3462
+ };
3463
+ Choices.prototype._createTemplates = function () {
3464
+ var _this = this;
3465
+ var callbackOnCreateTemplates = this.config.callbackOnCreateTemplates;
3466
+ var userTemplates = {};
3467
+ if (typeof callbackOnCreateTemplates === 'function') {
3468
+ userTemplates = callbackOnCreateTemplates.call(this, strToEl, escapeForTemplate, getClassNames);
3469
+ }
3470
+ var templating = {};
3471
+ Object.keys(this._templates).forEach(function (name) {
3472
+ if (name in userTemplates) {
3473
+ templating[name] = userTemplates[name].bind(_this);
3474
+ }
3475
+ else {
3476
+ templating[name] = _this._templates[name].bind(_this);
3477
+ }
3478
+ });
3479
+ this._templates = templating;
3480
+ };
3481
+ Choices.prototype._createElements = function () {
3482
+ var templating = this._templates;
3483
+ var _a = this, config = _a.config, isSelectOneElement = _a._isSelectOneElement;
3484
+ var position = config.position, classNames = config.classNames;
3485
+ var elementType = this._elementType;
3486
+ this.containerOuter = new Container({
3487
+ element: templating.containerOuter(config, this._direction, this._isSelectElement, isSelectOneElement, config.searchEnabled, elementType, config.labelId),
3488
+ classNames: classNames,
3489
+ type: elementType,
3490
+ position: position,
3491
+ });
3492
+ this.containerInner = new Container({
3493
+ element: templating.containerInner(config),
3494
+ classNames: classNames,
3495
+ type: elementType,
3496
+ position: position,
3497
+ });
3498
+ this.input = new Input({
3499
+ element: templating.input(config, this._placeholderValue),
3500
+ classNames: classNames,
3501
+ type: elementType,
3502
+ preventPaste: !config.paste,
3503
+ });
3504
+ this.choiceList = new List({
3505
+ element: templating.choiceList(config, isSelectOneElement),
3506
+ });
3507
+ this.itemList = new List({
3508
+ element: templating.itemList(config, isSelectOneElement),
3509
+ });
3510
+ this.dropdown = new Dropdown({
3511
+ element: templating.dropdown(config),
3512
+ classNames: classNames,
3513
+ type: elementType,
3514
+ });
3515
+ };
3516
+ Choices.prototype._createStructure = function () {
3517
+ var _a = this, containerInner = _a.containerInner, containerOuter = _a.containerOuter, passedElement = _a.passedElement;
3518
+ var dropdownElement = this.dropdown.element;
3519
+ // Hide original element
3520
+ passedElement.conceal();
3521
+ // Wrap input in container preserving DOM ordering
3522
+ containerInner.wrap(passedElement.element);
3523
+ // Wrapper inner container with outer container
3524
+ containerOuter.wrap(containerInner.element);
3525
+ if (this._isSelectOneElement) {
3526
+ this.input.placeholder = this.config.searchPlaceholderValue || '';
3527
+ }
3528
+ else {
3529
+ if (this._placeholderValue) {
3530
+ this.input.placeholder = this._placeholderValue;
3531
+ }
3532
+ this.input.setWidth();
3533
+ }
3534
+ containerOuter.element.appendChild(containerInner.element);
3535
+ containerOuter.element.appendChild(dropdownElement);
3536
+ containerInner.element.appendChild(this.itemList.element);
3537
+ dropdownElement.appendChild(this.choiceList.element);
3538
+ if (!this._isSelectOneElement) {
3539
+ containerInner.element.appendChild(this.input.element);
3540
+ }
3541
+ else if (this.config.searchEnabled) {
3542
+ dropdownElement.insertBefore(this.input.element, dropdownElement.firstChild);
3543
+ }
3544
+ this._highlightPosition = 0;
3545
+ this._isSearching = false;
3546
+ };
3547
+ Choices.prototype._initStore = function () {
3548
+ var _this = this;
3549
+ this._store.subscribe(this._render).withTxn(function () {
3550
+ _this._addPredefinedChoices(_this._presetChoices, _this._isSelectOneElement && !_this._hasNonChoicePlaceholder, false);
3551
+ });
3552
+ if (!this._store.choices.length || (this._isSelectOneElement && this._hasNonChoicePlaceholder)) {
3553
+ this._render();
3554
+ }
3555
+ };
3556
+ Choices.prototype._addPredefinedChoices = function (choices, selectFirstOption, withEvents) {
3557
+ var _this = this;
3558
+ if (selectFirstOption === void 0) { selectFirstOption = false; }
3559
+ if (withEvents === void 0) { withEvents = true; }
3560
+ if (selectFirstOption) {
3561
+ /**
3562
+ * If there is a selected choice already or the choice is not the first in
3563
+ * the array, add each choice normally.
3564
+ *
3565
+ * Otherwise we pre-select the first enabled choice in the array ("select-one" only)
3566
+ */
3567
+ var noSelectedChoices = choices.findIndex(function (choice) { return choice.selected; }) === -1;
3568
+ if (noSelectedChoices) {
3569
+ choices.some(function (choice) {
3570
+ if (choice.disabled || 'choices' in choice) {
3571
+ return false;
3572
+ }
3573
+ choice.selected = true;
3574
+ return true;
3575
+ });
3576
+ }
3577
+ }
3578
+ choices.forEach(function (item) {
3579
+ if ('choices' in item) {
3580
+ if (_this._isSelectElement) {
3581
+ _this._addGroup(item, withEvents);
3582
+ }
3583
+ }
3584
+ else {
3585
+ _this._addChoice(item, withEvents);
3586
+ }
3587
+ });
3588
+ };
3589
+ Choices.prototype._findAndSelectChoiceByValue = function (value, userTriggered) {
3590
+ var _this = this;
3591
+ if (userTriggered === void 0) { userTriggered = false; }
3592
+ // Check 'value' property exists and the choice isn't already selected
3593
+ var foundChoice = this._store.choices.find(function (choice) { return _this.config.valueComparer(choice.value, value); });
3594
+ if (foundChoice && !foundChoice.disabled && !foundChoice.selected) {
3595
+ this._addItem(foundChoice, true, userTriggered);
3596
+ return true;
3597
+ }
3598
+ return false;
3599
+ };
3600
+ Choices.prototype._generatePlaceholderValue = function () {
3601
+ var config = this.config;
3602
+ if (!config.placeholder) {
3603
+ return null;
3604
+ }
3605
+ if (this._hasNonChoicePlaceholder) {
3606
+ return config.placeholderValue;
3607
+ }
3608
+ if (this._isSelectElement) {
3609
+ var placeholderOption = this.passedElement.placeholderOption;
3610
+ return placeholderOption ? placeholderOption.text : null;
3611
+ }
3612
+ return null;
3613
+ };
3614
+ Choices.prototype._warnChoicesInitFailed = function (caller) {
3615
+ if (this.config.silent) {
3616
+ return;
3617
+ }
3618
+ if (!this.initialised) {
3619
+ throw new TypeError("".concat(caller, " called on a non-initialised instance of Choices"));
3620
+ }
3621
+ else if (!this.initialisedOK) {
3622
+ throw new TypeError("".concat(caller, " called for an element which has multiple instances of Choices initialised on it"));
3623
+ }
3624
+ };
3625
+ Choices.version = '11.1.0';
3626
+ return Choices;
3627
+ }());
3628
+
3629
+ return Choices;
3630
+
3631
+ }));