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