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