hotwire_combobox 0.3.1 → 0.4.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 (51) hide show
  1. checksums.yaml +4 -4
  2. data/MIT-LICENSE +1 -1
  3. data/README.md +19 -15
  4. data/app/assets/config/hw_combobox_manifest.js +1 -1
  5. data/app/assets/javascripts/controllers/hw_combobox_controller.js +34 -18
  6. data/app/assets/javascripts/hotwire_combobox.esm.js +147 -72
  7. data/app/assets/javascripts/hw_combobox/helpers.js +9 -0
  8. data/app/assets/javascripts/hw_combobox/models/combobox/autocomplete.js +14 -4
  9. data/app/assets/javascripts/hw_combobox/models/combobox/callbacks.js +46 -0
  10. data/app/assets/javascripts/hw_combobox/models/combobox/dialog.js +1 -4
  11. data/app/assets/javascripts/hw_combobox/models/combobox/filtering.js +19 -8
  12. data/app/assets/javascripts/hw_combobox/models/combobox/form_field.js +1 -2
  13. data/app/assets/javascripts/hw_combobox/models/combobox/multiselect.js +6 -3
  14. data/app/assets/javascripts/hw_combobox/models/combobox/navigation.js +2 -2
  15. data/app/assets/javascripts/hw_combobox/models/combobox/selection.js +4 -12
  16. data/app/assets/javascripts/hw_combobox/models/combobox/toggle.js +13 -18
  17. data/app/assets/javascripts/hw_combobox/models/combobox.js +1 -0
  18. data/app/assets/stylesheets/hotwire_combobox.css +13 -3
  19. data/app/presenters/hotwire_combobox/component/announced.rb +5 -0
  20. data/app/presenters/hotwire_combobox/component/associations.rb +18 -0
  21. data/app/presenters/hotwire_combobox/component/async.rb +6 -0
  22. data/app/presenters/hotwire_combobox/component/customizable.rb +8 -20
  23. data/app/presenters/hotwire_combobox/component/freetext.rb +26 -0
  24. data/app/presenters/hotwire_combobox/component/markup/dialog.rb +57 -0
  25. data/app/presenters/hotwire_combobox/component/markup/fieldset.rb +46 -0
  26. data/app/presenters/hotwire_combobox/component/markup/form.rb +6 -0
  27. data/app/presenters/hotwire_combobox/component/markup/handle.rb +7 -0
  28. data/app/presenters/hotwire_combobox/component/markup/hidden_field.rb +28 -0
  29. data/app/presenters/hotwire_combobox/component/markup/input.rb +44 -0
  30. data/app/presenters/hotwire_combobox/component/markup/label.rb +5 -0
  31. data/app/presenters/hotwire_combobox/component/markup/listbox.rb +14 -0
  32. data/app/presenters/hotwire_combobox/component/markup/wrapper.rb +7 -0
  33. data/app/presenters/hotwire_combobox/component/multiselect.rb +6 -0
  34. data/app/presenters/hotwire_combobox/component/paginated.rb +18 -0
  35. data/app/presenters/hotwire_combobox/component.rb +32 -398
  36. data/app/presenters/hotwire_combobox/listbox/group.rb +3 -15
  37. data/app/presenters/hotwire_combobox/listbox/item.rb +5 -12
  38. data/app/presenters/hotwire_combobox/listbox/option.rb +3 -19
  39. data/app/views/hotwire_combobox/_component.html.erb +28 -6
  40. data/app/views/hotwire_combobox/_pagination.html.erb +3 -3
  41. data/config/hw_importmap.rb +1 -1
  42. data/lib/hotwire_combobox/helper.rb +24 -65
  43. data/lib/hotwire_combobox/platform.rb +15 -0
  44. data/lib/hotwire_combobox/version.rb +1 -1
  45. data/lib/hotwire_combobox.rb +1 -0
  46. metadata +34 -11
  47. data/app/assets/javascripts/hotwire_combobox.umd.js +0 -1769
  48. data/app/views/hotwire_combobox/combobox/_dialog.html.erb +0 -9
  49. data/app/views/hotwire_combobox/combobox/_hidden_field.html.erb +0 -4
  50. data/app/views/hotwire_combobox/combobox/_input.html.erb +0 -2
  51. data/app/views/hotwire_combobox/combobox/_paginated_listbox.html.erb +0 -9
