@elastic/eui
Version:
Elastic UI Component Library
67 lines (65 loc) • 2.76 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useOverflow = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = require("react");
var _mutation_observer = require("../observer/mutation_observer");
var _resize_observer = require("../observer/resize_observer");
/*
* 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.
*/
/**
* 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.
*/
var useOverflow = exports.useOverflow = function useOverflow(_ref) {
var overflowHeight = _ref.overflowHeight;
var _useState = (0, _react.useState)(null),
_useState2 = (0, _slicedToArray2.default)(_useState, 2),
wrapperRef = _useState2[0],
setWrapperRef = _useState2[1];
var _useState3 = (0, _react.useState)(-1),
_useState4 = (0, _slicedToArray2.default)(_useState3, 2),
tabIndex = _useState4[0],
setTabIndex = _useState4[1];
var _useResizeObserver = (0, _resize_observer.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);
};
(0, _mutation_observer.useMutationObserver)(wrapperRef, doesOverflow, {
subtree: true,
childList: true
});
(0, _react.useEffect)(doesOverflow, [width, height, wrapperRef]);
var overflowHeightStyles = (0, _react.useMemo)(function () {
if (overflowHeight) {
var property = typeof overflowHeight === 'string' ? 'blockSize' : 'maxBlockSize';
return (0, _defineProperty2.default)({}, property, overflowHeight);
}
return {};
}, [overflowHeight]);
return {
setWrapperRef: setWrapperRef,
tabIndex: tabIndex,
overflowHeightStyles: overflowHeightStyles
};
};