UNPKG

@codeurs/react-simple-wheel-picker

Version:

- This package is simple and flexible wheel picker for React - This package move like same as native applications picker - This package support accessibility

80 lines 3.26 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); require("intersection-observer"); var react_1 = require("react"); var useScrollAnimation_1 = __importDefault(require("../hooks/useScrollAnimation")); var setRefs = function (data) { return function () { return data.reduce(function (result, value) { result[value.id] = react_1.createRef(); return result; }, {}); }; }; var calculatePercentageOfRootWithoutItem = function (rootHeight, itemHeight) { return 100 - (itemHeight / rootHeight) * 100; }; var calculateMarginVertical = function (rootHeight, itemHeight) { return calculatePercentageOfRootWithoutItem(rootHeight, itemHeight) / 2; }; var calculateRootMargin = function (rootHeight, itemHeight) { return "-" + calculateMarginVertical(rootHeight, itemHeight) + "% 0px"; }; var useObsever = function (data, selectedID, itemHeight, onChange) { var root = react_1.useRef(null); var refs = react_1.useMemo(setRefs(data), [data]); var observer = react_1.useRef(null); var _a = react_1.useState(selectedID), activeID = _a[0], setActiveID = _a[1]; var onScroll = useScrollAnimation_1.default(root, refs); react_1.useEffect(function () { var observerCallback = function (entries) { var ratios = entries.map(function (entry) { return entry.intersectionRatio; }); var max = ratios.indexOf(Math.max.apply(Math, ratios)); var entry = entries[max]; if (!entry.isIntersecting) return; var itemID = entry.target.getAttribute("data-itemid"); var itemValue = entry.target.getAttribute("data-itemvalue"); if (!itemID || !itemValue) { throw new Error("Can not found id or value"); } onScroll(data, itemID); setActiveID(itemID); onChange({ id: itemID, value: itemValue }); }; if (!observer.current && root.current) { observer.current = new IntersectionObserver(observerCallback, { root: root.current, rootMargin: calculateRootMargin(root.current.clientHeight, itemHeight), threshold: [0.3, 0.79] }); data.map(function (item) { var elm = refs[item.id].current; if (elm && observer.current) { observer.current.observe(elm); } }); var firstItem = refs[data[0].id].current; var item = refs[selectedID].current; if (firstItem && item) { root.current.scrollTo(0, item.offsetTop - firstItem.offsetTop); } } return function () { if (observer.current) { observer.current.disconnect(); observer.current = null; } }; }, [data, refs, root, itemHeight]); // eslint-disable-line return { root: root, refs: refs, activeID: activeID }; }; exports.default = useObsever; //# sourceMappingURL=useObserver.js.map