@react-aria/interactions 3.27.0 → 3.28.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 (118) hide show
  1. package/dist/import.mjs +21 -15
  2. package/dist/main.js +45 -39
  3. package/dist/main.js.map +1 -1
  4. package/dist/module.js +21 -15
  5. package/dist/module.js.map +1 -1
  6. package/dist/types/src/index.d.ts +31 -0
  7. package/package.json +16 -15
  8. package/src/index.ts +31 -35
  9. package/dist/PressResponder.main.js +0 -61
  10. package/dist/PressResponder.main.js.map +0 -1
  11. package/dist/PressResponder.mjs +0 -51
  12. package/dist/PressResponder.module.js +0 -51
  13. package/dist/PressResponder.module.js.map +0 -1
  14. package/dist/Pressable.main.js +0 -69
  15. package/dist/Pressable.main.js.map +0 -1
  16. package/dist/Pressable.mjs +0 -60
  17. package/dist/Pressable.module.js +0 -60
  18. package/dist/Pressable.module.js.map +0 -1
  19. package/dist/context.main.js +0 -30
  20. package/dist/context.main.js.map +0 -1
  21. package/dist/context.mjs +0 -21
  22. package/dist/context.module.js +0 -21
  23. package/dist/context.module.js.map +0 -1
  24. package/dist/createEventHandler.main.js +0 -46
  25. package/dist/createEventHandler.main.js.map +0 -1
  26. package/dist/createEventHandler.mjs +0 -41
  27. package/dist/createEventHandler.module.js +0 -41
  28. package/dist/createEventHandler.module.js.map +0 -1
  29. package/dist/focusSafely.main.js +0 -40
  30. package/dist/focusSafely.main.js.map +0 -1
  31. package/dist/focusSafely.mjs +0 -35
  32. package/dist/focusSafely.module.js +0 -35
  33. package/dist/focusSafely.module.js.map +0 -1
  34. package/dist/textSelection.main.js +0 -77
  35. package/dist/textSelection.main.js.map +0 -1
  36. package/dist/textSelection.mjs +0 -71
  37. package/dist/textSelection.module.js +0 -71
  38. package/dist/textSelection.module.js.map +0 -1
  39. package/dist/types.d.ts +0 -255
  40. package/dist/types.d.ts.map +0 -1
  41. package/dist/useFocus.main.js +0 -65
  42. package/dist/useFocus.main.js.map +0 -1
  43. package/dist/useFocus.mjs +0 -60
  44. package/dist/useFocus.module.js +0 -60
  45. package/dist/useFocus.module.js.map +0 -1
  46. package/dist/useFocusVisible.main.js +0 -265
  47. package/dist/useFocusVisible.main.js.map +0 -1
  48. package/dist/useFocusVisible.mjs +0 -253
  49. package/dist/useFocusVisible.module.js +0 -253
  50. package/dist/useFocusVisible.module.js.map +0 -1
  51. package/dist/useFocusWithin.main.js +0 -105
  52. package/dist/useFocusWithin.main.js.map +0 -1
  53. package/dist/useFocusWithin.mjs +0 -100
  54. package/dist/useFocusWithin.module.js +0 -100
  55. package/dist/useFocusWithin.module.js.map +0 -1
  56. package/dist/useFocusable.main.js +0 -113
  57. package/dist/useFocusable.main.js.map +0 -1
  58. package/dist/useFocusable.mjs +0 -101
  59. package/dist/useFocusable.module.js +0 -101
  60. package/dist/useFocusable.module.js.map +0 -1
  61. package/dist/useHover.main.js +0 -159
  62. package/dist/useHover.main.js.map +0 -1
  63. package/dist/useHover.mjs +0 -154
  64. package/dist/useHover.module.js +0 -154
  65. package/dist/useHover.module.js.map +0 -1
  66. package/dist/useInteractOutside.main.js +0 -106
  67. package/dist/useInteractOutside.main.js.map +0 -1
  68. package/dist/useInteractOutside.mjs +0 -101
  69. package/dist/useInteractOutside.module.js +0 -101
  70. package/dist/useInteractOutside.module.js.map +0 -1
  71. package/dist/useKeyboard.main.js +0 -30
  72. package/dist/useKeyboard.main.js.map +0 -1
  73. package/dist/useKeyboard.mjs +0 -25
  74. package/dist/useKeyboard.module.js +0 -25
  75. package/dist/useKeyboard.module.js.map +0 -1
  76. package/dist/useLongPress.main.js +0 -86
  77. package/dist/useLongPress.main.js.map +0 -1
  78. package/dist/useLongPress.mjs +0 -81
  79. package/dist/useLongPress.module.js +0 -81
  80. package/dist/useLongPress.module.js.map +0 -1
  81. package/dist/useMove.main.js +0 -272
  82. package/dist/useMove.main.js.map +0 -1
  83. package/dist/useMove.mjs +0 -267
  84. package/dist/useMove.module.js +0 -267
  85. package/dist/useMove.module.js.map +0 -1
  86. package/dist/usePress.main.js +0 -763
  87. package/dist/usePress.main.js.map +0 -1
  88. package/dist/usePress.mjs +0 -758
  89. package/dist/usePress.module.js +0 -758
  90. package/dist/usePress.module.js.map +0 -1
  91. package/dist/useScrollWheel.main.js +0 -41
  92. package/dist/useScrollWheel.main.js.map +0 -1
  93. package/dist/useScrollWheel.mjs +0 -36
  94. package/dist/useScrollWheel.module.js +0 -36
  95. package/dist/useScrollWheel.module.js.map +0 -1
  96. package/dist/utils.main.js +0 -163
  97. package/dist/utils.main.js.map +0 -1
  98. package/dist/utils.mjs +0 -154
  99. package/dist/utils.module.js +0 -154
  100. package/dist/utils.module.js.map +0 -1
  101. package/src/PressResponder.tsx +0 -67
  102. package/src/Pressable.tsx +0 -97
  103. package/src/context.ts +0 -23
  104. package/src/createEventHandler.ts +0 -55
  105. package/src/focusSafely.ts +0 -45
  106. package/src/textSelection.ts +0 -101
  107. package/src/useFocus.ts +0 -87
  108. package/src/useFocusVisible.ts +0 -357
  109. package/src/useFocusWithin.ts +0 -132
  110. package/src/useFocusable.tsx +0 -191
  111. package/src/useHover.ts +0 -222
  112. package/src/useInteractOutside.ts +0 -142
  113. package/src/useKeyboard.ts +0 -36
  114. package/src/useLongPress.ts +0 -135
  115. package/src/useMove.ts +0 -259
  116. package/src/usePress.ts +0 -1093
  117. package/src/useScrollWheel.ts +0 -41
  118. package/src/utils.ts +0 -174
