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,4748 @@
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
+ function __spreadArray(to, from, pack) {
54
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
55
+ if (ar || !(i in from)) {
56
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
57
+ ar[i] = from[i];
58
+ }
59
+ }
60
+ return to.concat(ar || Array.prototype.slice.call(from));
61
+ }
62
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
63
+ var e = new Error(message);
64
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
65
+ };
66
+
67
+ var ActionType = {
68
+ ADD_CHOICE: 'ADD_CHOICE',
69
+ REMOVE_CHOICE: 'REMOVE_CHOICE',
70
+ FILTER_CHOICES: 'FILTER_CHOICES',
71
+ ACTIVATE_CHOICES: 'ACTIVATE_CHOICES',
72
+ CLEAR_CHOICES: 'CLEAR_CHOICES',
73
+ ADD_GROUP: 'ADD_GROUP',
74
+ ADD_ITEM: 'ADD_ITEM',
75
+ REMOVE_ITEM: 'REMOVE_ITEM',
76
+ HIGHLIGHT_ITEM: 'HIGHLIGHT_ITEM',
77
+ };
78
+
79
+ var EventType = {
80
+ showDropdown: 'showDropdown',
81
+ hideDropdown: 'hideDropdown',
82
+ change: 'change',
83
+ choice: 'choice',
84
+ search: 'search',
85
+ addItem: 'addItem',
86
+ removeItem: 'removeItem',
87
+ highlightItem: 'highlightItem',
88
+ highlightChoice: 'highlightChoice',
89
+ unhighlightItem: 'unhighlightItem',
90
+ };
91
+
92
+ var KeyCodeMap = {
93
+ TAB_KEY: 9,
94
+ SHIFT_KEY: 16,
95
+ BACK_KEY: 46,
96
+ DELETE_KEY: 8,
97
+ ENTER_KEY: 13,
98
+ A_KEY: 65,
99
+ ESC_KEY: 27,
100
+ UP_KEY: 38,
101
+ DOWN_KEY: 40,
102
+ PAGE_UP_KEY: 33,
103
+ PAGE_DOWN_KEY: 34,
104
+ };
105
+
106
+ var ObjectsInConfig = ['fuseOptions', 'classNames'];
107
+
108
+ var PassedElementTypes = {
109
+ Text: 'text',
110
+ SelectOne: 'select-one',
111
+ SelectMultiple: 'select-multiple',
112
+ };
113
+
114
+ var addChoice = function (choice) { return ({
115
+ type: ActionType.ADD_CHOICE,
116
+ choice: choice,
117
+ }); };
118
+ var removeChoice = function (choice) { return ({
119
+ type: ActionType.REMOVE_CHOICE,
120
+ choice: choice,
121
+ }); };
122
+ var filterChoices = function (results) { return ({
123
+ type: ActionType.FILTER_CHOICES,
124
+ results: results,
125
+ }); };
126
+ var activateChoices = function (active) {
127
+ return ({
128
+ type: ActionType.ACTIVATE_CHOICES,
129
+ active: active,
130
+ });
131
+ };
132
+
133
+ var addGroup = function (group) { return ({
134
+ type: ActionType.ADD_GROUP,
135
+ group: group,
136
+ }); };
137
+
138
+ var addItem = function (item) { return ({
139
+ type: ActionType.ADD_ITEM,
140
+ item: item,
141
+ }); };
142
+ var removeItem$1 = function (item) { return ({
143
+ type: ActionType.REMOVE_ITEM,
144
+ item: item,
145
+ }); };
146
+ var highlightItem = function (item, highlighted) { return ({
147
+ type: ActionType.HIGHLIGHT_ITEM,
148
+ item: item,
149
+ highlighted: highlighted,
150
+ }); };
151
+
152
+ var getRandomNumber = function (min, max) { return Math.floor(Math.random() * (max - min) + min); };
153
+ var generateChars = function (length) {
154
+ return Array.from({ length: length }, function () { return getRandomNumber(0, 36).toString(36); }).join('');
155
+ };
156
+ var generateId = function (element, prefix) {
157
+ var id = element.id || (element.name && "".concat(element.name, "-").concat(generateChars(2))) || generateChars(4);
158
+ id = id.replace(/(:|\.|\[|\]|,)/g, '');
159
+ id = "".concat(prefix, "-").concat(id);
160
+ return id;
161
+ };
162
+ var getAdjacentEl = function (startEl, selector, direction) {
163
+ if (direction === void 0) { direction = 1; }
164
+ var prop = "".concat(direction > 0 ? 'next' : 'previous', "ElementSibling");
165
+ var sibling = startEl[prop];
166
+ while (sibling) {
167
+ if (sibling.matches(selector)) {
168
+ return sibling;
169
+ }
170
+ sibling = sibling[prop];
171
+ }
172
+ return null;
173
+ };
174
+ var isScrolledIntoView = function (element, parent, direction) {
175
+ if (direction === void 0) { direction = 1; }
176
+ var isVisible;
177
+ if (direction > 0) {
178
+ // In view from bottom
179
+ isVisible = parent.scrollTop + parent.offsetHeight >= element.offsetTop + element.offsetHeight;
180
+ }
181
+ else {
182
+ // In view from top
183
+ isVisible = element.offsetTop >= parent.scrollTop;
184
+ }
185
+ return isVisible;
186
+ };
187
+ var sanitise = function (value) {
188
+ if (typeof value !== 'string') {
189
+ if (value === null || value === undefined) {
190
+ return '';
191
+ }
192
+ if (typeof value === 'object') {
193
+ if ('raw' in value) {
194
+ return sanitise(value.raw);
195
+ }
196
+ if ('trusted' in value) {
197
+ return value.trusted;
198
+ }
199
+ }
200
+ return value;
201
+ }
202
+ return value
203
+ .replace(/&/g, '&amp;')
204
+ .replace(/>/g, '&gt;')
205
+ .replace(/</g, '&lt;')
206
+ .replace(/'/g, '&#039;')
207
+ .replace(/"/g, '&quot;');
208
+ };
209
+ var strToEl = (function () {
210
+ var tmpEl = document.createElement('div');
211
+ return function (str) {
212
+ tmpEl.innerHTML = str.trim();
213
+ var firstChild = tmpEl.children[0];
214
+ while (tmpEl.firstChild) {
215
+ tmpEl.removeChild(tmpEl.firstChild);
216
+ }
217
+ return firstChild;
218
+ };
219
+ })();
220
+ var resolveNoticeFunction = function (fn, value) {
221
+ return typeof fn === 'function' ? fn(sanitise(value), value) : fn;
222
+ };
223
+ var resolveStringFunction = function (fn) {
224
+ return typeof fn === 'function' ? fn() : fn;
225
+ };
226
+ var unwrapStringForRaw = function (s) {
227
+ if (typeof s === 'string') {
228
+ return s;
229
+ }
230
+ if (typeof s === 'object') {
231
+ if ('trusted' in s) {
232
+ return s.trusted;
233
+ }
234
+ if ('raw' in s) {
235
+ return s.raw;
236
+ }
237
+ }
238
+ return '';
239
+ };
240
+ var unwrapStringForEscaped = function (s) {
241
+ if (typeof s === 'string') {
242
+ return s;
243
+ }
244
+ if (typeof s === 'object') {
245
+ if ('escaped' in s) {
246
+ return s.escaped;
247
+ }
248
+ if ('trusted' in s) {
249
+ return s.trusted;
250
+ }
251
+ }
252
+ return '';
253
+ };
254
+ var escapeForTemplate = function (allowHTML, s) {
255
+ return allowHTML ? unwrapStringForEscaped(s) : sanitise(s);
256
+ };
257
+ var setElementHtml = function (el, allowHtml, html) {
258
+ el.innerHTML = escapeForTemplate(allowHtml, html);
259
+ };
260
+ var sortByAlpha = function (_a, _b) {
261
+ var value = _a.value, _c = _a.label, label = _c === void 0 ? value : _c;
262
+ var value2 = _b.value, _d = _b.label, label2 = _d === void 0 ? value2 : _d;
263
+ return unwrapStringForRaw(label).localeCompare(unwrapStringForRaw(label2), [], {
264
+ sensitivity: 'base',
265
+ ignorePunctuation: true,
266
+ numeric: true,
267
+ });
268
+ };
269
+ var sortByRank = function (a, b) {
270
+ return a.rank - b.rank;
271
+ };
272
+ var dispatchEvent = function (element, type, customArgs) {
273
+ if (customArgs === void 0) { customArgs = null; }
274
+ var event = new CustomEvent(type, {
275
+ detail: customArgs,
276
+ bubbles: true,
277
+ cancelable: true,
278
+ });
279
+ return element.dispatchEvent(event);
280
+ };
281
+ /**
282
+ * Returns an array of keys present on the first but missing on the second object
283
+ */
284
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
285
+ var diff = function (a, b) {
286
+ var aKeys = Object.keys(a).sort();
287
+ var bKeys = Object.keys(b).sort();
288
+ return aKeys.filter(function (i) { return bKeys.indexOf(i) < 0; });
289
+ };
290
+ var getClassNames = function (ClassNames) {
291
+ return Array.isArray(ClassNames) ? ClassNames : [ClassNames];
292
+ };
293
+ var getClassNamesSelector = function (option) {
294
+ if (option && Array.isArray(option)) {
295
+ return option
296
+ .map(function (item) {
297
+ return ".".concat(item);
298
+ })
299
+ .join('');
300
+ }
301
+ return ".".concat(option);
302
+ };
303
+ var addClassesToElement = function (element, className) {
304
+ var _a;
305
+ (_a = element.classList).add.apply(_a, getClassNames(className));
306
+ };
307
+ var removeClassesFromElement = function (element, className) {
308
+ var _a;
309
+ (_a = element.classList).remove.apply(_a, getClassNames(className));
310
+ };
311
+ var parseCustomProperties = function (customProperties) {
312
+ if (typeof customProperties !== 'undefined') {
313
+ try {
314
+ return JSON.parse(customProperties);
315
+ }
316
+ catch (e) {
317
+ return customProperties;
318
+ }
319
+ }
320
+ return {};
321
+ };
322
+ var updateClassList = function (item, add, remove) {
323
+ var itemEl = item.itemEl;
324
+ if (itemEl) {
325
+ removeClassesFromElement(itemEl, remove);
326
+ addClassesToElement(itemEl, add);
327
+ }
328
+ };
329
+
330
+ var Dropdown = /** @class */ (function () {
331
+ function Dropdown(_a) {
332
+ var element = _a.element, type = _a.type, classNames = _a.classNames;
333
+ this.element = element;
334
+ this.classNames = classNames;
335
+ this.type = type;
336
+ this.isActive = false;
337
+ }
338
+ /**
339
+ * Show dropdown to user by adding active state class
340
+ */
341
+ Dropdown.prototype.show = function () {
342
+ addClassesToElement(this.element, this.classNames.activeState);
343
+ this.element.setAttribute('aria-expanded', 'true');
344
+ this.isActive = true;
345
+ return this;
346
+ };
347
+ /**
348
+ * Hide dropdown from user
349
+ */
350
+ Dropdown.prototype.hide = function () {
351
+ removeClassesFromElement(this.element, this.classNames.activeState);
352
+ this.element.setAttribute('aria-expanded', 'false');
353
+ this.isActive = false;
354
+ return this;
355
+ };
356
+ return Dropdown;
357
+ }());
358
+
359
+ var Container = /** @class */ (function () {
360
+ function Container(_a) {
361
+ var element = _a.element, type = _a.type, classNames = _a.classNames, position = _a.position;
362
+ this.element = element;
363
+ this.classNames = classNames;
364
+ this.type = type;
365
+ this.position = position;
366
+ this.isOpen = false;
367
+ this.isFlipped = false;
368
+ this.isDisabled = false;
369
+ this.isLoading = false;
370
+ }
371
+ /**
372
+ * Determine whether container should be flipped based on passed
373
+ * dropdown position
374
+ */
375
+ Container.prototype.shouldFlip = function (dropdownPos, dropdownHeight) {
376
+ // If flip is enabled and the dropdown bottom position is
377
+ // greater than the window height flip the dropdown.
378
+ var shouldFlip = false;
379
+ if (this.position === 'auto') {
380
+ shouldFlip =
381
+ this.element.getBoundingClientRect().top - dropdownHeight >= 0 &&
382
+ !window.matchMedia("(min-height: ".concat(dropdownPos + 1, "px)")).matches;
383
+ }
384
+ else if (this.position === 'top') {
385
+ shouldFlip = true;
386
+ }
387
+ return shouldFlip;
388
+ };
389
+ Container.prototype.setActiveDescendant = function (activeDescendantID) {
390
+ this.element.setAttribute('aria-activedescendant', activeDescendantID);
391
+ };
392
+ Container.prototype.removeActiveDescendant = function () {
393
+ this.element.removeAttribute('aria-activedescendant');
394
+ };
395
+ Container.prototype.open = function (dropdownPos, dropdownHeight) {
396
+ addClassesToElement(this.element, this.classNames.openState);
397
+ this.element.setAttribute('aria-expanded', 'true');
398
+ this.isOpen = true;
399
+ if (this.shouldFlip(dropdownPos, dropdownHeight)) {
400
+ addClassesToElement(this.element, this.classNames.flippedState);
401
+ this.isFlipped = true;
402
+ }
403
+ };
404
+ Container.prototype.close = function () {
405
+ removeClassesFromElement(this.element, this.classNames.openState);
406
+ this.element.setAttribute('aria-expanded', 'false');
407
+ this.removeActiveDescendant();
408
+ this.isOpen = false;
409
+ // A dropdown flips if it does not have space within the page
410
+ if (this.isFlipped) {
411
+ removeClassesFromElement(this.element, this.classNames.flippedState);
412
+ this.isFlipped = false;
413
+ }
414
+ };
415
+ Container.prototype.addFocusState = function () {
416
+ addClassesToElement(this.element, this.classNames.focusState);
417
+ };
418
+ Container.prototype.removeFocusState = function () {
419
+ removeClassesFromElement(this.element, this.classNames.focusState);
420
+ };
421
+ Container.prototype.enable = function () {
422
+ removeClassesFromElement(this.element, this.classNames.disabledState);
423
+ this.element.removeAttribute('aria-disabled');
424
+ if (this.type === PassedElementTypes.SelectOne) {
425
+ this.element.setAttribute('tabindex', '0');
426
+ }
427
+ this.isDisabled = false;
428
+ };
429
+ Container.prototype.disable = function () {
430
+ addClassesToElement(this.element, this.classNames.disabledState);
431
+ this.element.setAttribute('aria-disabled', 'true');
432
+ if (this.type === PassedElementTypes.SelectOne) {
433
+ this.element.setAttribute('tabindex', '-1');
434
+ }
435
+ this.isDisabled = true;
436
+ };
437
+ Container.prototype.wrap = function (element) {
438
+ var el = this.element;
439
+ var parentNode = element.parentNode;
440
+ if (parentNode) {
441
+ if (element.nextSibling) {
442
+ parentNode.insertBefore(el, element.nextSibling);
443
+ }
444
+ else {
445
+ parentNode.appendChild(el);
446
+ }
447
+ }
448
+ el.appendChild(element);
449
+ };
450
+ Container.prototype.unwrap = function (element) {
451
+ var el = this.element;
452
+ var parentNode = el.parentNode;
453
+ if (parentNode) {
454
+ // Move passed element outside this element
455
+ parentNode.insertBefore(element, el);
456
+ // Remove this element
457
+ parentNode.removeChild(el);
458
+ }
459
+ };
460
+ Container.prototype.addLoadingState = function () {
461
+ addClassesToElement(this.element, this.classNames.loadingState);
462
+ this.element.setAttribute('aria-busy', 'true');
463
+ this.isLoading = true;
464
+ };
465
+ Container.prototype.removeLoadingState = function () {
466
+ removeClassesFromElement(this.element, this.classNames.loadingState);
467
+ this.element.removeAttribute('aria-busy');
468
+ this.isLoading = false;
469
+ };
470
+ return Container;
471
+ }());
472
+
473
+ var Input = /** @class */ (function () {
474
+ function Input(_a) {
475
+ var element = _a.element, type = _a.type, classNames = _a.classNames, preventPaste = _a.preventPaste;
476
+ this.element = element;
477
+ this.type = type;
478
+ this.classNames = classNames;
479
+ this.preventPaste = preventPaste;
480
+ this.isFocussed = this.element.isEqualNode(document.activeElement);
481
+ this.isDisabled = element.disabled;
482
+ this._onPaste = this._onPaste.bind(this);
483
+ this._onInput = this._onInput.bind(this);
484
+ this._onFocus = this._onFocus.bind(this);
485
+ this._onBlur = this._onBlur.bind(this);
486
+ }
487
+ Object.defineProperty(Input.prototype, "placeholder", {
488
+ set: function (placeholder) {
489
+ this.element.placeholder = placeholder;
490
+ },
491
+ enumerable: false,
492
+ configurable: true
493
+ });
494
+ Object.defineProperty(Input.prototype, "value", {
495
+ get: function () {
496
+ return this.element.value;
497
+ },
498
+ set: function (value) {
499
+ this.element.value = value;
500
+ },
501
+ enumerable: false,
502
+ configurable: true
503
+ });
504
+ Input.prototype.addEventListeners = function () {
505
+ var el = this.element;
506
+ el.addEventListener('paste', this._onPaste);
507
+ el.addEventListener('input', this._onInput, {
508
+ passive: true,
509
+ });
510
+ el.addEventListener('focus', this._onFocus, {
511
+ passive: true,
512
+ });
513
+ el.addEventListener('blur', this._onBlur, {
514
+ passive: true,
515
+ });
516
+ };
517
+ Input.prototype.removeEventListeners = function () {
518
+ var el = this.element;
519
+ el.removeEventListener('input', this._onInput);
520
+ el.removeEventListener('paste', this._onPaste);
521
+ el.removeEventListener('focus', this._onFocus);
522
+ el.removeEventListener('blur', this._onBlur);
523
+ };
524
+ Input.prototype.enable = function () {
525
+ var el = this.element;
526
+ el.removeAttribute('disabled');
527
+ this.isDisabled = false;
528
+ };
529
+ Input.prototype.disable = function () {
530
+ var el = this.element;
531
+ el.setAttribute('disabled', '');
532
+ this.isDisabled = true;
533
+ };
534
+ Input.prototype.focus = function () {
535
+ if (!this.isFocussed) {
536
+ this.element.focus();
537
+ }
538
+ };
539
+ Input.prototype.blur = function () {
540
+ if (this.isFocussed) {
541
+ this.element.blur();
542
+ }
543
+ };
544
+ Input.prototype.clear = function (setWidth) {
545
+ if (setWidth === void 0) { setWidth = true; }
546
+ this.element.value = '';
547
+ if (setWidth) {
548
+ this.setWidth();
549
+ }
550
+ return this;
551
+ };
552
+ /**
553
+ * Set the correct input width based on placeholder
554
+ * value or input value
555
+ */
556
+ Input.prototype.setWidth = function () {
557
+ // Resize input to contents or placeholder
558
+ var element = this.element;
559
+ element.style.minWidth = "".concat(element.placeholder.length + 1, "ch");
560
+ element.style.width = "".concat(element.value.length + 1, "ch");
561
+ };
562
+ Input.prototype.setActiveDescendant = function (activeDescendantID) {
563
+ this.element.setAttribute('aria-activedescendant', activeDescendantID);
564
+ };
565
+ Input.prototype.removeActiveDescendant = function () {
566
+ this.element.removeAttribute('aria-activedescendant');
567
+ };
568
+ Input.prototype._onInput = function () {
569
+ if (this.type !== PassedElementTypes.SelectOne) {
570
+ this.setWidth();
571
+ }
572
+ };
573
+ Input.prototype._onPaste = function (event) {
574
+ if (this.preventPaste) {
575
+ event.preventDefault();
576
+ }
577
+ };
578
+ Input.prototype._onFocus = function () {
579
+ this.isFocussed = true;
580
+ };
581
+ Input.prototype._onBlur = function () {
582
+ this.isFocussed = false;
583
+ };
584
+ return Input;
585
+ }());
586
+
587
+ var SCROLLING_SPEED = 4;
588
+
589
+ var List = /** @class */ (function () {
590
+ function List(_a) {
591
+ var element = _a.element;
592
+ this.element = element;
593
+ this.scrollPos = this.element.scrollTop;
594
+ this.height = this.element.offsetHeight;
595
+ }
596
+ List.prototype.prepend = function (node) {
597
+ var child = this.element.firstElementChild;
598
+ if (child) {
599
+ this.element.insertBefore(node, child);
600
+ }
601
+ else {
602
+ this.element.append(node);
603
+ }
604
+ };
605
+ List.prototype.scrollToTop = function () {
606
+ this.element.scrollTop = 0;
607
+ };
608
+ List.prototype.scrollToChildElement = function (element, direction) {
609
+ var _this = this;
610
+ if (!element) {
611
+ return;
612
+ }
613
+ var listHeight = this.element.offsetHeight;
614
+ // Scroll position of dropdown
615
+ var listScrollPosition = this.element.scrollTop + listHeight;
616
+ var elementHeight = element.offsetHeight;
617
+ // Distance from bottom of element to top of parent
618
+ var elementPos = element.offsetTop + elementHeight;
619
+ // Difference between the element and scroll position
620
+ var destination = direction > 0 ? this.element.scrollTop + elementPos - listScrollPosition : element.offsetTop;
621
+ requestAnimationFrame(function () {
622
+ _this._animateScroll(destination, direction);
623
+ });
624
+ };
625
+ List.prototype._scrollDown = function (scrollPos, strength, destination) {
626
+ var easing = (destination - scrollPos) / strength;
627
+ var distance = easing > 1 ? easing : 1;
628
+ this.element.scrollTop = scrollPos + distance;
629
+ };
630
+ List.prototype._scrollUp = function (scrollPos, strength, destination) {
631
+ var easing = (scrollPos - destination) / strength;
632
+ var distance = easing > 1 ? easing : 1;
633
+ this.element.scrollTop = scrollPos - distance;
634
+ };
635
+ List.prototype._animateScroll = function (destination, direction) {
636
+ var _this = this;
637
+ var strength = SCROLLING_SPEED;
638
+ var choiceListScrollTop = this.element.scrollTop;
639
+ var continueAnimation = false;
640
+ if (direction > 0) {
641
+ this._scrollDown(choiceListScrollTop, strength, destination);
642
+ if (choiceListScrollTop < destination) {
643
+ continueAnimation = true;
644
+ }
645
+ }
646
+ else {
647
+ this._scrollUp(choiceListScrollTop, strength, destination);
648
+ if (choiceListScrollTop > destination) {
649
+ continueAnimation = true;
650
+ }
651
+ }
652
+ if (continueAnimation) {
653
+ requestAnimationFrame(function () {
654
+ _this._animateScroll(destination, direction);
655
+ });
656
+ }
657
+ };
658
+ return List;
659
+ }());
660
+
661
+ var WrappedElement = /** @class */ (function () {
662
+ function WrappedElement(_a) {
663
+ var element = _a.element, classNames = _a.classNames;
664
+ this.element = element;
665
+ this.classNames = classNames;
666
+ this.isDisabled = false;
667
+ }
668
+ Object.defineProperty(WrappedElement.prototype, "isActive", {
669
+ get: function () {
670
+ return this.element.dataset.choice === 'active';
671
+ },
672
+ enumerable: false,
673
+ configurable: true
674
+ });
675
+ Object.defineProperty(WrappedElement.prototype, "dir", {
676
+ get: function () {
677
+ return this.element.dir;
678
+ },
679
+ enumerable: false,
680
+ configurable: true
681
+ });
682
+ Object.defineProperty(WrappedElement.prototype, "value", {
683
+ get: function () {
684
+ return this.element.value;
685
+ },
686
+ set: function (value) {
687
+ this.element.setAttribute('value', value);
688
+ this.element.value = value;
689
+ },
690
+ enumerable: false,
691
+ configurable: true
692
+ });
693
+ WrappedElement.prototype.conceal = function () {
694
+ var el = this.element;
695
+ // Hide passed input
696
+ addClassesToElement(el, this.classNames.input);
697
+ el.hidden = true;
698
+ // Remove element from tab index
699
+ el.tabIndex = -1;
700
+ // Backup original styles if any
701
+ var origStyle = el.getAttribute('style');
702
+ if (origStyle) {
703
+ el.setAttribute('data-choice-orig-style', origStyle);
704
+ }
705
+ el.setAttribute('data-choice', 'active');
706
+ };
707
+ WrappedElement.prototype.reveal = function () {
708
+ var el = this.element;
709
+ // Reinstate passed element
710
+ removeClassesFromElement(el, this.classNames.input);
711
+ el.hidden = false;
712
+ el.removeAttribute('tabindex');
713
+ // Recover original styles if any
714
+ var origStyle = el.getAttribute('data-choice-orig-style');
715
+ if (origStyle) {
716
+ el.removeAttribute('data-choice-orig-style');
717
+ el.setAttribute('style', origStyle);
718
+ }
719
+ else {
720
+ el.removeAttribute('style');
721
+ }
722
+ el.removeAttribute('data-choice');
723
+ };
724
+ WrappedElement.prototype.enable = function () {
725
+ this.element.removeAttribute('disabled');
726
+ this.element.disabled = false;
727
+ this.isDisabled = false;
728
+ };
729
+ WrappedElement.prototype.disable = function () {
730
+ this.element.setAttribute('disabled', '');
731
+ this.element.disabled = true;
732
+ this.isDisabled = true;
733
+ };
734
+ WrappedElement.prototype.triggerEvent = function (eventType, data) {
735
+ dispatchEvent(this.element, eventType, data || {});
736
+ };
737
+ return WrappedElement;
738
+ }());
739
+
740
+ var WrappedInput = /** @class */ (function (_super) {
741
+ __extends(WrappedInput, _super);
742
+ function WrappedInput() {
743
+ return _super !== null && _super.apply(this, arguments) || this;
744
+ }
745
+ return WrappedInput;
746
+ }(WrappedElement));
747
+
748
+ var coerceBool = function (arg, defaultValue) {
749
+ if (defaultValue === void 0) { defaultValue = true; }
750
+ return typeof arg === 'undefined' ? defaultValue : !!arg;
751
+ };
752
+ var stringToHtmlClass = function (input) {
753
+ if (typeof input === 'string') {
754
+ // eslint-disable-next-line no-param-reassign
755
+ input = input.split(' ').filter(function (s) { return s.length; });
756
+ }
757
+ if (Array.isArray(input) && input.length) {
758
+ return input;
759
+ }
760
+ return undefined;
761
+ };
762
+ var mapInputToChoice = function (value, allowGroup, allowRawString) {
763
+ if (allowRawString === void 0) { allowRawString = true; }
764
+ if (typeof value === 'string') {
765
+ var sanitisedValue = sanitise(value);
766
+ var userValue = allowRawString || sanitisedValue === value ? value : { escaped: sanitisedValue, raw: value };
767
+ var result_1 = mapInputToChoice({
768
+ value: value,
769
+ label: userValue,
770
+ selected: true,
771
+ }, false);
772
+ return result_1;
773
+ }
774
+ var groupOrChoice = value;
775
+ if ('choices' in groupOrChoice) {
776
+ if (!allowGroup) {
777
+ // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup
778
+ throw new TypeError("optGroup is not allowed");
779
+ }
780
+ var group = groupOrChoice;
781
+ var choices = group.choices.map(function (e) { return mapInputToChoice(e, false); });
782
+ var result_2 = {
783
+ id: 0, // actual ID will be assigned during _addGroup
784
+ label: unwrapStringForRaw(group.label) || group.value,
785
+ active: !!choices.length,
786
+ disabled: !!group.disabled,
787
+ choices: choices,
788
+ };
789
+ return result_2;
790
+ }
791
+ var choice = groupOrChoice;
792
+ var result = {
793
+ id: 0, // actual ID will be assigned during _addChoice
794
+ group: null, // actual group will be assigned during _addGroup but before _addChoice
795
+ score: 0, // used in search
796
+ rank: 0, // used in search, stable sort order
797
+ value: choice.value,
798
+ label: choice.label || choice.value,
799
+ active: coerceBool(choice.active),
800
+ selected: coerceBool(choice.selected, false),
801
+ disabled: coerceBool(choice.disabled, false),
802
+ placeholder: coerceBool(choice.placeholder, false),
803
+ highlighted: false,
804
+ labelClass: stringToHtmlClass(choice.labelClass),
805
+ labelDescription: choice.labelDescription,
806
+ customProperties: choice.customProperties,
807
+ };
808
+ return result;
809
+ };
810
+
811
+ var isHtmlInputElement = function (e) { return e.tagName === 'INPUT'; };
812
+ var isHtmlSelectElement = function (e) { return e.tagName === 'SELECT'; };
813
+ var isHtmlOption = function (e) { return e.tagName === 'OPTION'; };
814
+ var isHtmlOptgroup = function (e) { return e.tagName === 'OPTGROUP'; };
815
+
816
+ var WrappedSelect = /** @class */ (function (_super) {
817
+ __extends(WrappedSelect, _super);
818
+ function WrappedSelect(_a) {
819
+ var element = _a.element, classNames = _a.classNames, template = _a.template, extractPlaceholder = _a.extractPlaceholder;
820
+ var _this = _super.call(this, { element: element, classNames: classNames }) || this;
821
+ _this.template = template;
822
+ _this.extractPlaceholder = extractPlaceholder;
823
+ return _this;
824
+ }
825
+ Object.defineProperty(WrappedSelect.prototype, "placeholderOption", {
826
+ get: function () {
827
+ return (this.element.querySelector('option[value=""]') ||
828
+ // Backward compatibility layer for the non-standard placeholder attribute supported in older versions.
829
+ this.element.querySelector('option[placeholder]'));
830
+ },
831
+ enumerable: false,
832
+ configurable: true
833
+ });
834
+ WrappedSelect.prototype.addOptions = function (choices) {
835
+ var _this = this;
836
+ var fragment = document.createDocumentFragment();
837
+ choices.forEach(function (obj) {
838
+ var choice = obj;
839
+ if (choice.element) {
840
+ return;
841
+ }
842
+ var option = _this.template(choice);
843
+ fragment.appendChild(option);
844
+ choice.element = option;
845
+ });
846
+ this.element.appendChild(fragment);
847
+ };
848
+ WrappedSelect.prototype.optionsAsChoices = function () {
849
+ var _this = this;
850
+ var choices = [];
851
+ this.element.querySelectorAll(':scope > option, :scope > optgroup').forEach(function (e) {
852
+ if (isHtmlOption(e)) {
853
+ choices.push(_this._optionToChoice(e));
854
+ }
855
+ else if (isHtmlOptgroup(e)) {
856
+ choices.push(_this._optgroupToChoice(e));
857
+ }
858
+ // todo: hr as empty optgroup, requires displaying empty opt-groups to be useful
859
+ });
860
+ return choices;
861
+ };
862
+ // eslint-disable-next-line class-methods-use-this
863
+ WrappedSelect.prototype._optionToChoice = function (option) {
864
+ // option.value returns the label if there is no value attribute, which can break legacy placeholder attribute support
865
+ if (!option.hasAttribute('value') && option.hasAttribute('placeholder')) {
866
+ option.setAttribute('value', '');
867
+ option.value = '';
868
+ }
869
+ return {
870
+ id: 0,
871
+ group: null,
872
+ score: 0,
873
+ rank: 0,
874
+ value: option.value,
875
+ // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option
876
+ // 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`).
877
+ label: option.label,
878
+ element: option,
879
+ active: true,
880
+ // this returns true if nothing is selected on initial load, which will break placeholder support
881
+ selected: this.extractPlaceholder ? option.selected : option.hasAttribute('selected'),
882
+ disabled: option.disabled,
883
+ highlighted: false,
884
+ placeholder: this.extractPlaceholder && (!option.value || option.hasAttribute('placeholder')),
885
+ labelClass: typeof option.dataset.labelClass !== 'undefined' ? stringToHtmlClass(option.dataset.labelClass) : undefined,
886
+ labelDescription: typeof option.dataset.labelDescription !== 'undefined' ? option.dataset.labelDescription : undefined,
887
+ customProperties: parseCustomProperties(option.dataset.customProperties),
888
+ };
889
+ };
890
+ WrappedSelect.prototype._optgroupToChoice = function (optgroup) {
891
+ var _this = this;
892
+ var options = optgroup.querySelectorAll('option');
893
+ var choices = Array.from(options).map(function (option) { return _this._optionToChoice(option); });
894
+ return {
895
+ id: 0,
896
+ label: optgroup.label || '',
897
+ element: optgroup,
898
+ active: !!choices.length,
899
+ disabled: optgroup.disabled,
900
+ choices: choices,
901
+ };
902
+ };
903
+ return WrappedSelect;
904
+ }(WrappedElement));
905
+
906
+ var DEFAULT_CLASSNAMES = {
907
+ containerOuter: ['choices'],
908
+ containerInner: ['choices__inner'],
909
+ input: ['choices__input'],
910
+ inputCloned: ['choices__input--cloned'],
911
+ list: ['choices__list'],
912
+ listItems: ['choices__list--multiple'],
913
+ listSingle: ['choices__list--single'],
914
+ listDropdown: ['choices__list--dropdown'],
915
+ item: ['choices__item'],
916
+ itemSelectable: ['choices__item--selectable'],
917
+ itemDisabled: ['choices__item--disabled'],
918
+ itemChoice: ['choices__item--choice'],
919
+ description: ['choices__description'],
920
+ placeholder: ['choices__placeholder'],
921
+ group: ['choices__group'],
922
+ groupHeading: ['choices__heading'],
923
+ button: ['choices__button'],
924
+ activeState: ['is-active'],
925
+ focusState: ['is-focused'],
926
+ openState: ['is-open'],
927
+ disabledState: ['is-disabled'],
928
+ highlightedState: ['is-highlighted'],
929
+ selectedState: ['is-selected'],
930
+ flippedState: ['is-flipped'],
931
+ loadingState: ['is-loading'],
932
+ notice: ['choices__notice'],
933
+ addChoice: ['choices__item--selectable', 'add-choice'],
934
+ noResults: ['has-no-results'],
935
+ noChoices: ['has-no-choices'],
936
+ };
937
+ var DEFAULT_CONFIG = {
938
+ items: [],
939
+ choices: [],
940
+ silent: false,
941
+ renderChoiceLimit: -1,
942
+ maxItemCount: -1,
943
+ closeDropdownOnSelect: 'auto',
944
+ singleModeForMultiSelect: false,
945
+ addChoices: false,
946
+ addItems: true,
947
+ addItemFilter: function (value) { return !!value && value !== ''; },
948
+ removeItems: true,
949
+ removeItemButton: false,
950
+ removeItemButtonAlignLeft: false,
951
+ editItems: false,
952
+ allowHTML: false,
953
+ allowHtmlUserInput: false,
954
+ duplicateItemsAllowed: true,
955
+ delimiter: ',',
956
+ paste: true,
957
+ searchEnabled: true,
958
+ searchChoices: true,
959
+ searchFloor: 1,
960
+ searchResultLimit: 4,
961
+ searchFields: ['label', 'value'],
962
+ position: 'auto',
963
+ resetScrollPosition: true,
964
+ shouldSort: true,
965
+ shouldSortItems: false,
966
+ sorter: sortByAlpha,
967
+ shadowRoot: null,
968
+ placeholder: true,
969
+ placeholderValue: null,
970
+ searchPlaceholderValue: null,
971
+ prependValue: null,
972
+ appendValue: null,
973
+ renderSelectedChoices: 'auto',
974
+ loadingText: 'Loading...',
975
+ noResultsText: 'No results found',
976
+ noChoicesText: 'No choices to choose from',
977
+ itemSelectText: 'Press to select',
978
+ uniqueItemText: 'Only unique values can be added',
979
+ customAddItemText: 'Only values matching specific conditions can be added',
980
+ addItemText: function (value) { return "Press Enter to add <b>\"".concat(value, "\"</b>"); },
981
+ removeItemIconText: function () { return "Remove item"; },
982
+ removeItemLabelText: function (value) { return "Remove item: ".concat(value); },
983
+ maxItemText: function (maxItemCount) { return "Only ".concat(maxItemCount, " values can be added"); },
984
+ valueComparer: function (value1, value2) { return value1 === value2; },
985
+ fuseOptions: {
986
+ includeScore: true,
987
+ },
988
+ labelId: '',
989
+ callbackOnInit: null,
990
+ callbackOnCreateTemplates: null,
991
+ classNames: DEFAULT_CLASSNAMES,
992
+ appendGroupInSearch: false,
993
+ };
994
+
995
+ var removeItem = function (item) {
996
+ var itemEl = item.itemEl;
997
+ if (itemEl) {
998
+ itemEl.remove();
999
+ item.itemEl = undefined;
1000
+ }
1001
+ };
1002
+ function items(s, action, context) {
1003
+ var state = s;
1004
+ var update = true;
1005
+ switch (action.type) {
1006
+ case ActionType.ADD_ITEM: {
1007
+ action.item.selected = true;
1008
+ var el = action.item.element;
1009
+ if (el) {
1010
+ el.selected = true;
1011
+ el.setAttribute('selected', '');
1012
+ }
1013
+ state.push(action.item);
1014
+ break;
1015
+ }
1016
+ case ActionType.REMOVE_ITEM: {
1017
+ action.item.selected = false;
1018
+ var el = action.item.element;
1019
+ if (el) {
1020
+ el.selected = false;
1021
+ el.removeAttribute('selected');
1022
+ // 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
1023
+ var select = el.parentElement;
1024
+ if (select && isHtmlSelectElement(select) && select.type === PassedElementTypes.SelectOne) {
1025
+ select.value = '';
1026
+ }
1027
+ }
1028
+ // this is mixing concerns, but this is *so much faster*
1029
+ removeItem(action.item);
1030
+ state = state.filter(function (choice) { return choice.id !== action.item.id; });
1031
+ break;
1032
+ }
1033
+ case ActionType.REMOVE_CHOICE: {
1034
+ removeItem(action.choice);
1035
+ state = state.filter(function (item) { return item.id !== action.choice.id; });
1036
+ break;
1037
+ }
1038
+ case ActionType.HIGHLIGHT_ITEM: {
1039
+ var highlighted = action.highlighted;
1040
+ var item = state.find(function (obj) { return obj.id === action.item.id; });
1041
+ if (item && item.highlighted !== highlighted) {
1042
+ item.highlighted = highlighted;
1043
+ if (context) {
1044
+ updateClassList(item, highlighted ? context.classNames.highlightedState : context.classNames.selectedState, highlighted ? context.classNames.selectedState : context.classNames.highlightedState);
1045
+ }
1046
+ }
1047
+ break;
1048
+ }
1049
+ default: {
1050
+ update = false;
1051
+ break;
1052
+ }
1053
+ }
1054
+ return { state: state, update: update };
1055
+ }
1056
+
1057
+ function groups(s, action) {
1058
+ var state = s;
1059
+ var update = true;
1060
+ switch (action.type) {
1061
+ case ActionType.ADD_GROUP: {
1062
+ state.push(action.group);
1063
+ break;
1064
+ }
1065
+ case ActionType.CLEAR_CHOICES: {
1066
+ state = [];
1067
+ break;
1068
+ }
1069
+ default: {
1070
+ update = false;
1071
+ break;
1072
+ }
1073
+ }
1074
+ return { state: state, update: update };
1075
+ }
1076
+
1077
+ /* eslint-disable */
1078
+ function choices(s, action, context) {
1079
+ var state = s;
1080
+ var update = true;
1081
+ switch (action.type) {
1082
+ case ActionType.ADD_CHOICE: {
1083
+ state.push(action.choice);
1084
+ break;
1085
+ }
1086
+ case ActionType.REMOVE_CHOICE: {
1087
+ action.choice.choiceEl = undefined;
1088
+ if (action.choice.group) {
1089
+ action.choice.group.choices = action.choice.group.choices.filter(function (obj) { return obj.id !== action.choice.id; });
1090
+ }
1091
+ state = state.filter(function (obj) { return obj.id !== action.choice.id; });
1092
+ break;
1093
+ }
1094
+ case ActionType.ADD_ITEM:
1095
+ case ActionType.REMOVE_ITEM: {
1096
+ action.item.choiceEl = undefined;
1097
+ break;
1098
+ }
1099
+ case ActionType.FILTER_CHOICES: {
1100
+ // avoid O(n^2) algorithm complexity when searching/filtering choices
1101
+ var scoreLookup_1 = [];
1102
+ action.results.forEach(function (result) {
1103
+ scoreLookup_1[result.item.id] = result;
1104
+ });
1105
+ state.forEach(function (choice) {
1106
+ var result = scoreLookup_1[choice.id];
1107
+ if (result !== undefined) {
1108
+ choice.score = result.score;
1109
+ choice.rank = result.rank;
1110
+ choice.active = true;
1111
+ }
1112
+ else {
1113
+ choice.score = 0;
1114
+ choice.rank = 0;
1115
+ choice.active = false;
1116
+ }
1117
+ if (context && context.appendGroupInSearch) {
1118
+ choice.choiceEl = undefined;
1119
+ }
1120
+ });
1121
+ break;
1122
+ }
1123
+ case ActionType.ACTIVATE_CHOICES: {
1124
+ state.forEach(function (choice) {
1125
+ choice.active = action.active;
1126
+ if (context && context.appendGroupInSearch) {
1127
+ choice.choiceEl = undefined;
1128
+ }
1129
+ });
1130
+ break;
1131
+ }
1132
+ case ActionType.CLEAR_CHOICES: {
1133
+ state = [];
1134
+ break;
1135
+ }
1136
+ default: {
1137
+ update = false;
1138
+ break;
1139
+ }
1140
+ }
1141
+ return { state: state, update: update };
1142
+ }
1143
+
1144
+ var reducers = {
1145
+ groups: groups,
1146
+ items: items,
1147
+ choices: choices,
1148
+ };
1149
+ var Store = /** @class */ (function () {
1150
+ function Store(context) {
1151
+ this._state = this.defaultState;
1152
+ this._listeners = [];
1153
+ this._txn = 0;
1154
+ this._context = context;
1155
+ }
1156
+ Object.defineProperty(Store.prototype, "defaultState", {
1157
+ // eslint-disable-next-line class-methods-use-this
1158
+ get: function () {
1159
+ return {
1160
+ groups: [],
1161
+ items: [],
1162
+ choices: [],
1163
+ };
1164
+ },
1165
+ enumerable: false,
1166
+ configurable: true
1167
+ });
1168
+ // eslint-disable-next-line class-methods-use-this
1169
+ Store.prototype.changeSet = function (init) {
1170
+ return {
1171
+ groups: init,
1172
+ items: init,
1173
+ choices: init,
1174
+ };
1175
+ };
1176
+ Store.prototype.reset = function () {
1177
+ this._state = this.defaultState;
1178
+ var changes = this.changeSet(true);
1179
+ if (this._txn) {
1180
+ this._changeSet = changes;
1181
+ }
1182
+ else {
1183
+ this._listeners.forEach(function (l) { return l(changes); });
1184
+ }
1185
+ };
1186
+ Store.prototype.subscribe = function (onChange) {
1187
+ this._listeners.push(onChange);
1188
+ return this;
1189
+ };
1190
+ Store.prototype.dispatch = function (action) {
1191
+ var _this = this;
1192
+ var state = this._state;
1193
+ var hasChanges = false;
1194
+ var changes = this._changeSet || this.changeSet(false);
1195
+ Object.keys(reducers).forEach(function (key) {
1196
+ var stateUpdate = reducers[key](state[key], action, _this._context);
1197
+ if (stateUpdate.update) {
1198
+ hasChanges = true;
1199
+ changes[key] = true;
1200
+ state[key] = stateUpdate.state;
1201
+ }
1202
+ });
1203
+ if (hasChanges) {
1204
+ if (this._txn) {
1205
+ this._changeSet = changes;
1206
+ }
1207
+ else {
1208
+ this._listeners.forEach(function (l) { return l(changes); });
1209
+ }
1210
+ }
1211
+ };
1212
+ Store.prototype.withTxn = function (func) {
1213
+ this._txn++;
1214
+ try {
1215
+ func();
1216
+ }
1217
+ finally {
1218
+ this._txn = Math.max(0, this._txn - 1);
1219
+ if (!this._txn) {
1220
+ var changeSet_1 = this._changeSet;
1221
+ if (changeSet_1) {
1222
+ this._changeSet = undefined;
1223
+ this._listeners.forEach(function (l) { return l(changeSet_1); });
1224
+ }
1225
+ }
1226
+ }
1227
+ };
1228
+ Object.defineProperty(Store.prototype, "state", {
1229
+ /**
1230
+ * Get store object
1231
+ */
1232
+ get: function () {
1233
+ return this._state;
1234
+ },
1235
+ enumerable: false,
1236
+ configurable: true
1237
+ });
1238
+ Object.defineProperty(Store.prototype, "items", {
1239
+ /**
1240
+ * Get items from store
1241
+ */
1242
+ get: function () {
1243
+ return this.state.items;
1244
+ },
1245
+ enumerable: false,
1246
+ configurable: true
1247
+ });
1248
+ Object.defineProperty(Store.prototype, "highlightedActiveItems", {
1249
+ /**
1250
+ * Get highlighted items from store
1251
+ */
1252
+ get: function () {
1253
+ return this.items.filter(function (item) { return item.active && item.highlighted; });
1254
+ },
1255
+ enumerable: false,
1256
+ configurable: true
1257
+ });
1258
+ Object.defineProperty(Store.prototype, "choices", {
1259
+ /**
1260
+ * Get choices from store
1261
+ */
1262
+ get: function () {
1263
+ return this.state.choices;
1264
+ },
1265
+ enumerable: false,
1266
+ configurable: true
1267
+ });
1268
+ Object.defineProperty(Store.prototype, "activeChoices", {
1269
+ /**
1270
+ * Get active choices from store
1271
+ */
1272
+ get: function () {
1273
+ return this.choices.filter(function (choice) { return choice.active; });
1274
+ },
1275
+ enumerable: false,
1276
+ configurable: true
1277
+ });
1278
+ Object.defineProperty(Store.prototype, "searchableChoices", {
1279
+ /**
1280
+ * Get choices that can be searched (excluding placeholders or disabled choices)
1281
+ */
1282
+ get: function () {
1283
+ return this.choices.filter(function (choice) { return !choice.disabled && !choice.placeholder; });
1284
+ },
1285
+ enumerable: false,
1286
+ configurable: true
1287
+ });
1288
+ Object.defineProperty(Store.prototype, "groups", {
1289
+ /**
1290
+ * Get groups from store
1291
+ */
1292
+ get: function () {
1293
+ return this.state.groups;
1294
+ },
1295
+ enumerable: false,
1296
+ configurable: true
1297
+ });
1298
+ Object.defineProperty(Store.prototype, "activeGroups", {
1299
+ /**
1300
+ * Get active groups from store
1301
+ */
1302
+ get: function () {
1303
+ var _this = this;
1304
+ return this.state.groups.filter(function (group) {
1305
+ var isActive = group.active && !group.disabled;
1306
+ var hasActiveOptions = _this.state.choices.some(function (choice) { return choice.active && !choice.disabled; });
1307
+ return isActive && hasActiveOptions;
1308
+ }, []);
1309
+ },
1310
+ enumerable: false,
1311
+ configurable: true
1312
+ });
1313
+ Store.prototype.inTxn = function () {
1314
+ return this._txn > 0;
1315
+ };
1316
+ /**
1317
+ * Get single choice by it's ID
1318
+ */
1319
+ Store.prototype.getChoiceById = function (id) {
1320
+ return this.activeChoices.find(function (choice) { return choice.id === id; });
1321
+ };
1322
+ /**
1323
+ * Get group by group id
1324
+ */
1325
+ Store.prototype.getGroupById = function (id) {
1326
+ return this.groups.find(function (group) { return group.id === id; });
1327
+ };
1328
+ return Store;
1329
+ }());
1330
+
1331
+ var NoticeTypes = {
1332
+ noChoices: 'no-choices',
1333
+ noResults: 'no-results',
1334
+ addChoice: 'add-choice',
1335
+ generic: '',
1336
+ };
1337
+
1338
+ function _defineProperty(e, r, t) {
1339
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
1340
+ value: t,
1341
+ enumerable: !0,
1342
+ configurable: !0,
1343
+ writable: !0
1344
+ }) : e[r] = t, e;
1345
+ }
1346
+ function ownKeys(e, r) {
1347
+ var t = Object.keys(e);
1348
+ if (Object.getOwnPropertySymbols) {
1349
+ var o = Object.getOwnPropertySymbols(e);
1350
+ r && (o = o.filter(function (r) {
1351
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
1352
+ })), t.push.apply(t, o);
1353
+ }
1354
+ return t;
1355
+ }
1356
+ function _objectSpread2(e) {
1357
+ for (var r = 1; r < arguments.length; r++) {
1358
+ var t = null != arguments[r] ? arguments[r] : {};
1359
+ r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
1360
+ _defineProperty(e, r, t[r]);
1361
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
1362
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
1363
+ });
1364
+ }
1365
+ return e;
1366
+ }
1367
+ function _toPrimitive(t, r) {
1368
+ if ("object" != typeof t || !t) return t;
1369
+ var e = t[Symbol.toPrimitive];
1370
+ if (void 0 !== e) {
1371
+ var i = e.call(t, r || "default");
1372
+ if ("object" != typeof i) return i;
1373
+ throw new TypeError("@@toPrimitive must return a primitive value.");
1374
+ }
1375
+ return ("string" === r ? String : Number)(t);
1376
+ }
1377
+ function _toPropertyKey(t) {
1378
+ var i = _toPrimitive(t, "string");
1379
+ return "symbol" == typeof i ? i : i + "";
1380
+ }
1381
+
1382
+ /**
1383
+ * Fuse.js v7.0.0 - Lightweight fuzzy-search (http://fusejs.io)
1384
+ *
1385
+ * Copyright (c) 2023 Kiro Risk (http://kiro.me)
1386
+ * All Rights Reserved. Apache Software License 2.0
1387
+ *
1388
+ * http://www.apache.org/licenses/LICENSE-2.0
1389
+ */
1390
+
1391
+ function isArray(value) {
1392
+ return !Array.isArray ? getTag(value) === '[object Array]' : Array.isArray(value);
1393
+ }
1394
+
1395
+ // Adapted from: https://github.com/lodash/lodash/blob/master/.internal/baseToString.js
1396
+ const INFINITY = 1 / 0;
1397
+ function baseToString(value) {
1398
+ // Exit early for strings to avoid a performance hit in some environments.
1399
+ if (typeof value == 'string') {
1400
+ return value;
1401
+ }
1402
+ let result = value + '';
1403
+ return result == '0' && 1 / value == -INFINITY ? '-0' : result;
1404
+ }
1405
+ function toString(value) {
1406
+ return value == null ? '' : baseToString(value);
1407
+ }
1408
+ function isString(value) {
1409
+ return typeof value === 'string';
1410
+ }
1411
+ function isNumber(value) {
1412
+ return typeof value === 'number';
1413
+ }
1414
+
1415
+ // Adapted from: https://github.com/lodash/lodash/blob/master/isBoolean.js
1416
+ function isBoolean(value) {
1417
+ return value === true || value === false || isObjectLike(value) && getTag(value) == '[object Boolean]';
1418
+ }
1419
+ function isObject(value) {
1420
+ return typeof value === 'object';
1421
+ }
1422
+
1423
+ // Checks if `value` is object-like.
1424
+ function isObjectLike(value) {
1425
+ return isObject(value) && value !== null;
1426
+ }
1427
+ function isDefined(value) {
1428
+ return value !== undefined && value !== null;
1429
+ }
1430
+ function isBlank(value) {
1431
+ return !value.trim().length;
1432
+ }
1433
+
1434
+ // Gets the `toStringTag` of `value`.
1435
+ // Adapted from: https://github.com/lodash/lodash/blob/master/.internal/getTag.js
1436
+ function getTag(value) {
1437
+ return value == null ? value === undefined ? '[object Undefined]' : '[object Null]' : Object.prototype.toString.call(value);
1438
+ }
1439
+ const EXTENDED_SEARCH_UNAVAILABLE = 'Extended search is not available';
1440
+ const LOGICAL_SEARCH_UNAVAILABLE = 'Logical search is not available';
1441
+ const INCORRECT_INDEX_TYPE = "Incorrect 'index' type";
1442
+ const LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = key => `Invalid value for key ${key}`;
1443
+ const PATTERN_LENGTH_TOO_LARGE = max => `Pattern length exceeds max of ${max}.`;
1444
+ const MISSING_KEY_PROPERTY = name => `Missing ${name} property in key`;
1445
+ const INVALID_KEY_WEIGHT_VALUE = key => `Property 'weight' in key '${key}' must be a positive integer`;
1446
+ const hasOwn = Object.prototype.hasOwnProperty;
1447
+ class KeyStore {
1448
+ constructor(keys) {
1449
+ this._keys = [];
1450
+ this._keyMap = {};
1451
+ let totalWeight = 0;
1452
+ keys.forEach(key => {
1453
+ let obj = createKey(key);
1454
+ this._keys.push(obj);
1455
+ this._keyMap[obj.id] = obj;
1456
+ totalWeight += obj.weight;
1457
+ });
1458
+
1459
+ // Normalize weights so that their sum is equal to 1
1460
+ this._keys.forEach(key => {
1461
+ key.weight /= totalWeight;
1462
+ });
1463
+ }
1464
+ get(keyId) {
1465
+ return this._keyMap[keyId];
1466
+ }
1467
+ keys() {
1468
+ return this._keys;
1469
+ }
1470
+ toJSON() {
1471
+ return JSON.stringify(this._keys);
1472
+ }
1473
+ }
1474
+ function createKey(key) {
1475
+ let path = null;
1476
+ let id = null;
1477
+ let src = null;
1478
+ let weight = 1;
1479
+ let getFn = null;
1480
+ if (isString(key) || isArray(key)) {
1481
+ src = key;
1482
+ path = createKeyPath(key);
1483
+ id = createKeyId(key);
1484
+ } else {
1485
+ if (!hasOwn.call(key, 'name')) {
1486
+ throw new Error(MISSING_KEY_PROPERTY('name'));
1487
+ }
1488
+ const name = key.name;
1489
+ src = name;
1490
+ if (hasOwn.call(key, 'weight')) {
1491
+ weight = key.weight;
1492
+ if (weight <= 0) {
1493
+ throw new Error(INVALID_KEY_WEIGHT_VALUE(name));
1494
+ }
1495
+ }
1496
+ path = createKeyPath(name);
1497
+ id = createKeyId(name);
1498
+ getFn = key.getFn;
1499
+ }
1500
+ return {
1501
+ path,
1502
+ id,
1503
+ weight,
1504
+ src,
1505
+ getFn
1506
+ };
1507
+ }
1508
+ function createKeyPath(key) {
1509
+ return isArray(key) ? key : key.split('.');
1510
+ }
1511
+ function createKeyId(key) {
1512
+ return isArray(key) ? key.join('.') : key;
1513
+ }
1514
+ function get(obj, path) {
1515
+ let list = [];
1516
+ let arr = false;
1517
+ const deepGet = (obj, path, index) => {
1518
+ if (!isDefined(obj)) {
1519
+ return;
1520
+ }
1521
+ if (!path[index]) {
1522
+ // If there's no path left, we've arrived at the object we care about.
1523
+ list.push(obj);
1524
+ } else {
1525
+ let key = path[index];
1526
+ const value = obj[key];
1527
+ if (!isDefined(value)) {
1528
+ return;
1529
+ }
1530
+
1531
+ // If we're at the last value in the path, and if it's a string/number/bool,
1532
+ // add it to the list
1533
+ if (index === path.length - 1 && (isString(value) || isNumber(value) || isBoolean(value))) {
1534
+ list.push(toString(value));
1535
+ } else if (isArray(value)) {
1536
+ arr = true;
1537
+ // Search each item in the array.
1538
+ for (let i = 0, len = value.length; i < len; i += 1) {
1539
+ deepGet(value[i], path, index + 1);
1540
+ }
1541
+ } else if (path.length) {
1542
+ // An object. Recurse further.
1543
+ deepGet(value, path, index + 1);
1544
+ }
1545
+ }
1546
+ };
1547
+
1548
+ // Backwards compatibility (since path used to be a string)
1549
+ deepGet(obj, isString(path) ? path.split('.') : path, 0);
1550
+ return arr ? list : list[0];
1551
+ }
1552
+ const MatchOptions = {
1553
+ // Whether the matches should be included in the result set. When `true`, each record in the result
1554
+ // set will include the indices of the matched characters.
1555
+ // These can consequently be used for highlighting purposes.
1556
+ includeMatches: false,
1557
+ // When `true`, the matching function will continue to the end of a search pattern even if
1558
+ // a perfect match has already been located in the string.
1559
+ findAllMatches: false,
1560
+ // Minimum number of characters that must be matched before a result is considered a match
1561
+ minMatchCharLength: 1
1562
+ };
1563
+ const BasicOptions = {
1564
+ // When `true`, the algorithm continues searching to the end of the input even if a perfect
1565
+ // match is found before the end of the same input.
1566
+ isCaseSensitive: false,
1567
+ // When true, the matching function will continue to the end of a search pattern even if
1568
+ includeScore: false,
1569
+ // List of properties that will be searched. This also supports nested properties.
1570
+ keys: [],
1571
+ // Whether to sort the result list, by score
1572
+ shouldSort: true,
1573
+ // Default sort function: sort by ascending score, ascending index
1574
+ sortFn: (a, b) => a.score === b.score ? a.idx < b.idx ? -1 : 1 : a.score < b.score ? -1 : 1
1575
+ };
1576
+ const FuzzyOptions = {
1577
+ // Approximately where in the text is the pattern expected to be found?
1578
+ location: 0,
1579
+ // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match
1580
+ // (of both letters and location), a threshold of '1.0' would match anything.
1581
+ threshold: 0.6,
1582
+ // Determines how close the match must be to the fuzzy location (specified above).
1583
+ // An exact letter match which is 'distance' characters away from the fuzzy location
1584
+ // would score as a complete mismatch. A distance of '0' requires the match be at
1585
+ // the exact location specified, a threshold of '1000' would require a perfect match
1586
+ // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.
1587
+ distance: 100
1588
+ };
1589
+ const AdvancedOptions = {
1590
+ // When `true`, it enables the use of unix-like search commands
1591
+ useExtendedSearch: false,
1592
+ // The get function to use when fetching an object's properties.
1593
+ // The default will search nested paths *ie foo.bar.baz*
1594
+ getFn: get,
1595
+ // When `true`, search will ignore `location` and `distance`, so it won't matter
1596
+ // where in the string the pattern appears.
1597
+ // More info: https://fusejs.io/concepts/scoring-theory.html#fuzziness-score
1598
+ ignoreLocation: false,
1599
+ // When `true`, the calculation for the relevance score (used for sorting) will
1600
+ // ignore the field-length norm.
1601
+ // More info: https://fusejs.io/concepts/scoring-theory.html#field-length-norm
1602
+ ignoreFieldNorm: false,
1603
+ // The weight to determine how much field length norm effects scoring.
1604
+ fieldNormWeight: 1
1605
+ };
1606
+ var Config = _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, BasicOptions), MatchOptions), FuzzyOptions), AdvancedOptions);
1607
+ const SPACE = /[^ ]+/g;
1608
+
1609
+ // Field-length norm: the shorter the field, the higher the weight.
1610
+ // Set to 3 decimals to reduce index size.
1611
+ function norm(weight = 1, mantissa = 3) {
1612
+ const cache = new Map();
1613
+ const m = Math.pow(10, mantissa);
1614
+ return {
1615
+ get(value) {
1616
+ const numTokens = value.match(SPACE).length;
1617
+ if (cache.has(numTokens)) {
1618
+ return cache.get(numTokens);
1619
+ }
1620
+
1621
+ // Default function is 1/sqrt(x), weight makes that variable
1622
+ const norm = 1 / Math.pow(numTokens, 0.5 * weight);
1623
+
1624
+ // In place of `toFixed(mantissa)`, for faster computation
1625
+ const n = parseFloat(Math.round(norm * m) / m);
1626
+ cache.set(numTokens, n);
1627
+ return n;
1628
+ },
1629
+ clear() {
1630
+ cache.clear();
1631
+ }
1632
+ };
1633
+ }
1634
+ class FuseIndex {
1635
+ constructor({
1636
+ getFn = Config.getFn,
1637
+ fieldNormWeight = Config.fieldNormWeight
1638
+ } = {}) {
1639
+ this.norm = norm(fieldNormWeight, 3);
1640
+ this.getFn = getFn;
1641
+ this.isCreated = false;
1642
+ this.setIndexRecords();
1643
+ }
1644
+ setSources(docs = []) {
1645
+ this.docs = docs;
1646
+ }
1647
+ setIndexRecords(records = []) {
1648
+ this.records = records;
1649
+ }
1650
+ setKeys(keys = []) {
1651
+ this.keys = keys;
1652
+ this._keysMap = {};
1653
+ keys.forEach((key, idx) => {
1654
+ this._keysMap[key.id] = idx;
1655
+ });
1656
+ }
1657
+ create() {
1658
+ if (this.isCreated || !this.docs.length) {
1659
+ return;
1660
+ }
1661
+ this.isCreated = true;
1662
+
1663
+ // List is Array<String>
1664
+ if (isString(this.docs[0])) {
1665
+ this.docs.forEach((doc, docIndex) => {
1666
+ this._addString(doc, docIndex);
1667
+ });
1668
+ } else {
1669
+ // List is Array<Object>
1670
+ this.docs.forEach((doc, docIndex) => {
1671
+ this._addObject(doc, docIndex);
1672
+ });
1673
+ }
1674
+ this.norm.clear();
1675
+ }
1676
+ // Adds a doc to the end of the index
1677
+ add(doc) {
1678
+ const idx = this.size();
1679
+ if (isString(doc)) {
1680
+ this._addString(doc, idx);
1681
+ } else {
1682
+ this._addObject(doc, idx);
1683
+ }
1684
+ }
1685
+ // Removes the doc at the specified index of the index
1686
+ removeAt(idx) {
1687
+ this.records.splice(idx, 1);
1688
+
1689
+ // Change ref index of every subsquent doc
1690
+ for (let i = idx, len = this.size(); i < len; i += 1) {
1691
+ this.records[i].i -= 1;
1692
+ }
1693
+ }
1694
+ getValueForItemAtKeyId(item, keyId) {
1695
+ return item[this._keysMap[keyId]];
1696
+ }
1697
+ size() {
1698
+ return this.records.length;
1699
+ }
1700
+ _addString(doc, docIndex) {
1701
+ if (!isDefined(doc) || isBlank(doc)) {
1702
+ return;
1703
+ }
1704
+ let record = {
1705
+ v: doc,
1706
+ i: docIndex,
1707
+ n: this.norm.get(doc)
1708
+ };
1709
+ this.records.push(record);
1710
+ }
1711
+ _addObject(doc, docIndex) {
1712
+ let record = {
1713
+ i: docIndex,
1714
+ $: {}
1715
+ };
1716
+
1717
+ // Iterate over every key (i.e, path), and fetch the value at that key
1718
+ this.keys.forEach((key, keyIndex) => {
1719
+ let value = key.getFn ? key.getFn(doc) : this.getFn(doc, key.path);
1720
+ if (!isDefined(value)) {
1721
+ return;
1722
+ }
1723
+ if (isArray(value)) {
1724
+ let subRecords = [];
1725
+ const stack = [{
1726
+ nestedArrIndex: -1,
1727
+ value
1728
+ }];
1729
+ while (stack.length) {
1730
+ const {
1731
+ nestedArrIndex,
1732
+ value
1733
+ } = stack.pop();
1734
+ if (!isDefined(value)) {
1735
+ continue;
1736
+ }
1737
+ if (isString(value) && !isBlank(value)) {
1738
+ let subRecord = {
1739
+ v: value,
1740
+ i: nestedArrIndex,
1741
+ n: this.norm.get(value)
1742
+ };
1743
+ subRecords.push(subRecord);
1744
+ } else if (isArray(value)) {
1745
+ value.forEach((item, k) => {
1746
+ stack.push({
1747
+ nestedArrIndex: k,
1748
+ value: item
1749
+ });
1750
+ });
1751
+ } else ;
1752
+ }
1753
+ record.$[keyIndex] = subRecords;
1754
+ } else if (isString(value) && !isBlank(value)) {
1755
+ let subRecord = {
1756
+ v: value,
1757
+ n: this.norm.get(value)
1758
+ };
1759
+ record.$[keyIndex] = subRecord;
1760
+ }
1761
+ });
1762
+ this.records.push(record);
1763
+ }
1764
+ toJSON() {
1765
+ return {
1766
+ keys: this.keys,
1767
+ records: this.records
1768
+ };
1769
+ }
1770
+ }
1771
+ function createIndex(keys, docs, {
1772
+ getFn = Config.getFn,
1773
+ fieldNormWeight = Config.fieldNormWeight
1774
+ } = {}) {
1775
+ const myIndex = new FuseIndex({
1776
+ getFn,
1777
+ fieldNormWeight
1778
+ });
1779
+ myIndex.setKeys(keys.map(createKey));
1780
+ myIndex.setSources(docs);
1781
+ myIndex.create();
1782
+ return myIndex;
1783
+ }
1784
+ function parseIndex(data, {
1785
+ getFn = Config.getFn,
1786
+ fieldNormWeight = Config.fieldNormWeight
1787
+ } = {}) {
1788
+ const {
1789
+ keys,
1790
+ records
1791
+ } = data;
1792
+ const myIndex = new FuseIndex({
1793
+ getFn,
1794
+ fieldNormWeight
1795
+ });
1796
+ myIndex.setKeys(keys);
1797
+ myIndex.setIndexRecords(records);
1798
+ return myIndex;
1799
+ }
1800
+ function computeScore$1(pattern, {
1801
+ errors = 0,
1802
+ currentLocation = 0,
1803
+ expectedLocation = 0,
1804
+ distance = Config.distance,
1805
+ ignoreLocation = Config.ignoreLocation
1806
+ } = {}) {
1807
+ const accuracy = errors / pattern.length;
1808
+ if (ignoreLocation) {
1809
+ return accuracy;
1810
+ }
1811
+ const proximity = Math.abs(expectedLocation - currentLocation);
1812
+ if (!distance) {
1813
+ // Dodge divide by zero error.
1814
+ return proximity ? 1.0 : accuracy;
1815
+ }
1816
+ return accuracy + proximity / distance;
1817
+ }
1818
+ function convertMaskToIndices(matchmask = [], minMatchCharLength = Config.minMatchCharLength) {
1819
+ let indices = [];
1820
+ let start = -1;
1821
+ let end = -1;
1822
+ let i = 0;
1823
+ for (let len = matchmask.length; i < len; i += 1) {
1824
+ let match = matchmask[i];
1825
+ if (match && start === -1) {
1826
+ start = i;
1827
+ } else if (!match && start !== -1) {
1828
+ end = i - 1;
1829
+ if (end - start + 1 >= minMatchCharLength) {
1830
+ indices.push([start, end]);
1831
+ }
1832
+ start = -1;
1833
+ }
1834
+ }
1835
+
1836
+ // (i-1 - start) + 1 => i - start
1837
+ if (matchmask[i - 1] && i - start >= minMatchCharLength) {
1838
+ indices.push([start, i - 1]);
1839
+ }
1840
+ return indices;
1841
+ }
1842
+
1843
+ // Machine word size
1844
+ const MAX_BITS = 32;
1845
+ function search(text, pattern, patternAlphabet, {
1846
+ location = Config.location,
1847
+ distance = Config.distance,
1848
+ threshold = Config.threshold,
1849
+ findAllMatches = Config.findAllMatches,
1850
+ minMatchCharLength = Config.minMatchCharLength,
1851
+ includeMatches = Config.includeMatches,
1852
+ ignoreLocation = Config.ignoreLocation
1853
+ } = {}) {
1854
+ if (pattern.length > MAX_BITS) {
1855
+ throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS));
1856
+ }
1857
+ const patternLen = pattern.length;
1858
+ // Set starting location at beginning text and initialize the alphabet.
1859
+ const textLen = text.length;
1860
+ // Handle the case when location > text.length
1861
+ const expectedLocation = Math.max(0, Math.min(location, textLen));
1862
+ // Highest score beyond which we give up.
1863
+ let currentThreshold = threshold;
1864
+ // Is there a nearby exact match? (speedup)
1865
+ let bestLocation = expectedLocation;
1866
+
1867
+ // Performance: only computer matches when the minMatchCharLength > 1
1868
+ // OR if `includeMatches` is true.
1869
+ const computeMatches = minMatchCharLength > 1 || includeMatches;
1870
+ // A mask of the matches, used for building the indices
1871
+ const matchMask = computeMatches ? Array(textLen) : [];
1872
+ let index;
1873
+
1874
+ // Get all exact matches, here for speed up
1875
+ while ((index = text.indexOf(pattern, bestLocation)) > -1) {
1876
+ let score = computeScore$1(pattern, {
1877
+ currentLocation: index,
1878
+ expectedLocation,
1879
+ distance,
1880
+ ignoreLocation
1881
+ });
1882
+ currentThreshold = Math.min(score, currentThreshold);
1883
+ bestLocation = index + patternLen;
1884
+ if (computeMatches) {
1885
+ let i = 0;
1886
+ while (i < patternLen) {
1887
+ matchMask[index + i] = 1;
1888
+ i += 1;
1889
+ }
1890
+ }
1891
+ }
1892
+
1893
+ // Reset the best location
1894
+ bestLocation = -1;
1895
+ let lastBitArr = [];
1896
+ let finalScore = 1;
1897
+ let binMax = patternLen + textLen;
1898
+ const mask = 1 << patternLen - 1;
1899
+ for (let i = 0; i < patternLen; i += 1) {
1900
+ // Scan for the best match; each iteration allows for one more error.
1901
+ // Run a binary search to determine how far from the match location we can stray
1902
+ // at this error level.
1903
+ let binMin = 0;
1904
+ let binMid = binMax;
1905
+ while (binMin < binMid) {
1906
+ const score = computeScore$1(pattern, {
1907
+ errors: i,
1908
+ currentLocation: expectedLocation + binMid,
1909
+ expectedLocation,
1910
+ distance,
1911
+ ignoreLocation
1912
+ });
1913
+ if (score <= currentThreshold) {
1914
+ binMin = binMid;
1915
+ } else {
1916
+ binMax = binMid;
1917
+ }
1918
+ binMid = Math.floor((binMax - binMin) / 2 + binMin);
1919
+ }
1920
+
1921
+ // Use the result from this iteration as the maximum for the next.
1922
+ binMax = binMid;
1923
+ let start = Math.max(1, expectedLocation - binMid + 1);
1924
+ let finish = findAllMatches ? textLen : Math.min(expectedLocation + binMid, textLen) + patternLen;
1925
+
1926
+ // Initialize the bit array
1927
+ let bitArr = Array(finish + 2);
1928
+ bitArr[finish + 1] = (1 << i) - 1;
1929
+ for (let j = finish; j >= start; j -= 1) {
1930
+ let currentLocation = j - 1;
1931
+ let charMatch = patternAlphabet[text.charAt(currentLocation)];
1932
+ if (computeMatches) {
1933
+ // Speed up: quick bool to int conversion (i.e, `charMatch ? 1 : 0`)
1934
+ matchMask[currentLocation] = +!!charMatch;
1935
+ }
1936
+
1937
+ // First pass: exact match
1938
+ bitArr[j] = (bitArr[j + 1] << 1 | 1) & charMatch;
1939
+
1940
+ // Subsequent passes: fuzzy match
1941
+ if (i) {
1942
+ bitArr[j] |= (lastBitArr[j + 1] | lastBitArr[j]) << 1 | 1 | lastBitArr[j + 1];
1943
+ }
1944
+ if (bitArr[j] & mask) {
1945
+ finalScore = computeScore$1(pattern, {
1946
+ errors: i,
1947
+ currentLocation,
1948
+ expectedLocation,
1949
+ distance,
1950
+ ignoreLocation
1951
+ });
1952
+
1953
+ // This match will almost certainly be better than any existing match.
1954
+ // But check anyway.
1955
+ if (finalScore <= currentThreshold) {
1956
+ // Indeed it is
1957
+ currentThreshold = finalScore;
1958
+ bestLocation = currentLocation;
1959
+
1960
+ // Already passed `loc`, downhill from here on in.
1961
+ if (bestLocation <= expectedLocation) {
1962
+ break;
1963
+ }
1964
+
1965
+ // When passing `bestLocation`, don't exceed our current distance from `expectedLocation`.
1966
+ start = Math.max(1, 2 * expectedLocation - bestLocation);
1967
+ }
1968
+ }
1969
+ }
1970
+
1971
+ // No hope for a (better) match at greater error levels.
1972
+ const score = computeScore$1(pattern, {
1973
+ errors: i + 1,
1974
+ currentLocation: expectedLocation,
1975
+ expectedLocation,
1976
+ distance,
1977
+ ignoreLocation
1978
+ });
1979
+ if (score > currentThreshold) {
1980
+ break;
1981
+ }
1982
+ lastBitArr = bitArr;
1983
+ }
1984
+ const result = {
1985
+ isMatch: bestLocation >= 0,
1986
+ // Count exact matches (those with a score of 0) to be "almost" exact
1987
+ score: Math.max(0.001, finalScore)
1988
+ };
1989
+ if (computeMatches) {
1990
+ const indices = convertMaskToIndices(matchMask, minMatchCharLength);
1991
+ if (!indices.length) {
1992
+ result.isMatch = false;
1993
+ } else if (includeMatches) {
1994
+ result.indices = indices;
1995
+ }
1996
+ }
1997
+ return result;
1998
+ }
1999
+ function createPatternAlphabet(pattern) {
2000
+ let mask = {};
2001
+ for (let i = 0, len = pattern.length; i < len; i += 1) {
2002
+ const char = pattern.charAt(i);
2003
+ mask[char] = (mask[char] || 0) | 1 << len - i - 1;
2004
+ }
2005
+ return mask;
2006
+ }
2007
+ class BitapSearch {
2008
+ constructor(pattern, {
2009
+ location = Config.location,
2010
+ threshold = Config.threshold,
2011
+ distance = Config.distance,
2012
+ includeMatches = Config.includeMatches,
2013
+ findAllMatches = Config.findAllMatches,
2014
+ minMatchCharLength = Config.minMatchCharLength,
2015
+ isCaseSensitive = Config.isCaseSensitive,
2016
+ ignoreLocation = Config.ignoreLocation
2017
+ } = {}) {
2018
+ this.options = {
2019
+ location,
2020
+ threshold,
2021
+ distance,
2022
+ includeMatches,
2023
+ findAllMatches,
2024
+ minMatchCharLength,
2025
+ isCaseSensitive,
2026
+ ignoreLocation
2027
+ };
2028
+ this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase();
2029
+ this.chunks = [];
2030
+ if (!this.pattern.length) {
2031
+ return;
2032
+ }
2033
+ const addChunk = (pattern, startIndex) => {
2034
+ this.chunks.push({
2035
+ pattern,
2036
+ alphabet: createPatternAlphabet(pattern),
2037
+ startIndex
2038
+ });
2039
+ };
2040
+ const len = this.pattern.length;
2041
+ if (len > MAX_BITS) {
2042
+ let i = 0;
2043
+ const remainder = len % MAX_BITS;
2044
+ const end = len - remainder;
2045
+ while (i < end) {
2046
+ addChunk(this.pattern.substr(i, MAX_BITS), i);
2047
+ i += MAX_BITS;
2048
+ }
2049
+ if (remainder) {
2050
+ const startIndex = len - MAX_BITS;
2051
+ addChunk(this.pattern.substr(startIndex), startIndex);
2052
+ }
2053
+ } else {
2054
+ addChunk(this.pattern, 0);
2055
+ }
2056
+ }
2057
+ searchIn(text) {
2058
+ const {
2059
+ isCaseSensitive,
2060
+ includeMatches
2061
+ } = this.options;
2062
+ if (!isCaseSensitive) {
2063
+ text = text.toLowerCase();
2064
+ }
2065
+
2066
+ // Exact match
2067
+ if (this.pattern === text) {
2068
+ let result = {
2069
+ isMatch: true,
2070
+ score: 0
2071
+ };
2072
+ if (includeMatches) {
2073
+ result.indices = [[0, text.length - 1]];
2074
+ }
2075
+ return result;
2076
+ }
2077
+
2078
+ // Otherwise, use Bitap algorithm
2079
+ const {
2080
+ location,
2081
+ distance,
2082
+ threshold,
2083
+ findAllMatches,
2084
+ minMatchCharLength,
2085
+ ignoreLocation
2086
+ } = this.options;
2087
+ let allIndices = [];
2088
+ let totalScore = 0;
2089
+ let hasMatches = false;
2090
+ this.chunks.forEach(({
2091
+ pattern,
2092
+ alphabet,
2093
+ startIndex
2094
+ }) => {
2095
+ const {
2096
+ isMatch,
2097
+ score,
2098
+ indices
2099
+ } = search(text, pattern, alphabet, {
2100
+ location: location + startIndex,
2101
+ distance,
2102
+ threshold,
2103
+ findAllMatches,
2104
+ minMatchCharLength,
2105
+ includeMatches,
2106
+ ignoreLocation
2107
+ });
2108
+ if (isMatch) {
2109
+ hasMatches = true;
2110
+ }
2111
+ totalScore += score;
2112
+ if (isMatch && indices) {
2113
+ allIndices = [...allIndices, ...indices];
2114
+ }
2115
+ });
2116
+ let result = {
2117
+ isMatch: hasMatches,
2118
+ score: hasMatches ? totalScore / this.chunks.length : 1
2119
+ };
2120
+ if (hasMatches && includeMatches) {
2121
+ result.indices = allIndices;
2122
+ }
2123
+ return result;
2124
+ }
2125
+ }
2126
+ const registeredSearchers = [];
2127
+ function createSearcher(pattern, options) {
2128
+ for (let i = 0, len = registeredSearchers.length; i < len; i += 1) {
2129
+ let searcherClass = registeredSearchers[i];
2130
+ if (searcherClass.condition(pattern, options)) {
2131
+ return new searcherClass(pattern, options);
2132
+ }
2133
+ }
2134
+ return new BitapSearch(pattern, options);
2135
+ }
2136
+ const LogicalOperator = {
2137
+ AND: '$and',
2138
+ OR: '$or'
2139
+ };
2140
+ const KeyType = {
2141
+ PATH: '$path',
2142
+ PATTERN: '$val'
2143
+ };
2144
+ const isExpression = query => !!(query[LogicalOperator.AND] || query[LogicalOperator.OR]);
2145
+ const isPath = query => !!query[KeyType.PATH];
2146
+ const isLeaf = query => !isArray(query) && isObject(query) && !isExpression(query);
2147
+ const convertToExplicit = query => ({
2148
+ [LogicalOperator.AND]: Object.keys(query).map(key => ({
2149
+ [key]: query[key]
2150
+ }))
2151
+ });
2152
+
2153
+ // When `auto` is `true`, the parse function will infer and initialize and add
2154
+ // the appropriate `Searcher` instance
2155
+ function parse(query, options, {
2156
+ auto = true
2157
+ } = {}) {
2158
+ const next = query => {
2159
+ let keys = Object.keys(query);
2160
+ const isQueryPath = isPath(query);
2161
+ if (!isQueryPath && keys.length > 1 && !isExpression(query)) {
2162
+ return next(convertToExplicit(query));
2163
+ }
2164
+ if (isLeaf(query)) {
2165
+ const key = isQueryPath ? query[KeyType.PATH] : keys[0];
2166
+ const pattern = isQueryPath ? query[KeyType.PATTERN] : query[key];
2167
+ if (!isString(pattern)) {
2168
+ throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key));
2169
+ }
2170
+ const obj = {
2171
+ keyId: createKeyId(key),
2172
+ pattern
2173
+ };
2174
+ if (auto) {
2175
+ obj.searcher = createSearcher(pattern, options);
2176
+ }
2177
+ return obj;
2178
+ }
2179
+ let node = {
2180
+ children: [],
2181
+ operator: keys[0]
2182
+ };
2183
+ keys.forEach(key => {
2184
+ const value = query[key];
2185
+ if (isArray(value)) {
2186
+ value.forEach(item => {
2187
+ node.children.push(next(item));
2188
+ });
2189
+ }
2190
+ });
2191
+ return node;
2192
+ };
2193
+ if (!isExpression(query)) {
2194
+ query = convertToExplicit(query);
2195
+ }
2196
+ return next(query);
2197
+ }
2198
+
2199
+ // Practical scoring function
2200
+ function computeScore(results, {
2201
+ ignoreFieldNorm = Config.ignoreFieldNorm
2202
+ }) {
2203
+ results.forEach(result => {
2204
+ let totalScore = 1;
2205
+ result.matches.forEach(({
2206
+ key,
2207
+ norm,
2208
+ score
2209
+ }) => {
2210
+ const weight = key ? key.weight : null;
2211
+ totalScore *= Math.pow(score === 0 && weight ? Number.EPSILON : score, (weight || 1) * (ignoreFieldNorm ? 1 : norm));
2212
+ });
2213
+ result.score = totalScore;
2214
+ });
2215
+ }
2216
+ function transformMatches(result, data) {
2217
+ const matches = result.matches;
2218
+ data.matches = [];
2219
+ if (!isDefined(matches)) {
2220
+ return;
2221
+ }
2222
+ matches.forEach(match => {
2223
+ if (!isDefined(match.indices) || !match.indices.length) {
2224
+ return;
2225
+ }
2226
+ const {
2227
+ indices,
2228
+ value
2229
+ } = match;
2230
+ let obj = {
2231
+ indices,
2232
+ value
2233
+ };
2234
+ if (match.key) {
2235
+ obj.key = match.key.src;
2236
+ }
2237
+ if (match.idx > -1) {
2238
+ obj.refIndex = match.idx;
2239
+ }
2240
+ data.matches.push(obj);
2241
+ });
2242
+ }
2243
+ function transformScore(result, data) {
2244
+ data.score = result.score;
2245
+ }
2246
+ function format(results, docs, {
2247
+ includeMatches = Config.includeMatches,
2248
+ includeScore = Config.includeScore
2249
+ } = {}) {
2250
+ const transformers = [];
2251
+ if (includeMatches) transformers.push(transformMatches);
2252
+ if (includeScore) transformers.push(transformScore);
2253
+ return results.map(result => {
2254
+ const {
2255
+ idx
2256
+ } = result;
2257
+ const data = {
2258
+ item: docs[idx],
2259
+ refIndex: idx
2260
+ };
2261
+ if (transformers.length) {
2262
+ transformers.forEach(transformer => {
2263
+ transformer(result, data);
2264
+ });
2265
+ }
2266
+ return data;
2267
+ });
2268
+ }
2269
+ class Fuse {
2270
+ constructor(docs, options = {}, index) {
2271
+ this.options = _objectSpread2(_objectSpread2({}, Config), options);
2272
+ if (this.options.useExtendedSearch && !false) {
2273
+ throw new Error(EXTENDED_SEARCH_UNAVAILABLE);
2274
+ }
2275
+ this._keyStore = new KeyStore(this.options.keys);
2276
+ this.setCollection(docs, index);
2277
+ }
2278
+ setCollection(docs, index) {
2279
+ this._docs = docs;
2280
+ if (index && !(index instanceof FuseIndex)) {
2281
+ throw new Error(INCORRECT_INDEX_TYPE);
2282
+ }
2283
+ this._myIndex = index || createIndex(this.options.keys, this._docs, {
2284
+ getFn: this.options.getFn,
2285
+ fieldNormWeight: this.options.fieldNormWeight
2286
+ });
2287
+ }
2288
+ add(doc) {
2289
+ if (!isDefined(doc)) {
2290
+ return;
2291
+ }
2292
+ this._docs.push(doc);
2293
+ this._myIndex.add(doc);
2294
+ }
2295
+ remove(predicate = ( /* doc, idx */) => false) {
2296
+ const results = [];
2297
+ for (let i = 0, len = this._docs.length; i < len; i += 1) {
2298
+ const doc = this._docs[i];
2299
+ if (predicate(doc, i)) {
2300
+ this.removeAt(i);
2301
+ i -= 1;
2302
+ len -= 1;
2303
+ results.push(doc);
2304
+ }
2305
+ }
2306
+ return results;
2307
+ }
2308
+ removeAt(idx) {
2309
+ this._docs.splice(idx, 1);
2310
+ this._myIndex.removeAt(idx);
2311
+ }
2312
+ getIndex() {
2313
+ return this._myIndex;
2314
+ }
2315
+ search(query, {
2316
+ limit = -1
2317
+ } = {}) {
2318
+ const {
2319
+ includeMatches,
2320
+ includeScore,
2321
+ shouldSort,
2322
+ sortFn,
2323
+ ignoreFieldNorm
2324
+ } = this.options;
2325
+ let results = isString(query) ? isString(this._docs[0]) ? this._searchStringList(query) : this._searchObjectList(query) : this._searchLogical(query);
2326
+ computeScore(results, {
2327
+ ignoreFieldNorm
2328
+ });
2329
+ if (shouldSort) {
2330
+ results.sort(sortFn);
2331
+ }
2332
+ if (isNumber(limit) && limit > -1) {
2333
+ results = results.slice(0, limit);
2334
+ }
2335
+ return format(results, this._docs, {
2336
+ includeMatches,
2337
+ includeScore
2338
+ });
2339
+ }
2340
+ _searchStringList(query) {
2341
+ const searcher = createSearcher(query, this.options);
2342
+ const {
2343
+ records
2344
+ } = this._myIndex;
2345
+ const results = [];
2346
+
2347
+ // Iterate over every string in the index
2348
+ records.forEach(({
2349
+ v: text,
2350
+ i: idx,
2351
+ n: norm
2352
+ }) => {
2353
+ if (!isDefined(text)) {
2354
+ return;
2355
+ }
2356
+ const {
2357
+ isMatch,
2358
+ score,
2359
+ indices
2360
+ } = searcher.searchIn(text);
2361
+ if (isMatch) {
2362
+ results.push({
2363
+ item: text,
2364
+ idx,
2365
+ matches: [{
2366
+ score,
2367
+ value: text,
2368
+ norm,
2369
+ indices
2370
+ }]
2371
+ });
2372
+ }
2373
+ });
2374
+ return results;
2375
+ }
2376
+ _searchLogical(query) {
2377
+ {
2378
+ throw new Error(LOGICAL_SEARCH_UNAVAILABLE);
2379
+ }
2380
+ }
2381
+ _searchObjectList(query) {
2382
+ const searcher = createSearcher(query, this.options);
2383
+ const {
2384
+ keys,
2385
+ records
2386
+ } = this._myIndex;
2387
+ const results = [];
2388
+
2389
+ // List is Array<Object>
2390
+ records.forEach(({
2391
+ $: item,
2392
+ i: idx
2393
+ }) => {
2394
+ if (!isDefined(item)) {
2395
+ return;
2396
+ }
2397
+ let matches = [];
2398
+
2399
+ // Iterate over every key (i.e, path), and fetch the value at that key
2400
+ keys.forEach((key, keyIndex) => {
2401
+ matches.push(...this._findMatches({
2402
+ key,
2403
+ value: item[keyIndex],
2404
+ searcher
2405
+ }));
2406
+ });
2407
+ if (matches.length) {
2408
+ results.push({
2409
+ idx,
2410
+ item,
2411
+ matches
2412
+ });
2413
+ }
2414
+ });
2415
+ return results;
2416
+ }
2417
+ _findMatches({
2418
+ key,
2419
+ value,
2420
+ searcher
2421
+ }) {
2422
+ if (!isDefined(value)) {
2423
+ return [];
2424
+ }
2425
+ let matches = [];
2426
+ if (isArray(value)) {
2427
+ value.forEach(({
2428
+ v: text,
2429
+ i: idx,
2430
+ n: norm
2431
+ }) => {
2432
+ if (!isDefined(text)) {
2433
+ return;
2434
+ }
2435
+ const {
2436
+ isMatch,
2437
+ score,
2438
+ indices
2439
+ } = searcher.searchIn(text);
2440
+ if (isMatch) {
2441
+ matches.push({
2442
+ score,
2443
+ key,
2444
+ value: text,
2445
+ idx,
2446
+ norm,
2447
+ indices
2448
+ });
2449
+ }
2450
+ });
2451
+ } else {
2452
+ const {
2453
+ v: text,
2454
+ n: norm
2455
+ } = value;
2456
+ const {
2457
+ isMatch,
2458
+ score,
2459
+ indices
2460
+ } = searcher.searchIn(text);
2461
+ if (isMatch) {
2462
+ matches.push({
2463
+ score,
2464
+ key,
2465
+ value: text,
2466
+ norm,
2467
+ indices
2468
+ });
2469
+ }
2470
+ }
2471
+ return matches;
2472
+ }
2473
+ }
2474
+ Fuse.version = '7.0.0';
2475
+ Fuse.createIndex = createIndex;
2476
+ Fuse.parseIndex = parseIndex;
2477
+ Fuse.config = Config;
2478
+ {
2479
+ Fuse.parseQuery = parse;
2480
+ }
2481
+
2482
+ var SearchByFuse = /** @class */ (function () {
2483
+ function SearchByFuse(config) {
2484
+ this._haystack = [];
2485
+ this._fuseOptions = __assign(__assign({}, config.fuseOptions), { keys: __spreadArray([], config.searchFields, true), includeMatches: true });
2486
+ }
2487
+ SearchByFuse.prototype.index = function (data) {
2488
+ this._haystack = data;
2489
+ if (this._fuse) {
2490
+ this._fuse.setCollection(data);
2491
+ }
2492
+ };
2493
+ SearchByFuse.prototype.reset = function () {
2494
+ this._haystack = [];
2495
+ this._fuse = undefined;
2496
+ };
2497
+ SearchByFuse.prototype.isEmptyIndex = function () {
2498
+ return !this._haystack.length;
2499
+ };
2500
+ SearchByFuse.prototype.search = function (needle) {
2501
+ if (!this._fuse) {
2502
+ {
2503
+ this._fuse = new Fuse(this._haystack, this._fuseOptions);
2504
+ }
2505
+ }
2506
+ var results = this._fuse.search(needle);
2507
+ return results.map(function (value, i) {
2508
+ return {
2509
+ item: value.item,
2510
+ score: value.score || 0,
2511
+ rank: i + 1, // If value.score is used for sorting, this can create non-stable sorts!
2512
+ };
2513
+ });
2514
+ };
2515
+ return SearchByFuse;
2516
+ }());
2517
+
2518
+ function getSearcher(config) {
2519
+ {
2520
+ return new SearchByFuse(config);
2521
+ }
2522
+ }
2523
+
2524
+ /**
2525
+ * Helpers to create HTML elements used by Choices
2526
+ * Can be overridden by providing `callbackOnCreateTemplates` option.
2527
+ * `Choices.defaults.templates` allows access to the default template methods from `callbackOnCreateTemplates`
2528
+ */
2529
+ var isEmptyObject = function (obj) {
2530
+ // eslint-disable-next-line no-restricted-syntax
2531
+ for (var prop in obj) {
2532
+ if (Object.prototype.hasOwnProperty.call(obj, prop)) {
2533
+ return false;
2534
+ }
2535
+ }
2536
+ return true;
2537
+ };
2538
+ var assignCustomProperties = function (el, choice, withCustomProperties) {
2539
+ var dataset = el.dataset;
2540
+ var customProperties = choice.customProperties, labelClass = choice.labelClass, labelDescription = choice.labelDescription;
2541
+ if (labelClass) {
2542
+ dataset.labelClass = getClassNames(labelClass).join(' ');
2543
+ }
2544
+ if (labelDescription) {
2545
+ dataset.labelDescription = labelDescription;
2546
+ }
2547
+ if (withCustomProperties && customProperties) {
2548
+ if (typeof customProperties === 'string') {
2549
+ dataset.customProperties = customProperties;
2550
+ }
2551
+ else if (typeof customProperties === 'object' && !isEmptyObject(customProperties)) {
2552
+ dataset.customProperties = JSON.stringify(customProperties);
2553
+ }
2554
+ }
2555
+ };
2556
+ var addAriaLabel = function (docRoot, id, element) {
2557
+ var label = id && docRoot.querySelector("label[for='".concat(id, "']"));
2558
+ var text = label && label.innerText;
2559
+ if (text) {
2560
+ element.setAttribute('aria-label', text);
2561
+ }
2562
+ };
2563
+ var templates = {
2564
+ containerOuter: function (_a, dir, isSelectElement, isSelectOneElement, searchEnabled, passedElementType, labelId) {
2565
+ var containerOuter = _a.classNames.containerOuter;
2566
+ var div = document.createElement('div');
2567
+ addClassesToElement(div, containerOuter);
2568
+ div.dataset.type = passedElementType;
2569
+ if (dir) {
2570
+ div.dir = dir;
2571
+ }
2572
+ if (isSelectOneElement) {
2573
+ div.tabIndex = 0;
2574
+ }
2575
+ if (isSelectElement) {
2576
+ div.setAttribute('role', searchEnabled ? 'combobox' : 'listbox');
2577
+ if (searchEnabled) {
2578
+ div.setAttribute('aria-autocomplete', 'list');
2579
+ }
2580
+ else if (!labelId) {
2581
+ addAriaLabel(this._docRoot, this.passedElement.element.id, div);
2582
+ }
2583
+ div.setAttribute('aria-haspopup', 'true');
2584
+ div.setAttribute('aria-expanded', 'false');
2585
+ }
2586
+ if (labelId) {
2587
+ div.setAttribute('aria-labelledby', labelId);
2588
+ }
2589
+ return div;
2590
+ },
2591
+ containerInner: function (_a) {
2592
+ var containerInner = _a.classNames.containerInner;
2593
+ var div = document.createElement('div');
2594
+ addClassesToElement(div, containerInner);
2595
+ return div;
2596
+ },
2597
+ itemList: function (_a, isSelectOneElement) {
2598
+ var searchEnabled = _a.searchEnabled, _b = _a.classNames, list = _b.list, listSingle = _b.listSingle, listItems = _b.listItems;
2599
+ var div = document.createElement('div');
2600
+ addClassesToElement(div, list);
2601
+ addClassesToElement(div, isSelectOneElement ? listSingle : listItems);
2602
+ if (this._isSelectElement && searchEnabled) {
2603
+ div.setAttribute('role', 'listbox');
2604
+ }
2605
+ return div;
2606
+ },
2607
+ placeholder: function (_a, value) {
2608
+ var allowHTML = _a.allowHTML, placeholder = _a.classNames.placeholder;
2609
+ var div = document.createElement('div');
2610
+ addClassesToElement(div, placeholder);
2611
+ setElementHtml(div, allowHTML, value);
2612
+ return div;
2613
+ },
2614
+ item: function (_a, choice, removeItemButton) {
2615
+ 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;
2616
+ var rawValue = unwrapStringForRaw(choice.value);
2617
+ var div = document.createElement('div');
2618
+ addClassesToElement(div, item);
2619
+ if (choice.labelClass) {
2620
+ var spanLabel = document.createElement('span');
2621
+ setElementHtml(spanLabel, allowHTML, choice.label);
2622
+ addClassesToElement(spanLabel, choice.labelClass);
2623
+ div.appendChild(spanLabel);
2624
+ }
2625
+ else {
2626
+ setElementHtml(div, allowHTML, choice.label);
2627
+ }
2628
+ div.dataset.item = '';
2629
+ div.dataset.id = choice.id;
2630
+ div.dataset.value = rawValue;
2631
+ assignCustomProperties(div, choice, true);
2632
+ if (choice.disabled || this.containerOuter.isDisabled) {
2633
+ div.setAttribute('aria-disabled', 'true');
2634
+ }
2635
+ if (this._isSelectElement) {
2636
+ div.setAttribute('aria-selected', 'true');
2637
+ div.setAttribute('role', 'option');
2638
+ }
2639
+ if (choice.placeholder) {
2640
+ addClassesToElement(div, placeholder);
2641
+ div.dataset.placeholder = '';
2642
+ }
2643
+ addClassesToElement(div, choice.highlighted ? highlightedState : itemSelectable);
2644
+ if (removeItemButton) {
2645
+ if (choice.disabled) {
2646
+ removeClassesFromElement(div, itemSelectable);
2647
+ }
2648
+ div.dataset.deletable = '';
2649
+ var removeButton = document.createElement('button');
2650
+ removeButton.type = 'button';
2651
+ addClassesToElement(removeButton, button);
2652
+ setElementHtml(removeButton, true, resolveNoticeFunction(removeItemIconText, choice.value));
2653
+ var REMOVE_ITEM_LABEL = resolveNoticeFunction(removeItemLabelText, choice.value);
2654
+ if (REMOVE_ITEM_LABEL) {
2655
+ removeButton.setAttribute('aria-label', REMOVE_ITEM_LABEL);
2656
+ }
2657
+ removeButton.dataset.button = '';
2658
+ if (removeItemButtonAlignLeft) {
2659
+ div.insertAdjacentElement('afterbegin', removeButton);
2660
+ }
2661
+ else {
2662
+ div.appendChild(removeButton);
2663
+ }
2664
+ }
2665
+ return div;
2666
+ },
2667
+ choiceList: function (_a, isSelectOneElement) {
2668
+ var list = _a.classNames.list;
2669
+ var div = document.createElement('div');
2670
+ addClassesToElement(div, list);
2671
+ if (!isSelectOneElement) {
2672
+ div.setAttribute('aria-multiselectable', 'true');
2673
+ }
2674
+ div.setAttribute('role', 'listbox');
2675
+ return div;
2676
+ },
2677
+ choiceGroup: function (_a, _b) {
2678
+ var allowHTML = _a.allowHTML, _c = _a.classNames, group = _c.group, groupHeading = _c.groupHeading, itemDisabled = _c.itemDisabled;
2679
+ var id = _b.id, label = _b.label, disabled = _b.disabled;
2680
+ var rawLabel = unwrapStringForRaw(label);
2681
+ var div = document.createElement('div');
2682
+ addClassesToElement(div, group);
2683
+ if (disabled) {
2684
+ addClassesToElement(div, itemDisabled);
2685
+ }
2686
+ div.setAttribute('role', 'group');
2687
+ div.dataset.group = '';
2688
+ div.dataset.id = id;
2689
+ div.dataset.value = rawLabel;
2690
+ if (disabled) {
2691
+ div.setAttribute('aria-disabled', 'true');
2692
+ }
2693
+ var heading = document.createElement('div');
2694
+ addClassesToElement(heading, groupHeading);
2695
+ setElementHtml(heading, allowHTML, label || '');
2696
+ div.appendChild(heading);
2697
+ return div;
2698
+ },
2699
+ choice: function (_a, choice, selectText, groupName) {
2700
+ 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;
2701
+ // eslint-disable-next-line prefer-destructuring
2702
+ var label = choice.label;
2703
+ var rawValue = unwrapStringForRaw(choice.value);
2704
+ var div = document.createElement('div');
2705
+ div.id = choice.elementId;
2706
+ addClassesToElement(div, item);
2707
+ addClassesToElement(div, itemChoice);
2708
+ if (groupName && typeof label === 'string') {
2709
+ label = escapeForTemplate(allowHTML, label);
2710
+ label += " (".concat(groupName, ")");
2711
+ label = { trusted: label };
2712
+ }
2713
+ var describedBy = div;
2714
+ if (choice.labelClass) {
2715
+ var spanLabel = document.createElement('span');
2716
+ setElementHtml(spanLabel, allowHTML, label);
2717
+ addClassesToElement(spanLabel, choice.labelClass);
2718
+ describedBy = spanLabel;
2719
+ div.appendChild(spanLabel);
2720
+ }
2721
+ else {
2722
+ setElementHtml(div, allowHTML, label);
2723
+ }
2724
+ if (choice.labelDescription) {
2725
+ var descId = "".concat(choice.elementId, "-description");
2726
+ describedBy.setAttribute('aria-describedby', descId);
2727
+ var spanDesc = document.createElement('span');
2728
+ setElementHtml(spanDesc, allowHTML, choice.labelDescription);
2729
+ spanDesc.id = descId;
2730
+ addClassesToElement(spanDesc, description);
2731
+ div.appendChild(spanDesc);
2732
+ }
2733
+ if (choice.selected) {
2734
+ addClassesToElement(div, selectedState);
2735
+ }
2736
+ if (choice.placeholder) {
2737
+ addClassesToElement(div, placeholder);
2738
+ }
2739
+ div.setAttribute('role', choice.group ? 'treeitem' : 'option');
2740
+ div.dataset.choice = '';
2741
+ div.dataset.id = choice.id;
2742
+ div.dataset.value = rawValue;
2743
+ if (selectText) {
2744
+ div.dataset.selectText = selectText;
2745
+ }
2746
+ if (choice.group) {
2747
+ div.dataset.groupId = "".concat(choice.group.id);
2748
+ }
2749
+ assignCustomProperties(div, choice, false);
2750
+ if (choice.disabled) {
2751
+ addClassesToElement(div, itemDisabled);
2752
+ div.dataset.choiceDisabled = '';
2753
+ div.setAttribute('aria-disabled', 'true');
2754
+ }
2755
+ else {
2756
+ addClassesToElement(div, itemSelectable);
2757
+ div.dataset.choiceSelectable = '';
2758
+ }
2759
+ return div;
2760
+ },
2761
+ input: function (_a, placeholderValue) {
2762
+ var _b = _a.classNames, input = _b.input, inputCloned = _b.inputCloned, labelId = _a.labelId;
2763
+ var inp = document.createElement('input');
2764
+ inp.type = 'search';
2765
+ addClassesToElement(inp, input);
2766
+ addClassesToElement(inp, inputCloned);
2767
+ inp.autocomplete = 'off';
2768
+ inp.autocapitalize = 'off';
2769
+ inp.spellcheck = false;
2770
+ inp.setAttribute('aria-autocomplete', 'list');
2771
+ if (placeholderValue) {
2772
+ inp.setAttribute('aria-label', placeholderValue);
2773
+ }
2774
+ else if (!labelId) {
2775
+ addAriaLabel(this._docRoot, this.passedElement.element.id, inp);
2776
+ }
2777
+ return inp;
2778
+ },
2779
+ dropdown: function (_a) {
2780
+ var _b = _a.classNames, list = _b.list, listDropdown = _b.listDropdown;
2781
+ var div = document.createElement('div');
2782
+ addClassesToElement(div, list);
2783
+ addClassesToElement(div, listDropdown);
2784
+ div.setAttribute('aria-expanded', 'false');
2785
+ return div;
2786
+ },
2787
+ notice: function (_a, innerHTML, type) {
2788
+ var _b = _a.classNames, item = _b.item, itemChoice = _b.itemChoice, addChoice = _b.addChoice, noResults = _b.noResults, noChoices = _b.noChoices, noticeItem = _b.notice;
2789
+ if (type === void 0) { type = NoticeTypes.generic; }
2790
+ var notice = document.createElement('div');
2791
+ setElementHtml(notice, true, innerHTML);
2792
+ addClassesToElement(notice, item);
2793
+ addClassesToElement(notice, itemChoice);
2794
+ addClassesToElement(notice, noticeItem);
2795
+ // eslint-disable-next-line default-case
2796
+ switch (type) {
2797
+ case NoticeTypes.addChoice:
2798
+ addClassesToElement(notice, addChoice);
2799
+ break;
2800
+ case NoticeTypes.noResults:
2801
+ addClassesToElement(notice, noResults);
2802
+ break;
2803
+ case NoticeTypes.noChoices:
2804
+ addClassesToElement(notice, noChoices);
2805
+ break;
2806
+ }
2807
+ if (type === NoticeTypes.addChoice) {
2808
+ notice.dataset.choiceSelectable = '';
2809
+ notice.dataset.choice = '';
2810
+ }
2811
+ return notice;
2812
+ },
2813
+ option: function (choice) {
2814
+ // HtmlOptionElement's label value does not support HTML, so the avoid double escaping unwrap the untrusted string.
2815
+ var labelValue = unwrapStringForRaw(choice.label);
2816
+ var opt = new Option(labelValue, choice.value, false, choice.selected);
2817
+ assignCustomProperties(opt, choice, true);
2818
+ opt.disabled = choice.disabled;
2819
+ if (choice.selected) {
2820
+ opt.setAttribute('selected', '');
2821
+ }
2822
+ return opt;
2823
+ },
2824
+ };
2825
+
2826
+ /** @see {@link http://browserhacks.com/#hack-acea075d0ac6954f275a70023906050c} */
2827
+ var IS_IE11 = '-ms-scroll-limit' in document.documentElement.style &&
2828
+ '-ms-ime-align' in document.documentElement.style;
2829
+ var USER_DEFAULTS = {};
2830
+ var parseDataSetId = function (element) {
2831
+ if (!element) {
2832
+ return undefined;
2833
+ }
2834
+ return element.dataset.id ? parseInt(element.dataset.id, 10) : undefined;
2835
+ };
2836
+ var selectableChoiceIdentifier = '[data-choice-selectable]';
2837
+ /**
2838
+ * Choices
2839
+ * @author Josh Johnson<josh@joshuajohnson.co.uk>
2840
+ */
2841
+ var Choices = /** @class */ (function () {
2842
+ function Choices(element, userConfig) {
2843
+ if (element === void 0) { element = '[data-choice]'; }
2844
+ if (userConfig === void 0) { userConfig = {}; }
2845
+ var _this = this;
2846
+ this.initialisedOK = undefined;
2847
+ this._hasNonChoicePlaceholder = false;
2848
+ this._lastAddedChoiceId = 0;
2849
+ this._lastAddedGroupId = 0;
2850
+ var defaults = Choices.defaults;
2851
+ this.config = __assign(__assign(__assign({}, defaults.allOptions), defaults.options), userConfig);
2852
+ ObjectsInConfig.forEach(function (key) {
2853
+ _this.config[key] = __assign(__assign(__assign({}, defaults.allOptions[key]), defaults.options[key]), userConfig[key]);
2854
+ });
2855
+ var config = this.config;
2856
+ if (!config.silent) {
2857
+ this._validateConfig();
2858
+ }
2859
+ var docRoot = config.shadowRoot || document.documentElement;
2860
+ this._docRoot = docRoot;
2861
+ var passedElement = typeof element === 'string' ? docRoot.querySelector(element) : element;
2862
+ if (!passedElement ||
2863
+ typeof passedElement !== 'object' ||
2864
+ !(isHtmlInputElement(passedElement) || isHtmlSelectElement(passedElement))) {
2865
+ if (!passedElement && typeof element === 'string') {
2866
+ throw TypeError("Selector ".concat(element, " failed to find an element"));
2867
+ }
2868
+ throw TypeError("Expected one of the following types text|select-one|select-multiple");
2869
+ }
2870
+ var elementType = passedElement.type;
2871
+ var isText = elementType === PassedElementTypes.Text;
2872
+ if (isText || config.maxItemCount !== 1) {
2873
+ config.singleModeForMultiSelect = false;
2874
+ }
2875
+ if (config.singleModeForMultiSelect) {
2876
+ elementType = PassedElementTypes.SelectMultiple;
2877
+ }
2878
+ var isSelectOne = elementType === PassedElementTypes.SelectOne;
2879
+ var isSelectMultiple = elementType === PassedElementTypes.SelectMultiple;
2880
+ var isSelect = isSelectOne || isSelectMultiple;
2881
+ this._elementType = elementType;
2882
+ this._isTextElement = isText;
2883
+ this._isSelectOneElement = isSelectOne;
2884
+ this._isSelectMultipleElement = isSelectMultiple;
2885
+ this._isSelectElement = isSelectOne || isSelectMultiple;
2886
+ this._canAddUserChoices = (isText && config.addItems) || (isSelect && config.addChoices);
2887
+ if (typeof config.renderSelectedChoices !== 'boolean') {
2888
+ config.renderSelectedChoices = config.renderSelectedChoices === 'always' || isSelectOne;
2889
+ }
2890
+ if (config.closeDropdownOnSelect === 'auto') {
2891
+ config.closeDropdownOnSelect = isText || isSelectOne || config.singleModeForMultiSelect;
2892
+ }
2893
+ else {
2894
+ config.closeDropdownOnSelect = coerceBool(config.closeDropdownOnSelect);
2895
+ }
2896
+ if (config.placeholder) {
2897
+ if (config.placeholderValue) {
2898
+ this._hasNonChoicePlaceholder = true;
2899
+ }
2900
+ else if (passedElement.dataset.placeholder) {
2901
+ this._hasNonChoicePlaceholder = true;
2902
+ config.placeholderValue = passedElement.dataset.placeholder;
2903
+ }
2904
+ }
2905
+ if (userConfig.addItemFilter && typeof userConfig.addItemFilter !== 'function') {
2906
+ var re = userConfig.addItemFilter instanceof RegExp ? userConfig.addItemFilter : new RegExp(userConfig.addItemFilter);
2907
+ config.addItemFilter = re.test.bind(re);
2908
+ }
2909
+ if (this._isTextElement) {
2910
+ this.passedElement = new WrappedInput({
2911
+ element: passedElement,
2912
+ classNames: config.classNames,
2913
+ });
2914
+ }
2915
+ else {
2916
+ var selectEl = passedElement;
2917
+ this.passedElement = new WrappedSelect({
2918
+ element: selectEl,
2919
+ classNames: config.classNames,
2920
+ template: function (data) { return _this._templates.option(data); },
2921
+ extractPlaceholder: config.placeholder && !this._hasNonChoicePlaceholder,
2922
+ });
2923
+ }
2924
+ this.initialised = false;
2925
+ this._store = new Store(config);
2926
+ this._currentValue = '';
2927
+ config.searchEnabled = (!isText && config.searchEnabled) || isSelectMultiple;
2928
+ this._canSearch = config.searchEnabled;
2929
+ this._isScrollingOnIe = false;
2930
+ this._highlightPosition = 0;
2931
+ this._wasTap = true;
2932
+ this._placeholderValue = this._generatePlaceholderValue();
2933
+ this._baseId = generateId(passedElement, 'choices-');
2934
+ /**
2935
+ * setting direction in cases where it's explicitly set on passedElement
2936
+ * or when calculated direction is different from the document
2937
+ */
2938
+ this._direction = passedElement.dir;
2939
+ if (!this._direction) {
2940
+ var elementDirection = window.getComputedStyle(passedElement).direction;
2941
+ var documentDirection = window.getComputedStyle(document.documentElement).direction;
2942
+ if (elementDirection !== documentDirection) {
2943
+ this._direction = elementDirection;
2944
+ }
2945
+ }
2946
+ this._idNames = {
2947
+ itemChoice: 'item-choice',
2948
+ };
2949
+ this._templates = defaults.templates;
2950
+ this._render = this._render.bind(this);
2951
+ this._onFocus = this._onFocus.bind(this);
2952
+ this._onBlur = this._onBlur.bind(this);
2953
+ this._onKeyUp = this._onKeyUp.bind(this);
2954
+ this._onKeyDown = this._onKeyDown.bind(this);
2955
+ this._onInput = this._onInput.bind(this);
2956
+ this._onClick = this._onClick.bind(this);
2957
+ this._onTouchMove = this._onTouchMove.bind(this);
2958
+ this._onTouchEnd = this._onTouchEnd.bind(this);
2959
+ this._onMouseDown = this._onMouseDown.bind(this);
2960
+ this._onMouseOver = this._onMouseOver.bind(this);
2961
+ this._onFormReset = this._onFormReset.bind(this);
2962
+ this._onSelectKey = this._onSelectKey.bind(this);
2963
+ this._onEnterKey = this._onEnterKey.bind(this);
2964
+ this._onEscapeKey = this._onEscapeKey.bind(this);
2965
+ this._onDirectionKey = this._onDirectionKey.bind(this);
2966
+ this._onDeleteKey = this._onDeleteKey.bind(this);
2967
+ // If element has already been initialised with Choices, fail silently
2968
+ if (this.passedElement.isActive) {
2969
+ if (!config.silent) {
2970
+ console.warn('Trying to initialise Choices on element already initialised', { element: element });
2971
+ }
2972
+ this.initialised = true;
2973
+ this.initialisedOK = false;
2974
+ return;
2975
+ }
2976
+ // Let's go
2977
+ this.init();
2978
+ // preserve the selected item list after setup for form reset
2979
+ this._initialItems = this._store.items.map(function (choice) { return choice.value; });
2980
+ }
2981
+ Object.defineProperty(Choices, "defaults", {
2982
+ get: function () {
2983
+ return Object.preventExtensions({
2984
+ get options() {
2985
+ return USER_DEFAULTS;
2986
+ },
2987
+ get allOptions() {
2988
+ return DEFAULT_CONFIG;
2989
+ },
2990
+ get templates() {
2991
+ return templates;
2992
+ },
2993
+ });
2994
+ },
2995
+ enumerable: false,
2996
+ configurable: true
2997
+ });
2998
+ Choices.prototype.init = function () {
2999
+ if (this.initialised || this.initialisedOK !== undefined) {
3000
+ return;
3001
+ }
3002
+ this._searcher = getSearcher(this.config);
3003
+ this._loadChoices();
3004
+ this._createTemplates();
3005
+ this._createElements();
3006
+ this._createStructure();
3007
+ if ((this._isTextElement && !this.config.addItems) ||
3008
+ this.passedElement.element.hasAttribute('disabled') ||
3009
+ !!this.passedElement.element.closest('fieldset:disabled')) {
3010
+ this.disable();
3011
+ }
3012
+ else {
3013
+ this.enable();
3014
+ this._addEventListeners();
3015
+ }
3016
+ // should be triggered **after** disabled state to avoid additional re-draws
3017
+ this._initStore();
3018
+ this.initialised = true;
3019
+ this.initialisedOK = true;
3020
+ var callbackOnInit = this.config.callbackOnInit;
3021
+ // Run callback if it is a function
3022
+ if (typeof callbackOnInit === 'function') {
3023
+ callbackOnInit.call(this);
3024
+ }
3025
+ };
3026
+ Choices.prototype.destroy = function () {
3027
+ if (!this.initialised) {
3028
+ return;
3029
+ }
3030
+ this._removeEventListeners();
3031
+ this.passedElement.reveal();
3032
+ this.containerOuter.unwrap(this.passedElement.element);
3033
+ this._store._listeners = []; // prevents select/input value being wiped
3034
+ this.clearStore(false);
3035
+ this._stopSearch();
3036
+ this._templates = Choices.defaults.templates;
3037
+ this.initialised = false;
3038
+ this.initialisedOK = undefined;
3039
+ };
3040
+ Choices.prototype.enable = function () {
3041
+ if (this.passedElement.isDisabled) {
3042
+ this.passedElement.enable();
3043
+ }
3044
+ if (this.containerOuter.isDisabled) {
3045
+ this._addEventListeners();
3046
+ this.input.enable();
3047
+ this.containerOuter.enable();
3048
+ }
3049
+ return this;
3050
+ };
3051
+ Choices.prototype.disable = function () {
3052
+ if (!this.passedElement.isDisabled) {
3053
+ this.passedElement.disable();
3054
+ }
3055
+ if (!this.containerOuter.isDisabled) {
3056
+ this._removeEventListeners();
3057
+ this.input.disable();
3058
+ this.containerOuter.disable();
3059
+ }
3060
+ return this;
3061
+ };
3062
+ Choices.prototype.highlightItem = function (item, runEvent) {
3063
+ if (runEvent === void 0) { runEvent = true; }
3064
+ if (!item || !item.id) {
3065
+ return this;
3066
+ }
3067
+ var choice = this._store.items.find(function (c) { return c.id === item.id; });
3068
+ if (!choice || choice.highlighted) {
3069
+ return this;
3070
+ }
3071
+ this._store.dispatch(highlightItem(choice, true));
3072
+ if (runEvent) {
3073
+ this.passedElement.triggerEvent(EventType.highlightItem, this._getChoiceForOutput(choice));
3074
+ }
3075
+ return this;
3076
+ };
3077
+ Choices.prototype.unhighlightItem = function (item, runEvent) {
3078
+ if (runEvent === void 0) { runEvent = true; }
3079
+ if (!item || !item.id) {
3080
+ return this;
3081
+ }
3082
+ var choice = this._store.items.find(function (c) { return c.id === item.id; });
3083
+ if (!choice || !choice.highlighted) {
3084
+ return this;
3085
+ }
3086
+ this._store.dispatch(highlightItem(choice, false));
3087
+ if (runEvent) {
3088
+ this.passedElement.triggerEvent(EventType.unhighlightItem, this._getChoiceForOutput(choice));
3089
+ }
3090
+ return this;
3091
+ };
3092
+ Choices.prototype.highlightAll = function () {
3093
+ var _this = this;
3094
+ this._store.withTxn(function () {
3095
+ _this._store.items.forEach(function (item) {
3096
+ if (!item.highlighted) {
3097
+ _this._store.dispatch(highlightItem(item, true));
3098
+ _this.passedElement.triggerEvent(EventType.highlightItem, _this._getChoiceForOutput(item));
3099
+ }
3100
+ });
3101
+ });
3102
+ return this;
3103
+ };
3104
+ Choices.prototype.unhighlightAll = function () {
3105
+ var _this = this;
3106
+ this._store.withTxn(function () {
3107
+ _this._store.items.forEach(function (item) {
3108
+ if (item.highlighted) {
3109
+ _this._store.dispatch(highlightItem(item, false));
3110
+ _this.passedElement.triggerEvent(EventType.highlightItem, _this._getChoiceForOutput(item));
3111
+ }
3112
+ });
3113
+ });
3114
+ return this;
3115
+ };
3116
+ Choices.prototype.removeActiveItemsByValue = function (value) {
3117
+ var _this = this;
3118
+ this._store.withTxn(function () {
3119
+ _this._store.items.filter(function (item) { return item.value === value; }).forEach(function (item) { return _this._removeItem(item); });
3120
+ });
3121
+ return this;
3122
+ };
3123
+ Choices.prototype.removeActiveItems = function (excludedId) {
3124
+ var _this = this;
3125
+ this._store.withTxn(function () {
3126
+ _this._store.items.filter(function (_a) {
3127
+ var id = _a.id;
3128
+ return id !== excludedId;
3129
+ }).forEach(function (item) { return _this._removeItem(item); });
3130
+ });
3131
+ return this;
3132
+ };
3133
+ Choices.prototype.removeHighlightedItems = function (runEvent) {
3134
+ var _this = this;
3135
+ if (runEvent === void 0) { runEvent = false; }
3136
+ this._store.withTxn(function () {
3137
+ _this._store.highlightedActiveItems.forEach(function (item) {
3138
+ _this._removeItem(item);
3139
+ // If this action was performed by the user
3140
+ // trigger the event
3141
+ if (runEvent) {
3142
+ _this._triggerChange(item.value);
3143
+ }
3144
+ });
3145
+ });
3146
+ return this;
3147
+ };
3148
+ Choices.prototype.showDropdown = function (preventInputFocus) {
3149
+ var _this = this;
3150
+ if (this.dropdown.isActive) {
3151
+ return this;
3152
+ }
3153
+ if (preventInputFocus === undefined) {
3154
+ // eslint-disable-next-line no-param-reassign
3155
+ preventInputFocus = !this._canSearch;
3156
+ }
3157
+ requestAnimationFrame(function () {
3158
+ _this.dropdown.show();
3159
+ var rect = _this.dropdown.element.getBoundingClientRect();
3160
+ _this.containerOuter.open(rect.bottom, rect.height);
3161
+ if (!preventInputFocus) {
3162
+ _this.input.focus();
3163
+ }
3164
+ _this.passedElement.triggerEvent(EventType.showDropdown);
3165
+ });
3166
+ return this;
3167
+ };
3168
+ Choices.prototype.hideDropdown = function (preventInputBlur) {
3169
+ var _this = this;
3170
+ if (!this.dropdown.isActive) {
3171
+ return this;
3172
+ }
3173
+ requestAnimationFrame(function () {
3174
+ _this.dropdown.hide();
3175
+ _this.containerOuter.close();
3176
+ if (!preventInputBlur && _this._canSearch) {
3177
+ _this.input.removeActiveDescendant();
3178
+ _this.input.blur();
3179
+ }
3180
+ _this.passedElement.triggerEvent(EventType.hideDropdown);
3181
+ });
3182
+ return this;
3183
+ };
3184
+ Choices.prototype.getValue = function (valueOnly) {
3185
+ var _this = this;
3186
+ var values = this._store.items.map(function (item) {
3187
+ return (valueOnly ? item.value : _this._getChoiceForOutput(item));
3188
+ });
3189
+ return this._isSelectOneElement || this.config.singleModeForMultiSelect ? values[0] : values;
3190
+ };
3191
+ Choices.prototype.setValue = function (items) {
3192
+ var _this = this;
3193
+ if (!this.initialisedOK) {
3194
+ this._warnChoicesInitFailed('setValue');
3195
+ return this;
3196
+ }
3197
+ this._store.withTxn(function () {
3198
+ items.forEach(function (value) {
3199
+ if (value) {
3200
+ _this._addChoice(mapInputToChoice(value, false));
3201
+ }
3202
+ });
3203
+ });
3204
+ // @todo integrate with Store
3205
+ this._searcher.reset();
3206
+ return this;
3207
+ };
3208
+ Choices.prototype.setChoiceByValue = function (value) {
3209
+ var _this = this;
3210
+ if (!this.initialisedOK) {
3211
+ this._warnChoicesInitFailed('setChoiceByValue');
3212
+ return this;
3213
+ }
3214
+ if (this._isTextElement) {
3215
+ return this;
3216
+ }
3217
+ this._store.withTxn(function () {
3218
+ // If only one value has been passed, convert to array
3219
+ var choiceValue = Array.isArray(value) ? value : [value];
3220
+ // Loop through each value and
3221
+ choiceValue.forEach(function (val) { return _this._findAndSelectChoiceByValue(val); });
3222
+ _this.unhighlightAll();
3223
+ });
3224
+ // @todo integrate with Store
3225
+ this._searcher.reset();
3226
+ return this;
3227
+ };
3228
+ /**
3229
+ * Set choices of select input via an array of objects (or function that returns array of object or promise of it),
3230
+ * a value field name and a label field name.
3231
+ * This behaves the same as passing items via the choices option but can be called after initialising Choices.
3232
+ * This can also be used to add groups of choices (see example 2); Optionally pass a true `replaceChoices` value to remove any existing choices.
3233
+ * Optionally pass a `customProperties` object to add additional data to your choices (useful when searching/filtering etc).
3234
+ *
3235
+ * **Input types affected:** select-one, select-multiple
3236
+ *
3237
+ * @example
3238
+ * ```js
3239
+ * const example = new Choices(element);
3240
+ *
3241
+ * example.setChoices([
3242
+ * {value: 'One', label: 'Label One', disabled: true},
3243
+ * {value: 'Two', label: 'Label Two', selected: true},
3244
+ * {value: 'Three', label: 'Label Three'},
3245
+ * ], 'value', 'label', false);
3246
+ * ```
3247
+ *
3248
+ * @example
3249
+ * ```js
3250
+ * const example = new Choices(element);
3251
+ *
3252
+ * example.setChoices(async () => {
3253
+ * try {
3254
+ * const items = await fetch('/items');
3255
+ * return items.json()
3256
+ * } catch(err) {
3257
+ * console.error(err)
3258
+ * }
3259
+ * });
3260
+ * ```
3261
+ *
3262
+ * @example
3263
+ * ```js
3264
+ * const example = new Choices(element);
3265
+ *
3266
+ * example.setChoices([{
3267
+ * label: 'Group one',
3268
+ * id: 1,
3269
+ * disabled: false,
3270
+ * choices: [
3271
+ * {value: 'Child One', label: 'Child One', selected: true},
3272
+ * {value: 'Child Two', label: 'Child Two', disabled: true},
3273
+ * {value: 'Child Three', label: 'Child Three'},
3274
+ * ]
3275
+ * },
3276
+ * {
3277
+ * label: 'Group two',
3278
+ * id: 2,
3279
+ * disabled: false,
3280
+ * choices: [
3281
+ * {value: 'Child Four', label: 'Child Four', disabled: true},
3282
+ * {value: 'Child Five', label: 'Child Five'},
3283
+ * {value: 'Child Six', label: 'Child Six', customProperties: {
3284
+ * description: 'Custom description about child six',
3285
+ * random: 'Another random custom property'
3286
+ * }},
3287
+ * ]
3288
+ * }], 'value', 'label', false);
3289
+ * ```
3290
+ */
3291
+ Choices.prototype.setChoices = function (choicesArrayOrFetcher, value, label, replaceChoices, clearSearchFlag, replaceItems) {
3292
+ var _this = this;
3293
+ if (choicesArrayOrFetcher === void 0) { choicesArrayOrFetcher = []; }
3294
+ if (value === void 0) { value = 'value'; }
3295
+ if (label === void 0) { label = 'label'; }
3296
+ if (replaceChoices === void 0) { replaceChoices = false; }
3297
+ if (clearSearchFlag === void 0) { clearSearchFlag = true; }
3298
+ if (replaceItems === void 0) { replaceItems = false; }
3299
+ if (!this.initialisedOK) {
3300
+ this._warnChoicesInitFailed('setChoices');
3301
+ return this;
3302
+ }
3303
+ if (!this._isSelectElement) {
3304
+ throw new TypeError("setChoices can't be used with INPUT based Choices");
3305
+ }
3306
+ if (typeof value !== 'string' || !value) {
3307
+ throw new TypeError("value parameter must be a name of 'value' field in passed objects");
3308
+ }
3309
+ if (typeof choicesArrayOrFetcher === 'function') {
3310
+ // it's a choices fetcher function
3311
+ var fetcher_1 = choicesArrayOrFetcher(this);
3312
+ if (typeof Promise === 'function' && fetcher_1 instanceof Promise) {
3313
+ // that's a promise
3314
+ // eslint-disable-next-line no-promise-executor-return
3315
+ return new Promise(function (resolve) { return requestAnimationFrame(resolve); })
3316
+ .then(function () { return _this._handleLoadingState(true); })
3317
+ .then(function () { return fetcher_1; })
3318
+ .then(function (data) {
3319
+ return _this.setChoices(data, value, label, replaceChoices, clearSearchFlag, replaceItems);
3320
+ })
3321
+ .catch(function (err) {
3322
+ if (!_this.config.silent) {
3323
+ console.error(err);
3324
+ }
3325
+ })
3326
+ .then(function () { return _this._handleLoadingState(false); })
3327
+ .then(function () { return _this; });
3328
+ }
3329
+ // function returned something else than promise, let's check if it's an array of choices
3330
+ if (!Array.isArray(fetcher_1)) {
3331
+ throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: ".concat(typeof fetcher_1));
3332
+ }
3333
+ // recursion with results, it's sync and choices were cleared already
3334
+ return this.setChoices(fetcher_1, value, label, false);
3335
+ }
3336
+ if (!Array.isArray(choicesArrayOrFetcher)) {
3337
+ throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");
3338
+ }
3339
+ this.containerOuter.removeLoadingState();
3340
+ this._store.withTxn(function () {
3341
+ if (clearSearchFlag) {
3342
+ _this._isSearching = false;
3343
+ }
3344
+ // Clear choices if needed
3345
+ if (replaceChoices) {
3346
+ _this.clearChoices(true, replaceItems);
3347
+ }
3348
+ var isDefaultValue = value === 'value';
3349
+ var isDefaultLabel = label === 'label';
3350
+ choicesArrayOrFetcher.forEach(function (groupOrChoice) {
3351
+ if ('choices' in groupOrChoice) {
3352
+ var group = groupOrChoice;
3353
+ if (!isDefaultLabel) {
3354
+ group = __assign(__assign({}, group), { label: group[label] });
3355
+ }
3356
+ _this._addGroup(mapInputToChoice(group, true));
3357
+ }
3358
+ else {
3359
+ var choice = groupOrChoice;
3360
+ if (!isDefaultLabel || !isDefaultValue) {
3361
+ choice = __assign(__assign({}, choice), { value: choice[value], label: choice[label] });
3362
+ }
3363
+ var choiceFull = mapInputToChoice(choice, false);
3364
+ _this._addChoice(choiceFull);
3365
+ if (choiceFull.placeholder && !_this._hasNonChoicePlaceholder) {
3366
+ _this._placeholderValue = unwrapStringForEscaped(choiceFull.label);
3367
+ }
3368
+ }
3369
+ });
3370
+ _this.unhighlightAll();
3371
+ });
3372
+ // @todo integrate with Store
3373
+ this._searcher.reset();
3374
+ return this;
3375
+ };
3376
+ Choices.prototype.refresh = function (withEvents, selectFirstOption, deselectAll) {
3377
+ var _this = this;
3378
+ if (withEvents === void 0) { withEvents = false; }
3379
+ if (selectFirstOption === void 0) { selectFirstOption = false; }
3380
+ if (deselectAll === void 0) { deselectAll = false; }
3381
+ if (!this._isSelectElement) {
3382
+ if (!this.config.silent) {
3383
+ console.warn('refresh method can only be used on choices backed by a <select> element');
3384
+ }
3385
+ return this;
3386
+ }
3387
+ this._store.withTxn(function () {
3388
+ var choicesFromOptions = _this.passedElement.optionsAsChoices();
3389
+ // Build the list of items which require preserving
3390
+ var existingItems = {};
3391
+ if (!deselectAll) {
3392
+ _this._store.items.forEach(function (choice) {
3393
+ if (choice.id && choice.active && choice.selected) {
3394
+ existingItems[choice.value] = true;
3395
+ }
3396
+ });
3397
+ }
3398
+ _this.clearStore(false);
3399
+ var updateChoice = function (choice) {
3400
+ if (deselectAll) {
3401
+ _this._store.dispatch(removeItem$1(choice));
3402
+ }
3403
+ else if (existingItems[choice.value]) {
3404
+ choice.selected = true;
3405
+ }
3406
+ };
3407
+ choicesFromOptions.forEach(function (groupOrChoice) {
3408
+ if ('choices' in groupOrChoice) {
3409
+ groupOrChoice.choices.forEach(updateChoice);
3410
+ return;
3411
+ }
3412
+ updateChoice(groupOrChoice);
3413
+ });
3414
+ /* @todo only generate add events for the added options instead of all
3415
+ if (withEvents) {
3416
+ items.forEach((choice) => {
3417
+ if (existingItems[choice.value]) {
3418
+ this.passedElement.triggerEvent(
3419
+ EventType.removeItem,
3420
+ this._getChoiceForEvent(choice),
3421
+ );
3422
+ }
3423
+ });
3424
+ }
3425
+ */
3426
+ // load new choices & items
3427
+ _this._addPredefinedChoices(choicesFromOptions, selectFirstOption, withEvents);
3428
+ // re-do search if required
3429
+ if (_this._isSearching) {
3430
+ _this._searchChoices(_this.input.value);
3431
+ }
3432
+ });
3433
+ return this;
3434
+ };
3435
+ Choices.prototype.removeChoice = function (value) {
3436
+ var choice = this._store.choices.find(function (c) { return c.value === value; });
3437
+ if (!choice) {
3438
+ return this;
3439
+ }
3440
+ this._clearNotice();
3441
+ this._store.dispatch(removeChoice(choice));
3442
+ // @todo integrate with Store
3443
+ this._searcher.reset();
3444
+ if (choice.selected) {
3445
+ this.passedElement.triggerEvent(EventType.removeItem, this._getChoiceForOutput(choice));
3446
+ }
3447
+ return this;
3448
+ };
3449
+ Choices.prototype.clearChoices = function (clearOptions, clearItems) {
3450
+ var _this = this;
3451
+ if (clearOptions === void 0) { clearOptions = true; }
3452
+ if (clearItems === void 0) { clearItems = false; }
3453
+ if (clearOptions) {
3454
+ if (clearItems) {
3455
+ this.passedElement.element.replaceChildren('');
3456
+ }
3457
+ else {
3458
+ this.passedElement.element.querySelectorAll(':not([selected])').forEach(function (el) {
3459
+ el.remove();
3460
+ });
3461
+ }
3462
+ }
3463
+ this.itemList.element.replaceChildren('');
3464
+ this.choiceList.element.replaceChildren('');
3465
+ this._clearNotice();
3466
+ this._store.withTxn(function () {
3467
+ var items = clearItems ? [] : _this._store.items;
3468
+ _this._store.reset();
3469
+ items.forEach(function (item) {
3470
+ _this._store.dispatch(addChoice(item));
3471
+ _this._store.dispatch(addItem(item));
3472
+ });
3473
+ });
3474
+ // @todo integrate with Store
3475
+ this._searcher.reset();
3476
+ return this;
3477
+ };
3478
+ Choices.prototype.clearStore = function (clearOptions) {
3479
+ if (clearOptions === void 0) { clearOptions = true; }
3480
+ this.clearChoices(clearOptions, true);
3481
+ this._stopSearch();
3482
+ this._lastAddedChoiceId = 0;
3483
+ this._lastAddedGroupId = 0;
3484
+ return this;
3485
+ };
3486
+ Choices.prototype.clearInput = function () {
3487
+ var shouldSetInputWidth = !this._isSelectOneElement;
3488
+ this.input.clear(shouldSetInputWidth);
3489
+ this._stopSearch();
3490
+ return this;
3491
+ };
3492
+ Choices.prototype._validateConfig = function () {
3493
+ var config = this.config;
3494
+ var invalidConfigOptions = diff(config, DEFAULT_CONFIG);
3495
+ if (invalidConfigOptions.length) {
3496
+ console.warn('Unknown config option(s) passed', invalidConfigOptions.join(', '));
3497
+ }
3498
+ if (config.allowHTML && config.allowHtmlUserInput) {
3499
+ if (config.addItems) {
3500
+ console.warn('Warning: allowHTML/allowHtmlUserInput/addItems all being true is strongly not recommended and may lead to XSS attacks');
3501
+ }
3502
+ if (config.addChoices) {
3503
+ console.warn('Warning: allowHTML/allowHtmlUserInput/addChoices all being true is strongly not recommended and may lead to XSS attacks');
3504
+ }
3505
+ }
3506
+ };
3507
+ Choices.prototype._render = function (changes) {
3508
+ if (changes === void 0) { changes = { choices: true, groups: true, items: true }; }
3509
+ if (this._store.inTxn()) {
3510
+ return;
3511
+ }
3512
+ if (this._isSelectElement) {
3513
+ if (changes.choices || changes.groups) {
3514
+ this._renderChoices();
3515
+ }
3516
+ }
3517
+ if (changes.items) {
3518
+ this._renderItems();
3519
+ }
3520
+ };
3521
+ Choices.prototype._renderChoices = function () {
3522
+ var _this = this;
3523
+ if (!this._canAddItems()) {
3524
+ return; // block rendering choices if the input limit is reached.
3525
+ }
3526
+ var _a = this, config = _a.config, isSearching = _a._isSearching;
3527
+ var _b = this._store, activeGroups = _b.activeGroups, activeChoices = _b.activeChoices;
3528
+ var renderLimit = 0;
3529
+ if (isSearching && config.searchResultLimit > 0) {
3530
+ renderLimit = config.searchResultLimit;
3531
+ }
3532
+ else if (config.renderChoiceLimit > 0) {
3533
+ renderLimit = config.renderChoiceLimit;
3534
+ }
3535
+ if (this._isSelectElement) {
3536
+ var backingOptions = activeChoices.filter(function (choice) { return !choice.element; });
3537
+ if (backingOptions.length) {
3538
+ this.passedElement.addOptions(backingOptions);
3539
+ }
3540
+ }
3541
+ var fragment = document.createDocumentFragment();
3542
+ var renderableChoices = function (choices) {
3543
+ return choices.filter(function (choice) {
3544
+ return !choice.placeholder && (isSearching ? !!choice.rank : config.renderSelectedChoices || !choice.selected);
3545
+ });
3546
+ };
3547
+ var selectableChoices = false;
3548
+ var renderChoices = function (choices, withinGroup, groupLabel) {
3549
+ if (isSearching) {
3550
+ // sortByRank is used to ensure stable sorting, as scores are non-unique
3551
+ // this additionally ensures fuseOptions.sortFn is not ignored
3552
+ choices.sort(sortByRank);
3553
+ }
3554
+ else if (config.shouldSort) {
3555
+ choices.sort(config.sorter);
3556
+ }
3557
+ var choiceLimit = choices.length;
3558
+ choiceLimit = !withinGroup && renderLimit && choiceLimit > renderLimit ? renderLimit : choiceLimit;
3559
+ choiceLimit--;
3560
+ choices.every(function (choice, index) {
3561
+ // choiceEl being empty signals the contents has probably significantly changed
3562
+ var dropdownItem = choice.choiceEl || _this._templates.choice(config, choice, config.itemSelectText, groupLabel);
3563
+ choice.choiceEl = dropdownItem;
3564
+ fragment.appendChild(dropdownItem);
3565
+ if (isSearching || !choice.selected) {
3566
+ selectableChoices = true;
3567
+ }
3568
+ return index < choiceLimit;
3569
+ });
3570
+ };
3571
+ if (activeChoices.length) {
3572
+ if (config.resetScrollPosition) {
3573
+ requestAnimationFrame(function () { return _this.choiceList.scrollToTop(); });
3574
+ }
3575
+ if (!this._hasNonChoicePlaceholder && !isSearching && this._isSelectOneElement) {
3576
+ // If we have a placeholder choice along with groups
3577
+ renderChoices(activeChoices.filter(function (choice) { return choice.placeholder && !choice.group; }), false, undefined);
3578
+ }
3579
+ // If we have grouped options
3580
+ if (activeGroups.length && !isSearching) {
3581
+ if (config.shouldSort) {
3582
+ activeGroups.sort(config.sorter);
3583
+ }
3584
+ // render Choices without group first, regardless of sort, otherwise they won't be distinguishable
3585
+ // from the last group
3586
+ renderChoices(activeChoices.filter(function (choice) { return !choice.placeholder && !choice.group; }), false, undefined);
3587
+ activeGroups.forEach(function (group) {
3588
+ var groupChoices = renderableChoices(group.choices);
3589
+ if (groupChoices.length) {
3590
+ if (group.label) {
3591
+ var dropdownGroup = group.groupEl || _this._templates.choiceGroup(_this.config, group);
3592
+ group.groupEl = dropdownGroup;
3593
+ dropdownGroup.remove();
3594
+ fragment.appendChild(dropdownGroup);
3595
+ }
3596
+ renderChoices(groupChoices, true, config.appendGroupInSearch && isSearching ? group.label : undefined);
3597
+ }
3598
+ });
3599
+ }
3600
+ else {
3601
+ renderChoices(renderableChoices(activeChoices), false, undefined);
3602
+ }
3603
+ }
3604
+ if (!selectableChoices && (isSearching || !fragment.children.length || !config.renderSelectedChoices)) {
3605
+ if (!this._notice) {
3606
+ this._notice = {
3607
+ text: resolveStringFunction(isSearching ? config.noResultsText : config.noChoicesText),
3608
+ type: isSearching ? NoticeTypes.noResults : NoticeTypes.noChoices,
3609
+ };
3610
+ }
3611
+ fragment.replaceChildren('');
3612
+ }
3613
+ this._renderNotice(fragment);
3614
+ this.choiceList.element.replaceChildren(fragment);
3615
+ if (selectableChoices) {
3616
+ this._highlightChoice();
3617
+ }
3618
+ };
3619
+ Choices.prototype._renderItems = function () {
3620
+ var _this = this;
3621
+ var items = this._store.items || [];
3622
+ var itemList = this.itemList.element;
3623
+ var config = this.config;
3624
+ var fragment = document.createDocumentFragment();
3625
+ var itemFromList = function (item) {
3626
+ return itemList.querySelector("[data-item][data-id=\"".concat(item.id, "\"]"));
3627
+ };
3628
+ var addItemToFragment = function (item) {
3629
+ var el = item.itemEl;
3630
+ if (el && el.parentElement) {
3631
+ return;
3632
+ }
3633
+ el = itemFromList(item) || _this._templates.item(config, item, config.removeItemButton);
3634
+ item.itemEl = el;
3635
+ fragment.appendChild(el);
3636
+ };
3637
+ // new items
3638
+ items.forEach(addItemToFragment);
3639
+ var addedItems = !!fragment.childNodes.length;
3640
+ if (this._isSelectOneElement) {
3641
+ var existingItems = itemList.children.length;
3642
+ if (addedItems || existingItems > 1) {
3643
+ var placeholder = itemList.querySelector(getClassNamesSelector(config.classNames.placeholder));
3644
+ if (placeholder) {
3645
+ placeholder.remove();
3646
+ }
3647
+ }
3648
+ else if (!addedItems && !existingItems && this._placeholderValue) {
3649
+ addedItems = true;
3650
+ addItemToFragment(mapInputToChoice({
3651
+ selected: true,
3652
+ value: '',
3653
+ label: this._placeholderValue,
3654
+ placeholder: true,
3655
+ }, false));
3656
+ }
3657
+ }
3658
+ if (addedItems) {
3659
+ itemList.append(fragment);
3660
+ if (config.shouldSortItems && !this._isSelectOneElement) {
3661
+ items.sort(config.sorter);
3662
+ // push sorting into the DOM
3663
+ items.forEach(function (item) {
3664
+ var el = itemFromList(item);
3665
+ if (el) {
3666
+ el.remove();
3667
+ fragment.append(el);
3668
+ }
3669
+ });
3670
+ itemList.append(fragment);
3671
+ }
3672
+ }
3673
+ if (this._isTextElement) {
3674
+ // Update the value of the hidden input
3675
+ this.passedElement.value = items.map(function (_a) {
3676
+ var value = _a.value;
3677
+ return value;
3678
+ }).join(config.delimiter);
3679
+ }
3680
+ };
3681
+ Choices.prototype._displayNotice = function (text, type, openDropdown) {
3682
+ if (openDropdown === void 0) { openDropdown = true; }
3683
+ var oldNotice = this._notice;
3684
+ if (oldNotice &&
3685
+ ((oldNotice.type === type && oldNotice.text === text) ||
3686
+ (oldNotice.type === NoticeTypes.addChoice &&
3687
+ (type === NoticeTypes.noResults || type === NoticeTypes.noChoices)))) {
3688
+ if (openDropdown) {
3689
+ this.showDropdown(true);
3690
+ }
3691
+ return;
3692
+ }
3693
+ this._clearNotice();
3694
+ this._notice = text
3695
+ ? {
3696
+ text: text,
3697
+ type: type,
3698
+ }
3699
+ : undefined;
3700
+ this._renderNotice();
3701
+ if (openDropdown && text) {
3702
+ this.showDropdown(true);
3703
+ }
3704
+ };
3705
+ Choices.prototype._clearNotice = function () {
3706
+ if (!this._notice) {
3707
+ return;
3708
+ }
3709
+ var noticeElement = this.choiceList.element.querySelector(getClassNamesSelector(this.config.classNames.notice));
3710
+ if (noticeElement) {
3711
+ noticeElement.remove();
3712
+ }
3713
+ this._notice = undefined;
3714
+ };
3715
+ Choices.prototype._renderNotice = function (fragment) {
3716
+ var noticeConf = this._notice;
3717
+ if (noticeConf) {
3718
+ var notice = this._templates.notice(this.config, noticeConf.text, noticeConf.type);
3719
+ if (fragment) {
3720
+ fragment.append(notice);
3721
+ }
3722
+ else {
3723
+ this.choiceList.prepend(notice);
3724
+ }
3725
+ }
3726
+ };
3727
+ // eslint-disable-next-line class-methods-use-this
3728
+ Choices.prototype._getChoiceForOutput = function (choice, keyCode) {
3729
+ return {
3730
+ id: choice.id,
3731
+ highlighted: choice.highlighted,
3732
+ labelClass: choice.labelClass,
3733
+ labelDescription: choice.labelDescription,
3734
+ customProperties: choice.customProperties,
3735
+ disabled: choice.disabled,
3736
+ active: choice.active,
3737
+ label: choice.label,
3738
+ placeholder: choice.placeholder,
3739
+ value: choice.value,
3740
+ groupValue: choice.group ? choice.group.label : undefined,
3741
+ element: choice.element,
3742
+ keyCode: keyCode,
3743
+ };
3744
+ };
3745
+ Choices.prototype._triggerChange = function (value) {
3746
+ if (value === undefined || value === null) {
3747
+ return;
3748
+ }
3749
+ this.passedElement.triggerEvent(EventType.change, {
3750
+ value: value,
3751
+ });
3752
+ };
3753
+ Choices.prototype._handleButtonAction = function (element) {
3754
+ var _this = this;
3755
+ var items = this._store.items;
3756
+ if (!items.length || !this.config.removeItems || !this.config.removeItemButton) {
3757
+ return;
3758
+ }
3759
+ var id = element && parseDataSetId(element.parentElement);
3760
+ var itemToRemove = id && items.find(function (item) { return item.id === id; });
3761
+ if (!itemToRemove) {
3762
+ return;
3763
+ }
3764
+ this._store.withTxn(function () {
3765
+ // Remove item associated with button
3766
+ _this._removeItem(itemToRemove);
3767
+ _this._triggerChange(itemToRemove.value);
3768
+ if (_this._isSelectOneElement && !_this._hasNonChoicePlaceholder) {
3769
+ var placeholderChoice = (_this.config.shouldSort ? _this._store.choices.reverse() : _this._store.choices).find(function (choice) { return choice.placeholder; });
3770
+ if (placeholderChoice) {
3771
+ _this._addItem(placeholderChoice);
3772
+ _this.unhighlightAll();
3773
+ if (placeholderChoice.value) {
3774
+ _this._triggerChange(placeholderChoice.value);
3775
+ }
3776
+ }
3777
+ }
3778
+ });
3779
+ };
3780
+ Choices.prototype._handleItemAction = function (element, hasShiftKey) {
3781
+ var _this = this;
3782
+ if (hasShiftKey === void 0) { hasShiftKey = false; }
3783
+ var items = this._store.items;
3784
+ if (!items.length || !this.config.removeItems || this._isSelectOneElement) {
3785
+ return;
3786
+ }
3787
+ var id = parseDataSetId(element);
3788
+ if (!id) {
3789
+ return;
3790
+ }
3791
+ // We only want to select one item with a click
3792
+ // so we deselect any items that aren't the target
3793
+ // unless shift is being pressed
3794
+ items.forEach(function (item) {
3795
+ if (item.id === id && !item.highlighted) {
3796
+ _this.highlightItem(item);
3797
+ }
3798
+ else if (!hasShiftKey && item.highlighted) {
3799
+ _this.unhighlightItem(item);
3800
+ }
3801
+ });
3802
+ // Focus input as without focus, a user cannot do anything with a
3803
+ // highlighted item
3804
+ this.input.focus();
3805
+ };
3806
+ Choices.prototype._handleChoiceAction = function (element) {
3807
+ var _this = this;
3808
+ // If we are clicking on an option
3809
+ var id = parseDataSetId(element);
3810
+ var choice = id && this._store.getChoiceById(id);
3811
+ if (!choice || choice.disabled) {
3812
+ return false;
3813
+ }
3814
+ var hasActiveDropdown = this.dropdown.isActive;
3815
+ if (!choice.selected) {
3816
+ if (!this._canAddItems()) {
3817
+ return true; // causes _onEnterKey to early out
3818
+ }
3819
+ this._store.withTxn(function () {
3820
+ _this._addItem(choice, true, true);
3821
+ _this.clearInput();
3822
+ _this.unhighlightAll();
3823
+ });
3824
+ this._triggerChange(choice.value);
3825
+ }
3826
+ // We want to close the dropdown if we are dealing with a single select box
3827
+ if (hasActiveDropdown && this.config.closeDropdownOnSelect) {
3828
+ this.hideDropdown(true);
3829
+ this.containerOuter.element.focus();
3830
+ }
3831
+ return true;
3832
+ };
3833
+ Choices.prototype._handleBackspace = function (items) {
3834
+ var config = this.config;
3835
+ if (!config.removeItems || !items.length) {
3836
+ return;
3837
+ }
3838
+ var lastItem = items[items.length - 1];
3839
+ var hasHighlightedItems = items.some(function (item) { return item.highlighted; });
3840
+ // If editing the last item is allowed and there are not other selected items,
3841
+ // we can edit the item value. Otherwise if we can remove items, remove all selected items
3842
+ if (config.editItems && !hasHighlightedItems && lastItem) {
3843
+ this.input.value = lastItem.value;
3844
+ this.input.setWidth();
3845
+ this._removeItem(lastItem);
3846
+ this._triggerChange(lastItem.value);
3847
+ }
3848
+ else {
3849
+ if (!hasHighlightedItems) {
3850
+ // Highlight last item if none already highlighted
3851
+ this.highlightItem(lastItem, false);
3852
+ }
3853
+ this.removeHighlightedItems(true);
3854
+ }
3855
+ };
3856
+ Choices.prototype._loadChoices = function () {
3857
+ var _a;
3858
+ var _this = this;
3859
+ var config = this.config;
3860
+ if (this._isTextElement) {
3861
+ // Assign preset items from passed object first
3862
+ this._presetChoices = config.items.map(function (e) { return mapInputToChoice(e, false); });
3863
+ // Add any values passed from attribute
3864
+ if (this.passedElement.value) {
3865
+ var elementItems = this.passedElement.value
3866
+ .split(config.delimiter)
3867
+ .map(function (e) { return mapInputToChoice(e, false, _this.config.allowHtmlUserInput); });
3868
+ this._presetChoices = this._presetChoices.concat(elementItems);
3869
+ }
3870
+ this._presetChoices.forEach(function (choice) {
3871
+ choice.selected = true;
3872
+ });
3873
+ }
3874
+ else if (this._isSelectElement) {
3875
+ // Assign preset choices from passed object
3876
+ this._presetChoices = config.choices.map(function (e) { return mapInputToChoice(e, true); });
3877
+ // Create array of choices from option elements
3878
+ var choicesFromOptions = this.passedElement.optionsAsChoices();
3879
+ if (choicesFromOptions) {
3880
+ (_a = this._presetChoices).push.apply(_a, choicesFromOptions);
3881
+ }
3882
+ }
3883
+ };
3884
+ Choices.prototype._handleLoadingState = function (setLoading) {
3885
+ if (setLoading === void 0) { setLoading = true; }
3886
+ var el = this.itemList.element;
3887
+ if (setLoading) {
3888
+ this.disable();
3889
+ this.containerOuter.addLoadingState();
3890
+ if (this._isSelectOneElement) {
3891
+ el.replaceChildren(this._templates.placeholder(this.config, this.config.loadingText));
3892
+ }
3893
+ else {
3894
+ this.input.placeholder = this.config.loadingText;
3895
+ }
3896
+ }
3897
+ else {
3898
+ this.enable();
3899
+ this.containerOuter.removeLoadingState();
3900
+ if (this._isSelectOneElement) {
3901
+ el.replaceChildren('');
3902
+ this._render();
3903
+ }
3904
+ else {
3905
+ this.input.placeholder = this._placeholderValue || '';
3906
+ }
3907
+ }
3908
+ };
3909
+ Choices.prototype._handleSearch = function (value) {
3910
+ if (!this.input.isFocussed) {
3911
+ return;
3912
+ }
3913
+ // Check that we have a value to search and the input was an alphanumeric character
3914
+ if (value !== null && typeof value !== 'undefined' && value.length >= this.config.searchFloor) {
3915
+ var resultCount = this.config.searchChoices ? this._searchChoices(value) : 0;
3916
+ if (resultCount !== null) {
3917
+ // Trigger search event
3918
+ this.passedElement.triggerEvent(EventType.search, {
3919
+ value: value,
3920
+ resultCount: resultCount,
3921
+ });
3922
+ }
3923
+ }
3924
+ else if (this._store.choices.some(function (option) { return !option.active; })) {
3925
+ this._stopSearch();
3926
+ }
3927
+ };
3928
+ Choices.prototype._canAddItems = function () {
3929
+ var config = this.config;
3930
+ var maxItemCount = config.maxItemCount, maxItemText = config.maxItemText;
3931
+ if (!config.singleModeForMultiSelect && maxItemCount > 0 && maxItemCount <= this._store.items.length) {
3932
+ this.choiceList.element.replaceChildren('');
3933
+ this._notice = undefined;
3934
+ this._displayNotice(typeof maxItemText === 'function' ? maxItemText(maxItemCount) : maxItemText, NoticeTypes.addChoice);
3935
+ return false;
3936
+ }
3937
+ if (this._notice && this._notice.type === NoticeTypes.addChoice) {
3938
+ this._clearNotice();
3939
+ }
3940
+ return true;
3941
+ };
3942
+ Choices.prototype._canCreateItem = function (value) {
3943
+ var config = this.config;
3944
+ var canAddItem = true;
3945
+ var notice = '';
3946
+ if (canAddItem && typeof config.addItemFilter === 'function' && !config.addItemFilter(value)) {
3947
+ canAddItem = false;
3948
+ notice = resolveNoticeFunction(config.customAddItemText, value);
3949
+ }
3950
+ if (canAddItem) {
3951
+ var foundChoice = this._store.choices.find(function (choice) { return config.valueComparer(choice.value, value); });
3952
+ if (foundChoice) {
3953
+ if (this._isSelectElement) {
3954
+ // for exact matches, do not prompt to add it as a custom choice
3955
+ this._displayNotice('', NoticeTypes.addChoice);
3956
+ return false;
3957
+ }
3958
+ if (!config.duplicateItemsAllowed) {
3959
+ canAddItem = false;
3960
+ notice = resolveNoticeFunction(config.uniqueItemText, value);
3961
+ }
3962
+ }
3963
+ }
3964
+ if (canAddItem) {
3965
+ notice = resolveNoticeFunction(config.addItemText, value);
3966
+ }
3967
+ if (notice) {
3968
+ this._displayNotice(notice, NoticeTypes.addChoice);
3969
+ }
3970
+ return canAddItem;
3971
+ };
3972
+ Choices.prototype._searchChoices = function (value) {
3973
+ var newValue = value.trim().replace(/\s{2,}/, ' ');
3974
+ // signal input didn't change search
3975
+ if (!newValue.length || newValue === this._currentValue) {
3976
+ return null;
3977
+ }
3978
+ var searcher = this._searcher;
3979
+ if (searcher.isEmptyIndex()) {
3980
+ searcher.index(this._store.searchableChoices);
3981
+ }
3982
+ // If new value matches the desired length and is not the same as the current value with a space
3983
+ var results = searcher.search(newValue);
3984
+ this._currentValue = newValue;
3985
+ this._highlightPosition = 0;
3986
+ this._isSearching = true;
3987
+ var notice = this._notice;
3988
+ var noticeType = notice && notice.type;
3989
+ if (noticeType !== NoticeTypes.addChoice) {
3990
+ if (!results.length) {
3991
+ this._displayNotice(resolveStringFunction(this.config.noResultsText), NoticeTypes.noResults);
3992
+ }
3993
+ else {
3994
+ this._clearNotice();
3995
+ }
3996
+ }
3997
+ this._store.dispatch(filterChoices(results));
3998
+ return results.length;
3999
+ };
4000
+ Choices.prototype._stopSearch = function () {
4001
+ if (this._isSearching) {
4002
+ this._currentValue = '';
4003
+ this._isSearching = false;
4004
+ this._clearNotice();
4005
+ this._store.dispatch(activateChoices(true));
4006
+ this.passedElement.triggerEvent(EventType.search, {
4007
+ value: '',
4008
+ resultCount: 0,
4009
+ });
4010
+ }
4011
+ };
4012
+ Choices.prototype._addEventListeners = function () {
4013
+ var documentElement = this._docRoot;
4014
+ var outerElement = this.containerOuter.element;
4015
+ var inputElement = this.input.element;
4016
+ // capture events - can cancel event processing or propagation
4017
+ documentElement.addEventListener('touchend', this._onTouchEnd, true);
4018
+ outerElement.addEventListener('keydown', this._onKeyDown, true);
4019
+ outerElement.addEventListener('mousedown', this._onMouseDown, true);
4020
+ // passive events - doesn't call `preventDefault` or `stopPropagation`
4021
+ documentElement.addEventListener('click', this._onClick, { passive: true });
4022
+ documentElement.addEventListener('touchmove', this._onTouchMove, {
4023
+ passive: true,
4024
+ });
4025
+ this.dropdown.element.addEventListener('mouseover', this._onMouseOver, {
4026
+ passive: true,
4027
+ });
4028
+ if (this._isSelectOneElement) {
4029
+ outerElement.addEventListener('focus', this._onFocus, {
4030
+ passive: true,
4031
+ });
4032
+ outerElement.addEventListener('blur', this._onBlur, {
4033
+ passive: true,
4034
+ });
4035
+ }
4036
+ inputElement.addEventListener('keyup', this._onKeyUp, {
4037
+ passive: true,
4038
+ });
4039
+ inputElement.addEventListener('input', this._onInput, {
4040
+ passive: true,
4041
+ });
4042
+ inputElement.addEventListener('focus', this._onFocus, {
4043
+ passive: true,
4044
+ });
4045
+ inputElement.addEventListener('blur', this._onBlur, {
4046
+ passive: true,
4047
+ });
4048
+ if (inputElement.form) {
4049
+ inputElement.form.addEventListener('reset', this._onFormReset, {
4050
+ passive: true,
4051
+ });
4052
+ }
4053
+ this.input.addEventListeners();
4054
+ };
4055
+ Choices.prototype._removeEventListeners = function () {
4056
+ var documentElement = this._docRoot;
4057
+ var outerElement = this.containerOuter.element;
4058
+ var inputElement = this.input.element;
4059
+ documentElement.removeEventListener('touchend', this._onTouchEnd, true);
4060
+ outerElement.removeEventListener('keydown', this._onKeyDown, true);
4061
+ outerElement.removeEventListener('mousedown', this._onMouseDown, true);
4062
+ documentElement.removeEventListener('click', this._onClick);
4063
+ documentElement.removeEventListener('touchmove', this._onTouchMove);
4064
+ this.dropdown.element.removeEventListener('mouseover', this._onMouseOver);
4065
+ if (this._isSelectOneElement) {
4066
+ outerElement.removeEventListener('focus', this._onFocus);
4067
+ outerElement.removeEventListener('blur', this._onBlur);
4068
+ }
4069
+ inputElement.removeEventListener('keyup', this._onKeyUp);
4070
+ inputElement.removeEventListener('input', this._onInput);
4071
+ inputElement.removeEventListener('focus', this._onFocus);
4072
+ inputElement.removeEventListener('blur', this._onBlur);
4073
+ if (inputElement.form) {
4074
+ inputElement.form.removeEventListener('reset', this._onFormReset);
4075
+ }
4076
+ this.input.removeEventListeners();
4077
+ };
4078
+ Choices.prototype._onKeyDown = function (event) {
4079
+ var keyCode = event.keyCode;
4080
+ var hasActiveDropdown = this.dropdown.isActive;
4081
+ /*
4082
+ See:
4083
+ https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
4084
+ https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values
4085
+ https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF - UTF-16 surrogate pairs
4086
+ https://stackoverflow.com/a/70866532 - "Unidentified" for mobile
4087
+ http://www.unicode.org/versions/Unicode5.2.0/ch16.pdf#G19635 - U+FFFF is reserved (Section 16.7)
4088
+
4089
+ Logic: when a key event is sent, `event.key` represents its printable value _or_ one
4090
+ of a large list of special values indicating meta keys/functionality. In addition,
4091
+ key events for compose functionality contain a value of `Dead` when mid-composition.
4092
+
4093
+ I can't quite verify it, but non-English IMEs may also be able to generate key codes
4094
+ for code points in the surrogate-pair range, which could potentially be seen as having
4095
+ key.length > 1. Since `Fn` is one of the special keys, we can't distinguish by that
4096
+ alone.
4097
+
4098
+ Here, key.length === 1 means we know for sure the input was printable and not a special
4099
+ `key` value. When the length is greater than 1, it could be either a printable surrogate
4100
+ pair or a special `key` value. We can tell the difference by checking if the _character
4101
+ code_ value (not code point!) is in the "surrogate pair" range or not.
4102
+
4103
+ We don't use .codePointAt because an invalid code point would return 65535, which wouldn't
4104
+ pass the >= 0x10000 check we would otherwise use.
4105
+
4106
+ > ...The Unicode Standard sets aside 66 noncharacter code points. The last two code points
4107
+ > of each plane are noncharacters: U+FFFE and U+FFFF on the BMP...
4108
+ */
4109
+ var wasPrintableChar = event.key.length === 1 ||
4110
+ (event.key.length === 2 && event.key.charCodeAt(0) >= 0xd800) ||
4111
+ event.key === 'Unidentified';
4112
+ /*
4113
+ We do not show the dropdown if focusing out with esc or navigating through input fields.
4114
+ An activated search can still be opened with any other key.
4115
+ */
4116
+ if (!this._isTextElement &&
4117
+ !hasActiveDropdown &&
4118
+ keyCode !== KeyCodeMap.ESC_KEY &&
4119
+ keyCode !== KeyCodeMap.TAB_KEY &&
4120
+ keyCode !== KeyCodeMap.SHIFT_KEY) {
4121
+ this.showDropdown();
4122
+ if (!this.input.isFocussed && wasPrintableChar) {
4123
+ /*
4124
+ We update the input value with the pressed key as
4125
+ the input was not focussed at the time of key press
4126
+ therefore does not have the value of the key.
4127
+ */
4128
+ this.input.value += event.key;
4129
+ // browsers interpret a space as pagedown
4130
+ if (event.key === ' ') {
4131
+ event.preventDefault();
4132
+ }
4133
+ }
4134
+ }
4135
+ switch (keyCode) {
4136
+ case KeyCodeMap.A_KEY:
4137
+ return this._onSelectKey(event, this.itemList.element.hasChildNodes());
4138
+ case KeyCodeMap.ENTER_KEY:
4139
+ return this._onEnterKey(event, hasActiveDropdown);
4140
+ case KeyCodeMap.ESC_KEY:
4141
+ return this._onEscapeKey(event, hasActiveDropdown);
4142
+ case KeyCodeMap.UP_KEY:
4143
+ case KeyCodeMap.PAGE_UP_KEY:
4144
+ case KeyCodeMap.DOWN_KEY:
4145
+ case KeyCodeMap.PAGE_DOWN_KEY:
4146
+ return this._onDirectionKey(event, hasActiveDropdown);
4147
+ case KeyCodeMap.DELETE_KEY:
4148
+ case KeyCodeMap.BACK_KEY:
4149
+ return this._onDeleteKey(event, this._store.items, this.input.isFocussed);
4150
+ }
4151
+ };
4152
+ Choices.prototype._onKeyUp = function ( /* event: KeyboardEvent */) {
4153
+ this._canSearch = this.config.searchEnabled;
4154
+ };
4155
+ Choices.prototype._onInput = function ( /* event: InputEvent */) {
4156
+ var value = this.input.value;
4157
+ if (!value) {
4158
+ if (this._isTextElement) {
4159
+ this.hideDropdown(true);
4160
+ }
4161
+ else {
4162
+ this._stopSearch();
4163
+ }
4164
+ return;
4165
+ }
4166
+ if (!this._canAddItems()) {
4167
+ return;
4168
+ }
4169
+ if (this._canSearch) {
4170
+ // do the search even if the entered text can not be added
4171
+ this._handleSearch(value);
4172
+ }
4173
+ if (!this._canAddUserChoices) {
4174
+ return;
4175
+ }
4176
+ // determine if a notice needs to be displayed for why a search result can't be added
4177
+ this._canCreateItem(value);
4178
+ if (this._isSelectElement) {
4179
+ this._highlightPosition = 0; // reset to select the notice and/or exact match
4180
+ this._highlightChoice();
4181
+ }
4182
+ };
4183
+ Choices.prototype._onSelectKey = function (event, hasItems) {
4184
+ // If CTRL + A or CMD + A have been pressed and there are items to select
4185
+ if ((event.ctrlKey || event.metaKey) && hasItems) {
4186
+ this._canSearch = false;
4187
+ var shouldHightlightAll = this.config.removeItems && !this.input.value && this.input.element === document.activeElement;
4188
+ if (shouldHightlightAll) {
4189
+ this.highlightAll();
4190
+ }
4191
+ }
4192
+ };
4193
+ Choices.prototype._onEnterKey = function (event, hasActiveDropdown) {
4194
+ var _this = this;
4195
+ var value = this.input.value;
4196
+ var target = event.target;
4197
+ event.preventDefault();
4198
+ if (target && target.hasAttribute('data-button')) {
4199
+ this._handleButtonAction(target);
4200
+ return;
4201
+ }
4202
+ if (!hasActiveDropdown) {
4203
+ if (this._isSelectElement || this._notice) {
4204
+ this.showDropdown();
4205
+ }
4206
+ return;
4207
+ }
4208
+ var highlightedChoice = this.dropdown.element.querySelector(getClassNamesSelector(this.config.classNames.highlightedState));
4209
+ if (highlightedChoice && this._handleChoiceAction(highlightedChoice)) {
4210
+ return;
4211
+ }
4212
+ if (!target || !value) {
4213
+ this.hideDropdown(true);
4214
+ return;
4215
+ }
4216
+ if (!this._canAddItems()) {
4217
+ return;
4218
+ }
4219
+ var addedItem = false;
4220
+ this._store.withTxn(function () {
4221
+ addedItem = _this._findAndSelectChoiceByValue(value, true);
4222
+ if (!addedItem) {
4223
+ if (!_this._canAddUserChoices) {
4224
+ return;
4225
+ }
4226
+ if (!_this._canCreateItem(value)) {
4227
+ return;
4228
+ }
4229
+ _this._addChoice(mapInputToChoice(value, false, _this.config.allowHtmlUserInput), true, true);
4230
+ addedItem = true;
4231
+ }
4232
+ _this.clearInput();
4233
+ _this.unhighlightAll();
4234
+ });
4235
+ if (!addedItem) {
4236
+ return;
4237
+ }
4238
+ this._triggerChange(value);
4239
+ if (this.config.closeDropdownOnSelect) {
4240
+ this.hideDropdown(true);
4241
+ }
4242
+ };
4243
+ Choices.prototype._onEscapeKey = function (event, hasActiveDropdown) {
4244
+ if (hasActiveDropdown) {
4245
+ event.stopPropagation();
4246
+ this.hideDropdown(true);
4247
+ this._stopSearch();
4248
+ this.containerOuter.element.focus();
4249
+ }
4250
+ };
4251
+ Choices.prototype._onDirectionKey = function (event, hasActiveDropdown) {
4252
+ var keyCode = event.keyCode;
4253
+ // If up or down key is pressed, traverse through options
4254
+ if (hasActiveDropdown || this._isSelectOneElement) {
4255
+ this.showDropdown();
4256
+ this._canSearch = false;
4257
+ var directionInt = keyCode === KeyCodeMap.DOWN_KEY || keyCode === KeyCodeMap.PAGE_DOWN_KEY ? 1 : -1;
4258
+ var skipKey = event.metaKey || keyCode === KeyCodeMap.PAGE_DOWN_KEY || keyCode === KeyCodeMap.PAGE_UP_KEY;
4259
+ var nextEl = void 0;
4260
+ if (skipKey) {
4261
+ if (directionInt > 0) {
4262
+ nextEl = this.dropdown.element.querySelector("".concat(selectableChoiceIdentifier, ":last-of-type"));
4263
+ }
4264
+ else {
4265
+ nextEl = this.dropdown.element.querySelector(selectableChoiceIdentifier);
4266
+ }
4267
+ }
4268
+ else {
4269
+ var currentEl = this.dropdown.element.querySelector(getClassNamesSelector(this.config.classNames.highlightedState));
4270
+ if (currentEl) {
4271
+ nextEl = getAdjacentEl(currentEl, selectableChoiceIdentifier, directionInt);
4272
+ }
4273
+ else {
4274
+ nextEl = this.dropdown.element.querySelector(selectableChoiceIdentifier);
4275
+ }
4276
+ }
4277
+ if (nextEl) {
4278
+ // We prevent default to stop the cursor moving
4279
+ // when pressing the arrow
4280
+ if (!isScrolledIntoView(nextEl, this.choiceList.element, directionInt)) {
4281
+ this.choiceList.scrollToChildElement(nextEl, directionInt);
4282
+ }
4283
+ this._highlightChoice(nextEl);
4284
+ }
4285
+ // Prevent default to maintain cursor position whilst
4286
+ // traversing dropdown options
4287
+ event.preventDefault();
4288
+ }
4289
+ };
4290
+ Choices.prototype._onDeleteKey = function (event, items, hasFocusedInput) {
4291
+ // If backspace or delete key is pressed and the input has no value
4292
+ if (!this._isSelectOneElement && !event.target.value && hasFocusedInput) {
4293
+ this._handleBackspace(items);
4294
+ event.preventDefault();
4295
+ }
4296
+ };
4297
+ Choices.prototype._onTouchMove = function () {
4298
+ if (this._wasTap) {
4299
+ this._wasTap = false;
4300
+ }
4301
+ };
4302
+ Choices.prototype._onTouchEnd = function (event) {
4303
+ var target = (event || event.touches[0]).target;
4304
+ var touchWasWithinContainer = this._wasTap && this.containerOuter.element.contains(target);
4305
+ if (touchWasWithinContainer) {
4306
+ var containerWasExactTarget = target === this.containerOuter.element || target === this.containerInner.element;
4307
+ if (containerWasExactTarget) {
4308
+ if (this._isTextElement) {
4309
+ this.input.focus();
4310
+ }
4311
+ else if (this._isSelectMultipleElement) {
4312
+ this.showDropdown();
4313
+ }
4314
+ }
4315
+ // Prevents focus event firing
4316
+ event.stopPropagation();
4317
+ }
4318
+ this._wasTap = true;
4319
+ };
4320
+ /**
4321
+ * Handles mousedown event in capture mode for containetOuter.element
4322
+ */
4323
+ Choices.prototype._onMouseDown = function (event) {
4324
+ var target = event.target;
4325
+ if (!(target instanceof HTMLElement)) {
4326
+ return;
4327
+ }
4328
+ // If we have our mouse down on the scrollbar and are on IE11...
4329
+ if (IS_IE11 && this.choiceList.element.contains(target)) {
4330
+ // check if click was on a scrollbar area
4331
+ var firstChoice = this.choiceList.element.firstElementChild;
4332
+ this._isScrollingOnIe =
4333
+ this._direction === 'ltr' ? event.offsetX >= firstChoice.offsetWidth : event.offsetX < firstChoice.offsetLeft;
4334
+ }
4335
+ if (target === this.input.element) {
4336
+ return;
4337
+ }
4338
+ var item = target.closest('[data-button],[data-item],[data-choice]');
4339
+ if (item instanceof HTMLElement) {
4340
+ if ('button' in item.dataset) {
4341
+ this._handleButtonAction(item);
4342
+ }
4343
+ else if ('item' in item.dataset) {
4344
+ this._handleItemAction(item, event.shiftKey);
4345
+ }
4346
+ else if ('choice' in item.dataset) {
4347
+ this._handleChoiceAction(item);
4348
+ }
4349
+ }
4350
+ event.preventDefault();
4351
+ };
4352
+ /**
4353
+ * Handles mouseover event over this.dropdown
4354
+ * @param {MouseEvent} event
4355
+ */
4356
+ Choices.prototype._onMouseOver = function (_a) {
4357
+ var target = _a.target;
4358
+ if (target instanceof HTMLElement && 'choice' in target.dataset) {
4359
+ this._highlightChoice(target);
4360
+ }
4361
+ };
4362
+ Choices.prototype._onClick = function (_a) {
4363
+ var target = _a.target;
4364
+ var containerOuter = this.containerOuter;
4365
+ var clickWasWithinContainer = containerOuter.element.contains(target);
4366
+ if (clickWasWithinContainer) {
4367
+ if (!this.dropdown.isActive && !containerOuter.isDisabled) {
4368
+ if (this._isTextElement) {
4369
+ if (document.activeElement !== this.input.element) {
4370
+ this.input.focus();
4371
+ }
4372
+ }
4373
+ else {
4374
+ this.showDropdown();
4375
+ containerOuter.element.focus();
4376
+ }
4377
+ }
4378
+ else if (this._isSelectOneElement &&
4379
+ target !== this.input.element &&
4380
+ !this.dropdown.element.contains(target)) {
4381
+ this.hideDropdown();
4382
+ }
4383
+ }
4384
+ else {
4385
+ containerOuter.removeFocusState();
4386
+ this.hideDropdown(true);
4387
+ this.unhighlightAll();
4388
+ }
4389
+ };
4390
+ Choices.prototype._onFocus = function (_a) {
4391
+ var target = _a.target;
4392
+ var containerOuter = this.containerOuter;
4393
+ var focusWasWithinContainer = target && containerOuter.element.contains(target);
4394
+ if (!focusWasWithinContainer) {
4395
+ return;
4396
+ }
4397
+ var targetIsInput = target === this.input.element;
4398
+ if (this._isTextElement) {
4399
+ if (targetIsInput) {
4400
+ containerOuter.addFocusState();
4401
+ }
4402
+ }
4403
+ else if (this._isSelectMultipleElement) {
4404
+ if (targetIsInput) {
4405
+ this.showDropdown(true);
4406
+ // If element is a select box, the focused element is the container and the dropdown
4407
+ // isn't already open, focus and show dropdown
4408
+ containerOuter.addFocusState();
4409
+ }
4410
+ }
4411
+ else {
4412
+ containerOuter.addFocusState();
4413
+ if (targetIsInput) {
4414
+ this.showDropdown(true);
4415
+ }
4416
+ }
4417
+ };
4418
+ Choices.prototype._onBlur = function (_a) {
4419
+ var target = _a.target;
4420
+ var containerOuter = this.containerOuter;
4421
+ var blurWasWithinContainer = target && containerOuter.element.contains(target);
4422
+ if (blurWasWithinContainer && !this._isScrollingOnIe) {
4423
+ if (target === this.input.element) {
4424
+ containerOuter.removeFocusState();
4425
+ this.hideDropdown(true);
4426
+ if (this._isTextElement || this._isSelectMultipleElement) {
4427
+ this.unhighlightAll();
4428
+ }
4429
+ }
4430
+ else if (target === this.containerOuter.element) {
4431
+ // Remove the focus state when the past outerContainer was the target
4432
+ containerOuter.removeFocusState();
4433
+ // Also close the dropdown if search is disabled
4434
+ if (!this._canSearch) {
4435
+ this.hideDropdown(true);
4436
+ }
4437
+ }
4438
+ }
4439
+ else {
4440
+ // On IE11, clicking the scollbar blurs our input and thus
4441
+ // closes the dropdown. To stop this, we refocus our input
4442
+ // if we know we are on IE *and* are scrolling.
4443
+ this._isScrollingOnIe = false;
4444
+ this.input.element.focus();
4445
+ }
4446
+ };
4447
+ Choices.prototype._onFormReset = function () {
4448
+ var _this = this;
4449
+ this._store.withTxn(function () {
4450
+ _this.clearInput();
4451
+ _this.hideDropdown();
4452
+ _this.refresh(false, false, true);
4453
+ if (_this._initialItems.length) {
4454
+ _this.setChoiceByValue(_this._initialItems);
4455
+ }
4456
+ });
4457
+ };
4458
+ Choices.prototype._highlightChoice = function (el) {
4459
+ if (el === void 0) { el = null; }
4460
+ var choices = Array.from(this.dropdown.element.querySelectorAll(selectableChoiceIdentifier));
4461
+ if (!choices.length) {
4462
+ return;
4463
+ }
4464
+ var passedEl = el;
4465
+ var highlightedState = this.config.classNames.highlightedState;
4466
+ var highlightedChoices = Array.from(this.dropdown.element.querySelectorAll(getClassNamesSelector(highlightedState)));
4467
+ // Remove any highlighted choices
4468
+ highlightedChoices.forEach(function (choice) {
4469
+ removeClassesFromElement(choice, highlightedState);
4470
+ choice.setAttribute('aria-selected', 'false');
4471
+ });
4472
+ if (passedEl) {
4473
+ this._highlightPosition = choices.indexOf(passedEl);
4474
+ }
4475
+ else {
4476
+ // Highlight choice based on last known highlight location
4477
+ if (choices.length > this._highlightPosition) {
4478
+ // If we have an option to highlight
4479
+ passedEl = choices[this._highlightPosition];
4480
+ }
4481
+ else {
4482
+ // Otherwise highlight the option before
4483
+ passedEl = choices[choices.length - 1];
4484
+ }
4485
+ if (!passedEl) {
4486
+ passedEl = choices[0];
4487
+ }
4488
+ }
4489
+ addClassesToElement(passedEl, highlightedState);
4490
+ passedEl.setAttribute('aria-selected', 'true');
4491
+ this.passedElement.triggerEvent(EventType.highlightChoice, {
4492
+ el: passedEl,
4493
+ });
4494
+ if (this.dropdown.isActive) {
4495
+ // IE11 ignores aria-label and blocks virtual keyboard
4496
+ // if aria-activedescendant is set without a dropdown
4497
+ this.input.setActiveDescendant(passedEl.id);
4498
+ this.containerOuter.setActiveDescendant(passedEl.id);
4499
+ }
4500
+ };
4501
+ Choices.prototype._addItem = function (item, withEvents, userTriggered) {
4502
+ if (withEvents === void 0) { withEvents = true; }
4503
+ if (userTriggered === void 0) { userTriggered = false; }
4504
+ if (!item.id) {
4505
+ throw new TypeError('item.id must be set before _addItem is called for a choice/item');
4506
+ }
4507
+ if (this.config.singleModeForMultiSelect || this._isSelectOneElement) {
4508
+ this.removeActiveItems(item.id);
4509
+ }
4510
+ this._store.dispatch(addItem(item));
4511
+ if (withEvents) {
4512
+ this.passedElement.triggerEvent(EventType.addItem, this._getChoiceForOutput(item));
4513
+ if (userTriggered) {
4514
+ this.passedElement.triggerEvent(EventType.choice, this._getChoiceForOutput(item));
4515
+ }
4516
+ }
4517
+ };
4518
+ Choices.prototype._removeItem = function (item) {
4519
+ if (!item.id) {
4520
+ return;
4521
+ }
4522
+ this._store.dispatch(removeItem$1(item));
4523
+ var notice = this._notice;
4524
+ if (notice && notice.type === NoticeTypes.noChoices) {
4525
+ this._clearNotice();
4526
+ }
4527
+ this.passedElement.triggerEvent(EventType.removeItem, this._getChoiceForOutput(item));
4528
+ };
4529
+ Choices.prototype._addChoice = function (choice, withEvents, userTriggered) {
4530
+ if (withEvents === void 0) { withEvents = true; }
4531
+ if (userTriggered === void 0) { userTriggered = false; }
4532
+ if (choice.id) {
4533
+ throw new TypeError('Can not re-add a choice which has already been added');
4534
+ }
4535
+ var config = this.config;
4536
+ if (!config.duplicateItemsAllowed && this._store.choices.find(function (c) { return config.valueComparer(c.value, choice.value); })) {
4537
+ return;
4538
+ }
4539
+ // Generate unique id, in-place update is required so chaining _addItem works as expected
4540
+ this._lastAddedChoiceId++;
4541
+ choice.id = this._lastAddedChoiceId;
4542
+ choice.elementId = "".concat(this._baseId, "-").concat(this._idNames.itemChoice, "-").concat(choice.id);
4543
+ var prependValue = config.prependValue, appendValue = config.appendValue;
4544
+ if (prependValue) {
4545
+ choice.value = prependValue + choice.value;
4546
+ }
4547
+ if (appendValue) {
4548
+ choice.value += appendValue.toString();
4549
+ }
4550
+ if ((prependValue || appendValue) && choice.element) {
4551
+ choice.element.value = choice.value;
4552
+ }
4553
+ this._clearNotice();
4554
+ this._store.dispatch(addChoice(choice));
4555
+ if (choice.selected) {
4556
+ this._addItem(choice, withEvents, userTriggered);
4557
+ }
4558
+ };
4559
+ Choices.prototype._addGroup = function (group, withEvents) {
4560
+ var _this = this;
4561
+ if (withEvents === void 0) { withEvents = true; }
4562
+ if (group.id) {
4563
+ throw new TypeError('Can not re-add a group which has already been added');
4564
+ }
4565
+ this._store.dispatch(addGroup(group));
4566
+ if (!group.choices) {
4567
+ return;
4568
+ }
4569
+ // add unique id for the group(s), and do not store the full list of choices in this group
4570
+ this._lastAddedGroupId++;
4571
+ group.id = this._lastAddedGroupId;
4572
+ group.choices.forEach(function (item) {
4573
+ item.group = group;
4574
+ if (group.disabled) {
4575
+ item.disabled = true;
4576
+ }
4577
+ _this._addChoice(item, withEvents);
4578
+ });
4579
+ };
4580
+ Choices.prototype._createTemplates = function () {
4581
+ var _this = this;
4582
+ var callbackOnCreateTemplates = this.config.callbackOnCreateTemplates;
4583
+ var userTemplates = {};
4584
+ if (typeof callbackOnCreateTemplates === 'function') {
4585
+ userTemplates = callbackOnCreateTemplates.call(this, strToEl, escapeForTemplate, getClassNames);
4586
+ }
4587
+ var templating = {};
4588
+ Object.keys(this._templates).forEach(function (name) {
4589
+ if (name in userTemplates) {
4590
+ templating[name] = userTemplates[name].bind(_this);
4591
+ }
4592
+ else {
4593
+ templating[name] = _this._templates[name].bind(_this);
4594
+ }
4595
+ });
4596
+ this._templates = templating;
4597
+ };
4598
+ Choices.prototype._createElements = function () {
4599
+ var templating = this._templates;
4600
+ var _a = this, config = _a.config, isSelectOneElement = _a._isSelectOneElement;
4601
+ var position = config.position, classNames = config.classNames;
4602
+ var elementType = this._elementType;
4603
+ this.containerOuter = new Container({
4604
+ element: templating.containerOuter(config, this._direction, this._isSelectElement, isSelectOneElement, config.searchEnabled, elementType, config.labelId),
4605
+ classNames: classNames,
4606
+ type: elementType,
4607
+ position: position,
4608
+ });
4609
+ this.containerInner = new Container({
4610
+ element: templating.containerInner(config),
4611
+ classNames: classNames,
4612
+ type: elementType,
4613
+ position: position,
4614
+ });
4615
+ this.input = new Input({
4616
+ element: templating.input(config, this._placeholderValue),
4617
+ classNames: classNames,
4618
+ type: elementType,
4619
+ preventPaste: !config.paste,
4620
+ });
4621
+ this.choiceList = new List({
4622
+ element: templating.choiceList(config, isSelectOneElement),
4623
+ });
4624
+ this.itemList = new List({
4625
+ element: templating.itemList(config, isSelectOneElement),
4626
+ });
4627
+ this.dropdown = new Dropdown({
4628
+ element: templating.dropdown(config),
4629
+ classNames: classNames,
4630
+ type: elementType,
4631
+ });
4632
+ };
4633
+ Choices.prototype._createStructure = function () {
4634
+ var _a = this, containerInner = _a.containerInner, containerOuter = _a.containerOuter, passedElement = _a.passedElement;
4635
+ var dropdownElement = this.dropdown.element;
4636
+ // Hide original element
4637
+ passedElement.conceal();
4638
+ // Wrap input in container preserving DOM ordering
4639
+ containerInner.wrap(passedElement.element);
4640
+ // Wrapper inner container with outer container
4641
+ containerOuter.wrap(containerInner.element);
4642
+ if (this._isSelectOneElement) {
4643
+ this.input.placeholder = this.config.searchPlaceholderValue || '';
4644
+ }
4645
+ else {
4646
+ if (this._placeholderValue) {
4647
+ this.input.placeholder = this._placeholderValue;
4648
+ }
4649
+ this.input.setWidth();
4650
+ }
4651
+ containerOuter.element.appendChild(containerInner.element);
4652
+ containerOuter.element.appendChild(dropdownElement);
4653
+ containerInner.element.appendChild(this.itemList.element);
4654
+ dropdownElement.appendChild(this.choiceList.element);
4655
+ if (!this._isSelectOneElement) {
4656
+ containerInner.element.appendChild(this.input.element);
4657
+ }
4658
+ else if (this.config.searchEnabled) {
4659
+ dropdownElement.insertBefore(this.input.element, dropdownElement.firstChild);
4660
+ }
4661
+ this._highlightPosition = 0;
4662
+ this._isSearching = false;
4663
+ };
4664
+ Choices.prototype._initStore = function () {
4665
+ var _this = this;
4666
+ this._store.subscribe(this._render).withTxn(function () {
4667
+ _this._addPredefinedChoices(_this._presetChoices, _this._isSelectOneElement && !_this._hasNonChoicePlaceholder, false);
4668
+ });
4669
+ if (!this._store.choices.length || (this._isSelectOneElement && this._hasNonChoicePlaceholder)) {
4670
+ this._render();
4671
+ }
4672
+ };
4673
+ Choices.prototype._addPredefinedChoices = function (choices, selectFirstOption, withEvents) {
4674
+ var _this = this;
4675
+ if (selectFirstOption === void 0) { selectFirstOption = false; }
4676
+ if (withEvents === void 0) { withEvents = true; }
4677
+ if (selectFirstOption) {
4678
+ /**
4679
+ * If there is a selected choice already or the choice is not the first in
4680
+ * the array, add each choice normally.
4681
+ *
4682
+ * Otherwise we pre-select the first enabled choice in the array ("select-one" only)
4683
+ */
4684
+ var noSelectedChoices = choices.findIndex(function (choice) { return choice.selected; }) === -1;
4685
+ if (noSelectedChoices) {
4686
+ choices.some(function (choice) {
4687
+ if (choice.disabled || 'choices' in choice) {
4688
+ return false;
4689
+ }
4690
+ choice.selected = true;
4691
+ return true;
4692
+ });
4693
+ }
4694
+ }
4695
+ choices.forEach(function (item) {
4696
+ if ('choices' in item) {
4697
+ if (_this._isSelectElement) {
4698
+ _this._addGroup(item, withEvents);
4699
+ }
4700
+ }
4701
+ else {
4702
+ _this._addChoice(item, withEvents);
4703
+ }
4704
+ });
4705
+ };
4706
+ Choices.prototype._findAndSelectChoiceByValue = function (value, userTriggered) {
4707
+ var _this = this;
4708
+ if (userTriggered === void 0) { userTriggered = false; }
4709
+ // Check 'value' property exists and the choice isn't already selected
4710
+ var foundChoice = this._store.choices.find(function (choice) { return _this.config.valueComparer(choice.value, value); });
4711
+ if (foundChoice && !foundChoice.disabled && !foundChoice.selected) {
4712
+ this._addItem(foundChoice, true, userTriggered);
4713
+ return true;
4714
+ }
4715
+ return false;
4716
+ };
4717
+ Choices.prototype._generatePlaceholderValue = function () {
4718
+ var config = this.config;
4719
+ if (!config.placeholder) {
4720
+ return null;
4721
+ }
4722
+ if (this._hasNonChoicePlaceholder) {
4723
+ return config.placeholderValue;
4724
+ }
4725
+ if (this._isSelectElement) {
4726
+ var placeholderOption = this.passedElement.placeholderOption;
4727
+ return placeholderOption ? placeholderOption.text : null;
4728
+ }
4729
+ return null;
4730
+ };
4731
+ Choices.prototype._warnChoicesInitFailed = function (caller) {
4732
+ if (this.config.silent) {
4733
+ return;
4734
+ }
4735
+ if (!this.initialised) {
4736
+ throw new TypeError("".concat(caller, " called on a non-initialised instance of Choices"));
4737
+ }
4738
+ else if (!this.initialisedOK) {
4739
+ throw new TypeError("".concat(caller, " called for an element which has multiple instances of Choices initialised on it"));
4740
+ }
4741
+ };
4742
+ Choices.version = '11.1.0';
4743
+ return Choices;
4744
+ }());
4745
+
4746
+ return Choices;
4747
+
4748
+ }));