UNPKG

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