UNPKG

@elastic/eui

Version:

Elastic UI Component Library

61 lines (59 loc) 2.38 kB
import _defineProperty from "@babel/runtime/helpers/defineProperty"; import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ import { useEffect, useState, useMemo } from 'react'; import { useMutationObserver } from '../observer/mutation_observer'; import { useResizeObserver } from '../observer/resize_observer'; /** * Overflow logic - returns overflow-related state/logic/utils * * Detects whether the code block overflows and returns a tabIndex of 0 if so, * which allows keyboard users to use the up/down arrow keys to scroll through * the container. */ export var useOverflow = function useOverflow(_ref) { var overflowHeight = _ref.overflowHeight; var _useState = useState(null), _useState2 = _slicedToArray(_useState, 2), wrapperRef = _useState2[0], setWrapperRef = _useState2[1]; var _useState3 = useState(-1), _useState4 = _slicedToArray(_useState3, 2), tabIndex = _useState4[0], setTabIndex = _useState4[1]; var _useResizeObserver = useResizeObserver(wrapperRef), width = _useResizeObserver.width, height = _useResizeObserver.height; var doesOverflow = function doesOverflow() { if (!wrapperRef) return; var clientWidth = wrapperRef.clientWidth, clientHeight = wrapperRef.clientHeight, scrollWidth = wrapperRef.scrollWidth, scrollHeight = wrapperRef.scrollHeight; var doesOverflow = scrollHeight > clientHeight || scrollWidth > clientWidth; setTabIndex(doesOverflow ? 0 : -1); }; useMutationObserver(wrapperRef, doesOverflow, { subtree: true, childList: true }); useEffect(doesOverflow, [width, height, wrapperRef]); var overflowHeightStyles = useMemo(function () { if (overflowHeight) { var property = typeof overflowHeight === 'string' ? 'blockSize' : 'maxBlockSize'; return _defineProperty({}, property, overflowHeight); } return {}; }, [overflowHeight]); return { setWrapperRef: setWrapperRef, tabIndex: tabIndex, overflowHeightStyles: overflowHeightStyles }; };