UNPKG

2.23 kBPlain TextView Raw
1/*
2 * Copyright 2021 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 {getOwnerWindow} from '@react-aria/utils';
14
15function isStyleVisible(element: Element) {
16 const windowObject = getOwnerWindow(element);
17 if (!(element instanceof windowObject.HTMLElement) && !(element instanceof windowObject.SVGElement)) {
18 return false;
19 }
20
21 let {display, visibility} = element.style;
22
23 let isVisible = (
24 display !== 'none' &&
25 visibility !== 'hidden' &&
26 visibility !== 'collapse'
27 );
28
29 if (isVisible) {
30 const {getComputedStyle} = element.ownerDocument.defaultView as unknown as Window;
31 let {display: computedDisplay, visibility: computedVisibility} = getComputedStyle(element);
32
33 isVisible = (
34 computedDisplay !== 'none' &&
35 computedVisibility !== 'hidden' &&
36 computedVisibility !== 'collapse'
37 );
38 }
39
40 return isVisible;
41}
42
43function isAttributeVisible(element: Element, childElement?: Element) {
44 return (
45 !element.hasAttribute('hidden') &&
46 (element.nodeName === 'DETAILS' &&
47 childElement &&
48 childElement.nodeName !== 'SUMMARY'
49 ? element.hasAttribute('open')
50 : true)
51 );
52}
53
54/**
55 * Adapted from https://github.com/testing-library/jest-dom and
56 * https://github.com/vuejs/vue-test-utils-next/.
57 * Licensed under the MIT License.
58 * @param element - Element to evaluate for display or visibility.
59 */
60export function isElementVisible(element: Element, childElement?: Element) {
61 return (
62 element.nodeName !== '#comment' &&
63 isStyleVisible(element) &&
64 isAttributeVisible(element, childElement) &&
65 (!element.parentElement || isElementVisible(element.parentElement, element))
66 );
67}