@@ -1,357 +0,0 @@
1
- /*
2
- * Copyright 2020 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
-
13
- // Portions of the code in this file are based on code from react.
14
- // Original licensing for the following can be found in the
15
- // NOTICE file in the root directory of this source tree.
16
- // See https://github.com/facebook/react/tree/cc7c1aece46a6b69b41958d731e0fd27c94bfc6c/packages/react-interactions
17
-
18
- import {getOwnerDocument, getOwnerWindow, isMac, isVirtualClick, openLink} from '@react-aria/utils';
19
- import {ignoreFocusEvent} from './utils';
20
- import {PointerType} from '@react-types/shared';
21
- import {useEffect, useState} from 'react';
22
- import {useIsSSR} from '@react-aria/ssr';
23
-
24
- export type Modality = 'keyboard' | 'pointer' | 'virtual';
25
- type HandlerEvent = PointerEvent | MouseEvent | KeyboardEvent | FocusEvent | null;
26
- type Handler = (modality: Modality, e: HandlerEvent) => void;
27
- export type FocusVisibleHandler = (isFocusVisible: boolean) => void;
28
- export interface FocusVisibleProps {
29
- /** Whether the element is a text input. */
30
- isTextInput?: boolean,
31
- /** Whether the element will be auto focused. */
32
- autoFocus?: boolean
33
- }
34
-
35
- export interface FocusVisibleResult {
36
- /** Whether keyboard focus is visible globally. */
37
- isFocusVisible: boolean
38
- }
39
-
40
- let currentModality: null | Modality = null;
41
- let currentPointerType: PointerType = 'keyboard';
42
- export const changeHandlers = new Set<Handler>();
43
- interface GlobalListenerData {
44
- focus: () => void
45
- }
46
- export let hasSetupGlobalListeners: Map<Window, GlobalListenerData> = new Map<Window, GlobalListenerData>(); // We use a map here to support setting event listeners across multiple document objects.
47
- let hasEventBeforeFocus = false;
48
- let hasBlurredWindowRecently = false;
49
-
50
- // Only Tab or Esc keys will make focus visible on text input elements
51
- const FOCUS_VISIBLE_INPUT_KEYS = {
52
- Tab: true,
53
- Escape: true
54
- };
55
-
56
- function triggerChangeHandlers(modality: Modality, e: HandlerEvent) {
57
- for (let handler of changeHandlers) {
58
- handler(modality, e);
59
- }
60
- }
61
-
62
- /**
63
- * Helper function to determine if a KeyboardEvent is unmodified and could make keyboard focus styles visible.
64
- */
65
- function isValidKey(e: KeyboardEvent) {
66
- // Control and Shift keys trigger when navigating back to the tab with keyboard.
67
- return !(e.metaKey || (!isMac() && e.altKey) || e.ctrlKey || e.key === 'Control' || e.key === 'Shift' || e.key === 'Meta');
68
- }
69
-
70
-
71
- function handleKeyboardEvent(e: KeyboardEvent) {
72
- hasEventBeforeFocus = true;
73
- if (!(openLink as any).isOpening && isValidKey(e)) {
74
- currentModality = 'keyboard';
75
- currentPointerType = 'keyboard';
76
- triggerChangeHandlers('keyboard', e);
77
- }
78
- }
79
-
80
- function handlePointerEvent(e: PointerEvent | MouseEvent) {
81
- currentModality = 'pointer';
82
- currentPointerType = 'pointerType' in e ? e.pointerType as PointerType : 'mouse';
83
- if (e.type === 'mousedown' || e.type === 'pointerdown') {
84
- hasEventBeforeFocus = true;
85
- triggerChangeHandlers('pointer', e);
86
- }
87
- }
88
-
89
- function handleClickEvent(e: MouseEvent) {
90
- if (!(openLink as any).isOpening && isVirtualClick(e)) {
91
- hasEventBeforeFocus = true;
92
- currentModality = 'virtual';
93
- currentPointerType = 'virtual';
94
- }
95
- }
96
-
97
- function handleFocusEvent(e: FocusEvent) {
98
- // Firefox fires two extra focus events when the user first clicks into an iframe:
99
- // first on the window, then on the document. We ignore these events so they don't
100
- // cause keyboard focus rings to appear.
101
- if (e.target === window || e.target === document || ignoreFocusEvent || !e.isTrusted) {
102
- return;
103
- }
104
-
105
- // If a focus event occurs without a preceding keyboard or pointer event, switch to virtual modality.
106
- // This occurs, for example, when navigating a form with the next/previous buttons on iOS.
107
- if (!hasEventBeforeFocus && !hasBlurredWindowRecently) {
108
- currentModality = 'virtual';
109
- currentPointerType = 'virtual';
110
- triggerChangeHandlers('virtual', e);
111
- }
112
-
113
- hasEventBeforeFocus = false;
114
- hasBlurredWindowRecently = false;
115
- }
116
-
117
- function handleWindowBlur() {
118
- if (ignoreFocusEvent) {
119
- return;
120
- }
121
-
122
- // When the window is blurred, reset state. This is necessary when tabbing out of the window,
123
- // for example, since a subsequent focus event won't be fired.
124
- hasEventBeforeFocus = false;
125
- hasBlurredWindowRecently = true;
126
- }
127
-
128
- /**
129
- * Setup global event listeners to control when keyboard focus style should be visible.
130
- */
131
- function setupGlobalFocusEvents(element?: HTMLElement | null) {
132
- if (typeof window === 'undefined' || typeof document === 'undefined' || hasSetupGlobalListeners.get(getOwnerWindow(element))) {
133
- return;
134
- }
135
-
136
- const windowObject = getOwnerWindow(element);
137
- const documentObject = getOwnerDocument(element);
138
-
139
- // Programmatic focus() calls shouldn't affect the current input modality.
140
- // However, we need to detect other cases when a focus event occurs without
141
- // a preceding user event (e.g. screen reader focus). Overriding the focus
142
- // method on HTMLElement.prototype is a bit hacky, but works.
143
- let focus = windowObject.HTMLElement.prototype.focus;
144
- windowObject.HTMLElement.prototype.focus = function () {
145
- hasEventBeforeFocus = true;
146
- focus.apply(this, arguments as unknown as [options?: FocusOptions | undefined]);
147
- };
148
-
149
- documentObject.addEventListener('keydown', handleKeyboardEvent, true);
150
- documentObject.addEventListener('keyup', handleKeyboardEvent, true);
151
- documentObject.addEventListener('click', handleClickEvent, true);
152
-
153
- // Register focus events on the window so they are sure to happen
154
- // before React's event listeners (registered on the document).
155
- windowObject.addEventListener('focus', handleFocusEvent, true);
156
- windowObject.addEventListener('blur', handleWindowBlur, false);
157
-
158
- if (typeof PointerEvent !== 'undefined') {
159
- documentObject.addEventListener('pointerdown', handlePointerEvent, true);
160
- documentObject.addEventListener('pointermove', handlePointerEvent, true);
161
- documentObject.addEventListener('pointerup', handlePointerEvent, true);
162
- } else if (process.env.NODE_ENV === 'test') {
163
- documentObject.addEventListener('mousedown', handlePointerEvent, true);
164
- documentObject.addEventListener('mousemove', handlePointerEvent, true);
165
- documentObject.addEventListener('mouseup', handlePointerEvent, true);
166
- }
167
-
168
- // Add unmount handler
169
- windowObject.addEventListener('beforeunload', () => {
170
- tearDownWindowFocusTracking(element);
171
- }, {once: true});
172
-
173
- hasSetupGlobalListeners.set(windowObject, {focus});
174
- }
175
-
176
- const tearDownWindowFocusTracking = (element, loadListener?: () => void) => {
177
- const windowObject = getOwnerWindow(element);
178
- const documentObject = getOwnerDocument(element);
179
- if (loadListener) {
180
- documentObject.removeEventListener('DOMContentLoaded', loadListener);
181
- }
182
- if (!hasSetupGlobalListeners.has(windowObject)) {
183
- return;
184
- }
185
- windowObject.HTMLElement.prototype.focus = hasSetupGlobalListeners.get(windowObject)!.focus;
186
-
187
- documentObject.removeEventListener('keydown', handleKeyboardEvent, true);
188
- documentObject.removeEventListener('keyup', handleKeyboardEvent, true);
189
- documentObject.removeEventListener('click', handleClickEvent, true);
190
-
191
- windowObject.removeEventListener('focus', handleFocusEvent, true);
192
- windowObject.removeEventListener('blur', handleWindowBlur, false);
193
-
194
- if (typeof PointerEvent !== 'undefined') {
195
- documentObject.removeEventListener('pointerdown', handlePointerEvent, true);
196
- documentObject.removeEventListener('pointermove', handlePointerEvent, true);
197
- documentObject.removeEventListener('pointerup', handlePointerEvent, true);
198
- } else if (process.env.NODE_ENV === 'test') {
199
- documentObject.removeEventListener('mousedown', handlePointerEvent, true);
200
- documentObject.removeEventListener('mousemove', handlePointerEvent, true);
201
- documentObject.removeEventListener('mouseup', handlePointerEvent, true);
202
- }
203
-
204
- hasSetupGlobalListeners.delete(windowObject);
205
- };
206
-
207
- /**
208
- * EXPERIMENTAL
209
- * Adds a window (i.e. iframe) to the list of windows that are being tracked for focus visible.
210
- *
211
- * Sometimes apps render portions of their tree into an iframe. In this case, we cannot accurately track if the focus
212
- * is visible because we cannot see interactions inside the iframe. If you have this in your application's architecture,
213
- * then this function will attach event listeners inside the iframe. You should call `addWindowFocusTracking` with an
214
- * element from inside the window you wish to add. We'll retrieve the relevant elements based on that.
215
- * Note, you do not need to call this for the default window, as we call it for you.
216
- *
217
- * When you are ready to stop listening, but you do not wish to unmount the iframe, you may call the cleanup function
218
- * returned by `addWindowFocusTracking`. Otherwise, when you unmount the iframe, all listeners and state will be cleaned
219
- * up automatically for you.
220
- *
221
- * @param element @default document.body - The element provided will be used to get the window to add.
222
- * @returns A function to remove the event listeners and cleanup the state.
223
- */
224
- export function addWindowFocusTracking(element?: HTMLElement | null): () => void {
225
- const documentObject = getOwnerDocument(element);
226
- let loadListener;
227
- if (documentObject.readyState !== 'loading') {
228
- setupGlobalFocusEvents(element);
229
- } else {
230
- loadListener = () => {
231
- setupGlobalFocusEvents(element);
232
- };
233
- documentObject.addEventListener('DOMContentLoaded', loadListener);
234
- }
235
-
236
- return () => tearDownWindowFocusTracking(element, loadListener);
237
- }
238
-
239
- // Server-side rendering does not have the document object defined
240
- // eslint-disable-next-line no-restricted-globals
241
- if (typeof document !== 'undefined') {
242
- addWindowFocusTracking();
243
- }
244
-
245
- /**
246
- * If true, keyboard focus is visible.
247
- */
248
- export function isFocusVisible(): boolean {
249
- return currentModality !== 'pointer';
250
- }
251
-
252
- export function getInteractionModality(): Modality | null {
253
- return currentModality;
254
- }
255
-
256
- export function setInteractionModality(modality: Modality): void {
257
- currentModality = modality;
258
- currentPointerType = modality === 'pointer' ? 'mouse' : modality;
259
- triggerChangeHandlers(modality, null);
260
- }
261
-
262
- /** @private */
263
- export function getPointerType(): PointerType {
264
- return currentPointerType;
265
- }
266
-
267
- /**
268
- * Keeps state of the current modality.
269
- */
270
- export function useInteractionModality(): Modality | null {
271
- setupGlobalFocusEvents();
272
-
273
- let [modality, setModality] = useState(currentModality);
274
- useEffect(() => {
275
- let handler = () => {
276
- setModality(currentModality);
277
- };
278
-
279
- changeHandlers.add(handler);
280
- return () => {
281
- changeHandlers.delete(handler);
282
- };
283
- }, []);
284
-
285
- return useIsSSR() ? null : modality;
286
- }
287
-
288
- const nonTextInputTypes = new Set([
289
- 'checkbox',
290
- 'radio',
291
- 'range',
292
- 'color',
293
- 'file',
294
- 'image',
295
- 'button',
296
- 'submit',
297
- 'reset'
298
- ]);
299
-
300
- /**
301
- * If this is attached to text input component, return if the event is a focus event (Tab/Escape keys pressed) so that
302
- * focus visible style can be properly set.
303
- */
304
- function isKeyboardFocusEvent(isTextInput: boolean, modality: Modality, e: HandlerEvent) {
305
- let document = getOwnerDocument(e?.target as Element);
306
- const IHTMLInputElement = typeof window !== 'undefined' ? getOwnerWindow(e?.target as Element).HTMLInputElement : HTMLInputElement;
307
- const IHTMLTextAreaElement = typeof window !== 'undefined' ? getOwnerWindow(e?.target as Element).HTMLTextAreaElement : HTMLTextAreaElement;
308
- const IHTMLElement = typeof window !== 'undefined' ? getOwnerWindow(e?.target as Element).HTMLElement : HTMLElement;
309
- const IKeyboardEvent = typeof window !== 'undefined' ? getOwnerWindow(e?.target as Element).KeyboardEvent : KeyboardEvent;
310
-
311
- // For keyboard events that occur on a non-input element that will move focus into input element (aka ArrowLeft going from Datepicker button to the main input group)
312
- // we need to rely on the user passing isTextInput into here. This way we can skip toggling focus visiblity for said input element
313
- isTextInput = isTextInput ||
314
- (document.activeElement instanceof IHTMLInputElement && !nonTextInputTypes.has(document.activeElement.type)) ||
315
- document.activeElement instanceof IHTMLTextAreaElement ||
316
- (document.activeElement instanceof IHTMLElement && document.activeElement.isContentEditable);
317
- return !(isTextInput && modality === 'keyboard' && e instanceof IKeyboardEvent && !FOCUS_VISIBLE_INPUT_KEYS[e.key]);
318
- }
319
-
320
- /**
321
- * Manages focus visible state for the page, and subscribes individual components for updates.
322
- */
323
- export function useFocusVisible(props: FocusVisibleProps = {}): FocusVisibleResult {
324
- let {isTextInput, autoFocus} = props;
325
- let [isFocusVisibleState, setFocusVisible] = useState(autoFocus || isFocusVisible());
326
- useFocusVisibleListener((isFocusVisible) => {
327
- setFocusVisible(isFocusVisible);
328
- }, [isTextInput], {isTextInput});
329
-
330
- return {isFocusVisible: isFocusVisibleState};
331
- }
332
-
333
- /**
334
- * Listens for trigger change and reports if focus is visible (i.e., modality is not pointer).
335
- */
336
- export function useFocusVisibleListener(fn: FocusVisibleHandler, deps: ReadonlyArray<any>, opts?: {enabled?: boolean, isTextInput?: boolean}): void {
337
- setupGlobalFocusEvents();
338
-
339
- useEffect(() => {
340
- if (opts?.enabled === false) {
341
- return;
342
- }
343
- let handler = (modality: Modality, e: HandlerEvent) => {
344
- // We want to early return for any keyboard events that occur inside text inputs EXCEPT for Tab and Escape
345
- if (!isKeyboardFocusEvent(!!(opts?.isTextInput), modality, e)) {
346
- return;
347
- }
348
- fn(isFocusVisible());
349
- };
350
- changeHandlers.add(handler);
351
- return () => {
352
- changeHandlers.delete(handler);
353
- };
354
- // eslint-disable-next-line react-hooks/exhaustive-deps
355
- }, deps);
356
- }
357
-
@@ -1,132 +0,0 @@
1
- /*
2
- * Copyright 2020 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
-
13
- // Portions of the code in this file are based on code from react.
14
- // Original licensing for the following can be found in the
15
- // NOTICE file in the root directory of this source tree.
16
- // See https://github.com/facebook/react/tree/cc7c1aece46a6b69b41958d731e0fd27c94bfc6c/packages/react-interactions
17
-
18
- import {createSyntheticEvent, setEventTarget, useSyntheticBlurEvent} from './utils';
19
- import {DOMAttributes} from '@react-types/shared';
20
- import {FocusEvent, useCallback, useRef} from 'react';
21
- import {getActiveElement, getEventTarget, getOwnerDocument, nodeContains, useGlobalListeners} from '@react-aria/utils';
22
-
23
- export interface FocusWithinProps {
24
- /** Whether the focus within events should be disabled. */
25
- isDisabled?: boolean,
26
- /** Handler that is called when the target element or a descendant receives focus. */
27
- onFocusWithin?: (e: FocusEvent) => void,
28
- /** Handler that is called when the target element and all descendants lose focus. */
29
- onBlurWithin?: (e: FocusEvent) => void,
30
- /** Handler that is called when the the focus within state changes. */
31
- onFocusWithinChange?: (isFocusWithin: boolean) => void
32
- }
33
-
34
- export interface FocusWithinResult {
35
- /** Props to spread onto the target element. */
36
- focusWithinProps: DOMAttributes
37
- }
38
-
39
- /**
40
- * Handles focus events for the target and its descendants.
41
- */
42
- export function useFocusWithin(props: FocusWithinProps): FocusWithinResult {
43
- let {
44
- isDisabled,
45
- onBlurWithin,
46
- onFocusWithin,
47
- onFocusWithinChange
48
- } = props;
49
- let state = useRef({
50
- isFocusWithin: false
51
- });
52
-
53
- let {addGlobalListener, removeAllGlobalListeners} = useGlobalListeners();
54
-
55
- let onBlur = useCallback((e: FocusEvent) => {
56
- // Ignore events bubbling through portals.
57
- if (!nodeContains(e.currentTarget, e.target)) {
58
- return;
59
- }
60
-
61
- // We don't want to trigger onBlurWithin and then immediately onFocusWithin again
62
- // when moving focus inside the element. Only trigger if the currentTarget doesn't
63
- // include the relatedTarget (where focus is moving).
64
- if (state.current.isFocusWithin && !nodeContains(e.currentTarget as Element, e.relatedTarget as Element)) {
65
- state.current.isFocusWithin = false;
66
- removeAllGlobalListeners();
67
-
68
- if (onBlurWithin) {
69
- onBlurWithin(e);
70
- }
71
-
72
- if (onFocusWithinChange) {
73
- onFocusWithinChange(false);
74
- }
75
- }
76
- }, [onBlurWithin, onFocusWithinChange, state, removeAllGlobalListeners]);
77
-
78
- let onSyntheticFocus = useSyntheticBlurEvent(onBlur);
79
- let onFocus = useCallback((e: FocusEvent) => {
80
- // Ignore events bubbling through portals.
81
- if (!nodeContains(e.currentTarget, e.target)) {
82
- return;
83
- }
84
-
85
- // Double check that document.activeElement actually matches e.target in case a previously chained
86
- // focus handler already moved focus somewhere else.
87
- const ownerDocument = getOwnerDocument(e.target);
88
- const activeElement = getActiveElement(ownerDocument);
89
- if (!state.current.isFocusWithin && activeElement === getEventTarget(e.nativeEvent)) {
90
- if (onFocusWithin) {
91
- onFocusWithin(e);
92
- }
93
-
94
- if (onFocusWithinChange) {
95
- onFocusWithinChange(true);
96
- }
97
-
98
- state.current.isFocusWithin = true;
99
- onSyntheticFocus(e);
100
-
101
- // Browsers don't fire blur events when elements are removed from the DOM.
102
- // However, if a focus event occurs outside the element we're tracking, we
103
- // can manually fire onBlur.
104
- let currentTarget = e.currentTarget;
105
- addGlobalListener(ownerDocument, 'focus', e => {
106
- if (state.current.isFocusWithin && !nodeContains(currentTarget, e.target as Element)) {
107
- let nativeEvent = new ownerDocument.defaultView!.FocusEvent('blur', {relatedTarget: e.target});
108
- setEventTarget(nativeEvent, currentTarget);
109
- let event = createSyntheticEvent<FocusEvent>(nativeEvent);
110
- onBlur(event);
111
- }
112
- }, {capture: true});
113
- }
114
- }, [onFocusWithin, onFocusWithinChange, onSyntheticFocus, addGlobalListener, onBlur]);
115
-
116
- if (isDisabled) {
117
- return {
118
- focusWithinProps: {
119
- // These cannot be null, that would conflict in mergeProps
120
- onFocus: undefined,
121
- onBlur: undefined
122
- }
123
- };
124
- }
125
-
126
- return {
127
- focusWithinProps: {
128
- onFocus,
129
- onBlur
130
- }
131
- };
132
- }
@@ -1,191 +0,0 @@
1
- /*
2
- * Copyright 2020 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
-
13
- import {DOMAttributes, FocusableDOMProps, FocusableElement, FocusableProps, RefObject} from '@react-types/shared';
14
- import {focusSafely} from './';
15
- import {getOwnerWindow, isFocusable, mergeProps, mergeRefs, useObjectRef, useSyncRef} from '@react-aria/utils';
16
- import React, {ForwardedRef, forwardRef, MutableRefObject, ReactElement, ReactNode, useContext, useEffect, useRef} from 'react';
17
- import {useFocus} from './useFocus';
18
- import {useKeyboard} from './useKeyboard';
19
-
20
- export interface FocusableOptions<T = FocusableElement> extends FocusableProps<T>, FocusableDOMProps {
21
- /** Whether focus should be disabled. */
22
- isDisabled?: boolean
23
- }
24
-
25
- export interface FocusableProviderProps extends DOMAttributes {
26
- /** The child element to provide DOM props to. */
27
- children?: ReactNode
28
- }
29
-
30
- interface FocusableContextValue extends FocusableProviderProps {
31
- ref?: MutableRefObject<FocusableElement | null>
32
- }
33
-
34
- // Exported for @react-aria/collections, which forwards this context.
35
- /** @private */
36
- export let FocusableContext: React.Context<FocusableContextValue | null> = React.createContext<FocusableContextValue | null>(null);
37
-
38
- function useFocusableContext(ref: RefObject<FocusableElement | null>): FocusableContextValue {
39
- let context = useContext(FocusableContext) || {};
40
- useSyncRef(context, ref);
41
-
42
- // eslint-disable-next-line
43
- let {ref: _, ...otherProps} = context;
44
- return otherProps;
45
- }
46
-
47
- /**
48
- * Provides DOM props to the nearest focusable child.
49
- */
50
- export const FocusableProvider:
51
- React.ForwardRefExoticComponent<FocusableProviderProps & React.RefAttributes<FocusableElement>> =
52
- React.forwardRef(function FocusableProvider(props: FocusableProviderProps, ref: ForwardedRef<FocusableElement>) {
53
- let {children, ...otherProps} = props;
54
- let objRef = useObjectRef(ref);
55
- let context = {
56
- ...otherProps,
57
- ref: objRef
58
- };
59
-
60
- return (
61
- <FocusableContext.Provider value={context}>
62
- {children}
63
- </FocusableContext.Provider>
64
- );
65
- });
66
-
67
- export interface FocusableAria {
68
- /** Props for the focusable element. */
69
- focusableProps: DOMAttributes
70
- }
71
-
72
- /**
73
- * Used to make an element focusable and capable of auto focus.
74
- */
75
- export function useFocusable<T extends FocusableElement = FocusableElement>(props: FocusableOptions<T>, domRef: RefObject<FocusableElement | null>): FocusableAria {
76
- let {focusProps} = useFocus(props);
77
- let {keyboardProps} = useKeyboard(props);
78
- let interactions = mergeProps(focusProps, keyboardProps);
79
- let domProps = useFocusableContext(domRef);
80
- let interactionProps = props.isDisabled ? {} : domProps;
81
- let autoFocusRef = useRef(props.autoFocus);
82
-
83
- useEffect(() => {
84
- if (autoFocusRef.current && domRef.current) {
85
- focusSafely(domRef.current);
86
- }
87
- autoFocusRef.current = false;
88
- }, [domRef]);
89
-
90
- // Always set a tabIndex so that Safari allows focusing native buttons and inputs.
91
- let tabIndex: number | undefined = props.excludeFromTabOrder ? -1 : 0;
92
- if (props.isDisabled) {
93
- tabIndex = undefined;
94
- }
95
-
96
- return {
97
- focusableProps: mergeProps(
98
- {
99
- ...interactions,
100
- tabIndex
101
- },
102
- interactionProps
103
- )
104
- };
105
- }
106
-
107
- export interface FocusableComponentProps extends FocusableOptions {
108
- children: ReactElement<DOMAttributes, string>
109
- }
110
-
111
- export const Focusable:
112
- React.ForwardRefExoticComponent<FocusableComponentProps & React.RefAttributes<FocusableElement>> =
113
- forwardRef(({children, ...props}: FocusableComponentProps, ref: ForwardedRef<FocusableElement>) => {
114
- ref = useObjectRef(ref);
115
- let {focusableProps} = useFocusable(props, ref);
116
- let child = React.Children.only(children);
117
-
118
- useEffect(() => {
119
- if (process.env.NODE_ENV === 'production') {
120
- return;
121
- }
122
-
123
- let el = ref.current;
124
- if (!el || !(el instanceof getOwnerWindow(el).Element)) {
125
- console.error('<Focusable> child must forward its ref to a DOM element.');
126
- return;
127
- }
128
-
129
- if (!props.isDisabled && !isFocusable(el)) {
130
- console.warn('<Focusable> child must be focusable. Please ensure the tabIndex prop is passed through.');
131
- return;
132
- }
133
-
134
- if (
135
- el.localName !== 'button' &&
136
- el.localName !== 'input' &&
137
- el.localName !== 'select' &&
138
- el.localName !== 'textarea' &&
139
- el.localName !== 'a' &&
140
- el.localName !== 'area' &&
141
- el.localName !== 'summary' &&
142
- el.localName !== 'img' &&
143
- el.localName !== 'svg'
144
- ) {
145
- let role = el.getAttribute('role');
146
- if (!role) {
147
- console.warn('<Focusable> child must have an interactive ARIA role.');
148
- } else if (
149
- // https://w3c.github.io/aria/#widget_roles
150
- role !== 'application' &&
151
- role !== 'button' &&
152
- role !== 'checkbox' &&
153
- role !== 'combobox' &&
154
- role !== 'gridcell' &&
155
- role !== 'link' &&
156
- role !== 'menuitem' &&
157
- role !== 'menuitemcheckbox' &&
158
- role !== 'menuitemradio' &&
159
- role !== 'option' &&
160
- role !== 'radio' &&
161
- role !== 'searchbox' &&
162
- role !== 'separator' &&
163
- role !== 'slider' &&
164
- role !== 'spinbutton' &&
165
- role !== 'switch' &&
166
- role !== 'tab' &&
167
- role !== 'tabpanel' &&
168
- role !== 'textbox' &&
169
- role !== 'treeitem' &&
170
- // aria-describedby is also announced on these roles
171
- role !== 'img' &&
172
- role !== 'meter' &&
173
- role !== 'progressbar'
174
- ) {
175
- console.warn(`<Focusable> child must have an interactive ARIA role. Got "${role}".`);
176
- }
177
- }
178
- }, [ref, props.isDisabled]);
179
-
180
- // @ts-ignore
181
- let childRef = parseInt(React.version, 10) < 19 ? child.ref : child.props.ref;
182
-
183
- return React.cloneElement(
184
- child,
185
- {
186
- ...mergeProps(focusableProps, child.props),
187
- // @ts-ignore
188
- ref: mergeRefs(childRef, ref)
189
- }
190
- );
191
- });