UNPKG

2.62 kBPlain TextView Raw
1/*
2 * Copyright 2022 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
13import {getFocusableTreeWalker} from './FocusScope';
14import {RefObject} from '@react-types/shared';
15import {useLayoutEffect} from '@react-aria/utils';
16import {useState} from 'react';
17
18interface AriaHasTabbableChildOptions {
19 isDisabled?: boolean
20}
21
22// This was created for a special empty case of a component that can have child or
23// be empty, like Collection/Virtualizer/Table/ListView/etc. When these components
24// are empty they can have a message with a tabbable element, which is like them
25// being not empty, when it comes to focus and tab order.
26
27/**
28 * Returns whether an element has a tabbable child, and updates as children change.
29 * @private
30 */
31export function useHasTabbableChild(ref: RefObject<Element | null>, options?: AriaHasTabbableChildOptions): boolean {
32 let isDisabled = options?.isDisabled;
33 let [hasTabbableChild, setHasTabbableChild] = useState(false);
34
35 useLayoutEffect(() => {
36 if (ref?.current && !isDisabled) {
37 let update = () => {
38 if (ref.current) {
39 let walker = getFocusableTreeWalker(ref.current, {tabbable: true});
40 setHasTabbableChild(!!walker.nextNode());
41 }
42 };
43
44 update();
45
46 // Update when new elements are inserted, or the tabIndex/disabled attribute updates.
47 let observer = new MutationObserver(update);
48 observer.observe(ref.current, {
49 subtree: true,
50 childList: true,
51 attributes: true,
52 attributeFilter: ['tabIndex', 'disabled']
53 });
54
55 return () => {
56 // Disconnect mutation observer when a React update occurs on the top-level component
57 // so we update synchronously after re-rendering. Otherwise React will emit act warnings
58 // in tests since mutation observers fire asynchronously. The mutation observer is necessary
59 // so we also update if a child component re-renders and adds/removes something tabbable.
60 observer.disconnect();
61 };
62 }
63 });
64
65 return isDisabled ? false : hasTabbableChild;
66}