@@ -1,1769 +0,0 @@
1
- /*!
2
- HotwireCombobox 0.3.1
3
- */
4
- (function (global, factory) {
5
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@hotwired/stimulus')) :
6
- typeof define === 'function' && define.amd ? define(['@hotwired/stimulus'], factory) :
7
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.HotwireCombobox = factory(global.Stimulus));
8
- })(this, (function (stimulus) { 'use strict';
9
-
10
- const Combobox = {};
11
-
12
- Combobox.Actors = Base => class extends Base {
13
- _initializeActors() {
14
- this._actingListbox = this.listboxTarget;
15
- this._actingCombobox = this.comboboxTarget;
16
- }
17
-
18
- _forAllComboboxes(callback) {
19
- this._allComboboxes.forEach(callback);
20
- }
21
-
22
- get _actingListbox() {
23
- return this.actingListbox
24
- }
25
-
26
- set _actingListbox(listbox) {
27
- this.actingListbox = listbox;
28
- }
29
-
30
- get _actingCombobox() {
31
- return this.actingCombobox
32
- }
33
-
34
- set _actingCombobox(combobox) {
35
- this.actingCombobox = combobox;
36
- }
37
-
38
- get _allComboboxes() {
39
- return [ this.comboboxTarget, this.dialogComboboxTarget ]
40
- }
41
- };
42
-
43
- Combobox.Announcements = Base => class extends Base {
44
- _announceToScreenReader(display, action) {
45
- this.announcerTarget.innerText = `${display} ${action}`;
46
- }
47
- };
48
-
49
- Combobox.AsyncLoading = Base => class extends Base {
50
- get _isAsync() {
51
- return this.hasAsyncSrcValue
52
- }
53
-
54
- get _isSync() {
55
- return !this._isAsync
56
- }
57
- };
58
-
59
- function Concerns(Base, ...mixins) {
60
- return mixins.reduce((accumulator, current) => current(accumulator), Base)
61
- }
62
-
63
- function visible(target) {
64
- return !(target.hidden || target.closest("[hidden]"))
65
- }
66
-
67
- function wrapAroundAccess(array, index) {
68
- const first = 0;
69
- const last = array.length - 1;
70
-
71
- if (index < first) return array[last]
72
- if (index > last) return array[first]
73
- return array[index]
74
- }
75
-
76
- function applyFilter(query, { matching }) {
77
- return (target) => {
78
- if (query) {
79
- const value = target.getAttribute(matching) || "";
80
- const match = value.toLowerCase().includes(query.toLowerCase());
81
-
82
- target.hidden = !match;
83
- } else {
84
- target.hidden = false;
85
- }
86
- }
87
- }
88
-
89
- function cancel(event) {
90
- event.stopPropagation();
91
- event.preventDefault();
92
- }
93
-
94
- function startsWith(string, substring) {
95
- return string.toLowerCase().startsWith(substring.toLowerCase())
96
- }
97
-
98
- function debounce(fn, delay = 150) {
99
- let timeoutId = null;
100
-
101
- return (...args) => {
102
- const callback = () => fn.apply(this, args);
103
- clearTimeout(timeoutId);
104
- timeoutId = setTimeout(callback, delay);
105
- }
106
- }
107
-
108
- function isDeleteEvent(event) {
109
- return event.inputType === "deleteContentBackward" || event.inputType === "deleteWordBackward"
110
- }
111
-
112
- function sleep(ms) {
113
- return new Promise(resolve => setTimeout(resolve, ms))
114
- }
115
-
116
- function unselectedPortion(element) {
117
- if (element.selectionStart === element.selectionEnd) {
118
- return element.value
119
- } else {
120
- return element.value.substring(0, element.selectionStart)
121
- }
122
- }
123
-
124
- function dispatch(eventName, { target, cancelable, detail } = {}) {
125
- const event = new CustomEvent(eventName, {
126
- cancelable,
127
- bubbles: true,
128
- composed: true,
129
- detail
130
- });
131
-
132
- if (target && target.isConnected) {
133
- target.dispatchEvent(event);
134
- } else {
135
- document.documentElement.dispatchEvent(event);
136
- }
137
-
138
- return event
139
- }
140
-
141
- function nextRepaint() {
142
- if (document.visibilityState === "hidden") {
143
- return nextEventLoopTick()
144
- } else {
145
- return nextAnimationFrame()
146
- }
147
- }
148
-
149
- function nextAnimationFrame() {
150
- return new Promise((resolve) => requestAnimationFrame(() => resolve()))
151
- }
152
-
153
- function nextEventLoopTick() {
154
- return new Promise((resolve) => setTimeout(() => resolve(), 0))
155
- }
156
-
157
- Combobox.Autocomplete = Base => class extends Base {
158
- _connectListAutocomplete() {
159
- if (!this._autocompletesList) {
160
- this._visuallyHideListbox();
161
- }
162
- }
163
-
164
- _replaceFullQueryWithAutocompletedValue(option) {
165
- const autocompletedValue = option.getAttribute(this.autocompletableAttributeValue);
166
-
167
- this._fullQuery = autocompletedValue;
168
- this._actingCombobox.setSelectionRange(autocompletedValue.length, autocompletedValue.length);
169
- }
170
-
171
- _autocompleteMissingPortion(option) {
172
- const typedValue = this._typedQuery;
173
- const autocompletedValue = option.getAttribute(this.autocompletableAttributeValue);
174
-
175
- if (this._autocompletesInline && startsWith(autocompletedValue, typedValue)) {
176
- this._fullQuery = autocompletedValue;
177
- this._actingCombobox.setSelectionRange(typedValue.length, autocompletedValue.length);
178
- }
179
- }
180
-
181
- // +visuallyHideListbox+ hides the listbox from the user,
182
- // but makes it still searchable by JS.
183
- _visuallyHideListbox() {
184
- this.listboxTarget.style.display = "none";
185
- }
186
-
187
- get _isExactAutocompleteMatch() {
188
- return this._immediatelyAutocompletableValue === this._fullQuery
189
- }
190
-
191
- // All `_isExactAutocompleteMatch` matches are `_isPartialAutocompleteMatch` matches
192
- // but not all `_isPartialAutocompleteMatch` matches are `_isExactAutocompleteMatch` matches.
193
- get _isPartialAutocompleteMatch() {
194
- return !!this._immediatelyAutocompletableValue &&
195
- startsWith(this._immediatelyAutocompletableValue, this._fullQuery)
196
- }
197
-
198
- get _autocompletesList() {
199
- return this.autocompleteValue === "both" || this.autocompleteValue === "list"
200
- }
201
-
202
- get _autocompletesInline() {
203
- return this.autocompleteValue === "both" || this.autocompleteValue === "inline"
204
- }
205
-
206
- get _immediatelyAutocompletableValue() {
207
- return this._ensurableOption?.getAttribute(this.autocompletableAttributeValue)
208
- }
209
- };
210
-
211
- Combobox.Dialog = Base => class extends Base {
212
- rerouteListboxStreamToDialog({ detail: { newStream } }) {
213
- if (newStream.target == this.listboxTarget.id && this._dialogIsOpen) {
214
- newStream.setAttribute("target", this.dialogListboxTarget.id);
215
- }
216
- }
217
-
218
- _connectDialog() {
219
- if (window.visualViewport) {
220
- window.visualViewport.addEventListener("resize", this._resizeDialog);
221
- }
222
- }
223
-
224
- _disconnectDialog() {
225
- if (window.visualViewport) {
226
- window.visualViewport.removeEventListener("resize", this._resizeDialog);
227
- }
228
- }
229
-
230
- _moveArtifactsToDialog() {
231
- this.dialogComboboxTarget.value = this._fullQuery;
232
-
233
- this._actingCombobox = this.dialogComboboxTarget;
234
- this._actingListbox = this.dialogListboxTarget;
235
-
236
- this.dialogListboxTarget.append(...this.listboxTarget.children);
237
- }
238
-
239
- _moveArtifactsInline() {
240
- this.comboboxTarget.value = this._fullQuery;
241
-
242
- this._actingCombobox = this.comboboxTarget;
243
- this._actingListbox = this.listboxTarget;
244
-
245
- this.listboxTarget.append(...this.dialogListboxTarget.children);
246
- }
247
-
248
- _resizeDialog = () => {
249
- if (window.visualViewport) {
250
- this.dialogTarget.style.setProperty(
251
- "--hw-visual-viewport-height",
252
- `${window.visualViewport.height}px`
253
- );
254
- }
255
- }
256
-
257
- // After closing a dialog, focus returns to the last focused element.
258
- // +preventFocusingComboboxAfterClosingDialog+ focuses a placeholder element before opening
259
- // the dialog, so that the combobox is not focused again after closing, which would reopen.
260
- _preventFocusingComboboxAfterClosingDialog() {
261
- this.dialogFocusTrapTarget.focus();
262
- }
263
-
264
- get _isSmallViewport() {
265
- return window.matchMedia(`(max-width: ${this.smallViewportMaxWidthValue})`).matches
266
- }
267
-
268
- get _dialogIsOpen() {
269
- return this.dialogTarget.open
270
- }
271
- };
272
-
273
- Combobox.Events = Base => class extends Base {
274
- _dispatchPreselectionEvent({ isNewAndAllowed, previousValue }) {
275
- if (previousValue === this._incomingFieldValueString) return
276
-
277
- dispatch("hw-combobox:preselection", {
278
- target: this.element,
279
- detail: { ...this._eventableDetails, isNewAndAllowed, previousValue }
280
- });
281
- }
282
-
283
- _dispatchSelectionEvent() {
284
- dispatch("hw-combobox:selection", {
285
- target: this.element,
286
- detail: this._eventableDetails
287
- });
288
- }
289
-
290
- _dispatchRemovalEvent({ removedDisplay, removedValue }) {
291
- dispatch("hw-combobox:removal", {
292
- target: this.element,
293
- detail: { ...this._eventableDetails, removedDisplay, removedValue }
294
- });
295
- }
296
-
297
- get _eventableDetails() {
298
- return {
299
- value: this._incomingFieldValueString,
300
- display: this._fullQuery,
301
- query: this._typedQuery,
302
- fieldName: this._fieldName,
303
- isValid: this._valueIsValid
304
- }
305
- }
306
- };
307
-
308
- class FetchResponse {
309
- constructor(response) {
310
- this.response = response;
311
- }
312
- get statusCode() {
313
- return this.response.status;
314
- }
315
- get redirected() {
316
- return this.response.redirected;
317
- }
318
- get ok() {
319
- return this.response.ok;
320
- }
321
- get unauthenticated() {
322
- return this.statusCode === 401;
323
- }
324
- get unprocessableEntity() {
325
- return this.statusCode === 422;
326
- }
327
- get authenticationURL() {
328
- return this.response.headers.get("WWW-Authenticate");
329
- }
330
- get contentType() {
331
- const contentType = this.response.headers.get("Content-Type") || "";
332
- return contentType.replace(/;.*$/, "");
333
- }
334
- get headers() {
335
- return this.response.headers;
336
- }
337
- get html() {
338
- if (this.contentType.match(/^(application|text)\/(html|xhtml\+xml)$/)) {
339
- return this.text;
340
- }
341
- return Promise.reject(new Error(`Expected an HTML response but got "${this.contentType}" instead`));
342
- }
343
- get json() {
344
- if (this.contentType.match(/^application\/.*json$/)) {
345
- return this.responseJson || (this.responseJson = this.response.json());
346
- }
347
- return Promise.reject(new Error(`Expected a JSON response but got "${this.contentType}" instead`));
348
- }
349
- get text() {
350
- return this.responseText || (this.responseText = this.response.text());
351
- }
352
- get isTurboStream() {
353
- return this.contentType.match(/^text\/vnd\.turbo-stream\.html/);
354
- }
355
- async renderTurboStream() {
356
- if (this.isTurboStream) {
357
- if (window.Turbo) {
358
- await window.Turbo.renderStreamMessage(await this.text);
359
- } else {
360
- console.warn("You must set `window.Turbo = Turbo` to automatically process Turbo Stream events with request.js");
361
- }
362
- } else {
363
- return Promise.reject(new Error(`Expected a Turbo Stream response but got "${this.contentType}" instead`));
364
- }
365
- }
366
- }
367
-
368
- class RequestInterceptor {
369
- static register(interceptor) {
370
- this.interceptor = interceptor;
371
- }
372
- static get() {
373
- return this.interceptor;
374
- }
375
- static reset() {
376
- this.interceptor = undefined;
377
- }
378
- }
379
-
380
- function getCookie(name) {
381
- const cookies = document.cookie ? document.cookie.split("; ") : [];
382
- const prefix = `${encodeURIComponent(name)}=`;
383
- const cookie = cookies.find((cookie => cookie.startsWith(prefix)));
384
- if (cookie) {
385
- const value = cookie.split("=").slice(1).join("=");
386
- if (value) {
387
- return decodeURIComponent(value);
388
- }
389
- }
390
- }
391
-
392
- function compact(object) {
393
- const result = {};
394
- for (const key in object) {
395
- const value = object[key];
396
- if (value !== undefined) {
397
- result[key] = value;
398
- }
399
- }
400
- return result;
401
- }
402
-
403
- function metaContent(name) {
404
- const element = document.head.querySelector(`meta[name="${name}"]`);
405
- return element && element.content;
406
- }
407
-
408
- function stringEntriesFromFormData(formData) {
409
- return [ ...formData ].reduce(((entries, [name, value]) => entries.concat(typeof value === "string" ? [ [ name, value ] ] : [])), []);
410
- }
411
-
412
- function mergeEntries(searchParams, entries) {
413
- for (const [name, value] of entries) {
414
- if (value instanceof window.File) continue;
415
- if (searchParams.has(name) && !name.includes("[]")) {
416
- searchParams.delete(name);
417
- searchParams.set(name, value);
418
- } else {
419
- searchParams.append(name, value);
420
- }
421
- }
422
- }
423
-
424
- class FetchRequest {
425
- constructor(method, url, options = {}) {
426
- this.method = method;
427
- this.options = options;
428
- this.originalUrl = url.toString();
429
- }
430
- async perform() {
431
- try {
432
- const requestInterceptor = RequestInterceptor.get();
433
- if (requestInterceptor) {
434
- await requestInterceptor(this);
435
- }
436
- } catch (error) {
437
- console.error(error);
438
- }
439
- const response = new FetchResponse(await window.fetch(this.url, this.fetchOptions));
440
- if (response.unauthenticated && response.authenticationURL) {
441
- return Promise.reject(window.location.href = response.authenticationURL);
442
- }
443
- const responseStatusIsTurboStreamable = response.ok || response.unprocessableEntity;
444
- if (responseStatusIsTurboStreamable && response.isTurboStream) {
445
- await response.renderTurboStream();
446
- }
447
- return response;
448
- }
449
- addHeader(key, value) {
450
- const headers = this.additionalHeaders;
451
- headers[key] = value;
452
- this.options.headers = headers;
453
- }
454
- sameHostname() {
455
- if (!this.originalUrl.startsWith("http:")) {
456
- return true;
457
- }
458
- try {
459
- return new URL(this.originalUrl).hostname === window.location.hostname;
460
- } catch (_) {
461
- return true;
462
- }
463
- }
464
- get fetchOptions() {
465
- return {
466
- method: this.method.toUpperCase(),
467
- headers: this.headers,
468
- body: this.formattedBody,
469
- signal: this.signal,
470
- credentials: this.credentials,
471
- redirect: this.redirect
472
- };
473
- }
474
- get headers() {
475
- const baseHeaders = {
476
- "X-Requested-With": "XMLHttpRequest",
477
- "Content-Type": this.contentType,
478
- Accept: this.accept
479
- };
480
- if (this.sameHostname()) {
481
- baseHeaders["X-CSRF-Token"] = this.csrfToken;
482
- }
483
- return compact(Object.assign(baseHeaders, this.additionalHeaders));
484
- }
485
- get csrfToken() {
486
- return getCookie(metaContent("csrf-param")) || metaContent("csrf-token");
487
- }
488
- get contentType() {
489
- if (this.options.contentType) {
490
- return this.options.contentType;
491
- } else if (this.body == null || this.body instanceof window.FormData) {
492
- return undefined;
493
- } else if (this.body instanceof window.File) {
494
- return this.body.type;
495
- }
496
- return "application/json";
497
- }
498
- get accept() {
499
- switch (this.responseKind) {
500
- case "html":
501
- return "text/html, application/xhtml+xml";
502
-
503
- case "turbo-stream":
504
- return "text/vnd.turbo-stream.html, text/html, application/xhtml+xml";
505
-
506
- case "json":
507
- return "application/json, application/vnd.api+json";
508
-
509
- default:
510
- return "*/*";
511
- }
512
- }
513
- get body() {
514
- return this.options.body;
515
- }
516
- get query() {
517
- const originalQuery = (this.originalUrl.split("?")[1] || "").split("#")[0];
518
- const params = new URLSearchParams(originalQuery);
519
- let requestQuery = this.options.query;
520
- if (requestQuery instanceof window.FormData) {
521
- requestQuery = stringEntriesFromFormData(requestQuery);
522
- } else if (requestQuery instanceof window.URLSearchParams) {
523
- requestQuery = requestQuery.entries();
524
- } else {
525
- requestQuery = Object.entries(requestQuery || {});
526
- }
527
- mergeEntries(params, requestQuery);
528
- const query = params.toString();
529
- return query.length > 0 ? `?${query}` : "";
530
- }
531
- get url() {
532
- return this.originalUrl.split("?")[0].split("#")[0] + this.query;
533
- }
534
- get responseKind() {
535
- return this.options.responseKind || "html";
536
- }
537
- get signal() {
538
- return this.options.signal;
539
- }
540
- get redirect() {
541
- return this.options.redirect || "follow";
542
- }
543
- get credentials() {
544
- return this.options.credentials || "same-origin";
545
- }
546
- get additionalHeaders() {
547
- return this.options.headers || {};
548
- }
549
- get formattedBody() {
550
- const bodyIsAString = Object.prototype.toString.call(this.body) === "[object String]";
551
- const contentTypeIsJson = this.headers["Content-Type"] === "application/json";
552
- if (contentTypeIsJson && !bodyIsAString) {
553
- return JSON.stringify(this.body);
554
- }
555
- return this.body;
556
- }
557
- }
558
-
559
- async function get(url, options) {
560
- const request = new FetchRequest("get", url, options);
561
- return request.perform();
562
- }
563
-
564
- async function post(url, options) {
565
- const request = new FetchRequest("post", url, options);
566
- return request.perform();
567
- }
568
-
569
- // Copyright (c) 2021 Marcelo Lauxen
570
-
571
- // Permission is hereby granted, free of charge, to any person obtaining
572
- // a copy of this software and associated documentation files (the
573
- // "Software"), to deal in the Software without restriction, including
574
- // without limitation the rights to use, copy, modify, merge, publish,
575
- // distribute, sublicense, and/or sell copies of the Software, and to
576
- // permit persons to whom the Software is furnished to do so, subject to
577
- // the following conditions:
578
-
579
- // The above copyright notice and this permission notice shall be
580
- // included in all copies or substantial portions of the Software.
581
-
582
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
583
- // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
584
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
585
- // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
586
- // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
587
- // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
588
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
589
-
590
- Combobox.Filtering = Base => class extends Base {
591
- filterAndSelect({ inputType }) {
592
- this._filter(inputType);
593
-
594
- if (this._isSync) {
595
- this._selectOnQuery(inputType);
596
- }
597
- }
598
-
599
- _initializeFiltering() {
600
- this._debouncedFilterAsync = debounce(this._debouncedFilterAsync.bind(this));
601
- }
602
-
603
- _filter(inputType) {
604
- if (this._isAsync) {
605
- this._debouncedFilterAsync(inputType);
606
- } else {
607
- this._filterSync();
608
- }
609
-
610
- this._markQueried();
611
- }
612
-
613
- _debouncedFilterAsync(inputType) {
614
- this._filterAsync(inputType);
615
- }
616
-
617
- async _filterAsync(inputType) {
618
- const query = {
619
- q: this._fullQuery,
620
- input_type: inputType,
621
- for_id: this.element.dataset.asyncId
622
- };
623
-
624
- await get(this.asyncSrcValue, { responseKind: "turbo-stream", query });
625
- }
626
-
627
- _filterSync() {
628
- this._allFilterableOptionElements.forEach(
629
- applyFilter(
630
- this._fullQuery,
631
- { matching: this.filterableAttributeValue }
632
- )
633
- );
634
- }
635
-
636
- _clearQuery() {
637
- this._fullQuery = "";
638
- this.filterAndSelect({ inputType: "deleteContentBackward" });
639
- }
640
-
641
- _markQueried() {
642
- this._actingCombobox.toggleAttribute("data-queried", this._isQueried);
643
- }
644
-
645
- get _isQueried() {
646
- return this._fullQuery.length > 0
647
- }
648
-
649
- get _fullQuery() {
650
- return this._actingCombobox.value
651
- }
652
-
653
- set _fullQuery(value) {
654
- this._actingCombobox.value = value;
655
- }
656
-
657
- get _typedQuery() {
658
- return unselectedPortion(this._actingCombobox)
659
- }
660
- };
661
-
662
- Combobox.FormField = Base => class extends Base {
663
- get _fieldValue() {
664
- if (this._isMultiselect) {
665
- const currentValue = this.hiddenFieldTarget.value;
666
- const arrayFromValue = currentValue ? currentValue.split(",") : [];
667
-
668
- return new Set(arrayFromValue)
669
- } else {
670
- return this.hiddenFieldTarget.value
671
- }
672
- }
673
-
674
- get _fieldValueString() {
675
- if (this._isMultiselect) {
676
- return this._fieldValueArray.join(",")
677
- } else {
678
- return this.hiddenFieldTarget.value
679
- }
680
- }
681
-
682
- get _incomingFieldValueString() {
683
- if (this._isMultiselect) {
684
- const array = this._fieldValueArray;
685
-
686
- if (this.hiddenFieldTarget.dataset.valueForMultiselect) {
687
- array.push(this.hiddenFieldTarget.dataset.valueForMultiselect);
688
- }
689
-
690
- return array.join(",")
691
- } else {
692
- return this.hiddenFieldTarget.value
693
- }
694
- }
695
-
696
- get _fieldValueArray() {
697
- if (this._isMultiselect) {
698
- return Array.from(this._fieldValue)
699
- } else {
700
- return [ this.hiddenFieldTarget.value ]
701
- }
702
- }
703
-
704
- set _fieldValue(value) {
705
- if (this._isMultiselect) {
706
- this.hiddenFieldTarget.dataset.valueForMultiselect = value?.replace(/,/g, "");
707
- this.hiddenFieldTarget.dataset.displayForMultiselect = this._fullQuery;
708
- } else {
709
- this.hiddenFieldTarget.value = value;
710
- }
711
- }
712
-
713
- get _hasEmptyFieldValue() {
714
- if (this._isMultiselect) {
715
- return this.hiddenFieldTarget.dataset.valueForMultiselect == "" ||
716
- this.hiddenFieldTarget.dataset.valueForMultiselect == "undefined"
717
- } else {
718
- return this.hiddenFieldTarget.value === ""
719
- }
720
- }
721
-
722
- get _hasFieldValue() {
723
- return !this._hasEmptyFieldValue
724
- }
725
-
726
- get _fieldName() {
727
- return this.hiddenFieldTarget.name
728
- }
729
-
730
- set _fieldName(value) {
731
- this.hiddenFieldTarget.name = value;
732
- }
733
- };
734
-
735
- Combobox.Multiselect = Base => class extends Base {
736
- navigateChip(event) {
737
- this._chipKeyHandlers[event.key]?.call(this, event);
738
- }
739
-
740
- removeChip({ currentTarget, params }) {
741
- let display;
742
- const option = this._optionElementWithValue(params.value);
743
-
744
- if (option) {
745
- display = option.getAttribute(this.autocompletableAttributeValue);
746
- this._markNotSelected(option);
747
- this._markNotMultiselected(option);
748
- } else {
749
- display = params.value; // for new options
750
- }
751
-
752
- this._removeFromFieldValue(params.value);
753
- this._filter("hw:multiselectSync");
754
-
755
- currentTarget.closest("[data-hw-combobox-chip]").remove();
756
-
757
- if (!this._isSmallViewport) {
758
- this.openByFocusing();
759
- }
760
-
761
- this._announceToScreenReader(display, "removed");
762
- this._dispatchRemovalEvent({ removedDisplay: display, removedValue: params.value });
763
- }
764
-
765
- hideChipsForCache() {
766
- this.element.querySelectorAll("[data-hw-combobox-chip]").forEach(chip => chip.hidden = true);
767
- }
768
-
769
- _chipKeyHandlers = {
770
- Backspace: (event) => {
771
- this.removeChip(event);
772
- cancel(event);
773
- },
774
- Enter: (event) => {
775
- this.removeChip(event);
776
- cancel(event);
777
- },
778
- Space: (event) => {
779
- this.removeChip(event);
780
- cancel(event);
781
- },
782
- Escape: (event) => {
783
- this.openByFocusing();
784
- cancel(event);
785
- }
786
- }
787
-
788
- _connectMultiselect() {
789
- if (!this._isMultiPreselected) {
790
- this._preselectMultiple();
791
- this._markMultiPreselected();
792
- }
793
- }
794
-
795
- async _createChip(shouldReopen) {
796
- if (!this._isMultiselect) return
797
-
798
- this._beforeClearingMultiselectQuery(async (display, value) => {
799
- this._fullQuery = "";
800
- this._filter("hw:multiselectSync");
801
- this._requestChips(value);
802
- this._addToFieldValue(value);
803
- if (shouldReopen) {
804
- await nextRepaint();
805
- this.openByFocusing();
806
- }
807
- this._announceToScreenReader(display, "multi-selected. Press Shift + Tab, then Enter to remove.");
808
- });
809
- }
810
-
811
- async _requestChips(values) {
812
- await post(this.selectionChipSrcValue, {
813
- responseKind: "turbo-stream",
814
- query: {
815
- for_id: this.element.dataset.asyncId,
816
- combobox_values: values
817
- }
818
- });
819
- }
820
-
821
- _beforeClearingMultiselectQuery(callback) {
822
- const display = this.hiddenFieldTarget.dataset.displayForMultiselect;
823
- const value = this.hiddenFieldTarget.dataset.valueForMultiselect;
824
-
825
- if (value && !this._fieldValue.has(value)) {
826
- callback(display, value);
827
- }
828
-
829
- this.hiddenFieldTarget.dataset.displayForMultiselect = "";
830
- this.hiddenFieldTarget.dataset.valueForMultiselect = "";
831
- }
832
-
833
- _resetMultiselectionMarks() {
834
- if (!this._isMultiselect) return
835
-
836
- this._fieldValueArray.forEach(value => {
837
- const option = this._optionElementWithValue(value);
838
-
839
- if (option) {
840
- option.setAttribute("data-multiselected", "");
841
- option.hidden = true;
842
- }
843
- });
844
- }
845
-
846
- _markNotMultiselected(option) {
847
- if (!this._isMultiselect) return
848
-
849
- option.removeAttribute("data-multiselected");
850
- option.hidden = false;
851
- }
852
-
853
- _addToFieldValue(value) {
854
- const newValue = this._fieldValue;
855
-
856
- newValue.add(String(value));
857
- this.hiddenFieldTarget.value = Array.from(newValue).join(",");
858
-
859
- if (this._isSync) this._resetMultiselectionMarks();
860
- }
861
-
862
- _removeFromFieldValue(value) {
863
- const newValue = this._fieldValue;
864
-
865
- newValue.delete(String(value));
866
- this.hiddenFieldTarget.value = Array.from(newValue).join(",");
867
-
868
- if (this._isSync) this._resetMultiselectionMarks();
869
- }
870
-
871
- _focusLastChipDismisser() {
872
- this.chipDismisserTargets[this.chipDismisserTargets.length - 1]?.focus();
873
- }
874
-
875
- _markMultiPreselected() {
876
- this.element.dataset.multiPreselected = "";
877
- }
878
-
879
- get _isMultiselect() {
880
- return this.hasSelectionChipSrcValue
881
- }
882
-
883
- get _isSingleSelect() {
884
- return !this._isMultiselect
885
- }
886
-
887
- get _isMultiPreselected() {
888
- return this.element.hasAttribute("data-multi-preselected")
889
- }
890
- };
891
-
892
- Combobox.Navigation = Base => class extends Base {
893
- navigate(event) {
894
- if (this._autocompletesList) {
895
- this._navigationKeyHandlers[event.key]?.call(this, event);
896
- }
897
- }
898
-
899
- _navigationKeyHandlers = {
900
- ArrowUp: (event) => {
901
- this._selectIndex(this._selectedOptionIndex - 1);
902
- cancel(event);
903
- },
904
- ArrowDown: (event) => {
905
- this._selectIndex(this._selectedOptionIndex + 1);
906
-
907
- if (this._selectedOptionIndex === 0) {
908
- this._actingListbox.scrollTop = 0;
909
- }
910
-
911
- cancel(event);
912
- },
913
- Home: (event) => {
914
- this._selectIndex(0);
915
- cancel(event);
916
- },
917
- End: (event) => {
918
- this._selectIndex(this._visibleOptionElements.length - 1);
919
- cancel(event);
920
- },
921
- Enter: (event) => {
922
- this._closeAndBlur("hw:keyHandler:enter");
923
- cancel(event);
924
- },
925
- Escape: (event) => {
926
- this._closeAndBlur("hw:keyHandler:escape");
927
- cancel(event);
928
- },
929
- Backspace: (event) => {
930
- if (this._isMultiselect && !this._fullQuery) {
931
- this._focusLastChipDismisser();
932
- cancel(event);
933
- }
934
- }
935
- }
936
- };
937
-
938
- Combobox.NewOptions = Base => class extends Base {
939
- _shouldTreatAsNewOptionForFiltering(queryIsBeingRefined) {
940
- if (queryIsBeingRefined) {
941
- return this._isNewOptionWithNoPotentialMatches
942
- } else {
943
- return this._isNewOptionWithPotentialMatches
944
- }
945
- }
946
-
947
- // If the user is going to keep refining the query, we can't be sure whether
948
- // the option will end up being new or not unless there are no potential matches.
949
- // +_isNewOptionWithNoPotentialMatches+ allows us to make our best guess
950
- // while the state of the combobox is still in flux.
951
- //
952
- // It's okay for the combobox to say it's not new even if it will be eventually,
953
- // as only the final state matters for submission purposes. This method exists
954
- // as a best effort to keep the state accurate as often as we can.
955
- //
956
- // Note that the first visible option is automatically selected as you type.
957
- // So if there's a partial match, it's not a new option at this point.
958
- //
959
- // The final state is locked-in upon closing the combobox via `_isNewOptionWithPotentialMatches`.
960
- get _isNewOptionWithNoPotentialMatches() {
961
- return this._isNewOptionWithPotentialMatches && !this._isPartialAutocompleteMatch
962
- }
963
-
964
- // If the query is finalized, we don't care that there are potential matches
965
- // because new options can be substrings of existing options.
966
- //
967
- // We can't use `_isNewOptionWithNoPotentialMatches` because that would
968
- // rule out new options that are partial matches.
969
- get _isNewOptionWithPotentialMatches() {
970
- return this._isQueried && this._allowNew && !this._isExactAutocompleteMatch
971
- }
972
- };
973
-
974
- Combobox.Options = Base => class extends Base {
975
- _resetOptionsSilently() {
976
- this._resetOptions(this._deselect.bind(this));
977
- }
978
-
979
- _resetOptionsAndNotify() {
980
- this._resetOptions(this._deselectAndNotify.bind(this));
981
- }
982
-
983
- _resetOptions(deselectionStrategy) {
984
- this._fieldName = this.originalNameValue;
985
- deselectionStrategy();
986
- }
987
-
988
- _optionElementWithValue(value) {
989
- return this._actingListbox.querySelector(`[${this.filterableAttributeValue}][data-value='${value}']`)
990
- }
991
-
992
- _displayForOptionElement(element) {
993
- return element.getAttribute(this.autocompletableAttributeValue)
994
- }
995
-
996
- get _allowNew() {
997
- return !!this.nameWhenNewValue
998
- }
999
-
1000
- get _allOptions() {
1001
- return Array.from(this._allFilterableOptionElements)
1002
- }
1003
-
1004
- get _allFilterableOptionElements() {
1005
- return this._actingListbox.querySelectorAll(`[${this.filterableAttributeValue}]:not([data-multiselected])`)
1006
- }
1007
-
1008
- get _visibleOptionElements() {
1009
- return [ ...this._allFilterableOptionElements ].filter(visible)
1010
- }
1011
-
1012
- get _selectedOptionElement() {
1013
- return this._actingListbox.querySelector("[role=option][aria-selected=true]:not([data-multiselected])")
1014
- }
1015
-
1016
- get _multiselectedOptionElements() {
1017
- return this._actingListbox.querySelectorAll("[role=option][data-multiselected]")
1018
- }
1019
-
1020
- get _selectedOptionIndex() {
1021
- return [ ...this._visibleOptionElements ].indexOf(this._selectedOptionElement)
1022
- }
1023
-
1024
- get _isUnjustifiablyBlank() {
1025
- const valueIsMissing = this._hasEmptyFieldValue;
1026
- const noBlankOptionSelected = !this._selectedOptionElement;
1027
-
1028
- return valueIsMissing && noBlankOptionSelected
1029
- }
1030
- };
1031
-
1032
- Combobox.Selection = Base => class extends Base {
1033
- selectOnClick({ currentTarget, inputType }) {
1034
- this._forceSelectionAndFilter(currentTarget, inputType);
1035
- this._closeAndBlur("hw:optionRoleClick");
1036
- }
1037
-
1038
- _connectSelection() {
1039
- if (this.hasPrefilledDisplayValue) {
1040
- this._fullQuery = this.prefilledDisplayValue;
1041
- this._markQueried();
1042
- }
1043
- }
1044
-
1045
- _selectOnQuery(inputType) {
1046
- if (this._shouldTreatAsNewOptionForFiltering(!isDeleteEvent({ inputType: inputType }))) {
1047
- this._selectNew();
1048
- } else if (isDeleteEvent({ inputType: inputType })) {
1049
- this._deselect();
1050
- } else if (inputType === "hw:lockInSelection" && this._ensurableOption) {
1051
- this._selectAndAutocompleteMissingPortion(this._ensurableOption);
1052
- } else if (this._isOpen && this._visibleOptionElements[0]) {
1053
- this._selectAndAutocompleteMissingPortion(this._visibleOptionElements[0]);
1054
- } else if (this._isOpen) {
1055
- this._resetOptionsAndNotify();
1056
- this._markInvalid();
1057
- } else ;
1058
- }
1059
-
1060
- _select(option, autocompleteStrategy) {
1061
- const previousValue = this._fieldValueString;
1062
-
1063
- this._resetOptionsSilently();
1064
-
1065
- autocompleteStrategy(option);
1066
-
1067
- this._fieldValue = option.dataset.value;
1068
- this._markSelected(option);
1069
- this._markValid();
1070
- this._dispatchPreselectionEvent({ isNewAndAllowed: false, previousValue: previousValue });
1071
-
1072
- option.scrollIntoView({ block: "nearest" });
1073
- }
1074
-
1075
- _selectNew() {
1076
- const previousValue = this._fieldValueString;
1077
-
1078
- this._resetOptionsSilently();
1079
- this._fieldValue = this._fullQuery;
1080
- this._fieldName = this.nameWhenNewValue;
1081
- this._markValid();
1082
- this._dispatchPreselectionEvent({ isNewAndAllowed: true, previousValue: previousValue });
1083
- }
1084
-
1085
- _deselect() {
1086
- const previousValue = this._fieldValueString;
1087
-
1088
- if (this._selectedOptionElement) {
1089
- this._markNotSelected(this._selectedOptionElement);
1090
- }
1091
-
1092
- this._fieldValue = "";
1093
- this._setActiveDescendant("");
1094
-
1095
- return previousValue
1096
- }
1097
-
1098
- _deselectAndNotify() {
1099
- const previousValue = this._deselect();
1100
- this._dispatchPreselectionEvent({ isNewAndAllowed: false, previousValue: previousValue });
1101
- }
1102
-
1103
- _selectIndex(index) {
1104
- const option = wrapAroundAccess(this._visibleOptionElements, index);
1105
- this._forceSelectionWithoutFiltering(option);
1106
- }
1107
-
1108
- _preselectSingle() {
1109
- if (this._isSingleSelect && this._hasValueButNoSelection && this._allOptions.length < 100) {
1110
- const option = this._optionElementWithValue(this._fieldValue);
1111
- if (option) this._markSelected(option);
1112
- }
1113
- }
1114
-
1115
- _preselectMultiple() {
1116
- if (this._isMultiselect && this._hasValueButNoSelection) {
1117
- this._requestChips(this._fieldValueString);
1118
- this._resetMultiselectionMarks();
1119
- }
1120
- }
1121
-
1122
- _selectAndAutocompleteMissingPortion(option) {
1123
- this._select(option, this._autocompleteMissingPortion.bind(this));
1124
- }
1125
-
1126
- _selectAndAutocompleteFullQuery(option) {
1127
- this._select(option, this._replaceFullQueryWithAutocompletedValue.bind(this));
1128
- }
1129
-
1130
- _forceSelectionAndFilter(option, inputType) {
1131
- this._forceSelectionWithoutFiltering(option);
1132
- this._filter(inputType);
1133
- }
1134
-
1135
- _forceSelectionWithoutFiltering(option) {
1136
- this._selectAndAutocompleteFullQuery(option);
1137
- }
1138
-
1139
- _lockInSelection() {
1140
- if (this._shouldLockInSelection) {
1141
- this._forceSelectionAndFilter(this._ensurableOption, "hw:lockInSelection");
1142
- }
1143
- }
1144
-
1145
- _markSelected(option) {
1146
- if (this.hasSelectedClass) option.classList.add(this.selectedClass);
1147
- option.setAttribute("aria-selected", true);
1148
- this._setActiveDescendant(option.id);
1149
- }
1150
-
1151
- _markNotSelected(option) {
1152
- if (this.hasSelectedClass) option.classList.remove(this.selectedClass);
1153
- option.removeAttribute("aria-selected");
1154
- this._removeActiveDescendant();
1155
- }
1156
-
1157
- _setActiveDescendant(id) {
1158
- this._forAllComboboxes(el => el.setAttribute("aria-activedescendant", id));
1159
- }
1160
-
1161
- _removeActiveDescendant() {
1162
- this._setActiveDescendant("");
1163
- }
1164
-
1165
- get _hasValueButNoSelection() {
1166
- return this._hasFieldValue && !this._hasSelection
1167
- }
1168
-
1169
- get _hasSelection() {
1170
- if (this._isSingleSelect) {
1171
- this._selectedOptionElement;
1172
- } else {
1173
- this._multiselectedOptionElements.length > 0;
1174
- }
1175
- }
1176
-
1177
- get _shouldLockInSelection() {
1178
- return this._isQueried && !!this._ensurableOption && !this._isNewOptionWithPotentialMatches
1179
- }
1180
-
1181
- get _ensurableOption() {
1182
- return this._selectedOptionElement || this._visibleOptionElements[0]
1183
- }
1184
- };
1185
-
1186
- function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
1187
-
1188
- // Older browsers don't support event options, feature detect it.
1189
-
1190
- // Adopted and modified solution from Bohdan Didukh (2017)
1191
- // https://stackoverflow.com/questions/41594997/ios-10-safari-prevent-scrolling-behind-a-fixed-overlay-and-maintain-scroll-posi
1192
-
1193
- var hasPassiveEvents = false;
1194
- if (typeof window !== 'undefined') {
1195
- var passiveTestOptions = {
1196
- get passive() {
1197
- hasPassiveEvents = true;
1198
- return undefined;
1199
- }
1200
- };
1201
- window.addEventListener('testPassive', null, passiveTestOptions);
1202
- window.removeEventListener('testPassive', null, passiveTestOptions);
1203
- }
1204
-
1205
- var isIosDevice = typeof window !== 'undefined' && window.navigator && window.navigator.platform && (/iP(ad|hone|od)/.test(window.navigator.platform) || window.navigator.platform === 'MacIntel' && window.navigator.maxTouchPoints > 1);
1206
-
1207
-
1208
- var locks = [];
1209
- var documentListenerAdded = false;
1210
- var initialClientY = -1;
1211
- var previousBodyOverflowSetting = void 0;
1212
- var previousBodyPosition = void 0;
1213
- var previousBodyPaddingRight = void 0;
1214
-
1215
- // returns true if `el` should be allowed to receive touchmove events.
1216
- var allowTouchMove = function allowTouchMove(el) {
1217
- return locks.some(function (lock) {
1218
- if (lock.options.allowTouchMove && lock.options.allowTouchMove(el)) {
1219
- return true;
1220
- }
1221
-
1222
- return false;
1223
- });
1224
- };
1225
-
1226
- var preventDefault = function preventDefault(rawEvent) {
1227
- var e = rawEvent || window.event;
1228
-
1229
- // For the case whereby consumers adds a touchmove event listener to document.
1230
- // Recall that we do document.addEventListener('touchmove', preventDefault, { passive: false })
1231
- // in disableBodyScroll - so if we provide this opportunity to allowTouchMove, then
1232
- // the touchmove event on document will break.
1233
- if (allowTouchMove(e.target)) {
1234
- return true;
1235
- }
1236
-
1237
- // Do not prevent if the event has more than one touch (usually meaning this is a multi touch gesture like pinch to zoom).
1238
- if (e.touches.length > 1) return true;
1239
-
1240
- if (e.preventDefault) e.preventDefault();
1241
-
1242
- return false;
1243
- };
1244
-
1245
- var setOverflowHidden = function setOverflowHidden(options) {
1246
- // If previousBodyPaddingRight is already set, don't set it again.
1247
- if (previousBodyPaddingRight === undefined) {
1248
- var _reserveScrollBarGap = !!options && options.reserveScrollBarGap === true;
1249
- var scrollBarGap = window.innerWidth - document.documentElement.clientWidth;
1250
-
1251
- if (_reserveScrollBarGap && scrollBarGap > 0) {
1252
- var computedBodyPaddingRight = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'), 10);
1253
- previousBodyPaddingRight = document.body.style.paddingRight;
1254
- document.body.style.paddingRight = computedBodyPaddingRight + scrollBarGap + 'px';
1255
- }
1256
- }
1257
-
1258
- // If previousBodyOverflowSetting is already set, don't set it again.
1259
- if (previousBodyOverflowSetting === undefined) {
1260
- previousBodyOverflowSetting = document.body.style.overflow;
1261
- document.body.style.overflow = 'hidden';
1262
- }
1263
- };
1264
-
1265
- var restoreOverflowSetting = function restoreOverflowSetting() {
1266
- if (previousBodyPaddingRight !== undefined) {
1267
- document.body.style.paddingRight = previousBodyPaddingRight;
1268
-
1269
- // Restore previousBodyPaddingRight to undefined so setOverflowHidden knows it
1270
- // can be set again.
1271
- previousBodyPaddingRight = undefined;
1272
- }
1273
-
1274
- if (previousBodyOverflowSetting !== undefined) {
1275
- document.body.style.overflow = previousBodyOverflowSetting;
1276
-
1277
- // Restore previousBodyOverflowSetting to undefined
1278
- // so setOverflowHidden knows it can be set again.
1279
- previousBodyOverflowSetting = undefined;
1280
- }
1281
- };
1282
-
1283
- var setPositionFixed = function setPositionFixed() {
1284
- return window.requestAnimationFrame(function () {
1285
- // If previousBodyPosition is already set, don't set it again.
1286
- if (previousBodyPosition === undefined) {
1287
- previousBodyPosition = {
1288
- position: document.body.style.position,
1289
- top: document.body.style.top,
1290
- left: document.body.style.left
1291
- };
1292
-
1293
- // Update the dom inside an animation frame
1294
- var _window = window,
1295
- scrollY = _window.scrollY,
1296
- scrollX = _window.scrollX,
1297
- innerHeight = _window.innerHeight;
1298
-
1299
- document.body.style.position = 'fixed';
1300
- document.body.style.top = -scrollY + 'px';
1301
- document.body.style.left = -scrollX + 'px';
1302
-
1303
- setTimeout(function () {
1304
- return window.requestAnimationFrame(function () {
1305
- // Attempt to check if the bottom bar appeared due to the position change
1306
- var bottomBarHeight = innerHeight - window.innerHeight;
1307
- if (bottomBarHeight && scrollY >= innerHeight) {
1308
- // Move the content further up so that the bottom bar doesn't hide it
1309
- document.body.style.top = -(scrollY + bottomBarHeight);
1310
- }
1311
- });
1312
- }, 300);
1313
- }
1314
- });
1315
- };
1316
-
1317
- var restorePositionSetting = function restorePositionSetting() {
1318
- if (previousBodyPosition !== undefined) {
1319
- // Convert the position from "px" to Int
1320
- var y = -parseInt(document.body.style.top, 10);
1321
- var x = -parseInt(document.body.style.left, 10);
1322
-
1323
- // Restore styles
1324
- document.body.style.position = previousBodyPosition.position;
1325
- document.body.style.top = previousBodyPosition.top;
1326
- document.body.style.left = previousBodyPosition.left;
1327
-
1328
- // Restore scroll
1329
- window.scrollTo(x, y);
1330
-
1331
- previousBodyPosition = undefined;
1332
- }
1333
- };
1334
-
1335
- // https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Problems_and_solutions
1336
- var isTargetElementTotallyScrolled = function isTargetElementTotallyScrolled(targetElement) {
1337
- return targetElement ? targetElement.scrollHeight - targetElement.scrollTop <= targetElement.clientHeight : false;
1338
- };
1339
-
1340
- var handleScroll = function handleScroll(event, targetElement) {
1341
- var clientY = event.targetTouches[0].clientY - initialClientY;
1342
-
1343
- if (allowTouchMove(event.target)) {
1344
- return false;
1345
- }
1346
-
1347
- if (targetElement && targetElement.scrollTop === 0 && clientY > 0) {
1348
- // element is at the top of its scroll.
1349
- return preventDefault(event);
1350
- }
1351
-
1352
- if (isTargetElementTotallyScrolled(targetElement) && clientY < 0) {
1353
- // element is at the bottom of its scroll.
1354
- return preventDefault(event);
1355
- }
1356
-
1357
- event.stopPropagation();
1358
- return true;
1359
- };
1360
-
1361
- var disableBodyScroll = function disableBodyScroll(targetElement, options) {
1362
- // targetElement must be provided
1363
- if (!targetElement) {
1364
- // eslint-disable-next-line no-console
1365
- console.error('disableBodyScroll unsuccessful - targetElement must be provided when calling disableBodyScroll on IOS devices.');
1366
- return;
1367
- }
1368
-
1369
- // disableBodyScroll must not have been called on this targetElement before
1370
- if (locks.some(function (lock) {
1371
- return lock.targetElement === targetElement;
1372
- })) {
1373
- return;
1374
- }
1375
-
1376
- var lock = {
1377
- targetElement: targetElement,
1378
- options: options || {}
1379
- };
1380
-
1381
- locks = [].concat(_toConsumableArray(locks), [lock]);
1382
-
1383
- if (isIosDevice) {
1384
- setPositionFixed();
1385
- } else {
1386
- setOverflowHidden(options);
1387
- }
1388
-
1389
- if (isIosDevice) {
1390
- targetElement.ontouchstart = function (event) {
1391
- if (event.targetTouches.length === 1) {
1392
- // detect single touch.
1393
- initialClientY = event.targetTouches[0].clientY;
1394
- }
1395
- };
1396
- targetElement.ontouchmove = function (event) {
1397
- if (event.targetTouches.length === 1) {
1398
- // detect single touch.
1399
- handleScroll(event, targetElement);
1400
- }
1401
- };
1402
-
1403
- if (!documentListenerAdded) {
1404
- document.addEventListener('touchmove', preventDefault, hasPassiveEvents ? { passive: false } : undefined);
1405
- documentListenerAdded = true;
1406
- }
1407
- }
1408
- };
1409
-
1410
- var enableBodyScroll = function enableBodyScroll(targetElement) {
1411
- if (!targetElement) {
1412
- // eslint-disable-next-line no-console
1413
- console.error('enableBodyScroll unsuccessful - targetElement must be provided when calling enableBodyScroll on IOS devices.');
1414
- return;
1415
- }
1416
-
1417
- locks = locks.filter(function (lock) {
1418
- return lock.targetElement !== targetElement;
1419
- });
1420
-
1421
- if (isIosDevice) {
1422
- targetElement.ontouchstart = null;
1423
- targetElement.ontouchmove = null;
1424
-
1425
- if (documentListenerAdded && locks.length === 0) {
1426
- document.removeEventListener('touchmove', preventDefault, hasPassiveEvents ? { passive: false } : undefined);
1427
- documentListenerAdded = false;
1428
- }
1429
- }
1430
-
1431
- if (isIosDevice) {
1432
- restorePositionSetting();
1433
- } else {
1434
- restoreOverflowSetting();
1435
- }
1436
- };
1437
-
1438
- // MIT License
1439
-
1440
- // Copyright (c) 2018 Will Po
1441
-
1442
- // Permission is hereby granted, free of charge, to any person obtaining a copy
1443
- // of this software and associated documentation files (the "Software"), to deal
1444
- // in the Software without restriction, including without limitation the rights
1445
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1446
- // copies of the Software, and to permit persons to whom the Software is
1447
- // furnished to do so, subject to the following conditions:
1448
-
1449
- // The above copyright notice and this permission notice shall be included in all
1450
- // copies or substantial portions of the Software.
1451
-
1452
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1453
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1454
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1455
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1456
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1457
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1458
- // SOFTWARE.
1459
-
1460
- Combobox.Toggle = Base => class extends Base {
1461
- open() {
1462
- this.expandedValue = true;
1463
- }
1464
-
1465
- openByFocusing() {
1466
- this._actingCombobox.focus();
1467
- }
1468
-
1469
- close(inputType) {
1470
- if (this._isOpen) {
1471
- const shouldReopen = this._isMultiselect &&
1472
- this._isSync &&
1473
- !this._isSmallViewport &&
1474
- inputType != "hw:clickOutside" &&
1475
- inputType != "hw:focusOutside" &&
1476
- inputType != "hw:asyncCloser";
1477
-
1478
- this._lockInSelection();
1479
- this._clearInvalidQuery();
1480
-
1481
- this.expandedValue = false;
1482
-
1483
- this._dispatchSelectionEvent();
1484
-
1485
- if (inputType != "hw:keyHandler:escape") {
1486
- this._createChip(shouldReopen);
1487
- }
1488
-
1489
- if (this._isSingleSelect && this._selectedOptionElement) {
1490
- this._announceToScreenReader(this._displayForOptionElement(this._selectedOptionElement), "selected");
1491
- }
1492
- }
1493
- }
1494
-
1495
- toggle() {
1496
- if (this.expandedValue) {
1497
- this._closeAndBlur("hw:toggle");
1498
- } else {
1499
- this.openByFocusing();
1500
- }
1501
- }
1502
-
1503
- closeOnClickOutside(event) {
1504
- const target = event.target;
1505
-
1506
- if (!this._isOpen) return
1507
- if (this.mainWrapperTarget.contains(target) && !this._isDialogDismisser(target)) return
1508
- if (this._withinElementBounds(event)) return
1509
-
1510
- this._closeAndBlur("hw:clickOutside");
1511
- }
1512
-
1513
- closeOnFocusOutside({ target }) {
1514
- if (!this._isOpen) return
1515
- if (this.element.contains(target)) return
1516
-
1517
- this._closeAndBlur("hw:focusOutside");
1518
- }
1519
-
1520
- clearOrToggleOnHandleClick() {
1521
- if (this._isQueried) {
1522
- this._clearQuery();
1523
- this._actingCombobox.focus();
1524
- } else {
1525
- this.toggle();
1526
- }
1527
- }
1528
-
1529
- _closeAndBlur(inputType) {
1530
- this.close(inputType);
1531
- this._actingCombobox.blur();
1532
- }
1533
-
1534
- // Some browser extensions like 1Password overlay elements on top of the combobox.
1535
- // Hovering over these elements emits a click event for some reason.
1536
- // These events don't contain any telling information, so we use `_withinElementBounds`
1537
- // as an alternative to check whether the click is legitimate.
1538
- _withinElementBounds(event) {
1539
- const { left, right, top, bottom } = this.mainWrapperTarget.getBoundingClientRect();
1540
- const { clientX, clientY } = event;
1541
-
1542
- return clientX >= left && clientX <= right && clientY >= top && clientY <= bottom
1543
- }
1544
-
1545
- _isDialogDismisser(target) {
1546
- return target.closest("dialog") && target.role != "combobox"
1547
- }
1548
-
1549
- _expand() {
1550
- if (this._isSync) {
1551
- this._preselectSingle();
1552
- }
1553
-
1554
- if (this._autocompletesList && this._isSmallViewport) {
1555
- this._openInDialog();
1556
- } else {
1557
- this._openInline();
1558
- }
1559
-
1560
- this._actingCombobox.setAttribute("aria-expanded", true); // needs to happen after setting acting combobox
1561
- }
1562
-
1563
- // +._collapse()+ differs from `.close()` in that it might be called by stimulus on connect because
1564
- // it interprets a change in `expandedValue` — whereas `.close()` is only called internally by us.
1565
- _collapse() {
1566
- this._actingCombobox.setAttribute("aria-expanded", false); // needs to happen before resetting acting combobox
1567
-
1568
- if (this._dialogIsOpen) {
1569
- this._closeInDialog();
1570
- } else {
1571
- this._closeInline();
1572
- }
1573
- }
1574
-
1575
- _openInDialog() {
1576
- this._moveArtifactsToDialog();
1577
- this._preventFocusingComboboxAfterClosingDialog();
1578
- this._preventBodyScroll();
1579
- this.dialogTarget.showModal();
1580
- }
1581
-
1582
- _openInline() {
1583
- this.listboxTarget.hidden = false;
1584
- }
1585
-
1586
- _closeInDialog() {
1587
- this._moveArtifactsInline();
1588
- this.dialogTarget.close();
1589
- this._restoreBodyScroll();
1590
- this._actingCombobox.scrollIntoView({ block: "center" });
1591
- }
1592
-
1593
- _closeInline() {
1594
- this.listboxTarget.hidden = true;
1595
- }
1596
-
1597
- _preventBodyScroll() {
1598
- disableBodyScroll(this.dialogListboxTarget);
1599
- }
1600
-
1601
- _restoreBodyScroll() {
1602
- enableBodyScroll(this.dialogListboxTarget);
1603
- }
1604
-
1605
- _clearInvalidQuery() {
1606
- if (this._isUnjustifiablyBlank) {
1607
- this._deselect();
1608
- this._clearQuery();
1609
- }
1610
- }
1611
-
1612
- get _isOpen() {
1613
- return this.expandedValue
1614
- }
1615
- };
1616
-
1617
- Combobox.Validity = Base => class extends Base {
1618
- _markValid() {
1619
- if (this._valueIsInvalid) return
1620
-
1621
- this._forAllComboboxes(combobox => {
1622
- if (this.hasInvalidClass) {
1623
- combobox.classList.remove(this.invalidClass);
1624
- }
1625
-
1626
- combobox.removeAttribute("aria-invalid");
1627
- combobox.removeAttribute("aria-errormessage");
1628
- });
1629
- }
1630
-
1631
- _markInvalid() {
1632
- if (this._valueIsValid) return
1633
-
1634
- this._forAllComboboxes(combobox => {
1635
- if (this.hasInvalidClass) {
1636
- combobox.classList.add(this.invalidClass);
1637
- }
1638
-
1639
- combobox.setAttribute("aria-invalid", true);
1640
- combobox.setAttribute("aria-errormessage", `Please select a valid option for ${combobox.name}`);
1641
- });
1642
- }
1643
-
1644
- get _valueIsValid() {
1645
- return !this._valueIsInvalid
1646
- }
1647
-
1648
- // +_valueIsInvalid+ only checks if `comboboxTarget` (and not `_actingCombobox`) is required
1649
- // because the `required` attribute is only forwarded to the `comboboxTarget` element
1650
- get _valueIsInvalid() {
1651
- const isRequiredAndEmpty = this.comboboxTarget.required && this._hasEmptyFieldValue;
1652
- return isRequiredAndEmpty
1653
- }
1654
- };
1655
-
1656
- window.HOTWIRE_COMBOBOX_STREAM_DELAY = 0; // ms, for testing purposes
1657
-
1658
- const concerns = [
1659
- stimulus.Controller,
1660
- Combobox.Actors,
1661
- Combobox.Announcements,
1662
- Combobox.AsyncLoading,
1663
- Combobox.Autocomplete,
1664
- Combobox.Dialog,
1665
- Combobox.Events,
1666
- Combobox.Filtering,
1667
- Combobox.FormField,
1668
- Combobox.Multiselect,
1669
- Combobox.Navigation,
1670
- Combobox.NewOptions,
1671
- Combobox.Options,
1672
- Combobox.Selection,
1673
- Combobox.Toggle,
1674
- Combobox.Validity
1675
- ];
1676
-
1677
- class HwComboboxController extends Concerns(...concerns) {
1678
- static classes = [
1679
- "invalid",
1680
- "selected"
1681
- ]
1682
-
1683
- static targets = [
1684
- "announcer",
1685
- "combobox",
1686
- "chipDismisser",
1687
- "closer",
1688
- "dialog",
1689
- "dialogCombobox",
1690
- "dialogFocusTrap",
1691
- "dialogListbox",
1692
- "endOfOptionsStream",
1693
- "handle",
1694
- "hiddenField",
1695
- "listbox",
1696
- "mainWrapper"
1697
- ]
1698
-
1699
- static values = {
1700
- asyncSrc: String,
1701
- autocompletableAttribute: String,
1702
- autocomplete: String,
1703
- expanded: Boolean,
1704
- filterableAttribute: String,
1705
- nameWhenNew: String,
1706
- originalName: String,
1707
- prefilledDisplay: String,
1708
- selectionChipSrc: String,
1709
- smallViewportMaxWidth: String
1710
- }
1711
-
1712
- initialize() {
1713
- this._initializeActors();
1714
- this._initializeFiltering();
1715
- }
1716
-
1717
- connect() {
1718
- this.idempotentConnect();
1719
- }
1720
-
1721
- idempotentConnect() {
1722
- this._connectSelection();
1723
- this._connectMultiselect();
1724
- this._connectListAutocomplete();
1725
- this._connectDialog();
1726
- }
1727
-
1728
- disconnect() {
1729
- this._disconnectDialog();
1730
- }
1731
-
1732
- expandedValueChanged() {
1733
- if (this.expandedValue) {
1734
- this._expand();
1735
- } else {
1736
- this._collapse();
1737
- }
1738
- }
1739
-
1740
- async endOfOptionsStreamTargetConnected(element) {
1741
- const inputType = element.dataset.inputType;
1742
- const delay = window.HOTWIRE_COMBOBOX_STREAM_DELAY;
1743
-
1744
- this._resetMultiselectionMarks();
1745
-
1746
- if (inputType === "hw:multiselectSync") {
1747
- this.openByFocusing();
1748
- } else if (inputType && inputType !== "hw:lockInSelection") {
1749
- if (delay) await sleep(delay);
1750
- this._selectOnQuery(inputType);
1751
- } else {
1752
- this._preselectSingle();
1753
- }
1754
- }
1755
-
1756
- closerTargetConnected() {
1757
- this._closeAndBlur("hw:asyncCloser");
1758
- }
1759
-
1760
- // Use +_printStack+ for debugging purposes
1761
- _printStack() {
1762
- const err = new Error();
1763
- console.log(err.stack || err.stacktrace);
1764
- }
1765
- }
1766
-
1767
- return HwComboboxController;
1768
-
1769
- }));