@primer/behaviors 0.0.0-202201892424 → 0.0.0-2022027213841

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 (78) hide show
  1. package/dist/cjs/anchored-position.d.ts +15 -0
  2. package/dist/cjs/anchored-position.js +210 -0
  3. package/dist/cjs/focus-trap.d.ts +1 -0
  4. package/dist/cjs/focus-trap.js +86 -0
  5. package/dist/cjs/focus-zone.d.ts +32 -0
  6. package/dist/cjs/focus-zone.js +410 -0
  7. package/dist/{index.d.ts → cjs/index.d.ts} +0 -0
  8. package/dist/cjs/index.js +16 -0
  9. package/dist/{polyfills → cjs/polyfills}/event-listener-signal.d.ts +0 -0
  10. package/dist/cjs/polyfills/event-listener-signal.js +44 -0
  11. package/dist/{scroll-into-view.d.ts → cjs/scroll-into-view.d.ts} +0 -0
  12. package/dist/cjs/scroll-into-view.js +21 -0
  13. package/dist/{utils → cjs/utils}/index.d.ts +0 -0
  14. package/dist/cjs/utils/index.js +15 -0
  15. package/dist/cjs/utils/iterate-focusable-elements.d.ts +9 -0
  16. package/dist/cjs/utils/iterate-focusable-elements.js +68 -0
  17. package/dist/{utils → cjs/utils}/unique-id.d.ts +0 -0
  18. package/dist/cjs/utils/unique-id.js +8 -0
  19. package/dist/{utils → cjs/utils}/user-agent.d.ts +0 -0
  20. package/dist/cjs/utils/user-agent.js +11 -0
  21. package/dist/esm/anchored-position.d.ts +15 -0
  22. package/dist/esm/anchored-position.js +206 -0
  23. package/dist/esm/focus-trap.d.ts +1 -0
  24. package/dist/esm/focus-trap.js +82 -0
  25. package/dist/esm/focus-zone.d.ts +32 -0
  26. package/dist/esm/focus-zone.js +406 -0
  27. package/{lib-esm → dist/esm}/index.d.ts +0 -0
  28. package/{lib/index.d.ts → dist/esm/index.js} +0 -0
  29. package/{lib-esm → dist/esm}/polyfills/event-listener-signal.d.ts +0 -0
  30. package/dist/esm/polyfills/event-listener-signal.js +40 -0
  31. package/{lib-esm → dist/esm}/scroll-into-view.d.ts +0 -0
  32. package/dist/esm/scroll-into-view.js +17 -0
  33. package/{lib-esm → dist/esm}/utils/index.d.ts +0 -0
  34. package/{lib/utils/index.d.ts → dist/esm/utils/index.js} +0 -0
  35. package/dist/esm/utils/iterate-focusable-elements.d.ts +9 -0
  36. package/dist/esm/utils/iterate-focusable-elements.js +61 -0
  37. package/{lib-esm → dist/esm}/utils/unique-id.d.ts +0 -0
  38. package/dist/esm/utils/unique-id.js +4 -0
  39. package/{lib-esm → dist/esm}/utils/user-agent.d.ts +0 -0
  40. package/dist/esm/utils/user-agent.js +7 -0
  41. package/package.json +18 -30
  42. package/utils/package.json +6 -6
  43. package/dist/anchored-position.d.ts +0 -89
  44. package/dist/focus-trap.d.ts +0 -12
  45. package/dist/focus-zone.d.ts +0 -137
  46. package/dist/utils/iterate-focusable-elements.d.ts +0 -42
  47. package/lib/anchored-position.d.ts +0 -89
  48. package/lib/anchored-position.js +0 -316
  49. package/lib/focus-trap.d.ts +0 -12
  50. package/lib/focus-trap.js +0 -179
  51. package/lib/focus-zone.d.ts +0 -137
  52. package/lib/focus-zone.js +0 -578
  53. package/lib/index.js +0 -57
  54. package/lib/polyfills/event-listener-signal.d.ts +0 -6
  55. package/lib/polyfills/event-listener-signal.js +0 -64
  56. package/lib/scroll-into-view.d.ts +0 -7
  57. package/lib/scroll-into-view.js +0 -42
  58. package/lib/utils/index.js +0 -44
  59. package/lib/utils/iterate-focusable-elements.d.ts +0 -42
  60. package/lib/utils/iterate-focusable-elements.js +0 -113
  61. package/lib/utils/unique-id.d.ts +0 -1
  62. package/lib/utils/unique-id.js +0 -12
  63. package/lib/utils/user-agent.d.ts +0 -1
  64. package/lib/utils/user-agent.js +0 -15
  65. package/lib-esm/anchored-position.d.ts +0 -89
  66. package/lib-esm/anchored-position.js +0 -309
  67. package/lib-esm/focus-trap.d.ts +0 -12
  68. package/lib-esm/focus-trap.js +0 -170
  69. package/lib-esm/focus-zone.d.ts +0 -137
  70. package/lib-esm/focus-zone.js +0 -559
  71. package/lib-esm/index.js +0 -4
  72. package/lib-esm/polyfills/event-listener-signal.js +0 -57
  73. package/lib-esm/scroll-into-view.js +0 -35
  74. package/lib-esm/utils/index.js +0 -3
  75. package/lib-esm/utils/iterate-focusable-elements.d.ts +0 -42
  76. package/lib-esm/utils/iterate-focusable-elements.js +0 -102
  77. package/lib-esm/utils/unique-id.js +0 -5
  78. package/lib-esm/utils/user-agent.js +0 -8
