UNPKG

scroll-u

Version:

high-performance scrollable list component

403 lines (390 loc) 18.9 kB
'use strict'; var jsxRuntime = require('react/jsx-runtime'); var React = require('react'); /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; var DefaultScrollBar = function (_a) { var height = _a.height, top = _a.top; return (jsxRuntime.jsx("div", { style: { position: 'absolute', right: 4, top: 0, width: 4, height: '100%', background: '#eee', borderRadius: 3, overflow: 'hidden', pointerEvents: 'none', zIndex: 15 }, children: jsxRuntime.jsx("div", { style: { position: 'absolute', width: '100%', height: "".concat(height, "px"), top: "".concat(top, "px"), background: '#007bff', borderRadius: 3, transition: 'top 0.2s ease-out', } }) })); }; var ScrollU = React.forwardRef(function (props, ref) { var className = props.className, renderItem = props.renderItem, _a = props.initialItems, initialItems = _a === void 0 ? [] : _a, _b = props.showScrollBar, showScrollBar = _b === void 0 ? true : _b, _c = props.scrollBarRender, scrollBarRender = _c === void 0 ? function (height, top) { return (jsxRuntime.jsx(DefaultScrollBar, { height: height, top: top })); } : _c; var containerRef = React.useRef(null); var contentRef = React.useRef(null); var _d = React.useState(0), translateY = _d[0], setTranslateY = _d[1]; var _e = React.useState({ height: 0, top: 0 }), scrollBar = _e[0], setScroll = _e[1]; var clearButtonTimer = React.useRef(null); var clearTopItemTimer = React.useRef(null); var _f = React.useState(initialItems), items = _f[0], setItems = _f[1]; var _g = React.useState(false), isLoadingPre = _g[0], setIsLoadingPre = _g[1]; var _h = React.useState(false), isLoadingNext = _h[0], setIsLoadingNext = _h[1]; var lastPreMsgId = React.useRef(null); var lastNextMsgId = React.useRef(null); var firstItemRef = React.useRef(null); var lastItemRef = React.useRef(null); var rafId = React.useRef(null); var intersectionObserver = React.useRef(null); var _j = React.useState(false), pendingPreAdjust = _j[0], setPendingPreAdjust = _j[1]; var handlePre = React.useCallback(function () { return __awaiter(void 0, void 0, void 0, function () { var first, currentMsgId, newItems_1, currentTranslateY, oldHeight; var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: if (isLoadingPre || !renderItem) return [2 /*return*/]; first = items.length > 0 ? items[0] : undefined; if (first && React.isValidElement(first)) { currentMsgId = (_a = first.props) === null || _a === void 0 ? void 0 : _a.msgId; if (typeof currentMsgId === 'number' && lastPreMsgId.current === currentMsgId) { console.log('handlePre - Skipping duplicate request for msgId:', currentMsgId); return [2 /*return*/]; } lastPreMsgId.current = currentMsgId; } setIsLoadingPre(true); _b.label = 1; case 1: _b.trys.push([1, , 3, 4]); return [4 /*yield*/, renderItem('pre', first)]; case 2: newItems_1 = _b.sent(); if (!newItems_1 || newItems_1.length === 0) { return [2 /*return*/]; } currentTranslateY = translateY; oldHeight = contentRef.current ? contentRef.current.offsetHeight : 0; setPendingPreAdjust({ oldHeight: oldHeight, currentTranslateY: currentTranslateY }); setItems(function (prev) { return __spreadArray(__spreadArray([], newItems_1, true), prev, true); }); return [3 /*break*/, 4]; case 3: setIsLoadingPre(false); lastPreMsgId.current = null; return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }, [isLoadingPre, renderItem, items, translateY]); React.useImperativeHandle(ref, function () { return ({ updateNodes: function (handler) { setItems(function (nextItems) { // need to update offset when item change. var currentTranslateY = translateY; var oldHeight = contentRef.current ? contentRef.current.offsetHeight : 0; setPendingPreAdjust({ oldHeight: oldHeight, currentTranslateY: currentTranslateY }); return handler(nextItems); }); }, listNodes: function () { return items; }, trigerRender: function (direction) { if (direction === 'pre') { handlePre(); } else { handleNext(); } } }); }); var handleNext = React.useCallback(function () { return __awaiter(void 0, void 0, void 0, function () { var last, currentMsgId, newItems_2; var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: if (isLoadingNext || !renderItem) return [2 /*return*/]; last = items.length > 0 ? items[items.length - 1] : undefined; if (last && React.isValidElement(last)) { currentMsgId = (_a = last.props) === null || _a === void 0 ? void 0 : _a.msgId; if (typeof currentMsgId === 'number' && lastNextMsgId.current === currentMsgId) { console.log('handleNext - Skipping duplicate request for msgId:', currentMsgId); return [2 /*return*/]; } lastNextMsgId.current = currentMsgId; } _b.label = 1; case 1: _b.trys.push([1, , 3, 4]); setIsLoadingNext(true); return [4 /*yield*/, renderItem('next', last)]; case 2: newItems_2 = _b.sent(); if (!newItems_2 || newItems_2.length == 0) { return [2 /*return*/]; } setItems(function (prev) { return __spreadArray(__spreadArray([], prev, true), newItems_2, true); }); return [3 /*break*/, 4]; case 3: setIsLoadingNext(false); lastNextMsgId.current = null; // reset return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }, [isLoadingNext, renderItem, items]); var setupIntersectionObserver = React.useCallback(function () { if (intersectionObserver.current) { intersectionObserver.current.disconnect(); } intersectionObserver.current = new IntersectionObserver(function (entries) { entries.forEach(function (entry) { if (entry.isIntersecting) { if (entry.target === firstItemRef.current) { handlePre(); } else if (entry.target === lastItemRef.current) { handleNext(); } } }); }, { root: containerRef.current, rootMargin: '50px', threshold: 0.1 }); if (firstItemRef.current) { intersectionObserver.current.observe(firstItemRef.current); } else { console.log('First item ref is null'); } if (lastItemRef.current) { intersectionObserver.current.observe(lastItemRef.current); } else { console.log('Last item ref is null'); } }, [items.length]); var cleanItemsFromButton = React.useCallback(function () { var _a; var removeIndex = -1; var container = containerRef.current; var nodes = (_a = contentRef.current) === null || _a === void 0 ? void 0 : _a.children; if (container && nodes) { var containerRect = container.getBoundingClientRect(); for (var i = nodes.length - 1; i >= 0; i--) { var node = nodes[i]; if (!node) continue; var itemRect = node.getBoundingClientRect(); if (itemRect.top > containerRect.bottom) { removeIndex = i; } else { break; } } if (removeIndex !== -1 && removeIndex < (nodes === null || nodes === void 0 ? void 0 : nodes.length) - 1) { removeIndex += 1; // prevent reload from button setItems(function (prev) { return prev.slice(0, removeIndex); }); } } }, [containerRef, contentRef]); var cleanItemsFromTop = React.useCallback(function () { var _a; var removeIndex = -1; var container = containerRef.current; var nodes = (_a = contentRef.current) === null || _a === void 0 ? void 0 : _a.children; if (container && nodes) { var containerRect = container.getBoundingClientRect(); for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; if (!node) continue; var itemRect = node.getBoundingClientRect(); if (itemRect.bottom < containerRect.top) { removeIndex = i; } else { break; } } } if (removeIndex !== -1 && removeIndex > 0) { removeIndex -= 1; // prevent reload from top var currentTranslateY = translateY; var oldHeight = contentRef.current ? contentRef.current.offsetHeight : 0; setPendingPreAdjust({ oldHeight: oldHeight, currentTranslateY: currentTranslateY }); setItems(function (prev) { return prev.slice(removeIndex); }); } }, [containerRef, contentRef]); var startInertia = function (initialVelocity) { var velocity = initialVelocity; var animate = function () { if (Math.abs(velocity) < 0.1) { return; } setTranslateY(function (prev) { var next = prev - velocity; var max = containerRef.current.offsetHeight * 0.01; var min = containerRef.current.offsetHeight - contentRef.current.offsetHeight; var newTranslateY = Math.max(min, Math.min(max, next)); return newTranslateY; }); velocity *= 0.35; rafId.current = requestAnimationFrame(animate); }; rafId.current = requestAnimationFrame(animate); }; React.useEffect(function () { if (contentRef.current && containerRef.current) { var containerHeight = containerRef.current.offsetHeight; var contentHeight = contentRef.current.offsetHeight; var topHiddenHeight = Math.max(0, -translateY); var scrollBarHeight = (containerHeight / contentHeight) * containerHeight; var scrollBarTop = (topHiddenHeight / contentHeight) * containerHeight; setScroll({ height: scrollBarHeight, top: scrollBarTop, }); } }, [translateY, items]); var handleScroll = React.useCallback(function (event) { event.preventDefault(); if (clearButtonTimer.current) { clearTimeout(clearButtonTimer.current); } clearButtonTimer.current = setTimeout(cleanItemsFromButton, 300); if (clearTopItemTimer.current) { clearTimeout(clearTopItemTimer.current); } clearTopItemTimer.current = setTimeout(cleanItemsFromTop, 500); var deltaY = event.deltaY; startInertia(deltaY); }, []); React.useEffect(function () { var container = containerRef.current; if (container) { container.addEventListener('wheel', handleScroll, { passive: false }); return function () { container.removeEventListener('wheel', handleScroll); if (clearButtonTimer.current) { clearTimeout(clearButtonTimer.current); } }; } }, [handleScroll]); React.useEffect(function () { setupIntersectionObserver(); return function () { if (intersectionObserver.current) { intersectionObserver.current.disconnect(); } }; }, [items.length]); React.useLayoutEffect(function () { if (pendingPreAdjust && contentRef.current) { var newHeight = contentRef.current.offsetHeight; var heightDiff_1 = newHeight - pendingPreAdjust.oldHeight; if (heightDiff_1 !== 0) { setTranslateY(function (prevTranslateY) { return prevTranslateY - heightDiff_1; }); } setPendingPreAdjust(false); } }, [items, pendingPreAdjust]); return (jsxRuntime.jsxs("div", { ref: containerRef, className: className, style: { height: '100%', // 或 100%,由父容器控制 overflow: 'hidden', // 关键 position: 'relative', width: '100%', display: 'flex', flexDirection: 'column', }, children: [jsxRuntime.jsx("div", { ref: contentRef, style: { transform: "translateY(".concat(translateY, "px)"), willChange: 'transform', paddingRight: showScrollBar ? 20 : 0, }, children: items.map(function (item, index) { var isFirst = index === 0; var isLast = index === items.length - 1; if (isFirst || isLast) { return (jsxRuntime.jsx("div", { ref: isFirst ? firstItemRef : lastItemRef, children: item }, index)); } return jsxRuntime.jsx("div", { children: item }, index); }) }), showScrollBar && (scrollBarRender(scrollBar.height, scrollBar.top))] })); }); exports.DefaultScrollBar = DefaultScrollBar; exports.ScrollU = ScrollU; //# sourceMappingURL=index.js.map