UNPKG

@fluentui/react-northstar

Version:
348 lines (344 loc) 15.6 kB
import { useCallbackRef, useDeepMemo, useEventCallback, useFirstMount, useIsomorphicLayoutEffect } from '@fluentui/react-bindings'; import * as PopperJs from '@popperjs/core'; import * as React from 'react'; import { getReactFiberFromNode } from '../getReactFiberFromNode'; import { isBrowser } from '../isBrowser'; import { getBoundary } from './getBoundary'; import { getScrollParent } from './getScrollParent'; import { isIntersectingModifier } from './isIntersectingModifier'; import { applyRtlToOffset, getPlacement } from './positioningHelper'; // // Dev utils to detect if nodes have "autoFocus" props. // /** * Detects if a passed HTML node has "autoFocus" prop on a React's fiber. Is needed as React handles autofocus behavior * in React DOM and will not pass "autoFocus" to an actual HTML. * * @param {Node} node * @returns {Boolean} */ function hasAutofocusProp(node) { // https://github.com/facebook/react/blob/848bb2426e44606e0a55dfe44c7b3ece33772485/packages/react-dom/src/client/ReactDOMHostConfig.js#L157-L166 var isAutoFocusableElement = node.nodeName === 'BUTTON' || node.nodeName === 'INPUT' || node.nodeName === 'SELECT' || node.nodeName === 'TEXTAREA'; if (isAutoFocusableElement) { return !!getReactFiberFromNode(node).pendingProps.autoFocus; } return false; } function hasAutofocusFilter(node) { return hasAutofocusProp(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; } /** * Provides a callback to resolve Popper options, it's stable and should be used as a dependency to trigger updates * of Popper options. * * A callback is used there intentionally as some of Popper.js modifiers require DOM nodes (targer, container, arrow) * that can't be resolved properly during an initial rendering. * * @param {PopperOptions} options * @param {React.MutableRefObject} popperOriginalPositionRef * * @returns {Function} */ function usePopperOptions(options, popperOriginalPositionRef) { var autoSize = options.autoSize, flipBoundary = options.flipBoundary, offset = options.offset, onStateUpdate = options.onStateUpdate, overflowBoundary = options.overflowBoundary, rtl = options.rtl, unstable_disableTether = options.unstable_disableTether, unstable_pinned = options.unstable_pinned; var placement = getPlacement(options.align, options.position, options.rtl); var strategy = options.positionFixed ? 'fixed' : 'absolute'; var handleStateUpdate = useEventCallback(function (_ref) { var state = _ref.state; if (onStateUpdate) { onStateUpdate(state); } }); var offsetModifier = React.useMemo(function () { return offset ? { name: 'offset', options: { offset: rtl ? applyRtlToOffset(offset) : offset } } : null; }, [offset, rtl]); var userModifiers = useDeepMemo(function () { return options.modifiers; }, options.modifiers); return React.useCallback(function (target, container, arrow) { var scrollParentElement = getScrollParent(container); var hasScrollableElement = scrollParentElement ? scrollParentElement !== scrollParentElement.ownerDocument.body : false; var modifiers = [isIntersectingModifier, /** * We are setting the position to `fixed` in the first effect to prevent scroll jumps in case of the content * with managed focus. Modifier sets the position to `fixed` before all other modifier effects. Another part of * a patch modifies ".forceUpdate()" directly after a Popper will be created. */ { name: 'positionStyleFix', enabled: true, phase: 'afterWrite', effect: function effect(_ref2) { var state = _ref2.state, instance = _ref2.instance; // ".isFirstRun" is a part of our patch, on a first evaluation it will "undefined" // should be disabled for subsequent runs as it breaks positioning for them if (instance.isFirstRun !== false) { popperOriginalPositionRef.current = state.elements.popper.style['position']; state.elements.popper.style['position'] = 'fixed'; } return function () {}; }, requires: [] }, { name: 'flip', options: { flipVariations: true } }, /** * unstable_pinned disables the flip modifier by setting flip.enabled to false; this * disables automatic repositioning of the popper box; it will always be placed according to * the values of `align` and `position` props, regardless of the size of the component, the * reference element or the viewport. */ unstable_pinned && { name: 'flip', enabled: false }, /** * When the popper box is placed in the context of a scrollable element, we need to set * preventOverflow.escapeWithReference to true and flip.boundariesElement to 'scrollParent' * (default is 'viewport') so that the popper box will stick with the targetRef when we * scroll targetRef out of the viewport. */ hasScrollableElement && { name: 'flip', options: { boundary: 'clippingParents' } }, hasScrollableElement && { name: 'preventOverflow', options: { boundary: 'clippingParents' } }, offsetModifier].concat(typeof userModifiers === 'function' ? userModifiers(target, container, arrow) : userModifiers, [ /** * This modifier is necessary to retain behaviour from popper v1 where untethered poppers are allowed by * default. i.e. popper is still rendered fully in the viewport even if anchor element is no longer in the * viewport. */ unstable_disableTether && { name: 'preventOverflow', options: { altAxis: unstable_disableTether === 'all', tether: false } }, flipBoundary && { name: 'flip', options: { altBoundary: true, boundary: getBoundary(container, flipBoundary) } }, overflowBoundary && { name: 'preventOverflow', options: { altBoundary: true, boundary: getBoundary(container, overflowBoundary) } }, { name: 'onUpdate', enabled: true, phase: 'afterWrite', fn: handleStateUpdate }, autoSize && { // Similar code as popper-maxsize-modifier: https://github.com/atomiks/popper.js/blob/master/src/modifiers/maxSize.js // popper-maxsize-modifier only calculates the max sizes. // This modifier can apply max sizes always, or apply the max sizes only when overflow is detected name: 'applyMaxSize', enabled: true, phase: 'beforeWrite', requiresIfExists: ['offset', 'preventOverflow', 'flip'], options: { altBoundary: true, boundary: getBoundary(container, overflowBoundary) }, fn: function fn(_ref3) { var state = _ref3.state, modifierOptions = _ref3.options; var overflow = PopperJs.detectOverflow(state, modifierOptions); var _ref4 = state.modifiersData.preventOverflow || { x: 0, y: 0 }, x = _ref4.x, y = _ref4.y; var _state$rects$popper = state.rects.popper, width = _state$rects$popper.width, height = _state$rects$popper.height; var _state$placement$spli = state.placement.split('-'), basePlacement = _state$placement$spli[0]; var widthProp = basePlacement === 'left' ? 'left' : 'right'; var heightProp = basePlacement === 'top' ? 'top' : 'bottom'; var applyMaxWidth = autoSize === 'always' || autoSize === 'width-always' || overflow[widthProp] > 0 && (autoSize === true || autoSize === 'width'); var applyMaxHeight = autoSize === 'always' || autoSize === 'height-always' || overflow[heightProp] > 0 && (autoSize === true || autoSize === 'height'); if (applyMaxWidth) { state.styles.popper.maxWidth = width - overflow[widthProp] - x + "px"; } if (applyMaxHeight) { state.styles.popper.maxHeight = height - overflow[heightProp] - y + "px"; } } }, /** * This modifier is necessary in order to render the pointer. Refs are resolved in effects, so it can't be * placed under computed modifiers. Deep merge is not required as this modifier has only these properties. */ { name: 'arrow', enabled: !!arrow, options: { element: arrow } }]).filter(Boolean); var popperOptions = { modifiers: modifiers, placement: placement, strategy: strategy, onFirstUpdate: function onFirstUpdate(state) { return handleStateUpdate({ state: state }); } }; return popperOptions; }, [autoSize, flipBoundary, offsetModifier, overflowBoundary, placement, strategy, unstable_disableTether, unstable_pinned, userModifiers, // These can be skipped from deps as they will not ever change handleStateUpdate, popperOriginalPositionRef]); } /** * Exposes Popper positioning API via React hook. Contains few important differences between an official "react-popper" * package: * - style attributes are applied directly on DOM to avoid re-renders * - refs changes and resolution is handled properly without re-renders * - contains a specific to React fix related to initial positioning when containers have components with managed focus * to avoid focus jumps * * @param {PopperOptions} options */ export function usePopper(options) { if (options === void 0) { options = {}; } var _options = options, _options$enabled = _options.enabled, enabled = _options$enabled === void 0 ? true : _options$enabled; var isFirstMount = useFirstMount(); var popperOriginalPositionRef = React.useRef('absolute'); var resolvePopperOptions = usePopperOptions(options, popperOriginalPositionRef); var popperInstanceRef = React.useRef(null); var handlePopperUpdate = useEventCallback(function () { var _popperInstanceRef$cu; (_popperInstanceRef$cu = popperInstanceRef.current) == null ? void 0 : _popperInstanceRef$cu.destroy(); popperInstanceRef.current = null; var popperInstance = null; if (isBrowser() && enabled) { if (targetRef.current && containerRef.current) { popperInstance = PopperJs.createPopper(targetRef.current, containerRef.current, resolvePopperOptions(targetRef.current, containerRef.current, arrowRef.current)); } } if (popperInstance) { /** * The patch updates `.forceUpdate()` Popper function which restores the original position before the first * forceUpdate() call. See also "positionStyleFix" modifier in usePopperOptions(). */ var originalForceUpdate = popperInstance.forceUpdate; popperInstance.isFirstRun = true; popperInstance.forceUpdate = function () { if (popperInstance.isFirstRun) { popperInstance.state.elements.popper.style['position'] = popperOriginalPositionRef.current; popperInstance.isFirstRun = false; } originalForceUpdate(); }; } popperInstanceRef.current = popperInstance; }); // Refs are managed by useCallbackRef() to handle ref updates scenarios. // // The first scenario are updates for a targetRef, we can handle it properly only via callback refs, but it causes // re-renders (we would like to avoid them). // // The second problem is related to refs resolution on React's layer: refs are resolved in the same order as effects // that causes an issue when you have a container inside a target, for example: a menu in ChatMessage. // // function ChatMessage(props) { // <div className="message" ref={targetRef}> // 3) ref will be resolved only now, but it's too late already // <Popper target={targetRef}> // 2) create a popper instance // <div className="menu" /> // 1) capture ref from this element // </Popper> // </div> // } // // Check a demo on CodeSandbox: https://codesandbox.io/s/popper-refs-emy60. // // This again can be solved with callback refs. It's not a huge issue as with hooks we are moving popper's creation // to ChatMessage itself, however, without `useCallback()` refs it's still a Pandora box. var targetRef = useCallbackRef(null, handlePopperUpdate, true); var containerRef = useCallbackRef(null, handlePopperUpdate, true); var arrowRef = useCallbackRef(null, handlePopperUpdate, true); React.useImperativeHandle(options.popperRef, function () { return { updatePosition: function updatePosition() { var _popperInstanceRef$cu2; (_popperInstanceRef$cu2 = popperInstanceRef.current) == null ? void 0 : _popperInstanceRef$cu2.update(); } }; }, []); useIsomorphicLayoutEffect(function () { handlePopperUpdate(); return function () { var _popperInstanceRef$cu3; (_popperInstanceRef$cu3 = popperInstanceRef.current) == null ? void 0 : _popperInstanceRef$cu3.destroy(); popperInstanceRef.current = null; }; }, [options.enabled]); useIsomorphicLayoutEffect(function () { if (!isFirstMount) { var _popperInstanceRef$cu4; (_popperInstanceRef$cu4 = popperInstanceRef.current) == null ? void 0 : _popperInstanceRef$cu4.setOptions(resolvePopperOptions(targetRef.current, containerRef.current, arrowRef.current)); } }, [resolvePopperOptions]); if (process.env.NODE_ENV !== 'production') { // This checked should run only in development mode // eslint-disable-next-line react-hooks/rules-of-hooks React.useEffect(function () { if (containerRef.current) { var _contentNode$ownerDoc; var contentNode = containerRef.current; var treeWalker = (_contentNode$ownerDoc = contentNode.ownerDocument) == null ? void 0 : _contentNode$ownerDoc.createTreeWalker(contentNode, NodeFilter.SHOW_ELEMENT, { acceptNode: hasAutofocusFilter }); while (treeWalker.nextNode()) { var node = treeWalker.currentNode; // eslint-disable-next-line no-console console.warn('<Popper>:', node); // eslint-disable-next-line no-console console.warn(['<Popper>: ^ this node contains "autoFocus" prop on a React element. This can break the initial', 'positioning of an element and cause a window jump effect. This issue occurs because React polyfills', '"autoFocus" behavior to solve inconsistencies between different browsers:', 'https://github.com/facebook/react/issues/11851#issuecomment-351787078', '\n', 'However, ".focus()" in this case occurs before any other React effects will be executed', '(React.useEffect(), componentDidMount(), etc.) and we can not prevent this behavior. If you really', 'want to use "autoFocus" please add "position: fixed" to styles of the element that is wrapped by', '"Popper".', "In general, it's not recommended to use \"autoFocus\" as it may break accessibility aspects:", 'https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-autofocus.md', '\n', 'We suggest to use the "trapFocus" prop on Fluent components or a catch "ref" and then use', '"ref.current.focus" in React.useEffect():', 'https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element'].join(' ')); } } // We run this check once, no need to add deps here // TODO: Should be rework to handle options.enabled and contentRef updates // eslint-disable-next-line react-hooks/exhaustive-deps }, []); } return { targetRef: targetRef, containerRef: containerRef, arrowRef: arrowRef }; } //# sourceMappingURL=usePopper.js.map