Repository URL to install this package:
|
Version:
3.12.16 ▾
|
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { memo, useCallback, useEffect, useRef, useState, useMemo } from 'react';
import getScrollableParent from '@filerobot/explorer/lib/utils/getScrollableParent';
import StyledVirtualGrid from './VirtualGrid.styled';
import VirtualGridItem from './VirtualGridItem';
import { defaultGetItemKey, getLayoutInfo } from './VirtualGrid.utils';
// TODO: Refactor the VirtualGrid to consider also the skeleton loading to avoid jumping, and use the same size of skeleton's and align items size.
/**
* A Virtual grid that applies (windowing) concept for reusing the DOM elements and avoid rerendering for all items.
* @param {Array} items - The items that will be used in the grid (required).
* @param {ReactNode} children - The children that will be rendered for each item (required).
* @param {String} injectedItemPropName - The name of the prop that will be injected in the children (optional).
* @param {Number} overscan - The number of items that will be rendered before and after the viewport in rows (optional).
* @param {Function} getItemKey - The function that will be used to get the item key (optional).
* @param {Boolean} stopChildEventsPropagation - if `true`, the children's items click events won't be propagated outside of the virtual grid component (incase of needing to handle some specific case on grid's container empty space click).
* @param {Number} columnMinWidth - The minimum width of the column in pixels (optional - default is 214px).
* @param {String} scrollToKeyOnMount - The key of the item that will be scrolled to on mount the grid (optional).
* @param {ReactRef} apiRef - the reference that will contain the api functions to deal with the grid (optional)
* 1- `scrollToItem({ key, index })` function that scrolls the grid to the specified item's key, the key should be the same property that's returned from getItemKey, index should be the item's index.
* @returns {ReactNode} - The VirtualGrid component.
*/
import { jsx as _jsx } from "react/jsx-runtime";
var VirtualGrid = function VirtualGrid(_ref) {
var children = _ref.children,
_ref$items = _ref.items,
items = _ref$items === void 0 ? [] : _ref$items,
_ref$injectedItemProp = _ref.injectedItemPropName,
injectedItemPropName = _ref$injectedItemProp === void 0 ? 'item' : _ref$injectedItemProp,
_ref$overscan = _ref.overscan,
overscan = _ref$overscan === void 0 ? 3 : _ref$overscan,
_ref$columnMinWidth = _ref.columnMinWidth,
columnMinWidth = _ref$columnMinWidth === void 0 ? 214 : _ref$columnMinWidth,
_ref$getItemKey = _ref.getItemKey,
getItemKey = _ref$getItemKey === void 0 ? defaultGetItemKey : _ref$getItemKey,
_ref$stopChildEventsP = _ref.stopChildEventsPropagation,
stopChildEventsPropagation = _ref$stopChildEventsP === void 0 ? true : _ref$stopChildEventsP,
apiRef = _ref.apiRef;
var isUnMounting = useRef(false);
var _useState = useState(0),
_useState2 = _slicedToArray(_useState, 2),
scrollTop = _useState2[0],
setScrollTop = _useState2[1];
var scrollableElementRef = useRef(null);
var _useState3 = useState({
elementHeight: 1,
columnsCount: 6,
rowsCount: 6,
rowGap: 0
}),
_useState4 = _slicedToArray(_useState3, 2),
layoutInfo = _useState4[0],
setLayoutInfo = _useState4[1];
var gridContainerRef = useRef(null);
var animationFramesIds = useRef({
resize: null,
scroll: null
});
var gappedElementHeight = layoutInfo.elementHeight + layoutInfo.rowGap;
var rowsOffset = Math.max(Math.floor(scrollTop / gappedElementHeight) - overscan, 0);
var offsetY = rowsOffset * gappedElementHeight;
var containerHeight = useMemo(function () {
var totalRowsCount = Math.ceil(items.length / layoutInfo.columnsCount);
return totalRowsCount * layoutInfo.elementHeight + layoutInfo.rowGap * (totalRowsCount - 1);
}, [items.length, layoutInfo.columnsCount, layoutInfo.elementHeight, layoutInfo.rowGap]);
var calculateLayoutInfo = useCallback(function () {
if (isUnMounting.current) {
return;
}
if (animationFramesIds.current.resize) {
cancelAnimationFrame(animationFramesIds.current.resize);
animationFramesIds.current.resize = null;
}
animationFramesIds.current.resize = requestAnimationFrame(function () {
var gridContainer = gridContainerRef.current;
var _getLayoutInfo = getLayoutInfo(gridContainer, scrollableElementRef.current, columnMinWidth),
_getLayoutInfo$elemen = _getLayoutInfo.elementWidth,
elementWidth = _getLayoutInfo$elemen === void 0 ? 1 : _getLayoutInfo$elemen,
_getLayoutInfo$elemen2 = _getLayoutInfo.elementHeight,
elementHeight = _getLayoutInfo$elemen2 === void 0 ? 1 : _getLayoutInfo$elemen2,
_getLayoutInfo$column = _getLayoutInfo.columnsCount,
columnsCount = _getLayoutInfo$column === void 0 ? 1 : _getLayoutInfo$column,
_getLayoutInfo$rowsCo = _getLayoutInfo.rowsCount,
rowsCount = _getLayoutInfo$rowsCo === void 0 ? 1 : _getLayoutInfo$rowsCo,
_getLayoutInfo$rowGap = _getLayoutInfo.rowGap,
rowGap = _getLayoutInfo$rowGap === void 0 ? 0 : _getLayoutInfo$rowGap;
animationFramesIds.current.resize = null;
if (elementWidth === 0 || elementHeight === 0) {
return;
}
setLayoutInfo({
elementHeight: elementHeight,
columnsCount: columnsCount,
rowsCount: rowsCount,
rowGap: rowGap
});
});
}, [columnMinWidth]);
var scrollToItem = useCallback(function (_ref2) {
var key = _ref2.key,
index = _ref2.index;
if ((key || index) && items.length > 0) {
var itemIndex = index || items.findIndex(function (item) {
return getItemKey(item) === key;
});
if (itemIndex > -1) {
var _gridContainerRef$cur;
var itemRow = Math.floor(itemIndex / layoutInfo.columnsCount);
var itemOffset = itemRow * gappedElementHeight;
scrollableElementRef.current.scrollTo({
top: (((_gridContainerRef$cur = gridContainerRef.current) === null || _gridContainerRef$cur === void 0 ? void 0 : _gridContainerRef$cur.offsetTop) || 0) + itemOffset,
behavior: 'smooth'
});
}
}
}, [layoutInfo.columnsCount, gappedElementHeight, items]);
var handleScroll = useCallback(function (e) {
var _target$scrollTop;
if (isUnMounting.current) {
return;
}
if (animationFramesIds.current.scroll) {
cancelAnimationFrame(animationFramesIds.current.scroll);
animationFramesIds.current.scroll = null;
}
var target = e.currentTarget;
var scrollTopValue = target ? (_target$scrollTop = target.scrollTop) !== null && _target$scrollTop !== void 0 ? _target$scrollTop : target.scrollY : 0;
var _ref3 = gridContainerRef.current || {},
_ref3$offsetTop = _ref3.offsetTop,
offsetTop = _ref3$offsetTop === void 0 ? 0 : _ref3$offsetTop,
_ref3$offsetHeight = _ref3.offsetHeight,
offsetHeight = _ref3$offsetHeight === void 0 ? 0 : _ref3$offsetHeight;
var scrollTopRelativeToGridContainer = scrollTopValue - offsetTop;
animationFramesIds.current.scroll = requestAnimationFrame(function () {
animationFramesIds.current.scroll = null;
// TODO: Check maybe we shouldn't trigger change in state unless the row is almost getting to change for avoiding additional rerender?.
// But maybe it won't make the component's scroll smooth so it's need a check to make sure of that.
setScrollTop(Math.min(Math.max(0, scrollTopRelativeToGridContainer), offsetHeight));
});
}, []);
var handleGridContainerClick = useCallback(function (e) {
if (e.target !== e.currentTarget && stopChildEventsPropagation) {
e.stopPropagation();
}
}, []);
useEffect(function () {
if (apiRef) {
apiRef.current = _objectSpread(_objectSpread({}, apiRef.current), {}, {
scrollToItem: scrollToItem
});
}
}, [scrollToItem]);
useEffect(function () {
isUnMounting.current = false;
scrollableElementRef.current = getScrollableParent(gridContainerRef.current);
var scrollableElement = scrollableElementRef.current;
scrollableElement.addEventListener('scroll', handleScroll);
return function () {
scrollableElement.removeEventListener('scroll', handleScroll);
isUnMounting.current = true;
cancelAnimationFrame(animationFramesIds.current.scroll);
cancelAnimationFrame(animationFramesIds.current.resize);
};
}, [containerHeight]);
useEffect(function () {
window.addEventListener('resize', calculateLayoutInfo);
var gridContainer = gridContainerRef.current;
var resizeObserver;
if (gridContainer) {
resizeObserver = new ResizeObserver(calculateLayoutInfo);
resizeObserver.observe(gridContainer);
}
return function () {
window.removeEventListener('resize', calculateLayoutInfo);
if (resizeObserver) {
resizeObserver.disconnect();
}
};
}, [calculateLayoutInfo]);
var renderItem = useCallback(function (item, index) {
return /*#__PURE__*/_jsx(VirtualGridItem, {
itemPropName: injectedItemPropName,
item: item,
index: index,
children: children
}, getItemKey(item, index));
}, [children, getItemKey, injectedItemPropName]);
var startItemIndex = Math.max(0, Math.min(rowsOffset * layoutInfo.columnsCount, items.length - layoutInfo.columnsCount));
var visibleItemsCount = useMemo(function () {
return layoutInfo.rowsCount * layoutInfo.columnsCount + overscan * layoutInfo.columnsCount * 2;
}, [layoutInfo.rowsCount, layoutInfo.columnsCount, overscan]);
return /*#__PURE__*/_jsx(StyledVirtualGrid.RootContainer, {
children: /*#__PURE__*/_jsx(StyledVirtualGrid.GridContainer, {
ref: gridContainerRef,
onClick: handleGridContainerClick,
$transform: offsetY,
$height: containerHeight,
columnMinWidth: columnMinWidth,
children: items.slice(startItemIndex, startItemIndex + visibleItemsCount).map(renderItem)
})
});
};
export default /*#__PURE__*/memo(VirtualGrid);