@@ -1,559 +0,0 @@
1
- import { polyfill as eventListenerSignalPolyfill } from './polyfills/event-listener-signal.js';
2
- import { isMacOS } from './utils/user-agent.js';
3
- import { iterateFocusableElements } from './utils/iterate-focusable-elements.js';
4
- import { uniqueId } from './utils/unique-id.js';
5
- eventListenerSignalPolyfill();
6
- export let FocusKeys;
7
-
8
- (function (FocusKeys) {
9
- FocusKeys[FocusKeys["ArrowHorizontal"] = 1] = "ArrowHorizontal";
10
- FocusKeys[FocusKeys["ArrowVertical"] = 2] = "ArrowVertical";
11
- FocusKeys[FocusKeys["JK"] = 4] = "JK";
12
- FocusKeys[FocusKeys["HL"] = 8] = "HL";
13
- FocusKeys[FocusKeys["HomeAndEnd"] = 16] = "HomeAndEnd";
14
- FocusKeys[FocusKeys["PageUpDown"] = 256] = "PageUpDown";
15
- FocusKeys[FocusKeys["WS"] = 32] = "WS";
16
- FocusKeys[FocusKeys["AD"] = 64] = "AD";
17
- FocusKeys[FocusKeys["Tab"] = 128] = "Tab";
18
- FocusKeys[FocusKeys["ArrowAll"] = FocusKeys.ArrowHorizontal | FocusKeys.ArrowVertical] = "ArrowAll";
19
- FocusKeys[FocusKeys["HJKL"] = FocusKeys.HL | FocusKeys.JK] = "HJKL";
20
- FocusKeys[FocusKeys["WASD"] = FocusKeys.WS | FocusKeys.AD] = "WASD";
21
- FocusKeys[FocusKeys["All"] = FocusKeys.ArrowAll | FocusKeys.HJKL | FocusKeys.HomeAndEnd | FocusKeys.PageUpDown | FocusKeys.WASD | FocusKeys.Tab] = "All";
22
- })(FocusKeys || (FocusKeys = {}));
23
-
24
- const KEY_TO_BIT = {
25
- ArrowLeft: FocusKeys.ArrowHorizontal,
26
- ArrowDown: FocusKeys.ArrowVertical,
27
- ArrowUp: FocusKeys.ArrowVertical,
28
- ArrowRight: FocusKeys.ArrowHorizontal,
29
- h: FocusKeys.HL,
30
- j: FocusKeys.JK,
31
- k: FocusKeys.JK,
32
- l: FocusKeys.HL,
33
- a: FocusKeys.AD,
34
- s: FocusKeys.WS,
35
- w: FocusKeys.WS,
36
- d: FocusKeys.AD,
37
- Tab: FocusKeys.Tab,
38
- Home: FocusKeys.HomeAndEnd,
39
- End: FocusKeys.HomeAndEnd,
40
- PageUp: FocusKeys.PageUpDown,
41
- PageDown: FocusKeys.PageUpDown
42
- };
43
- const KEY_TO_DIRECTION = {
44
- ArrowLeft: 'previous',
45
- ArrowDown: 'next',
46
- ArrowUp: 'previous',
47
- ArrowRight: 'next',
48
- h: 'previous',
49
- j: 'next',
50
- k: 'previous',
51
- l: 'next',
52
- a: 'previous',
53
- s: 'next',
54
- w: 'previous',
55
- d: 'next',
56
- Tab: 'next',
57
- Home: 'start',
58
- End: 'end',
59
- PageUp: 'start',
60
- PageDown: 'end'
61
- };
62
- /**
63
- * Options that control the behavior of the arrow focus behavior.
64
- */
65
-
66
- function getDirection(keyboardEvent) {
67
- const direction = KEY_TO_DIRECTION[keyboardEvent.key];
68
-
69
- if (keyboardEvent.key === 'Tab' && keyboardEvent.shiftKey) {
70
- return 'previous';
71
- }
72
-
73
- const isMac = isMacOS();
74
-
75
- if (isMac && keyboardEvent.metaKey || !isMac && keyboardEvent.ctrlKey) {
76
- if (keyboardEvent.key === 'ArrowLeft' || keyboardEvent.key === 'ArrowUp') {
77
- return 'start';
78
- } else if (keyboardEvent.key === 'ArrowRight' || keyboardEvent.key === 'ArrowDown') {
79
- return 'end';
80
- }
81
- }
82
-
83
- return direction;
84
- }
85
- /**
86
- * There are some situations where we do not want various keys to affect focus. This function
87
- * checks for those situations.
88
- * 1. Home and End should not move focus when a text input or textarea is active
89
- * 2. Keys that would normally type characters into an input or navigate a select element should be ignored
90
- * 3. The down arrow sometimes should not move focus when a select is active since that sometimes invokes the dropdown
91
- * 4. Page Up and Page Down within a textarea should not have any effect
92
- * 5. When in a text input or textarea, left should only move focus if the cursor is at the beginning of the input
93
- * 6. When in a text input or textarea, right should only move focus if the cursor is at the end of the input
94
- * 7. When in a textarea, up and down should only move focus if cursor is at the beginning or end, respectively.
95
- * @param keyboardEvent
96
- * @param activeElement
97
- */
98
-
99
-
100
- function shouldIgnoreFocusHandling(keyboardEvent, activeElement) {
101
- const key = keyboardEvent.key; // Get the number of characters in `key`, accounting for double-wide UTF-16 chars. If keyLength
102
- // is 1, we can assume it's a "printable" character. Otherwise it's likely a control character.
103
- // One exception is the Tab key, which is technically printable, but browsers generally assign
104
- // its function to move focus rather than type a <TAB> character.
105
-
106
- const keyLength = [...key].length;
107
- const isTextInput = activeElement instanceof HTMLInputElement && activeElement.type === 'text' || activeElement instanceof HTMLTextAreaElement; // If we would normally type a character into an input, ignore
108
- // Also, Home and End keys should never affect focus when in a text input
109
-
110
- if (isTextInput && (keyLength === 1 || key === 'Home' || key === 'End')) {
111
- return true;
112
- } // Some situations we want to ignore with <select> elements
113
-
114
-
115
- if (activeElement instanceof HTMLSelectElement) {
116
- // Regular typeable characters change the selection, so ignore those
117
- if (keyLength === 1) {
118
- return true;
119
- } // On macOS, bare ArrowDown opens the select, so ignore that
120
-
121
-
122
- if (key === 'ArrowDown' && isMacOS() && !keyboardEvent.metaKey) {
123
- return true;
124
- } // On other platforms, Alt+ArrowDown opens the select, so ignore that
125
-
126
-
127
- if (key === 'ArrowDown' && !isMacOS() && keyboardEvent.altKey) {
128
- return true;
129
- }
130
- } // Ignore page up and page down for textareas
131
-
132
-
133
- if (activeElement instanceof HTMLTextAreaElement && (key === 'PageUp' || key === 'PageDown')) {
134
- return true;
135
- }
136
-
137
- if (isTextInput) {
138
- const textInput = activeElement;
139
- const cursorAtStart = textInput.selectionStart === 0 && textInput.selectionEnd === 0;
140
- const cursorAtEnd = textInput.selectionStart === textInput.value.length && textInput.selectionEnd === textInput.value.length; // When in a text area or text input, only move focus left/right if at beginning/end of the field
141
-
142
- if (key === 'ArrowLeft' && !cursorAtStart) {
143
- return true;
144
- }
145
-
146
- if (key === 'ArrowRight' && !cursorAtEnd) {
147
- return true;
148
- } // When in a text area, only move focus up/down if at beginning/end of the field
149
-
150
-
151
- if (textInput instanceof HTMLTextAreaElement) {
152
- if (key === 'ArrowUp' && !cursorAtStart) {
153
- return true;
154
- }
155
-
156
- if (key === 'ArrowDown' && !cursorAtEnd) {
157
- return true;
158
- }
159
- }
160
- }
161
-
162
- return false;
163
- }
164
-
165
- export const isActiveDescendantAttribute = 'data-is-active-descendant';
166
- /**
167
- * A value of activated-directly for data-is-active-descendant indicates the descendant was activated
168
- * by a manual user interaction with intent to move active descendant. This usually translates to the
169
- * user pressing one of the bound keys (up/down arrow, etc) to move through the focus zone. This is
170
- * intended to be roughly equivalent to the :focus-visible pseudo-class
171
- **/
172
-
173
- export const activeDescendantActivatedDirectly = 'activated-directly';
174
- /**
175
- * A value of activated-indirectly for data-is-active-descendant indicates the descendant was activated
176
- * implicitly, and not by a direct key press. This includes focus zone being created from scratch, focusable
177
- * elements being added/removed, and mouseover events. This is intended to be roughly equivalent
178
- * to :focus:not(:focus-visible)
179
- **/
180
-
181
- export const activeDescendantActivatedIndirectly = 'activated-indirectly';
182
- export const hasActiveDescendantAttribute = 'data-has-active-descendant';
183
- /**
184
- * Sets up the arrow key focus behavior for all focusable elements in the given `container`.
185
- * @param container
186
- * @param settings
187
- * @returns
188
- */
189
-
190
- export function focusZone(container, settings) {
191
- var _settings$bindKeys, _settings$focusOutBeh, _settings$focusInStra, _settings$abortSignal;
192
-
193
- const focusableElements = [];
194
- const savedTabIndex = new WeakMap();
195
- const bindKeys = (_settings$bindKeys = settings === null || settings === void 0 ? void 0 : settings.bindKeys) !== null && _settings$bindKeys !== void 0 ? _settings$bindKeys : (settings !== null && settings !== void 0 && settings.getNextFocusable ? FocusKeys.ArrowAll : FocusKeys.ArrowVertical) | FocusKeys.HomeAndEnd;
196
- const focusOutBehavior = (_settings$focusOutBeh = settings === null || settings === void 0 ? void 0 : settings.focusOutBehavior) !== null && _settings$focusOutBeh !== void 0 ? _settings$focusOutBeh : 'stop';
197
- const focusInStrategy = (_settings$focusInStra = settings === null || settings === void 0 ? void 0 : settings.focusInStrategy) !== null && _settings$focusInStra !== void 0 ? _settings$focusInStra : 'previous';
198
- const activeDescendantControl = settings === null || settings === void 0 ? void 0 : settings.activeDescendantControl;
199
- const activeDescendantCallback = settings === null || settings === void 0 ? void 0 : settings.onActiveDescendantChanged;
200
- let currentFocusedElement;
201
-
202
- function getFirstFocusableElement() {
203
- return focusableElements[0];
204
- }
205
-
206
- function isActiveDescendantInputFocused() {
207
- return document.activeElement === activeDescendantControl;
208
- }
209
-
210
- function updateFocusedElement(to, directlyActivated = false) {
211
- const from = currentFocusedElement;
212
- currentFocusedElement = to;
213
-
214
- if (activeDescendantControl) {
215
- if (to && isActiveDescendantInputFocused()) {
216
- setActiveDescendant(from, to, directlyActivated);
217
- } else {
218
- clearActiveDescendant();
219
- }
220
-
221
- return;
222
- }
223
-
224
- if (from && from !== to && savedTabIndex.has(from)) {
225
- from.setAttribute('tabindex', '-1');
226
- }
227
-
228
- to === null || to === void 0 ? void 0 : to.setAttribute('tabindex', '0');
229
- }
230
-
231
- function setActiveDescendant(from, to, directlyActivated = false) {
232
- if (!to.id) {
233
- to.setAttribute('id', uniqueId());
234
- }
235
-
236
- if (from && from !== to) {
237
- from.removeAttribute(isActiveDescendantAttribute);
238
- }
239
-
240
- if (!activeDescendantControl || !directlyActivated && activeDescendantControl.getAttribute('aria-activedescendant') === to.id) {
241
- // prevent active descendant callback from being called repeatedly if the same element is activated (e.g. via mousemove)
242
- return;
243
- }
244
-
245
- activeDescendantControl.setAttribute('aria-activedescendant', to.id);
246
- container.setAttribute(hasActiveDescendantAttribute, to.id);
247
- to.setAttribute(isActiveDescendantAttribute, directlyActivated ? activeDescendantActivatedDirectly : activeDescendantActivatedIndirectly);
248
- activeDescendantCallback === null || activeDescendantCallback === void 0 ? void 0 : activeDescendantCallback(to, from, directlyActivated);
249
- }
250
-
251
- function clearActiveDescendant(previouslyActiveElement = currentFocusedElement) {
252
- if (focusInStrategy === 'first') {
253
- currentFocusedElement = undefined;
254
- }
255
-
256
- activeDescendantControl === null || activeDescendantControl === void 0 ? void 0 : activeDescendantControl.removeAttribute('aria-activedescendant');
257
- container.removeAttribute(hasActiveDescendantAttribute);
258
- previouslyActiveElement === null || previouslyActiveElement === void 0 ? void 0 : previouslyActiveElement.removeAttribute(isActiveDescendantAttribute);
259
- activeDescendantCallback === null || activeDescendantCallback === void 0 ? void 0 : activeDescendantCallback(undefined, previouslyActiveElement, false);
260
- }
261
-
262
- function beginFocusManagement(...elements) {
263
- const filteredElements = elements.filter(e => {
264
- var _settings$focusableEl, _settings$focusableEl2;
265
-
266
- return (_settings$focusableEl = settings === null || settings === void 0 ? void 0 : (_settings$focusableEl2 = settings.focusableElementFilter) === null || _settings$focusableEl2 === void 0 ? void 0 : _settings$focusableEl2.call(settings, e)) !== null && _settings$focusableEl !== void 0 ? _settings$focusableEl : true;
267
- });
268
-
269
- if (filteredElements.length === 0) {
270
- return;
271
- } // Insert all elements atomically. Assume that all passed elements are well-ordered.
272
-
273
-
274
- const insertIndex = focusableElements.findIndex(e => (e.compareDocumentPosition(filteredElements[0]) & Node.DOCUMENT_POSITION_PRECEDING) > 0);
275
- focusableElements.splice(insertIndex === -1 ? focusableElements.length : insertIndex, 0, ...filteredElements);
276
-
277
- for (const element of filteredElements) {
278
- // Set tabindex="-1" on all tabbable elements, but save the original
279
- // value in case we need to disable the behavior
280
- if (!savedTabIndex.has(element)) {
281
- savedTabIndex.set(element, element.getAttribute('tabindex'));
282
- }
283
-
284
- element.setAttribute('tabindex', '-1');
285
- }
286
-
287
- if (!currentFocusedElement) {
288
- updateFocusedElement(getFirstFocusableElement());
289
- }
290
- }
291
-
292
- function endFocusManagement(...elements) {
293
- for (const element of elements) {
294
- const focusableElementIndex = focusableElements.indexOf(element);
295
-
296
- if (focusableElementIndex >= 0) {
297
- focusableElements.splice(focusableElementIndex, 1);
298
- }
299
-
300
- const savedIndex = savedTabIndex.get(element);
301
-
302
- if (savedIndex !== undefined) {
303
- if (savedIndex === null) {
304
- element.removeAttribute('tabindex');
305
- } else {
306
- element.setAttribute('tabindex', savedIndex);
307
- }
308
-
309
- savedTabIndex.delete(element);
310
- } // If removing the last-focused element, move focus to the first element in the list.
311
-
312
-
313
- if (element === currentFocusedElement) {
314
- const nextElementToFocus = getFirstFocusableElement();
315
- updateFocusedElement(nextElementToFocus);
316
- }
317
- }
318
- } // Take all tabbable elements within container under management
319
-
320
-
321
- beginFocusManagement(...iterateFocusableElements(container)); // Open the first tabbable element for tabbing
322
-
323
- updateFocusedElement(getFirstFocusableElement()); // If the DOM structure of the container changes, make sure we keep our state up-to-date
324
- // with respect to the focusable elements cache and its order
325
-
326
- const observer = new MutationObserver(mutations => {
327
- // Perform all removals first, in case element order has simply changed
328
- for (const mutation of mutations) {
329
- for (const removedNode of mutation.removedNodes) {
330
- if (removedNode instanceof HTMLElement) {
331
- endFocusManagement(...iterateFocusableElements(removedNode));
332
- }
333
- }
334
- }
335
-
336
- for (const mutation of mutations) {
337
- for (const addedNode of mutation.addedNodes) {
338
- if (addedNode instanceof HTMLElement) {
339
- beginFocusManagement(...iterateFocusableElements(addedNode));
340
- }
341
- }
342
- }
343
- });
344
- observer.observe(container, {
345
- subtree: true,
346
- childList: true
347
- });
348
- const controller = new AbortController();
349
- const signal = (_settings$abortSignal = settings === null || settings === void 0 ? void 0 : settings.abortSignal) !== null && _settings$abortSignal !== void 0 ? _settings$abortSignal : controller.signal;
350
- signal.addEventListener('abort', () => {
351
- // Clean up any modifications
352
- endFocusManagement(...focusableElements);
353
- });
354
- let elementIndexFocusedByClick = undefined;
355
- container.addEventListener('mousedown', event => {
356
- // Since focusin is only called when focus changes, we need to make sure the clicked
357
- // element isn't already focused.
358
- if (event.target instanceof HTMLElement && event.target !== document.activeElement) {
359
- elementIndexFocusedByClick = focusableElements.indexOf(event.target);
360
- }
361
- }, {
362
- signal
363
- });
364
-
365
- if (activeDescendantControl) {
366
- container.addEventListener('focusin', event => {
367
- if (event.target instanceof HTMLElement && focusableElements.includes(event.target)) {
368
- // Move focus to the activeDescendantControl if one of the descendants is focused
369
- activeDescendantControl.focus();
370
- updateFocusedElement(event.target);
371
- }
372
- });
373
- container.addEventListener('mousemove', ({
374
- target
375
- }) => {
376
- if (!(target instanceof Node)) {
377
- return;
378
- }
379
-
380
- const focusableElement = focusableElements.find(element => element.contains(target));
381
-
382
- if (focusableElement) {
383
- updateFocusedElement(focusableElement);
384
- }
385
- }, {
386
- signal,
387
- capture: true
388
- }); // Listeners specifically on the controlling element
389
-
390
- activeDescendantControl.addEventListener('focusin', () => {
391
- // Focus moved into the active descendant input. Activate current or first descendant.
392
- if (!currentFocusedElement) {
393
- updateFocusedElement(getFirstFocusableElement());
394
- } else {
395
- setActiveDescendant(undefined, currentFocusedElement);
396
- }
397
- });
398
- activeDescendantControl.addEventListener('focusout', () => {
399
- clearActiveDescendant();
400
- });
401
- } else {
402
- // This is called whenever focus enters an element in the container
403
- container.addEventListener('focusin', event => {
404
- if (event.target instanceof HTMLElement) {
405
- // If a click initiated the focus movement, we always want to set our internal state
406
- // to reflect the clicked element as the currently focused one.
407
- if (elementIndexFocusedByClick !== undefined) {
408
- if (elementIndexFocusedByClick >= 0) {
409
- if (focusableElements[elementIndexFocusedByClick] !== currentFocusedElement) {
410
- updateFocusedElement(focusableElements[elementIndexFocusedByClick]);
411
- }
412
- }
413
-
414
- elementIndexFocusedByClick = undefined;
415
- } else {
416
- // Set tab indexes and internal state based on the focus handling strategy
417
- if (focusInStrategy === 'previous') {
418
- updateFocusedElement(event.target);
419
- } else if (focusInStrategy === 'closest' || focusInStrategy === 'first') {
420
- if (event.relatedTarget instanceof Element && !container.contains(event.relatedTarget)) {
421
- // Regardless of the previously focused element, if we're coming from outside the
422
- // container, put focus onto the first encountered element (from above, it's The
423
- // first element of the container; from below, it's the last). If the
424
- // focusInStrategy is set to "first", lastKeyboardFocusDirection will always
425
- // be undefined.
426
- const targetElementIndex = lastKeyboardFocusDirection === 'previous' ? focusableElements.length - 1 : 0;
427
- const targetElement = focusableElements[targetElementIndex];
428
- targetElement === null || targetElement === void 0 ? void 0 : targetElement.focus();
429
- return;
430
- } else {
431
- updateFocusedElement(event.target);
432
- }
433
- } else if (typeof focusInStrategy === 'function') {
434
- if (event.relatedTarget instanceof Element && !container.contains(event.relatedTarget)) {
435
- const elementToFocus = focusInStrategy(event.relatedTarget);
436
- const requestedFocusElementIndex = elementToFocus ? focusableElements.indexOf(elementToFocus) : -1;
437
-
438
- if (requestedFocusElementIndex >= 0 && elementToFocus instanceof HTMLElement) {
439
- // Since we are calling focus() this handler will run again synchronously. Therefore,
440
- // we don't want to let this invocation finish since it will clobber the value of
441
- // currentFocusedElement.
442
- elementToFocus.focus();
443
- return;
444
- } else {
445
- // eslint-disable-next-line no-console
446
- console.warn('Element requested is not a known focusable element.');
447
- }
448
- } else {
449
- updateFocusedElement(event.target);
450
- }
451
- }
452
- }
453
- }
454
-
455
- lastKeyboardFocusDirection = undefined;
456
- }, {
457
- signal
458
- });
459
- }
460
-
461
- const keyboardEventRecipient = activeDescendantControl !== null && activeDescendantControl !== void 0 ? activeDescendantControl : container; // If the strategy is "closest", we need to capture the direction that the user
462
- // is trying to move focus before our focusin handler is executed.
463
-
464
- let lastKeyboardFocusDirection = undefined;
465
-
466
- if (focusInStrategy === 'closest') {
467
- document.addEventListener('keydown', event => {
468
- if (event.key === 'Tab') {
469
- lastKeyboardFocusDirection = getDirection(event);
470
- }
471
- }, {
472
- signal,
473
- capture: true
474
- });
475
- }
476
-
477
- function getCurrentFocusedIndex() {
478
- if (!currentFocusedElement) {
479
- return 0;
480
- }
481
-
482
- const focusedIndex = focusableElements.indexOf(currentFocusedElement);
483
- const fallbackIndex = currentFocusedElement === container ? -1 : 0;
484
- return focusedIndex !== -1 ? focusedIndex : fallbackIndex;
485
- } // "keydown" is the event that triggers DOM focus change, so that is what we use here
486
-
487
-
488
- keyboardEventRecipient.addEventListener('keydown', event => {
489
- if (event.key in KEY_TO_DIRECTION) {
490
- const keyBit = KEY_TO_BIT[event.key]; // Check if the pressed key (keyBit) is one that is being used for focus (bindKeys)
491
-
492
- if (!event.defaultPrevented && (keyBit & bindKeys) > 0 && !shouldIgnoreFocusHandling(event, document.activeElement)) {
493
- // Moving forward or backward?
494
- const direction = getDirection(event);
495
- let nextElementToFocus = undefined; // If there is a custom function that retrieves the next focusable element, try calling that first.
496
-
497
- if (settings !== null && settings !== void 0 && settings.getNextFocusable) {
498
- var _document$activeEleme;
499
-
500
- nextElementToFocus = settings.getNextFocusable(direction, (_document$activeEleme = document.activeElement) !== null && _document$activeEleme !== void 0 ? _document$activeEleme : undefined, event);
501
- }
502
-
503
- if (!nextElementToFocus) {
504
- const lastFocusedIndex = getCurrentFocusedIndex();
505
- let nextFocusedIndex = lastFocusedIndex;
506
-
507
- if (direction === 'previous') {
508
- nextFocusedIndex -= 1;
509
- } else if (direction === 'start') {
510
- nextFocusedIndex = 0;
511
- } else if (direction === 'next') {
512
- nextFocusedIndex += 1;
513
- } else {
514
- // end
515
- nextFocusedIndex = focusableElements.length - 1;
516
- }
517
-
518
- if (nextFocusedIndex < 0) {
519
- // Tab should never cause focus to wrap. Use focusTrap for that behavior.
520
- if (focusOutBehavior === 'wrap' && event.key !== 'Tab') {
521
- nextFocusedIndex = focusableElements.length - 1;
522
- } else {
523
- nextFocusedIndex = 0;
524
- }
525
- }
526
-
527
- if (nextFocusedIndex >= focusableElements.length) {
528
- if (focusOutBehavior === 'wrap' && event.key !== 'Tab') {
529
- nextFocusedIndex = 0;
530
- } else {
531
- nextFocusedIndex = focusableElements.length - 1;
532
- }
533
- }
534
-
535
- if (lastFocusedIndex !== nextFocusedIndex) {
536
- nextElementToFocus = focusableElements[nextFocusedIndex];
537
- }
538
- }
539
-
540
- if (activeDescendantControl) {
541
- updateFocusedElement(nextElementToFocus || currentFocusedElement, true);
542
- } else if (nextElementToFocus) {
543
- lastKeyboardFocusDirection = direction; // updateFocusedElement will be called implicitly when focus moves, as long as the event isn't prevented somehow
544
-
545
- nextElementToFocus.focus();
546
- } // Tab should always allow escaping from this container, so only
547
- // preventDefault if tab key press already resulted in a focus movement
548
-
549
-
550
- if (event.key !== 'Tab' || nextElementToFocus) {
551
- event.preventDefault();
552
- }
553
- }
554
- }
555
- }, {
556
- signal
557
- });
558
- return controller;
559
- }
package/lib-esm/index.js DELETED
@@ -1,4 +0,0 @@
1
- export * from './anchored-position.js';
2
- export * from './focus-trap.js';
3
- export * from './focus-zone.js';
4
- export * from './scroll-into-view.js';
@@ -1,57 +0,0 @@
1
- /*
2
-
3
- This file polyfills the following: https://github.com/whatwg/dom/issues/911
4
- Once all targeted browsers support this DOM feature, this polyfill can be deleted.
5
-
6
- This allows users to pass an AbortSignal to a call to addEventListener as part of the
7
- AddEventListenerOptions object. When the signal is aborted, the event listener is
8
- removed.
9
-
10
- */
11
- let signalSupported = false; // eslint-disable-next-line @typescript-eslint/no-empty-function
12
-
13
- function noop() {}
14
-
15
- try {
16
- const options = Object.create({}, {
17
- signal: {
18
- get() {
19
- signalSupported = true;
20
- }
21
-
22
- }
23
- });
24
- window.addEventListener('test', noop, options);
25
- window.removeEventListener('test', noop, options);
26
- } catch (e) {
27
- /* */
28
- }
29
-
30
- function featureSupported() {
31
- return signalSupported;
32
- }
33
-
34
- function monkeyPatch() {
35
- if (typeof window === 'undefined') {
36
- return;
37
- }
38
-
39
- const originalAddEventListener = EventTarget.prototype.addEventListener;
40
-
41
- EventTarget.prototype.addEventListener = function (name, originalCallback, optionsOrCapture) {
42
- if (typeof optionsOrCapture === 'object' && 'signal' in optionsOrCapture && optionsOrCapture.signal instanceof AbortSignal) {
43
- originalAddEventListener.call(optionsOrCapture.signal, 'abort', () => {
44
- this.removeEventListener(name, originalCallback, optionsOrCapture);
45
- });
46
- }
47
-
48
- return originalAddEventListener.call(this, name, originalCallback, optionsOrCapture);
49
- };
50
- }
51
-
52
- export function polyfill() {
53
- if (!featureSupported()) {
54
- monkeyPatch();
55
- signalSupported = true;
56
- }
57
- }
@@ -1,35 +0,0 @@
1
- export function scrollIntoView(child, viewingArea, {
2
- direction = 'vertical',
3
- startMargin = 0,
4
- endMargin = 0,
5
- behavior = 'smooth'
6
- } = {}) {
7
- const startSide = direction === 'vertical' ? 'top' : 'left';
8
- const endSide = direction === 'vertical' ? 'bottom' : 'right';
9
- const scrollSide = direction === 'vertical' ? 'scrollTop' : 'scrollLeft';
10
- const {
11
- [startSide]: childStart,
12
- [endSide]: childEnd
13
- } = child.getBoundingClientRect();
14
- const {
15
- [startSide]: viewingAreaStart,
16
- [endSide]: viewingAreaEnd
17
- } = viewingArea.getBoundingClientRect();
18
- const isChildStartAboveViewingArea = childStart < viewingAreaStart + startMargin;
19
- const isChildBottomBelowViewingArea = childEnd > viewingAreaEnd - endMargin;
20
-
21
- if (isChildStartAboveViewingArea) {
22
- const scrollHeightToChildStart = childStart - viewingAreaStart + viewingArea[scrollSide];
23
- viewingArea.scrollTo({
24
- behavior,
25
- [startSide]: scrollHeightToChildStart - startMargin
26
- });
27
- } else if (isChildBottomBelowViewingArea) {
28
- const scrollHeightToChildBottom = childEnd - viewingAreaEnd + viewingArea[scrollSide];
29
- viewingArea.scrollTo({
30
- behavior,
31
- [startSide]: scrollHeightToChildBottom + endMargin
32
- });
33
- } // either completely in view or outside viewing area on both ends, don't scroll
34
-
35
- }
@@ -1,3 +0,0 @@
1
- export * from './iterate-focusable-elements.js';
2
- export * from './unique-id.js';
3
- export * from './user-agent.js';