UNPKG

@renderlesskit/react

Version:

Collection of headless components/hooks that are accessible, composable, customizable from low level to build your own UI & Design System powered by Reakit

83 lines (73 loc) 2.54 kB
import * as React from "react"; import { isSelfTarget } from "reakit-utils"; import { useSafeLayoutEffect } from "@chakra-ui/hooks"; function useLastValue(value) { var lastValue = React.useRef(null); useSafeLayoutEffect(() => { lastValue.current = value; }, [value]); return lastValue; } export var useAnimation = props => { var { visible } = props; var [animating, setAnimating] = React.useState(false); var lastVisible = useLastValue(visible); var visibleHasChanged = lastVisible.current != null && lastVisible.current !== visible; var [state, setState] = React.useState(null); var raf = React.useRef(0); if (!animating && visibleHasChanged) { // Sets animating to true when when visible is updated setAnimating(true); } React.useEffect(() => { // Double RAF is needed so the browser has enough time to paint the // default styles before processing the `data-enter` attribute. Otherwise // it wouldn't be considered a transition. // See https://github.com/reakit/reakit/issues/643 raf.current = window.requestAnimationFrame(() => { raf.current = window.requestAnimationFrame(() => { if (visible) { setState("enter"); } else if (animating) { setState("leave"); } else { setState(null); } }); }); return () => window.cancelAnimationFrame(raf.current); }, [visible, animating]); var stopAnimation = React.useCallback(() => setAnimating(false), []); var onEnd = React.useCallback(event => { if (!isSelfTarget(event)) return; if (!animating) return; // Ignores number animated stopAnimation(); }, [animating, stopAnimation]); return { state, animating, onEnd }; }; export function getElementHeight(el) { if (!(el !== null && el !== void 0 && el.current)) { return "auto"; } return el.current.scrollHeight; } export function getElementWidth(el) { if (!(el !== null && el !== void 0 && el.current)) { return "auto"; } return el.current.scrollWidth; } // https://github.com/mui-org/material-ui/blob/da362266f7c137bf671d7e8c44c84ad5cfc0e9e2/packages/material-ui/src/styles/transitions.js#L89-L98 export function getAutoSizeDuration(size) { if (!size || typeof size === "string") { return 0; } var constant = size / 36; // https://www.wolframalpha.com/input/?i=(4+%2B+15+*+(x+%2F+36+)+**+0.25+%2B+(x+%2F+36)+%2F+5)+*+10 return Math.round((4 + 15 * constant ** 0.25 + constant / 5) * 10); } //# sourceMappingURL=helpers.js.map