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