neue Homepage auf react basis

This commit is contained in:
2026-08-07 21:39:30 +02:00
parent 164bdd19ad
commit ee89442c04
52191 changed files with 1230242 additions and 58 deletions
File diff suppressed because it is too large Load Diff
+23
View File
@@ -0,0 +1,23 @@
# License
MIT License
Copyright (c) 2020 Material-UI SAS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+3
View File
@@ -0,0 +1,3 @@
# x-virtualizer
Virtualization engine
+22
View File
@@ -0,0 +1,22 @@
export declare const DEFAULT_COLUMNS: {
field: string;
}[];
export declare const DEFAULT_PARAMS: {
resizeThrottleMs: number;
columns: {
field: string;
}[];
dimensions: {
autoHeight: boolean;
columnsTotalWidth: number;
leftPinnedWidth: number;
rightPinnedWidth: number;
topPinnedHeight: number;
bottomPinnedHeight: number;
};
virtualization: {
isRtl: boolean;
rowBufferPx: number;
columnBufferPx: number;
};
};
+22
View File
@@ -0,0 +1,22 @@
export declare const DEFAULT_COLUMNS: {
field: string;
}[];
export declare const DEFAULT_PARAMS: {
resizeThrottleMs: number;
columns: {
field: string;
}[];
dimensions: {
autoHeight: boolean;
columnsTotalWidth: number;
leftPinnedWidth: number;
rightPinnedWidth: number;
topPinnedHeight: number;
bottomPinnedHeight: number;
};
virtualization: {
isRtl: boolean;
rowBufferPx: number;
columnBufferPx: number;
};
};
+26
View File
@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DEFAULT_PARAMS = exports.DEFAULT_COLUMNS = void 0;
const DEFAULT_COLUMNS = exports.DEFAULT_COLUMNS = [{
field: 'DEFAULT_COLUMN'
}];
const DEFAULT_PARAMS = exports.DEFAULT_PARAMS = {
resizeThrottleMs: 100,
columns: DEFAULT_COLUMNS,
dimensions: {
autoHeight: false,
columnsTotalWidth: 0,
leftPinnedWidth: 0,
rightPinnedWidth: 0,
topPinnedHeight: 0,
bottomPinnedHeight: 0
},
virtualization: {
isRtl: false,
rowBufferPx: 150,
columnBufferPx: 150
}
};
+20
View File
@@ -0,0 +1,20 @@
export const DEFAULT_COLUMNS = [{
field: 'DEFAULT_COLUMN'
}];
export const DEFAULT_PARAMS = {
resizeThrottleMs: 100,
columns: DEFAULT_COLUMNS,
dimensions: {
autoHeight: false,
columnsTotalWidth: 0,
leftPinnedWidth: 0,
rightPinnedWidth: 0,
topPinnedHeight: 0,
bottomPinnedHeight: 0
},
virtualization: {
isRtl: false,
rowBufferPx: 150,
columnBufferPx: 150
}
};
+32
View File
@@ -0,0 +1,32 @@
import { Store } from '@mui/x-internals/store';
import type { integer } from '@mui/x-internals/types';
import type { BaseState, ParamsWithDefaults } from "../useVirtualizer.mjs";
import type { ColumnWithWidth, RowId } from "../models/index.mjs";
import type { CellColSpanInfo } from "../models/colspan.mjs";
import { Virtualization } from "./virtualization/index.mjs";
type ColumnIndex = number;
type ColspanMap = Map<RowId, Record<ColumnIndex, CellColSpanInfo>>;
export type ColspanParams = {
enabled: boolean;
getColspan: (rowId: RowId, column: ColumnWithWidth, columnIndex: integer) => integer;
};
export declare const Colspan: {
initialize: typeof initializeState;
use: typeof useColspan;
selectors: {};
};
export declare namespace Colspan {
type State = {
colspanMap: ColspanMap;
};
type API = ReturnType<typeof useColspan>;
}
declare function initializeState(_params: ParamsWithDefaults): {
colspanMap: Map<any, any>;
};
declare function useColspan(store: Store<BaseState & Colspan.State>, params: ParamsWithDefaults, api: Virtualization.API): {
resetColSpan: () => void;
getCellColSpanInfo: (rowId: RowId, columnIndex: integer) => CellColSpanInfo | undefined;
calculateColSpan: (rowId: RowId, minFirstColumn: integer, maxLastColumn: integer, columns: ColumnWithWidth[]) => void;
};
export {};
+32
View File
@@ -0,0 +1,32 @@
import { Store } from '@mui/x-internals/store';
import type { integer } from '@mui/x-internals/types';
import type { BaseState, ParamsWithDefaults } from "../useVirtualizer.js";
import type { ColumnWithWidth, RowId } from "../models/index.js";
import type { CellColSpanInfo } from "../models/colspan.js";
import { Virtualization } from "./virtualization/index.js";
type ColumnIndex = number;
type ColspanMap = Map<RowId, Record<ColumnIndex, CellColSpanInfo>>;
export type ColspanParams = {
enabled: boolean;
getColspan: (rowId: RowId, column: ColumnWithWidth, columnIndex: integer) => integer;
};
export declare const Colspan: {
initialize: typeof initializeState;
use: typeof useColspan;
selectors: {};
};
export declare namespace Colspan {
type State = {
colspanMap: ColspanMap;
};
type API = ReturnType<typeof useColspan>;
}
declare function initializeState(_params: ParamsWithDefaults): {
colspanMap: Map<any, any>;
};
declare function useColspan(store: Store<BaseState & Colspan.State>, params: ParamsWithDefaults, api: Virtualization.API): {
resetColSpan: () => void;
getCellColSpanInfo: (rowId: RowId, columnIndex: integer) => CellColSpanInfo | undefined;
calculateColSpan: (rowId: RowId, minFirstColumn: integer, maxLastColumn: integer, columns: ColumnWithWidth[]) => void;
};
export {};
+95
View File
@@ -0,0 +1,95 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Colspan = void 0;
var _useEventCallback = _interopRequireDefault(require("@mui/utils/useEventCallback"));
/* eslint-disable import/export, @typescript-eslint/no-redeclare */
const selectors = {};
const Colspan = exports.Colspan = {
initialize: initializeState,
use: useColspan,
selectors
};
function initializeState(_params) {
return {
colspanMap: new Map()
};
}
function useColspan(store, params, api) {
const getColspan = params.colspan?.getColspan;
const resetColSpan = () => {
store.state.colspanMap = new Map();
};
const getCellColSpanInfo = (rowId, columnIndex) => {
return store.state.colspanMap.get(rowId)?.[columnIndex];
};
// Calculate `colSpan` for each cell in the row
const calculateColSpan = (0, _useEventCallback.default)(getColspan ? (rowId, minFirstColumn, maxLastColumn, columns) => {
for (let i = minFirstColumn; i < maxLastColumn; i += 1) {
const cellProps = calculateCellColSpan(store.state.colspanMap, i, rowId, minFirstColumn, maxLastColumn, columns, getColspan);
if (cellProps.colSpan > 1) {
i += cellProps.colSpan - 1;
}
}
} : () => {});
api.calculateColSpan = calculateColSpan;
return {
resetColSpan,
getCellColSpanInfo,
calculateColSpan
};
}
function calculateCellColSpan(lookup, columnIndex, rowId, minFirstColumnIndex, maxLastColumnIndex, columns, getColspan) {
const columnsLength = columns.length;
const column = columns[columnIndex];
const colSpan = getColspan(rowId, column, columnIndex);
if (!colSpan || colSpan === 1) {
setCellColSpanInfo(lookup, rowId, columnIndex, {
spannedByColSpan: false,
cellProps: {
colSpan: 1,
width: column.computedWidth
}
});
return {
colSpan: 1
};
}
let width = column.computedWidth;
for (let j = 1; j < colSpan; j += 1) {
const nextColumnIndex = columnIndex + j;
// Cells should be spanned only within their column section (left-pinned, right-pinned and unpinned).
if (nextColumnIndex >= minFirstColumnIndex && nextColumnIndex < maxLastColumnIndex) {
const nextColumn = columns[nextColumnIndex];
width += nextColumn.computedWidth;
setCellColSpanInfo(lookup, rowId, columnIndex + j, {
spannedByColSpan: true,
rightVisibleCellIndex: Math.min(columnIndex + colSpan, columnsLength - 1),
leftVisibleCellIndex: columnIndex
});
}
setCellColSpanInfo(lookup, rowId, columnIndex, {
spannedByColSpan: false,
cellProps: {
colSpan,
width
}
});
}
return {
colSpan
};
}
function setCellColSpanInfo(colspanMap, rowId, columnIndex, cellColSpanInfo) {
let columnInfo = colspanMap.get(rowId);
if (!columnInfo) {
columnInfo = {};
colspanMap.set(rowId, columnInfo);
}
columnInfo[columnIndex] = cellColSpanInfo;
}
+89
View File
@@ -0,0 +1,89 @@
import useEventCallback from '@mui/utils/useEventCallback';
/* eslint-disable import/export, @typescript-eslint/no-redeclare */
const selectors = {};
export const Colspan = {
initialize: initializeState,
use: useColspan,
selectors
};
function initializeState(_params) {
return {
colspanMap: new Map()
};
}
function useColspan(store, params, api) {
const getColspan = params.colspan?.getColspan;
const resetColSpan = () => {
store.state.colspanMap = new Map();
};
const getCellColSpanInfo = (rowId, columnIndex) => {
return store.state.colspanMap.get(rowId)?.[columnIndex];
};
// Calculate `colSpan` for each cell in the row
const calculateColSpan = useEventCallback(getColspan ? (rowId, minFirstColumn, maxLastColumn, columns) => {
for (let i = minFirstColumn; i < maxLastColumn; i += 1) {
const cellProps = calculateCellColSpan(store.state.colspanMap, i, rowId, minFirstColumn, maxLastColumn, columns, getColspan);
if (cellProps.colSpan > 1) {
i += cellProps.colSpan - 1;
}
}
} : () => {});
api.calculateColSpan = calculateColSpan;
return {
resetColSpan,
getCellColSpanInfo,
calculateColSpan
};
}
function calculateCellColSpan(lookup, columnIndex, rowId, minFirstColumnIndex, maxLastColumnIndex, columns, getColspan) {
const columnsLength = columns.length;
const column = columns[columnIndex];
const colSpan = getColspan(rowId, column, columnIndex);
if (!colSpan || colSpan === 1) {
setCellColSpanInfo(lookup, rowId, columnIndex, {
spannedByColSpan: false,
cellProps: {
colSpan: 1,
width: column.computedWidth
}
});
return {
colSpan: 1
};
}
let width = column.computedWidth;
for (let j = 1; j < colSpan; j += 1) {
const nextColumnIndex = columnIndex + j;
// Cells should be spanned only within their column section (left-pinned, right-pinned and unpinned).
if (nextColumnIndex >= minFirstColumnIndex && nextColumnIndex < maxLastColumnIndex) {
const nextColumn = columns[nextColumnIndex];
width += nextColumn.computedWidth;
setCellColSpanInfo(lookup, rowId, columnIndex + j, {
spannedByColSpan: true,
rightVisibleCellIndex: Math.min(columnIndex + colSpan, columnsLength - 1),
leftVisibleCellIndex: columnIndex
});
}
setCellColSpanInfo(lookup, rowId, columnIndex, {
spannedByColSpan: false,
cellProps: {
colSpan,
width
}
});
}
return {
colSpan
};
}
function setCellColSpanInfo(colspanMap, rowId, columnIndex, cellColSpanInfo) {
let columnInfo = colspanMap.get(rowId);
if (!columnInfo) {
columnInfo = {};
colspanMap.set(rowId, columnInfo);
}
columnInfo[columnIndex] = cellColSpanInfo;
}
+59
View File
@@ -0,0 +1,59 @@
import { Store } from '@mui/x-internals/store';
import { ColumnWithWidth, DimensionsState, RowId, RowsMetaState, Size } from "../models/index.mjs";
import type { BaseState, ParamsWithDefaults } from "../useVirtualizer.mjs";
export type DimensionsParams = {
rowHeight: number;
columnsTotalWidth?: number;
leftPinnedWidth?: number;
rightPinnedWidth?: number;
topPinnedHeight?: number;
bottomPinnedHeight?: number;
autoHeight?: boolean;
minimalContentHeight?: number | string;
scrollbarSize?: number;
};
export declare const Dimensions: {
initialize: typeof initializeState;
use: typeof useDimensions;
selectors: {
rootSize: (state: BaseState) => Size;
dimensions: (state: BaseState) => DimensionsState;
rowHeight: (state: BaseState) => number;
columnsTotalWidth: (state: BaseState) => number;
contentHeight: (state: BaseState) => number;
autoHeight: (state: BaseState) => boolean;
minimalContentHeight: (state: BaseState) => string | number | undefined;
rowsMeta: (state: BaseState) => RowsMetaState;
rowPositions: (state: BaseState) => number[];
columnPositions: (_: any, columns: ColumnWithWidth[]) => number[];
needsHorizontalScrollbar: (state: BaseState) => boolean;
needsVerticalScrollbar: (state: BaseState) => boolean;
};
};
export declare namespace Dimensions {
type State = {
rootSize: Size;
dimensions: DimensionsState;
rowsMeta: RowsMetaState;
rowHeights: Map<any, any>;
};
type API = ReturnType<typeof useDimensions>;
}
declare function initializeState(params: ParamsWithDefaults): Dimensions.State;
declare function useDimensions(store: Store<BaseState>, params: ParamsWithDefaults, _api: {}): {
updateDimensions: (firstUpdate?: boolean) => void;
debouncedUpdateDimensions: (((firstUpdate?: boolean) => void) & import("@mui/x-internals/throttle").Cancelable) | undefined;
rowsMeta: {
getRowHeight: (rowId: RowId) => any;
setLastMeasuredRowIndex: (index: number) => void;
storeRowHeightMeasurement: (id: RowId, height: number) => void;
hydrateRowsMeta: () => void;
observeRowHeight: (element: Element, rowId: RowId) => () => void | undefined;
rowHasAutoHeight: (id: RowId) => any;
getRowHeightEntry: (rowId: RowId) => any;
getLastMeasuredRowIndex: () => number;
resetRowHeights: () => void;
};
};
export declare function observeRootNode(node: Element | null, store: Store<BaseState>, setRootSize: (size: Size) => void): (() => void) | undefined;
export {};
+59
View File
@@ -0,0 +1,59 @@
import { Store } from '@mui/x-internals/store';
import { ColumnWithWidth, DimensionsState, RowId, RowsMetaState, Size } from "../models/index.js";
import type { BaseState, ParamsWithDefaults } from "../useVirtualizer.js";
export type DimensionsParams = {
rowHeight: number;
columnsTotalWidth?: number;
leftPinnedWidth?: number;
rightPinnedWidth?: number;
topPinnedHeight?: number;
bottomPinnedHeight?: number;
autoHeight?: boolean;
minimalContentHeight?: number | string;
scrollbarSize?: number;
};
export declare const Dimensions: {
initialize: typeof initializeState;
use: typeof useDimensions;
selectors: {
rootSize: (state: BaseState) => Size;
dimensions: (state: BaseState) => DimensionsState;
rowHeight: (state: BaseState) => number;
columnsTotalWidth: (state: BaseState) => number;
contentHeight: (state: BaseState) => number;
autoHeight: (state: BaseState) => boolean;
minimalContentHeight: (state: BaseState) => string | number | undefined;
rowsMeta: (state: BaseState) => RowsMetaState;
rowPositions: (state: BaseState) => number[];
columnPositions: (_: any, columns: ColumnWithWidth[]) => number[];
needsHorizontalScrollbar: (state: BaseState) => boolean;
needsVerticalScrollbar: (state: BaseState) => boolean;
};
};
export declare namespace Dimensions {
type State = {
rootSize: Size;
dimensions: DimensionsState;
rowsMeta: RowsMetaState;
rowHeights: Map<any, any>;
};
type API = ReturnType<typeof useDimensions>;
}
declare function initializeState(params: ParamsWithDefaults): Dimensions.State;
declare function useDimensions(store: Store<BaseState>, params: ParamsWithDefaults, _api: {}): {
updateDimensions: (firstUpdate?: boolean) => void;
debouncedUpdateDimensions: (((firstUpdate?: boolean) => void) & import("@mui/x-internals/throttle").Cancelable) | undefined;
rowsMeta: {
getRowHeight: (rowId: RowId) => any;
setLastMeasuredRowIndex: (index: number) => void;
storeRowHeightMeasurement: (id: RowId, height: number) => void;
hydrateRowsMeta: () => void;
observeRowHeight: (element: Element, rowId: RowId) => () => void | undefined;
rowHasAutoHeight: (id: RowId) => any;
getRowHeightEntry: (rowId: RowId) => any;
getLastMeasuredRowIndex: () => number;
resetRowHeights: () => void;
};
};
export declare function observeRootNode(node: Element | null, store: Store<BaseState>, setRootSize: (size: Size) => void): (() => void) | undefined;
export {};
+631
View File
@@ -0,0 +1,631 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Dimensions = void 0;
exports.observeRootNode = observeRootNode;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _ownerDocument = _interopRequireDefault(require("@mui/utils/ownerDocument"));
var _useLazyRef = _interopRequireDefault(require("@mui/utils/useLazyRef"));
var _useEnhancedEffect = _interopRequireDefault(require("@mui/utils/useEnhancedEffect"));
var _useEventCallback = _interopRequireDefault(require("@mui/utils/useEventCallback"));
var _throttle = require("@mui/x-internals/throttle");
var _isDeepEqual = require("@mui/x-internals/isDeepEqual");
var _math = require("@mui/x-internals/math");
var _store = require("@mui/x-internals/store");
var _models = require("../models");
/* eslint-disable import/export, @typescript-eslint/no-redeclare */
/* eslint-disable no-underscore-dangle */
// Max time between hasScrollY flips that still counts as the same render
// chain. Feedback loops (#20539) flip within one browser frame; user-paced
// resize (#22510) flips are separated by ResizeObserver ticks + resizeThrottleMs.
const OSCILLATION_FLIP_WINDOW_MS = 100;
const EMPTY_DIMENSIONS = {
isReady: false,
root: _models.Size.EMPTY,
viewportOuterSize: _models.Size.EMPTY,
viewportInnerSize: _models.Size.EMPTY,
contentSize: _models.Size.EMPTY,
minimumSize: _models.Size.EMPTY,
hasScrollX: false,
hasScrollY: false,
scrollbarSize: 0,
rowWidth: 0,
rowHeight: 0,
columnsTotalWidth: 0,
leftPinnedWidth: 0,
rightPinnedWidth: 0,
topContainerHeight: 0,
bottomContainerHeight: 0,
autoHeight: false,
minimalContentHeight: undefined
};
const selectors = {
rootSize: state => state.rootSize,
dimensions: state => state.dimensions,
rowHeight: state => state.dimensions.rowHeight,
columnsTotalWidth: state => state.dimensions.columnsTotalWidth,
contentHeight: state => state.dimensions.contentSize.height,
autoHeight: state => state.dimensions.autoHeight,
minimalContentHeight: state => state.dimensions.minimalContentHeight,
rowsMeta: state => state.rowsMeta,
rowPositions: state => state.rowsMeta.positions,
columnPositions: (0, _store.createSelectorMemoized)((_, columns) => {
const positions = [];
let currentPosition = 0;
for (let i = 0; i < columns.length; i += 1) {
positions.push(currentPosition);
currentPosition += columns[i].computedWidth;
}
return positions;
}),
needsHorizontalScrollbar: state => state.dimensions.viewportInnerSize.width > 0 && state.dimensions.columnsTotalWidth > state.dimensions.viewportInnerSize.width,
needsVerticalScrollbar: state => state.dimensions.viewportInnerSize.height > 0 && state.dimensions.contentSize.height > state.dimensions.viewportInnerSize.height
};
const Dimensions = exports.Dimensions = {
initialize: initializeState,
use: useDimensions,
selectors
};
function initializeState(params) {
const {
rowCount,
rows,
getRowHeight,
dimensions: dimensionsParams
} = params;
const {
columnsTotalWidth,
rowHeight,
autoHeight,
minimalContentHeight,
topPinnedHeight,
bottomPinnedHeight
} = dimensionsParams;
// Calculate the initial content height and row positions so the
// initial render gets the correct size.
const positions = [];
let currentPageTotalHeight = 0;
if (getRowHeight && rows.length > 0) {
for (let i = 0; i < rows.length; i += 1) {
positions.push(currentPageTotalHeight);
const height = getRowHeight(rows[i]);
currentPageTotalHeight += typeof height === 'number' ? height : rowHeight;
}
} else {
for (let i = 0; i < rowCount; i += 1) {
positions.push(i * rowHeight);
}
currentPageTotalHeight = rowCount * rowHeight;
}
// Reflect the pinned zone sizes in the container heights at initialization, mirroring
// `updateDimensions`. The pinned rows' measured height is still 0 in `rowsMeta`
// below (pinned rows are measured later), so each container height is just its static
// pinned size.
const topContainerHeight = topPinnedHeight;
const bottomContainerHeight = bottomPinnedHeight;
const dimensions = (0, _extends2.default)({}, EMPTY_DIMENSIONS, dimensionsParams, {
autoHeight,
minimalContentHeight,
topContainerHeight,
bottomContainerHeight,
contentSize: {
width: columnsTotalWidth,
height: (0, _math.roundToDecimalPlaces)(currentPageTotalHeight, 1)
}
});
const rowsMeta = {
currentPageTotalHeight,
positions,
pinnedTopRowsTotalHeight: 0,
pinnedBottomRowsTotalHeight: 0
};
const rowHeights = new Map();
return {
rootSize: _models.Size.EMPTY,
dimensions,
rowsMeta,
rowHeights
};
}
function useDimensions(store, params, _api) {
const isFirstSizing = React.useRef(true);
// Vertical scrollbar oscillation detector. Counts consecutive hasScrollY
// flips with no row-height change. After 2 flips within
// OSCILLATION_FLIP_WINDOW_MS it is a layout feedback loop, so hasScrollY is
// forced off. The counter resets on row-height changes or when the previous
// flip is older than the window (user-paced resize, not a loop).
// Only vertical scrollbar can oscillate because column widths are never 'auto'.
// https://github.com/mui/mui-x/issues/20539
// https://github.com/mui/mui-x/issues/22510
const scrollYOscillation = React.useRef({
counter: 0,
heights: {
content: 0,
pinnedTop: 0,
pinnedBottom: 0
},
lastFlipTimestamp: 0
});
const {
layout,
dimensions: {
rowHeight,
columnsTotalWidth,
leftPinnedWidth,
rightPinnedWidth,
topPinnedHeight,
bottomPinnedHeight
},
onResize
} = params;
const updateDimensions = React.useCallback(firstUpdate => {
if (firstUpdate) {
isFirstSizing.current = false;
}
if (isFirstSizing.current) {
return;
}
const containerNode = layout.refs.container.current;
const rootSize = selectors.rootSize(store.state);
const rowsMeta = selectors.rowsMeta(store.state);
// All the floating point dimensions should be rounded to .1 decimal places to avoid subpixel rendering issues
// https://github.com/mui/mui-x/issues/9550#issuecomment-1619020477
// https://github.com/mui/mui-x/issues/15721
// Prefer measuring on a virtual-scrollbar widget when the layout exposes
// one, because its `scrollbar-width` / `::-webkit-scrollbar` styling may
// differ from the rest of the document and is what actually drives the
// size we care about for layout math.
const scrollbarMeasurementNode = layout.refs.scrollbarVertical?.current ?? layout.refs.scrollbarHorizontal?.current ?? containerNode;
const scrollbarSize = measureScrollbarSize(scrollbarMeasurementNode, params.dimensions.scrollbarSize);
const topContainerHeight = topPinnedHeight + rowsMeta.pinnedTopRowsTotalHeight;
const bottomContainerHeight = bottomPinnedHeight + rowsMeta.pinnedBottomRowsTotalHeight;
const contentSize = {
width: columnsTotalWidth,
height: (0, _math.roundToDecimalPlaces)(rowsMeta.currentPageTotalHeight, 1)
};
const prevDimensions = store.state.dimensions;
let viewportOuterSize;
let viewportInnerSize;
let hasScrollX = false;
let hasScrollY = false;
if (params.dimensions.autoHeight) {
hasScrollY = false;
hasScrollX = Math.round(columnsTotalWidth) > Math.round(rootSize.width);
viewportOuterSize = {
width: rootSize.width,
height: topContainerHeight + bottomContainerHeight + contentSize.height
};
viewportInnerSize = {
width: Math.max(0, viewportOuterSize.width - (hasScrollY ? scrollbarSize : 0)),
height: Math.max(0, viewportOuterSize.height - (hasScrollX ? scrollbarSize : 0))
};
} else {
viewportOuterSize = {
width: rootSize.width,
height: rootSize.height
};
viewportInnerSize = {
width: Math.max(0, viewportOuterSize.width),
height: Math.max(0, viewportOuterSize.height - topContainerHeight - bottomContainerHeight)
};
const content = contentSize;
const container = viewportInnerSize;
const hasScrollXIfNoYScrollBar = content.width > container.width;
const hasScrollYIfNoXScrollBar = content.height > container.height;
if (hasScrollXIfNoYScrollBar || hasScrollYIfNoXScrollBar) {
hasScrollY = hasScrollYIfNoXScrollBar;
hasScrollX = content.width + (hasScrollY ? scrollbarSize : 0) > container.width;
// We recalculate the scroll y to consider the size of the x scrollbar.
if (hasScrollX) {
hasScrollY = content.height + scrollbarSize > container.height;
}
}
// Detect vertical scrollbar oscillation — caused by stale rootSize or
// the horizontal scrollbar's height cascading. See scrollYOscillation.
{
const osc = scrollYOscillation.current;
const heightsChanged = rowsMeta.currentPageTotalHeight !== osc.heights.content || rowsMeta.pinnedTopRowsTotalHeight !== osc.heights.pinnedTop || rowsMeta.pinnedBottomRowsTotalHeight !== osc.heights.pinnedBottom;
if (heightsChanged) {
osc.counter = 0;
osc.heights = {
content: rowsMeta.currentPageTotalHeight,
pinnedTop: rowsMeta.pinnedTopRowsTotalHeight,
pinnedBottom: rowsMeta.pinnedBottomRowsTotalHeight
};
}
if (prevDimensions.isReady && hasScrollY !== prevDimensions.hasScrollY) {
// performance.now is monotonic; Date.now can jump (NTP, clock change).
const now = performance.now();
if (now - osc.lastFlipTimestamp > OSCILLATION_FLIP_WINDOW_MS) {
osc.counter = 0;
}
osc.lastFlipTimestamp = now;
if (!heightsChanged) {
osc.counter += 1;
}
if (osc.counter >= 2) {
hasScrollY = false;
// Recompute hasScrollX without the vertical scrollbar's width impact,
// otherwise the cascade (hasScrollY → narrower viewport → hasScrollX)
// keeps the horizontal scrollbar/filler alive and the root keeps resizing.
hasScrollX = hasScrollXIfNoYScrollBar;
}
}
}
if (hasScrollY) {
viewportInnerSize.width -= scrollbarSize;
}
if (hasScrollX) {
viewportInnerSize.height -= scrollbarSize;
}
}
if (params.disableHorizontalScroll) {
hasScrollX = false;
}
if (params.disableVerticalScroll) {
hasScrollY = false;
}
const rowWidth = Math.max(viewportOuterSize.width, columnsTotalWidth + (hasScrollY ? scrollbarSize : 0));
const minimumSize = {
width: columnsTotalWidth,
height: topContainerHeight + contentSize.height + bottomContainerHeight
};
const newDimensions = {
isReady: true,
root: rootSize,
viewportOuterSize,
viewportInnerSize,
contentSize,
minimumSize,
hasScrollX,
hasScrollY,
scrollbarSize,
rowWidth,
rowHeight,
columnsTotalWidth,
leftPinnedWidth,
rightPinnedWidth,
topContainerHeight,
bottomContainerHeight,
autoHeight: params.dimensions.autoHeight,
minimalContentHeight: params.dimensions.minimalContentHeight
};
if ((0, _isDeepEqual.isDeepEqual)(prevDimensions, newDimensions)) {
return;
}
store.update({
dimensions: newDimensions
});
onResize?.(newDimensions.root);
}, [store, layout.refs.container, layout.refs.scrollbarHorizontal, layout.refs.scrollbarVertical, params.dimensions.scrollbarSize, params.dimensions.autoHeight, params.dimensions.minimalContentHeight, params.disableHorizontalScroll, params.disableVerticalScroll, onResize, rowHeight, columnsTotalWidth, leftPinnedWidth, rightPinnedWidth, topPinnedHeight, bottomPinnedHeight]);
const {
resizeThrottleMs
} = params;
const updateDimensionCallback = (0, _useEventCallback.default)(updateDimensions);
const debouncedUpdateDimensions = React.useMemo(() => resizeThrottleMs > 0 ? (0, _throttle.throttle)(updateDimensionCallback, resizeThrottleMs) : undefined, [resizeThrottleMs, updateDimensionCallback]);
React.useEffect(() => debouncedUpdateDimensions?.clear, [debouncedUpdateDimensions]);
(0, _useEnhancedEffect.default)(updateDimensions, [updateDimensions]);
(0, _useEnhancedEffect.default)(() => {
store.update({
dimensions: (0, _extends2.default)({}, store.state.dimensions, {
autoHeight: params.dimensions.autoHeight,
minimalContentHeight: params.dimensions.minimalContentHeight
})
});
}, [store, params.dimensions.autoHeight, params.dimensions.minimalContentHeight]);
const rowsMeta = useRowsMeta(store, params, updateDimensions);
return {
updateDimensions,
debouncedUpdateDimensions,
rowsMeta
};
}
function useRowsMeta(store, params, updateDimensions) {
const heightCache = store.state.rowHeights;
const {
rows,
getRowHeight: getRowHeightProp,
getRowSpacing,
getEstimatedRowHeight
} = params;
const lastMeasuredRowIndex = React.useRef(-1);
const hasRowWithAutoHeight = React.useRef(false);
const isHeightMetaValid = React.useRef(false);
const pinnedRows = params.pinnedRows;
const rowHeight = (0, _store.useStore)(store, selectors.rowHeight);
const getRowHeightEntry = (0, _useEventCallback.default)(rowId => {
let entry = heightCache.get(rowId);
if (entry === undefined) {
entry = {
content: store.state.dimensions.rowHeight,
spacingTop: 0,
spacingBottom: 0,
detail: 0,
autoHeight: false,
needsFirstMeasurement: true
};
heightCache.set(rowId, entry);
}
return entry;
});
const {
applyRowHeight
} = params;
const processHeightEntry = React.useCallback(row => {
// HACK: rowHeight trails behind the most up-to-date value just enough to
// mess the initial rowsMeta hydration :/
eslintUseValue(rowHeight);
const dimensions = selectors.dimensions(store.state);
const baseRowHeight = dimensions.rowHeight;
const entry = getRowHeightEntry(row.id);
if (!getRowHeightProp) {
entry.content = baseRowHeight;
entry.needsFirstMeasurement = false;
} else {
const rowHeightFromUser = getRowHeightProp(row);
if (rowHeightFromUser === 'auto') {
if (entry.needsFirstMeasurement) {
const estimatedRowHeight = getEstimatedRowHeight ? getEstimatedRowHeight(row) : baseRowHeight;
// If the row was not measured yet use the estimated row height
entry.content = estimatedRowHeight ?? baseRowHeight;
}
hasRowWithAutoHeight.current = true;
entry.autoHeight = true;
} else {
// Default back to base rowHeight if getRowHeight returns null value.
entry.content = rowHeightFromUser ?? dimensions.rowHeight;
entry.needsFirstMeasurement = false;
entry.autoHeight = false;
}
}
if (getRowSpacing) {
const spacing = getRowSpacing(row);
entry.spacingTop = spacing.top ?? 0;
entry.spacingBottom = spacing.bottom ?? 0;
} else {
entry.spacingTop = 0;
entry.spacingBottom = 0;
}
applyRowHeight?.(entry, row);
return entry;
}, [store, getRowHeightProp, getRowHeightEntry, getEstimatedRowHeight, rowHeight, getRowSpacing, applyRowHeight]);
const hydrateRowsMeta = React.useCallback(() => {
hasRowWithAutoHeight.current = false;
const pinnedTopRowsTotalHeight = pinnedRows?.top.reduce((acc, row) => {
const entry = processHeightEntry(row);
return acc + entry.content + entry.spacingTop + entry.spacingBottom + entry.detail;
}, 0) ?? 0;
const pinnedBottomRowsTotalHeight = pinnedRows?.bottom.reduce((acc, row) => {
const entry = processHeightEntry(row);
return acc + entry.content + entry.spacingTop + entry.spacingBottom + entry.detail;
}, 0) ?? 0;
const positions = [];
const currentPageTotalHeight = rows.reduce((acc, row) => {
positions.push(acc);
const entry = processHeightEntry(row);
const total = entry.content + entry.spacingTop + entry.spacingBottom + entry.detail;
return acc + total;
}, 0);
if (!hasRowWithAutoHeight.current) {
// No row has height=auto, so all rows are already measured
lastMeasuredRowIndex.current = Infinity;
}
const didHeightsChange = pinnedTopRowsTotalHeight !== store.state.rowsMeta.pinnedTopRowsTotalHeight || pinnedBottomRowsTotalHeight !== store.state.rowsMeta.pinnedBottomRowsTotalHeight || currentPageTotalHeight !== store.state.rowsMeta.currentPageTotalHeight;
const rowsMeta = {
currentPageTotalHeight,
positions,
pinnedTopRowsTotalHeight,
pinnedBottomRowsTotalHeight
};
store.set('rowsMeta', rowsMeta);
if (didHeightsChange) {
updateDimensions();
}
isHeightMetaValid.current = true;
}, [store, pinnedRows, rows, processHeightEntry, updateDimensions]);
const hydrateRowsMetaLatest = (0, _useEventCallback.default)(hydrateRowsMeta);
const getRowHeight = rowId => {
return heightCache.get(rowId)?.content ?? selectors.rowHeight(store.state);
};
const storeRowHeightMeasurement = (id, height) => {
const entry = getRowHeightEntry(id);
const didChange = entry.content !== height;
entry.needsFirstMeasurement = false;
entry.content = height;
isHeightMetaValid.current && (isHeightMetaValid.current = !didChange);
};
const rowHasAutoHeight = id => {
return heightCache.get(id)?.autoHeight ?? false;
};
const getLastMeasuredRowIndex = () => {
return lastMeasuredRowIndex.current;
};
const setLastMeasuredRowIndex = index => {
if (hasRowWithAutoHeight.current && index > lastMeasuredRowIndex.current) {
lastMeasuredRowIndex.current = index;
}
};
const resetRowHeights = () => {
heightCache.clear();
hydrateRowsMeta();
};
const resizeObserver = (0, _useLazyRef.default)(() => typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(entries => {
for (let i = 0; i < entries.length; i += 1) {
const entry = entries[i];
const height = entry.borderBoxSize && entry.borderBoxSize.length > 0 ? entry.borderBoxSize[0].blockSize : entry.contentRect.height;
const rowId = entry.target.__mui_id;
const focusedVirtualRowId = params.focusedVirtualCell?.()?.id;
if (focusedVirtualRowId === rowId && height === 0) {
// Focused virtual row has 0 height.
// We don't want to store it to avoid scroll jumping.
// https://github.com/mui/mui-x/issues/14726
return;
}
storeRowHeightMeasurement(rowId, height);
}
if (!isHeightMetaValid.current) {
// Avoids "ResizeObserver loop completed with undelivered notifications" error
requestAnimationFrame(() => {
hydrateRowsMetaLatest();
});
}
})).current;
const observeRowHeight = (element, rowId) => {
element.__mui_id = rowId;
resizeObserver?.observe(element);
return () => resizeObserver?.unobserve(element);
};
// The effect is used to build the rows meta data - currentPageTotalHeight and positions.
// Because of variable row height this is needed for the virtualization
(0, _useEnhancedEffect.default)(() => {
hydrateRowsMeta();
}, [hydrateRowsMeta]);
return {
getRowHeight,
setLastMeasuredRowIndex,
storeRowHeightMeasurement,
hydrateRowsMeta,
observeRowHeight,
rowHasAutoHeight,
getRowHeightEntry,
getLastMeasuredRowIndex,
resetRowHeights
};
}
function observeRootNode(node, store, setRootSize) {
if (!node) {
return undefined;
}
const bounds = node.getBoundingClientRect();
const initialSize = {
width: (0, _math.roundToDecimalPlaces)(bounds.width, 1),
height: (0, _math.roundToDecimalPlaces)(bounds.height, 1)
};
if (store.state.rootSize === _models.Size.EMPTY || !_models.Size.equals(initialSize, store.state.rootSize)) {
setRootSize(initialSize);
}
if (typeof ResizeObserver === 'undefined') {
return undefined;
}
const observer = new ResizeObserver(([entry]) => {
if (!entry) {
return;
}
const rootSize = {
width: (0, _math.roundToDecimalPlaces)(entry.contentRect.width, 1),
height: (0, _math.roundToDecimalPlaces)(entry.contentRect.height, 1)
};
if (!_models.Size.equals(rootSize, store.state.rootSize)) {
setRootSize(rootSize);
}
});
observer.observe(node);
return () => {
observer.disconnect();
};
}
const scrollbarSizeCache = new WeakMap();
function measureScrollbarSize(element, scrollbarSize) {
if (scrollbarSize !== undefined) {
return scrollbarSize;
}
if (element === null) {
return 0;
}
const htmlElement = element;
const doc = (0, _ownerDocument.default)(element);
const view = doc.defaultView;
// We don't expect the scrollbar size styles to change, so we can cache the size and reuse it on every dimensions update.
// The scrollbar size is expected to change when the browser zoom or display scale changes while the element stays mounted, which `devicePixelRatio` reflects.
// Other layout changes (container resize, row/column updates) keep the same `devicePixelRatio`,
// so we can reuse the cached size and skip re-measuring the DOM (`getComputedStyle` + forced reflow) on every dimensions update.
//
// Only a value measured directly from the element is authoritative: it reflects the real scrollbar, including
// `::-webkit-scrollbar` pseudo styling that the probe-div fallback can't replicate. A cached probe estimate must
// not short-circuit here, otherwise it would mask the real size once the element becomes scrollable.
const devicePixelRatio = view?.devicePixelRatio ?? 1;
const cached = scrollbarSizeCache.get(element);
if (cached !== undefined && cached.devicePixelRatio === devicePixelRatio && cached.measuredDirectly) {
return cached.size;
}
const computed = view?.getComputedStyle(htmlElement);
// First, try measuring `element` directly. When `element` is a scroll widget
// that already has overflowing content (the typical case for the timeline's
// virtual scrollbars), its rendered scrollbar reflects whatever
// `scrollbar-width` / `::-webkit-scrollbar` styling is applied to *this*
// element, which is exactly what we need.
const canScrollY = computed?.overflowY === 'auto' || computed?.overflowY === 'scroll';
const canScrollX = computed?.overflowX === 'auto' || computed?.overflowX === 'scroll';
const hasScrollY = canScrollY && htmlElement.scrollHeight > htmlElement.clientHeight;
const hasScrollX = canScrollX && htmlElement.scrollWidth > htmlElement.clientWidth;
// `offsetWidth` / `offsetHeight` include borders, while `clientWidth` /
// `clientHeight` do not. Subtract borders so direct measurement only returns
// the scrollbar size.
const borderWidth = parseCSSPixelValue(computed?.borderLeftWidth) + parseCSSPixelValue(computed?.borderRightWidth);
const borderHeight = parseCSSPixelValue(computed?.borderTopWidth) + parseCSSPixelValue(computed?.borderBottomWidth);
const directSize = Math.max(hasScrollY ? htmlElement.offsetWidth - htmlElement.clientWidth - borderWidth : 0, hasScrollX ? htmlElement.offsetHeight - htmlElement.clientHeight - borderHeight : 0);
if (hasScrollY || hasScrollX) {
const size = Math.max(0, directSize);
scrollbarSizeCache.set(element, {
size,
devicePixelRatio,
measuredDirectly: true
});
return size;
}
// The element isn't scrollable yet, so it can't be measured directly. Reuse a
// probe estimate cached at the same `devicePixelRatio` to avoid re-running the
// (expensive) probe on every dimensions update while the element stays
// non-scrollable. Once it becomes scrollable, the direct measurement above
// takes over and replaces this estimate.
if (cached !== undefined && cached.devicePixelRatio === devicePixelRatio) {
return cached.size;
}
// Fall back to a probe div appended to `element`. `scrollbar-width` is not
// inherited, so copy it from the target element's computed style; otherwise
// a parent that opts into `scrollbar-width: thin` would still be measured
// with default scrollbar size.
const scrollDiv = doc.createElement('div');
scrollDiv.style.width = '99px';
scrollDiv.style.height = '99px';
scrollDiv.style.position = 'absolute';
scrollDiv.style.overflow = 'scroll';
if (computed?.scrollbarWidth) {
scrollDiv.style.scrollbarWidth = computed.scrollbarWidth;
}
scrollDiv.className = 'scrollDiv';
element.appendChild(scrollDiv);
const size = scrollDiv.offsetWidth - scrollDiv.clientWidth;
element.removeChild(scrollDiv);
scrollbarSizeCache.set(element, {
size,
devicePixelRatio,
measuredDirectly: false
});
return size;
}
function parseCSSPixelValue(value) {
const parsedValue = Number.parseFloat(value ?? '0');
return Number.isNaN(parsedValue) ? 0 : parsedValue;
}
function eslintUseValue(_) {}
+623
View File
@@ -0,0 +1,623 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import ownerDocument from '@mui/utils/ownerDocument';
import useLazyRef from '@mui/utils/useLazyRef';
import useLayoutEffect from '@mui/utils/useEnhancedEffect';
import useEventCallback from '@mui/utils/useEventCallback';
import { throttle } from '@mui/x-internals/throttle';
import { isDeepEqual } from '@mui/x-internals/isDeepEqual';
import { roundToDecimalPlaces } from '@mui/x-internals/math';
import { useStore, createSelectorMemoized } from '@mui/x-internals/store';
import { Size } from "../models/index.mjs";
/* eslint-disable import/export, @typescript-eslint/no-redeclare */
/* eslint-disable no-underscore-dangle */
// Max time between hasScrollY flips that still counts as the same render
// chain. Feedback loops (#20539) flip within one browser frame; user-paced
// resize (#22510) flips are separated by ResizeObserver ticks + resizeThrottleMs.
const OSCILLATION_FLIP_WINDOW_MS = 100;
const EMPTY_DIMENSIONS = {
isReady: false,
root: Size.EMPTY,
viewportOuterSize: Size.EMPTY,
viewportInnerSize: Size.EMPTY,
contentSize: Size.EMPTY,
minimumSize: Size.EMPTY,
hasScrollX: false,
hasScrollY: false,
scrollbarSize: 0,
rowWidth: 0,
rowHeight: 0,
columnsTotalWidth: 0,
leftPinnedWidth: 0,
rightPinnedWidth: 0,
topContainerHeight: 0,
bottomContainerHeight: 0,
autoHeight: false,
minimalContentHeight: undefined
};
const selectors = {
rootSize: state => state.rootSize,
dimensions: state => state.dimensions,
rowHeight: state => state.dimensions.rowHeight,
columnsTotalWidth: state => state.dimensions.columnsTotalWidth,
contentHeight: state => state.dimensions.contentSize.height,
autoHeight: state => state.dimensions.autoHeight,
minimalContentHeight: state => state.dimensions.minimalContentHeight,
rowsMeta: state => state.rowsMeta,
rowPositions: state => state.rowsMeta.positions,
columnPositions: createSelectorMemoized((_, columns) => {
const positions = [];
let currentPosition = 0;
for (let i = 0; i < columns.length; i += 1) {
positions.push(currentPosition);
currentPosition += columns[i].computedWidth;
}
return positions;
}),
needsHorizontalScrollbar: state => state.dimensions.viewportInnerSize.width > 0 && state.dimensions.columnsTotalWidth > state.dimensions.viewportInnerSize.width,
needsVerticalScrollbar: state => state.dimensions.viewportInnerSize.height > 0 && state.dimensions.contentSize.height > state.dimensions.viewportInnerSize.height
};
export const Dimensions = {
initialize: initializeState,
use: useDimensions,
selectors
};
function initializeState(params) {
const {
rowCount,
rows,
getRowHeight,
dimensions: dimensionsParams
} = params;
const {
columnsTotalWidth,
rowHeight,
autoHeight,
minimalContentHeight,
topPinnedHeight,
bottomPinnedHeight
} = dimensionsParams;
// Calculate the initial content height and row positions so the
// initial render gets the correct size.
const positions = [];
let currentPageTotalHeight = 0;
if (getRowHeight && rows.length > 0) {
for (let i = 0; i < rows.length; i += 1) {
positions.push(currentPageTotalHeight);
const height = getRowHeight(rows[i]);
currentPageTotalHeight += typeof height === 'number' ? height : rowHeight;
}
} else {
for (let i = 0; i < rowCount; i += 1) {
positions.push(i * rowHeight);
}
currentPageTotalHeight = rowCount * rowHeight;
}
// Reflect the pinned zone sizes in the container heights at initialization, mirroring
// `updateDimensions`. The pinned rows' measured height is still 0 in `rowsMeta`
// below (pinned rows are measured later), so each container height is just its static
// pinned size.
const topContainerHeight = topPinnedHeight;
const bottomContainerHeight = bottomPinnedHeight;
const dimensions = _extends({}, EMPTY_DIMENSIONS, dimensionsParams, {
autoHeight,
minimalContentHeight,
topContainerHeight,
bottomContainerHeight,
contentSize: {
width: columnsTotalWidth,
height: roundToDecimalPlaces(currentPageTotalHeight, 1)
}
});
const rowsMeta = {
currentPageTotalHeight,
positions,
pinnedTopRowsTotalHeight: 0,
pinnedBottomRowsTotalHeight: 0
};
const rowHeights = new Map();
return {
rootSize: Size.EMPTY,
dimensions,
rowsMeta,
rowHeights
};
}
function useDimensions(store, params, _api) {
const isFirstSizing = React.useRef(true);
// Vertical scrollbar oscillation detector. Counts consecutive hasScrollY
// flips with no row-height change. After 2 flips within
// OSCILLATION_FLIP_WINDOW_MS it is a layout feedback loop, so hasScrollY is
// forced off. The counter resets on row-height changes or when the previous
// flip is older than the window (user-paced resize, not a loop).
// Only vertical scrollbar can oscillate because column widths are never 'auto'.
// https://github.com/mui/mui-x/issues/20539
// https://github.com/mui/mui-x/issues/22510
const scrollYOscillation = React.useRef({
counter: 0,
heights: {
content: 0,
pinnedTop: 0,
pinnedBottom: 0
},
lastFlipTimestamp: 0
});
const {
layout,
dimensions: {
rowHeight,
columnsTotalWidth,
leftPinnedWidth,
rightPinnedWidth,
topPinnedHeight,
bottomPinnedHeight
},
onResize
} = params;
const updateDimensions = React.useCallback(firstUpdate => {
if (firstUpdate) {
isFirstSizing.current = false;
}
if (isFirstSizing.current) {
return;
}
const containerNode = layout.refs.container.current;
const rootSize = selectors.rootSize(store.state);
const rowsMeta = selectors.rowsMeta(store.state);
// All the floating point dimensions should be rounded to .1 decimal places to avoid subpixel rendering issues
// https://github.com/mui/mui-x/issues/9550#issuecomment-1619020477
// https://github.com/mui/mui-x/issues/15721
// Prefer measuring on a virtual-scrollbar widget when the layout exposes
// one, because its `scrollbar-width` / `::-webkit-scrollbar` styling may
// differ from the rest of the document and is what actually drives the
// size we care about for layout math.
const scrollbarMeasurementNode = layout.refs.scrollbarVertical?.current ?? layout.refs.scrollbarHorizontal?.current ?? containerNode;
const scrollbarSize = measureScrollbarSize(scrollbarMeasurementNode, params.dimensions.scrollbarSize);
const topContainerHeight = topPinnedHeight + rowsMeta.pinnedTopRowsTotalHeight;
const bottomContainerHeight = bottomPinnedHeight + rowsMeta.pinnedBottomRowsTotalHeight;
const contentSize = {
width: columnsTotalWidth,
height: roundToDecimalPlaces(rowsMeta.currentPageTotalHeight, 1)
};
const prevDimensions = store.state.dimensions;
let viewportOuterSize;
let viewportInnerSize;
let hasScrollX = false;
let hasScrollY = false;
if (params.dimensions.autoHeight) {
hasScrollY = false;
hasScrollX = Math.round(columnsTotalWidth) > Math.round(rootSize.width);
viewportOuterSize = {
width: rootSize.width,
height: topContainerHeight + bottomContainerHeight + contentSize.height
};
viewportInnerSize = {
width: Math.max(0, viewportOuterSize.width - (hasScrollY ? scrollbarSize : 0)),
height: Math.max(0, viewportOuterSize.height - (hasScrollX ? scrollbarSize : 0))
};
} else {
viewportOuterSize = {
width: rootSize.width,
height: rootSize.height
};
viewportInnerSize = {
width: Math.max(0, viewportOuterSize.width),
height: Math.max(0, viewportOuterSize.height - topContainerHeight - bottomContainerHeight)
};
const content = contentSize;
const container = viewportInnerSize;
const hasScrollXIfNoYScrollBar = content.width > container.width;
const hasScrollYIfNoXScrollBar = content.height > container.height;
if (hasScrollXIfNoYScrollBar || hasScrollYIfNoXScrollBar) {
hasScrollY = hasScrollYIfNoXScrollBar;
hasScrollX = content.width + (hasScrollY ? scrollbarSize : 0) > container.width;
// We recalculate the scroll y to consider the size of the x scrollbar.
if (hasScrollX) {
hasScrollY = content.height + scrollbarSize > container.height;
}
}
// Detect vertical scrollbar oscillation — caused by stale rootSize or
// the horizontal scrollbar's height cascading. See scrollYOscillation.
{
const osc = scrollYOscillation.current;
const heightsChanged = rowsMeta.currentPageTotalHeight !== osc.heights.content || rowsMeta.pinnedTopRowsTotalHeight !== osc.heights.pinnedTop || rowsMeta.pinnedBottomRowsTotalHeight !== osc.heights.pinnedBottom;
if (heightsChanged) {
osc.counter = 0;
osc.heights = {
content: rowsMeta.currentPageTotalHeight,
pinnedTop: rowsMeta.pinnedTopRowsTotalHeight,
pinnedBottom: rowsMeta.pinnedBottomRowsTotalHeight
};
}
if (prevDimensions.isReady && hasScrollY !== prevDimensions.hasScrollY) {
// performance.now is monotonic; Date.now can jump (NTP, clock change).
const now = performance.now();
if (now - osc.lastFlipTimestamp > OSCILLATION_FLIP_WINDOW_MS) {
osc.counter = 0;
}
osc.lastFlipTimestamp = now;
if (!heightsChanged) {
osc.counter += 1;
}
if (osc.counter >= 2) {
hasScrollY = false;
// Recompute hasScrollX without the vertical scrollbar's width impact,
// otherwise the cascade (hasScrollY → narrower viewport → hasScrollX)
// keeps the horizontal scrollbar/filler alive and the root keeps resizing.
hasScrollX = hasScrollXIfNoYScrollBar;
}
}
}
if (hasScrollY) {
viewportInnerSize.width -= scrollbarSize;
}
if (hasScrollX) {
viewportInnerSize.height -= scrollbarSize;
}
}
if (params.disableHorizontalScroll) {
hasScrollX = false;
}
if (params.disableVerticalScroll) {
hasScrollY = false;
}
const rowWidth = Math.max(viewportOuterSize.width, columnsTotalWidth + (hasScrollY ? scrollbarSize : 0));
const minimumSize = {
width: columnsTotalWidth,
height: topContainerHeight + contentSize.height + bottomContainerHeight
};
const newDimensions = {
isReady: true,
root: rootSize,
viewportOuterSize,
viewportInnerSize,
contentSize,
minimumSize,
hasScrollX,
hasScrollY,
scrollbarSize,
rowWidth,
rowHeight,
columnsTotalWidth,
leftPinnedWidth,
rightPinnedWidth,
topContainerHeight,
bottomContainerHeight,
autoHeight: params.dimensions.autoHeight,
minimalContentHeight: params.dimensions.minimalContentHeight
};
if (isDeepEqual(prevDimensions, newDimensions)) {
return;
}
store.update({
dimensions: newDimensions
});
onResize?.(newDimensions.root);
}, [store, layout.refs.container, layout.refs.scrollbarHorizontal, layout.refs.scrollbarVertical, params.dimensions.scrollbarSize, params.dimensions.autoHeight, params.dimensions.minimalContentHeight, params.disableHorizontalScroll, params.disableVerticalScroll, onResize, rowHeight, columnsTotalWidth, leftPinnedWidth, rightPinnedWidth, topPinnedHeight, bottomPinnedHeight]);
const {
resizeThrottleMs
} = params;
const updateDimensionCallback = useEventCallback(updateDimensions);
const debouncedUpdateDimensions = React.useMemo(() => resizeThrottleMs > 0 ? throttle(updateDimensionCallback, resizeThrottleMs) : undefined, [resizeThrottleMs, updateDimensionCallback]);
React.useEffect(() => debouncedUpdateDimensions?.clear, [debouncedUpdateDimensions]);
useLayoutEffect(updateDimensions, [updateDimensions]);
useLayoutEffect(() => {
store.update({
dimensions: _extends({}, store.state.dimensions, {
autoHeight: params.dimensions.autoHeight,
minimalContentHeight: params.dimensions.minimalContentHeight
})
});
}, [store, params.dimensions.autoHeight, params.dimensions.minimalContentHeight]);
const rowsMeta = useRowsMeta(store, params, updateDimensions);
return {
updateDimensions,
debouncedUpdateDimensions,
rowsMeta
};
}
function useRowsMeta(store, params, updateDimensions) {
const heightCache = store.state.rowHeights;
const {
rows,
getRowHeight: getRowHeightProp,
getRowSpacing,
getEstimatedRowHeight
} = params;
const lastMeasuredRowIndex = React.useRef(-1);
const hasRowWithAutoHeight = React.useRef(false);
const isHeightMetaValid = React.useRef(false);
const pinnedRows = params.pinnedRows;
const rowHeight = useStore(store, selectors.rowHeight);
const getRowHeightEntry = useEventCallback(rowId => {
let entry = heightCache.get(rowId);
if (entry === undefined) {
entry = {
content: store.state.dimensions.rowHeight,
spacingTop: 0,
spacingBottom: 0,
detail: 0,
autoHeight: false,
needsFirstMeasurement: true
};
heightCache.set(rowId, entry);
}
return entry;
});
const {
applyRowHeight
} = params;
const processHeightEntry = React.useCallback(row => {
// HACK: rowHeight trails behind the most up-to-date value just enough to
// mess the initial rowsMeta hydration :/
eslintUseValue(rowHeight);
const dimensions = selectors.dimensions(store.state);
const baseRowHeight = dimensions.rowHeight;
const entry = getRowHeightEntry(row.id);
if (!getRowHeightProp) {
entry.content = baseRowHeight;
entry.needsFirstMeasurement = false;
} else {
const rowHeightFromUser = getRowHeightProp(row);
if (rowHeightFromUser === 'auto') {
if (entry.needsFirstMeasurement) {
const estimatedRowHeight = getEstimatedRowHeight ? getEstimatedRowHeight(row) : baseRowHeight;
// If the row was not measured yet use the estimated row height
entry.content = estimatedRowHeight ?? baseRowHeight;
}
hasRowWithAutoHeight.current = true;
entry.autoHeight = true;
} else {
// Default back to base rowHeight if getRowHeight returns null value.
entry.content = rowHeightFromUser ?? dimensions.rowHeight;
entry.needsFirstMeasurement = false;
entry.autoHeight = false;
}
}
if (getRowSpacing) {
const spacing = getRowSpacing(row);
entry.spacingTop = spacing.top ?? 0;
entry.spacingBottom = spacing.bottom ?? 0;
} else {
entry.spacingTop = 0;
entry.spacingBottom = 0;
}
applyRowHeight?.(entry, row);
return entry;
}, [store, getRowHeightProp, getRowHeightEntry, getEstimatedRowHeight, rowHeight, getRowSpacing, applyRowHeight]);
const hydrateRowsMeta = React.useCallback(() => {
hasRowWithAutoHeight.current = false;
const pinnedTopRowsTotalHeight = pinnedRows?.top.reduce((acc, row) => {
const entry = processHeightEntry(row);
return acc + entry.content + entry.spacingTop + entry.spacingBottom + entry.detail;
}, 0) ?? 0;
const pinnedBottomRowsTotalHeight = pinnedRows?.bottom.reduce((acc, row) => {
const entry = processHeightEntry(row);
return acc + entry.content + entry.spacingTop + entry.spacingBottom + entry.detail;
}, 0) ?? 0;
const positions = [];
const currentPageTotalHeight = rows.reduce((acc, row) => {
positions.push(acc);
const entry = processHeightEntry(row);
const total = entry.content + entry.spacingTop + entry.spacingBottom + entry.detail;
return acc + total;
}, 0);
if (!hasRowWithAutoHeight.current) {
// No row has height=auto, so all rows are already measured
lastMeasuredRowIndex.current = Infinity;
}
const didHeightsChange = pinnedTopRowsTotalHeight !== store.state.rowsMeta.pinnedTopRowsTotalHeight || pinnedBottomRowsTotalHeight !== store.state.rowsMeta.pinnedBottomRowsTotalHeight || currentPageTotalHeight !== store.state.rowsMeta.currentPageTotalHeight;
const rowsMeta = {
currentPageTotalHeight,
positions,
pinnedTopRowsTotalHeight,
pinnedBottomRowsTotalHeight
};
store.set('rowsMeta', rowsMeta);
if (didHeightsChange) {
updateDimensions();
}
isHeightMetaValid.current = true;
}, [store, pinnedRows, rows, processHeightEntry, updateDimensions]);
const hydrateRowsMetaLatest = useEventCallback(hydrateRowsMeta);
const getRowHeight = rowId => {
return heightCache.get(rowId)?.content ?? selectors.rowHeight(store.state);
};
const storeRowHeightMeasurement = (id, height) => {
const entry = getRowHeightEntry(id);
const didChange = entry.content !== height;
entry.needsFirstMeasurement = false;
entry.content = height;
isHeightMetaValid.current &&= !didChange;
};
const rowHasAutoHeight = id => {
return heightCache.get(id)?.autoHeight ?? false;
};
const getLastMeasuredRowIndex = () => {
return lastMeasuredRowIndex.current;
};
const setLastMeasuredRowIndex = index => {
if (hasRowWithAutoHeight.current && index > lastMeasuredRowIndex.current) {
lastMeasuredRowIndex.current = index;
}
};
const resetRowHeights = () => {
heightCache.clear();
hydrateRowsMeta();
};
const resizeObserver = useLazyRef(() => typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(entries => {
for (let i = 0; i < entries.length; i += 1) {
const entry = entries[i];
const height = entry.borderBoxSize && entry.borderBoxSize.length > 0 ? entry.borderBoxSize[0].blockSize : entry.contentRect.height;
const rowId = entry.target.__mui_id;
const focusedVirtualRowId = params.focusedVirtualCell?.()?.id;
if (focusedVirtualRowId === rowId && height === 0) {
// Focused virtual row has 0 height.
// We don't want to store it to avoid scroll jumping.
// https://github.com/mui/mui-x/issues/14726
return;
}
storeRowHeightMeasurement(rowId, height);
}
if (!isHeightMetaValid.current) {
// Avoids "ResizeObserver loop completed with undelivered notifications" error
requestAnimationFrame(() => {
hydrateRowsMetaLatest();
});
}
})).current;
const observeRowHeight = (element, rowId) => {
element.__mui_id = rowId;
resizeObserver?.observe(element);
return () => resizeObserver?.unobserve(element);
};
// The effect is used to build the rows meta data - currentPageTotalHeight and positions.
// Because of variable row height this is needed for the virtualization
useLayoutEffect(() => {
hydrateRowsMeta();
}, [hydrateRowsMeta]);
return {
getRowHeight,
setLastMeasuredRowIndex,
storeRowHeightMeasurement,
hydrateRowsMeta,
observeRowHeight,
rowHasAutoHeight,
getRowHeightEntry,
getLastMeasuredRowIndex,
resetRowHeights
};
}
export function observeRootNode(node, store, setRootSize) {
if (!node) {
return undefined;
}
const bounds = node.getBoundingClientRect();
const initialSize = {
width: roundToDecimalPlaces(bounds.width, 1),
height: roundToDecimalPlaces(bounds.height, 1)
};
if (store.state.rootSize === Size.EMPTY || !Size.equals(initialSize, store.state.rootSize)) {
setRootSize(initialSize);
}
if (typeof ResizeObserver === 'undefined') {
return undefined;
}
const observer = new ResizeObserver(([entry]) => {
if (!entry) {
return;
}
const rootSize = {
width: roundToDecimalPlaces(entry.contentRect.width, 1),
height: roundToDecimalPlaces(entry.contentRect.height, 1)
};
if (!Size.equals(rootSize, store.state.rootSize)) {
setRootSize(rootSize);
}
});
observer.observe(node);
return () => {
observer.disconnect();
};
}
const scrollbarSizeCache = new WeakMap();
function measureScrollbarSize(element, scrollbarSize) {
if (scrollbarSize !== undefined) {
return scrollbarSize;
}
if (element === null) {
return 0;
}
const htmlElement = element;
const doc = ownerDocument(element);
const view = doc.defaultView;
// We don't expect the scrollbar size styles to change, so we can cache the size and reuse it on every dimensions update.
// The scrollbar size is expected to change when the browser zoom or display scale changes while the element stays mounted, which `devicePixelRatio` reflects.
// Other layout changes (container resize, row/column updates) keep the same `devicePixelRatio`,
// so we can reuse the cached size and skip re-measuring the DOM (`getComputedStyle` + forced reflow) on every dimensions update.
//
// Only a value measured directly from the element is authoritative: it reflects the real scrollbar, including
// `::-webkit-scrollbar` pseudo styling that the probe-div fallback can't replicate. A cached probe estimate must
// not short-circuit here, otherwise it would mask the real size once the element becomes scrollable.
const devicePixelRatio = view?.devicePixelRatio ?? 1;
const cached = scrollbarSizeCache.get(element);
if (cached !== undefined && cached.devicePixelRatio === devicePixelRatio && cached.measuredDirectly) {
return cached.size;
}
const computed = view?.getComputedStyle(htmlElement);
// First, try measuring `element` directly. When `element` is a scroll widget
// that already has overflowing content (the typical case for the timeline's
// virtual scrollbars), its rendered scrollbar reflects whatever
// `scrollbar-width` / `::-webkit-scrollbar` styling is applied to *this*
// element, which is exactly what we need.
const canScrollY = computed?.overflowY === 'auto' || computed?.overflowY === 'scroll';
const canScrollX = computed?.overflowX === 'auto' || computed?.overflowX === 'scroll';
const hasScrollY = canScrollY && htmlElement.scrollHeight > htmlElement.clientHeight;
const hasScrollX = canScrollX && htmlElement.scrollWidth > htmlElement.clientWidth;
// `offsetWidth` / `offsetHeight` include borders, while `clientWidth` /
// `clientHeight` do not. Subtract borders so direct measurement only returns
// the scrollbar size.
const borderWidth = parseCSSPixelValue(computed?.borderLeftWidth) + parseCSSPixelValue(computed?.borderRightWidth);
const borderHeight = parseCSSPixelValue(computed?.borderTopWidth) + parseCSSPixelValue(computed?.borderBottomWidth);
const directSize = Math.max(hasScrollY ? htmlElement.offsetWidth - htmlElement.clientWidth - borderWidth : 0, hasScrollX ? htmlElement.offsetHeight - htmlElement.clientHeight - borderHeight : 0);
if (hasScrollY || hasScrollX) {
const size = Math.max(0, directSize);
scrollbarSizeCache.set(element, {
size,
devicePixelRatio,
measuredDirectly: true
});
return size;
}
// The element isn't scrollable yet, so it can't be measured directly. Reuse a
// probe estimate cached at the same `devicePixelRatio` to avoid re-running the
// (expensive) probe on every dimensions update while the element stays
// non-scrollable. Once it becomes scrollable, the direct measurement above
// takes over and replaces this estimate.
if (cached !== undefined && cached.devicePixelRatio === devicePixelRatio) {
return cached.size;
}
// Fall back to a probe div appended to `element`. `scrollbar-width` is not
// inherited, so copy it from the target element's computed style; otherwise
// a parent that opts into `scrollbar-width: thin` would still be measured
// with default scrollbar size.
const scrollDiv = doc.createElement('div');
scrollDiv.style.width = '99px';
scrollDiv.style.height = '99px';
scrollDiv.style.position = 'absolute';
scrollDiv.style.overflow = 'scroll';
if (computed?.scrollbarWidth) {
scrollDiv.style.scrollbarWidth = computed.scrollbarWidth;
}
scrollDiv.className = 'scrollDiv';
element.appendChild(scrollDiv);
const size = scrollDiv.offsetWidth - scrollDiv.clientWidth;
element.removeChild(scrollDiv);
scrollbarSizeCache.set(element, {
size,
devicePixelRatio,
measuredDirectly: false
});
return size;
}
function parseCSSPixelValue(value) {
const parsedValue = Number.parseFloat(value ?? '0');
return Number.isNaN(parsedValue) ? 0 : parsedValue;
}
function eslintUseValue(_) {}
+5
View File
@@ -0,0 +1,5 @@
export * from "./colspan.mjs";
export * from "./dimensions.mjs";
export * from "./keyboard.mjs";
export * from "./rowspan.mjs";
export * from "./virtualization/index.mjs";
+5
View File
@@ -0,0 +1,5 @@
export * from "./colspan.js";
export * from "./dimensions.js";
export * from "./keyboard.js";
export * from "./rowspan.js";
export * from "./virtualization/index.js";
+60
View File
@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _colspan = require("./colspan");
Object.keys(_colspan).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _colspan[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _colspan[key];
}
});
});
var _dimensions = require("./dimensions");
Object.keys(_dimensions).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _dimensions[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _dimensions[key];
}
});
});
var _keyboard = require("./keyboard");
Object.keys(_keyboard).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _keyboard[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _keyboard[key];
}
});
});
var _rowspan = require("./rowspan");
Object.keys(_rowspan).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _rowspan[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _rowspan[key];
}
});
});
var _virtualization = require("./virtualization");
Object.keys(_virtualization).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _virtualization[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _virtualization[key];
}
});
});
+5
View File
@@ -0,0 +1,5 @@
export * from "./colspan.mjs";
export * from "./dimensions.mjs";
export * from "./keyboard.mjs";
export * from "./rowspan.mjs";
export * from "./virtualization/index.mjs";
+16
View File
@@ -0,0 +1,16 @@
import { Store } from '@mui/x-internals/store';
import type { BaseState, ParamsWithDefaults } from "../useVirtualizer.mjs";
export declare const Keyboard: {
initialize: typeof initializeState;
use: typeof useKeyboard;
selectors: {};
};
export declare namespace Keyboard {
type State = {};
type API = ReturnType<typeof useKeyboard>;
}
declare function initializeState(_params: ParamsWithDefaults): Keyboard.State;
declare function useKeyboard(store: Store<BaseState & Keyboard.State>, params: ParamsWithDefaults, _api: {}): {
getViewportPageSize: () => number;
};
export {};
+16
View File
@@ -0,0 +1,16 @@
import { Store } from '@mui/x-internals/store';
import type { BaseState, ParamsWithDefaults } from "../useVirtualizer.js";
export declare const Keyboard: {
initialize: typeof initializeState;
use: typeof useKeyboard;
selectors: {};
};
export declare namespace Keyboard {
type State = {};
type API = ReturnType<typeof useKeyboard>;
}
declare function initializeState(_params: ParamsWithDefaults): Keyboard.State;
declare function useKeyboard(store: Store<BaseState & Keyboard.State>, params: ParamsWithDefaults, _api: {}): {
getViewportPageSize: () => number;
};
export {};
+40
View File
@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Keyboard = void 0;
var _dimensions = require("./dimensions");
var _virtualization = require("./virtualization");
/* eslint-disable import/export, @typescript-eslint/no-redeclare */
const selectors = {};
const Keyboard = exports.Keyboard = {
initialize: initializeState,
use: useKeyboard,
selectors
};
function initializeState(_params) {
return {};
}
function useKeyboard(store, params, _api) {
const getViewportPageSize = () => {
const dimensions = _dimensions.Dimensions.selectors.dimensions(store.state);
if (!dimensions.isReady) {
return 0;
}
// TODO: Use a combination of scrollTop, dimensions.viewportInnerSize.height and rowsMeta.possitions
// to find out the maximum number of rows that can fit in the visible part of the grid
if (params.getRowHeight) {
const renderContext = _virtualization.Virtualization.selectors.renderContext(store.state);
const viewportPageSize = renderContext.lastRowIndex - renderContext.firstRowIndex;
return Math.min(viewportPageSize - 1, params.rows.length);
}
const maximumPageSizeWithoutScrollBar = Math.floor(dimensions.viewportInnerSize.height / dimensions.rowHeight);
return Math.min(maximumPageSizeWithoutScrollBar, params.rows.length);
};
return {
getViewportPageSize
};
}
+35
View File
@@ -0,0 +1,35 @@
import { Dimensions } from "./dimensions.mjs";
import { Virtualization } from "./virtualization/index.mjs";
/* eslint-disable import/export, @typescript-eslint/no-redeclare */
const selectors = {};
export const Keyboard = {
initialize: initializeState,
use: useKeyboard,
selectors
};
function initializeState(_params) {
return {};
}
function useKeyboard(store, params, _api) {
const getViewportPageSize = () => {
const dimensions = Dimensions.selectors.dimensions(store.state);
if (!dimensions.isReady) {
return 0;
}
// TODO: Use a combination of scrollTop, dimensions.viewportInnerSize.height and rowsMeta.possitions
// to find out the maximum number of rows that can fit in the visible part of the grid
if (params.getRowHeight) {
const renderContext = Virtualization.selectors.renderContext(store.state);
const viewportPageSize = renderContext.lastRowIndex - renderContext.firstRowIndex;
return Math.min(viewportPageSize - 1, params.rows.length);
}
const maximumPageSizeWithoutScrollBar = Math.floor(dimensions.viewportInnerSize.height / dimensions.rowHeight);
return Math.min(maximumPageSizeWithoutScrollBar, params.rows.length);
};
return {
getViewportPageSize
};
}
+25
View File
@@ -0,0 +1,25 @@
import { Store } from '@mui/x-internals/store';
import type { BaseState, ParamsWithDefaults } from "../useVirtualizer.mjs";
import type { RowSpanningState } from "../models/rowspan.mjs";
import { Virtualization } from "./virtualization/index.mjs";
export declare const Rowspan: {
initialize: typeof initializeState;
use: typeof useRowspan;
selectors: {
state: (state: Rowspan.State) => RowSpanningState;
hiddenCells: (state: Rowspan.State) => Record<any, Record<number, boolean>>;
spannedCells: (state: Rowspan.State) => Record<any, Record<number, number>>;
hiddenCellsOriginMap: (state: Rowspan.State) => Record<number, Record<number, number>>;
};
};
export declare namespace Rowspan {
type State = {
rowSpanning: RowSpanningState;
};
type API = ReturnType<typeof useRowspan>;
}
declare function initializeState(params: ParamsWithDefaults): Rowspan.State;
declare function useRowspan(store: Store<BaseState & Rowspan.State>, _params: ParamsWithDefaults, _api: Virtualization.API): {
getHiddenCellsOrigin: () => Record<number, Record<number, number>>;
};
export {};
+25
View File
@@ -0,0 +1,25 @@
import { Store } from '@mui/x-internals/store';
import type { BaseState, ParamsWithDefaults } from "../useVirtualizer.js";
import type { RowSpanningState } from "../models/rowspan.js";
import { Virtualization } from "./virtualization/index.js";
export declare const Rowspan: {
initialize: typeof initializeState;
use: typeof useRowspan;
selectors: {
state: (state: Rowspan.State) => RowSpanningState;
hiddenCells: (state: Rowspan.State) => Record<any, Record<number, boolean>>;
spannedCells: (state: Rowspan.State) => Record<any, Record<number, number>>;
hiddenCellsOriginMap: (state: Rowspan.State) => Record<number, Record<number, number>>;
};
};
export declare namespace Rowspan {
type State = {
rowSpanning: RowSpanningState;
};
type API = ReturnType<typeof useRowspan>;
}
declare function initializeState(params: ParamsWithDefaults): Rowspan.State;
declare function useRowspan(store: Store<BaseState & Rowspan.State>, _params: ParamsWithDefaults, _api: Virtualization.API): {
getHiddenCellsOrigin: () => Record<number, Record<number, number>>;
};
export {};
+42
View File
@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Rowspan = void 0;
/* eslint-disable import/export, @typescript-eslint/no-redeclare */
const EMPTY_RANGE = {
firstRowIndex: 0,
lastRowIndex: 0
};
const EMPTY_CACHES = {
spannedCells: {},
hiddenCells: {},
hiddenCellOriginMap: {}
};
const selectors = {
state: state => state.rowSpanning,
hiddenCells: state => state.rowSpanning.caches.hiddenCells,
spannedCells: state => state.rowSpanning.caches.spannedCells,
hiddenCellsOriginMap: state => state.rowSpanning.caches.hiddenCellOriginMap
};
const Rowspan = exports.Rowspan = {
initialize: initializeState,
use: useRowspan,
selectors
};
function initializeState(params) {
return {
rowSpanning: params.initialState?.rowSpanning ?? {
caches: EMPTY_CACHES,
processedRange: EMPTY_RANGE
}
};
}
function useRowspan(store, _params, _api) {
const getHiddenCellsOrigin = () => selectors.hiddenCellsOriginMap(store.state);
return {
getHiddenCellsOrigin
};
}
+36
View File
@@ -0,0 +1,36 @@
/* eslint-disable import/export, @typescript-eslint/no-redeclare */
const EMPTY_RANGE = {
firstRowIndex: 0,
lastRowIndex: 0
};
const EMPTY_CACHES = {
spannedCells: {},
hiddenCells: {},
hiddenCellOriginMap: {}
};
const selectors = {
state: state => state.rowSpanning,
hiddenCells: state => state.rowSpanning.caches.hiddenCells,
spannedCells: state => state.rowSpanning.caches.spannedCells,
hiddenCellsOriginMap: state => state.rowSpanning.caches.hiddenCellOriginMap
};
export const Rowspan = {
initialize: initializeState,
use: useRowspan,
selectors
};
function initializeState(params) {
return {
rowSpanning: params.initialState?.rowSpanning ?? {
caches: EMPTY_CACHES,
processedRange: EMPTY_RANGE
}
};
}
function useRowspan(store, _params, _api) {
const getHiddenCellsOrigin = () => selectors.hiddenCellsOriginMap(store.state);
return {
getHiddenCellsOrigin
};
}
@@ -0,0 +1,2 @@
export * from "./layout.mjs";
export * from "./virtualization.mjs";
@@ -0,0 +1,2 @@
export * from "./layout.js";
export * from "./virtualization.js";
@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _layout = require("./layout");
Object.keys(_layout).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _layout[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _layout[key];
}
});
});
var _virtualization = require("./virtualization");
Object.keys(_virtualization).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _virtualization[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _virtualization[key];
}
});
});
@@ -0,0 +1,2 @@
export * from "./layout.mjs";
export * from "./virtualization.mjs";
@@ -0,0 +1,103 @@
import * as React from 'react';
import { Store } from '@mui/x-internals/store';
import { Dimensions } from "../dimensions.mjs";
import { Virtualization, type VirtualizationLayoutParams } from "./virtualization.mjs";
import type { BaseState, ParamsWithDefaults } from "../../useVirtualizer.mjs";
type RequiredAPI = Dimensions.API;
type BaseElements = {
scroller: React.RefObject<HTMLElement | null>;
container: React.RefObject<HTMLElement | null>;
};
type AnyElements = BaseElements & Record<string, React.RefObject<HTMLElement | null>>;
export declare abstract class Layout<E extends AnyElements = AnyElements> {
static elements: readonly (keyof AnyElements)[];
refs: E;
constructor(refs: E);
abstract use(store: Store<BaseState>, params: ParamsWithDefaults, api: RequiredAPI, layoutParams: VirtualizationLayoutParams): any;
refSetter(name: keyof E): (node: HTMLDivElement | null) => void;
}
type DataGridElements = BaseElements & {
scrollbarVertical: React.RefObject<HTMLElement | null>;
scrollbarHorizontal: React.RefObject<HTMLElement | null>;
};
export declare class LayoutDataGrid extends Layout<DataGridElements> {
static elements: readonly ['scroller', 'container', 'content', 'positioner', 'scrollbarVertical', 'scrollbarHorizontal'];
use(store: Store<BaseState>, _params: ParamsWithDefaults, api: RequiredAPI, layoutParams: VirtualizationLayoutParams): void;
static selectors: {
containerProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
ref: any;
};
scrollerProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
ref: any;
style: {
overflowX: "hidden" | undefined;
overflowY: "hidden" | undefined;
};
role: string;
tabIndex: number | undefined;
};
scrollerContentProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: React.CSSProperties | undefined;
role: string;
};
viewportProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: {
width: number;
height: number;
};
role: string;
};
contentProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: React.CSSProperties;
role: string;
};
positionerProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: {
transform: string;
};
};
containerVerticalProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: {
transform: string;
};
} | undefined;
scrollbarHorizontalProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
ref: any;
scrollPosition: {
current: import("../../index.mjs").ScrollPosition;
};
};
scrollbarVerticalProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
ref: any;
scrollPosition: {
current: import("../../index.mjs").ScrollPosition;
};
};
scrollAreaProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
scrollPosition: {
current: import("../../index.mjs").ScrollPosition;
};
};
};
}
type ListElements = BaseElements;
export declare class LayoutList extends Layout<ListElements> {
static elements: readonly ['scroller', 'container', 'content', 'positioner'];
use(store: Store<BaseState>, _params: ParamsWithDefaults, _api: RequiredAPI, layoutParams: VirtualizationLayoutParams): void;
static selectors: {
containerProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
ref: any;
style: React.CSSProperties;
role: string;
tabIndex: number | undefined;
};
contentProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: React.CSSProperties;
role: string;
};
positionerProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: React.CSSProperties;
};
};
}
export {};
@@ -0,0 +1,103 @@
import * as React from 'react';
import { Store } from '@mui/x-internals/store';
import { Dimensions } from "../dimensions.js";
import { Virtualization, type VirtualizationLayoutParams } from "./virtualization.js";
import type { BaseState, ParamsWithDefaults } from "../../useVirtualizer.js";
type RequiredAPI = Dimensions.API;
type BaseElements = {
scroller: React.RefObject<HTMLElement | null>;
container: React.RefObject<HTMLElement | null>;
};
type AnyElements = BaseElements & Record<string, React.RefObject<HTMLElement | null>>;
export declare abstract class Layout<E extends AnyElements = AnyElements> {
static elements: readonly (keyof AnyElements)[];
refs: E;
constructor(refs: E);
abstract use(store: Store<BaseState>, params: ParamsWithDefaults, api: RequiredAPI, layoutParams: VirtualizationLayoutParams): any;
refSetter(name: keyof E): (node: HTMLDivElement | null) => void;
}
type DataGridElements = BaseElements & {
scrollbarVertical: React.RefObject<HTMLElement | null>;
scrollbarHorizontal: React.RefObject<HTMLElement | null>;
};
export declare class LayoutDataGrid extends Layout<DataGridElements> {
static elements: readonly ['scroller', 'container', 'content', 'positioner', 'scrollbarVertical', 'scrollbarHorizontal'];
use(store: Store<BaseState>, _params: ParamsWithDefaults, api: RequiredAPI, layoutParams: VirtualizationLayoutParams): void;
static selectors: {
containerProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
ref: any;
};
scrollerProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
ref: any;
style: {
overflowX: "hidden" | undefined;
overflowY: "hidden" | undefined;
};
role: string;
tabIndex: number | undefined;
};
scrollerContentProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: React.CSSProperties | undefined;
role: string;
};
viewportProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: {
width: number;
height: number;
};
role: string;
};
contentProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: React.CSSProperties;
role: string;
};
positionerProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: {
transform: string;
};
};
containerVerticalProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: {
transform: string;
};
} | undefined;
scrollbarHorizontalProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
ref: any;
scrollPosition: {
current: import("../../index.js").ScrollPosition;
};
};
scrollbarVerticalProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
ref: any;
scrollPosition: {
current: import("../../index.js").ScrollPosition;
};
};
scrollAreaProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
scrollPosition: {
current: import("../../index.js").ScrollPosition;
};
};
};
}
type ListElements = BaseElements;
export declare class LayoutList extends Layout<ListElements> {
static elements: readonly ['scroller', 'container', 'content', 'positioner'];
use(store: Store<BaseState>, _params: ParamsWithDefaults, _api: RequiredAPI, layoutParams: VirtualizationLayoutParams): void;
static selectors: {
containerProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
ref: any;
style: React.CSSProperties;
role: string;
tabIndex: number | undefined;
};
contentProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: React.CSSProperties;
role: string;
};
positionerProps: (args_0: Virtualization.State<Layout<AnyElements>> & Dimensions.State) => {
style: React.CSSProperties;
};
};
}
export {};
@@ -0,0 +1,254 @@
"use strict";
'use client';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LayoutList = exports.LayoutDataGrid = exports.Layout = void 0;
var React = _interopRequireWildcard(require("react"));
var _useForkRef = _interopRequireDefault(require("@mui/utils/useForkRef"));
var _useEventCallback = _interopRequireDefault(require("@mui/utils/useEventCallback"));
var _platform = require("@base-ui/utils/platform");
var _store = require("@mui/x-internals/store");
var _dimensions = require("../../features/dimensions");
var _virtualization = require("./virtualization");
var _useRefCallback = _interopRequireDefault(require("../../utils/useRefCallback"));
/* eslint-disable react-hooks/rules-of-hooks */
class Layout {
static elements = ['scroller', 'container'];
constructor(refs) {
this.refs = refs;
}
refSetter(name) {
return node => {
if (this.refs[name].current !== node) {
this.refs[name].current = node;
}
};
}
}
exports.Layout = Layout;
class LayoutDataGrid extends Layout {
static elements = ['scroller', 'container', 'content', 'positioner', 'scrollbarVertical', 'scrollbarHorizontal'];
use(store, _params, api, layoutParams) {
const {
scrollerRef,
containerRef
} = layoutParams;
const scrollbarVerticalRef = useScrollbarRefCallback(this.refs.scroller, this.refSetter('scrollbarVertical'), 'scrollTop', api.updateDimensions);
const scrollbarHorizontalRef = useScrollbarRefCallback(this.refs.scroller, this.refSetter('scrollbarHorizontal'), 'scrollLeft', api.updateDimensions);
store.state.virtualization.context = {
scrollerRef,
containerRef,
scrollbarVerticalRef,
scrollbarHorizontalRef
};
}
static selectors = {
containerProps: (0, _store.createSelectorMemoized)(_virtualization.Virtualization.selectors.context, context => ({
ref: context.containerRef
})),
scrollerProps: (0, _store.createSelectorMemoized)(_virtualization.Virtualization.selectors.context, _dimensions.Dimensions.selectors.autoHeight, _dimensions.Dimensions.selectors.needsHorizontalScrollbar, (context, autoHeight, needsHorizontalScrollbar) => ({
ref: context.scrollerRef,
style: {
// TODO: fall back to overflow: 'auto' if no overflowX or overflowY is set?
overflowX: !needsHorizontalScrollbar ? 'hidden' : undefined,
overflowY: autoHeight ? 'hidden' : undefined
// TODO: should include display: 'flex', flexDirection: 'column' since the Content has flexBasis and flexShrink?
},
role: 'presentation',
// `tabIndex` shouldn't be used along role=presentation, but it fixes a Firefox bug
// https://github.com/mui/mui-x/pull/13891#discussion_r1683416024
tabIndex: _platform.platform.engine.gecko ? -1 : undefined
})),
scrollerContentProps: (0, _store.createSelectorMemoized)(_virtualization.Virtualization.selectors.layoutMode, _dimensions.Dimensions.selectors.dimensions, _dimensions.Dimensions.selectors.needsVerticalScrollbar, _dimensions.Dimensions.selectors.needsHorizontalScrollbar, (layoutMode, dimensions, needsVerticalScrollbar, needsHorizontalScrollbar) => {
let style;
if (layoutMode === 'controlled') {
const {
contentSize,
scrollbarSize,
topContainerHeight,
bottomContainerHeight,
minimalContentHeight,
columnsTotalWidth,
viewportOuterSize
} = dimensions;
const verticalScrollbarSize = needsVerticalScrollbar ? scrollbarSize : 0;
const horizontalScrollbarSize = needsHorizontalScrollbar ? scrollbarSize : 0;
const contentHeight = contentSize.height === 0 ? minimalContentHeight : contentSize.height;
const width = needsHorizontalScrollbar ? verticalScrollbarSize + columnsTotalWidth : 'auto';
const height = cssAdd(cssAdd(cssAdd(contentHeight, topContainerHeight), bottomContainerHeight), horizontalScrollbarSize);
style = {
width: cssMax(width, viewportOuterSize.width - verticalScrollbarSize),
height: cssMax(height, viewportOuterSize.height - horizontalScrollbarSize),
flex: '0 0 auto'
};
}
return {
style,
role: 'presentation'
};
}),
viewportProps: (0, _store.createSelectorMemoized)(_dimensions.Dimensions.selectors.dimensions, dimensions => ({
style: {
width: dimensions.viewportOuterSize.width,
height: dimensions.viewportOuterSize.height
},
role: 'presentation'
})),
contentProps: (0, _store.createSelectorMemoized)(_dimensions.Dimensions.selectors.contentHeight, _dimensions.Dimensions.selectors.minimalContentHeight, _dimensions.Dimensions.selectors.columnsTotalWidth, _dimensions.Dimensions.selectors.needsHorizontalScrollbar, (contentHeight, minimalContentHeight, columnsTotalWidth, needsHorizontalScrollbar) => ({
style: {
width: needsHorizontalScrollbar ? columnsTotalWidth : 'auto',
height: contentHeight === 0 ? minimalContentHeight : contentHeight,
flex: '0 0 auto'
},
role: 'presentation'
})),
positionerProps: (0, _store.createSelectorMemoized)(_virtualization.Virtualization.selectors.layoutMode, _virtualization.Virtualization.selectors.offsetTop, _virtualization.Virtualization.selectors.scrollPosition, (layoutMode, offsetTop, scrollPosition) => ({
style: {
transform: layoutMode === 'uncontrolled' ? `translate3d(0, ${offsetTop}px, 0)` : `translate3d(${-scrollPosition.current.left}px, ${offsetTop - scrollPosition.current.top}px, 0)`
}
})),
containerVerticalProps: (0, _store.createSelectorMemoized)(_virtualization.Virtualization.selectors.layoutMode, _virtualization.Virtualization.selectors.scrollPosition, (layoutMode, scrollPosition) => layoutMode === 'uncontrolled' ? undefined : {
style: {
transform: `translate3d(${-scrollPosition.current.left}px, 0, 0)`
}
}),
scrollbarHorizontalProps: (0, _store.createSelectorMemoized)(_virtualization.Virtualization.selectors.context, _virtualization.Virtualization.selectors.scrollPosition, (context, scrollPosition) => ({
ref: context.scrollbarHorizontalRef,
scrollPosition
})),
scrollbarVerticalProps: (0, _store.createSelectorMemoized)(_virtualization.Virtualization.selectors.context, _virtualization.Virtualization.selectors.scrollPosition, (context, scrollPosition) => ({
ref: context.scrollbarVerticalRef,
scrollPosition
})),
scrollAreaProps: (0, _store.createSelectorMemoized)(_virtualization.Virtualization.selectors.scrollPosition, scrollPosition => ({
scrollPosition
}))
};
}
exports.LayoutDataGrid = LayoutDataGrid;
class LayoutList extends Layout {
static elements = ['scroller', 'container', 'content', 'positioner'];
use(store, _params, _api, layoutParams) {
const {
scrollerRef,
containerRef
} = layoutParams;
const mergedRef = (0, _useForkRef.default)(scrollerRef, containerRef);
store.state.virtualization.context = {
mergedRef
};
}
static selectors = {
containerProps: (0, _store.createSelectorMemoized)(_virtualization.Virtualization.selectors.context, _dimensions.Dimensions.selectors.autoHeight, _dimensions.Dimensions.selectors.needsHorizontalScrollbar, (context, autoHeight, needsHorizontalScrollbar) => ({
ref: context.mergedRef,
style: {
overflowX: !needsHorizontalScrollbar ? 'hidden' : undefined,
overflowY: autoHeight ? 'hidden' : undefined,
position: 'relative'
},
role: 'presentation',
// `tabIndex` shouldn't be used along role=presentation, but it fixes a Firefox bug
// https://github.com/mui/mui-x/pull/13891#discussion_r1683416024
tabIndex: _platform.platform.engine.gecko ? -1 : undefined
})),
contentProps: (0, _store.createSelectorMemoized)(_dimensions.Dimensions.selectors.contentHeight, contentHeight => ({
style: {
position: 'absolute',
display: 'inline-block',
width: '100%',
height: contentHeight,
top: 0,
left: 0,
zIndex: -1
},
role: 'presentation'
})),
positionerProps: (0, _store.createSelectorMemoized)(_virtualization.Virtualization.selectors.offsetTop, offsetTop => ({
style: {
height: offsetTop
}
}))
};
}
exports.LayoutList = LayoutList;
function useScrollbarRefCallback(scrollerRef, refSetter, scrollProperty, updateDimensions) {
const isLocked = React.useRef(false);
const lastPosition = React.useRef(0);
const handleScrollerScroll = (0, _useEventCallback.default)(scrollbar => {
const scroller = scrollerRef.current;
if (!scroller) {
return;
}
const scrollerPosition = scroller[scrollProperty];
if (scrollerPosition === lastPosition.current) {
return;
}
lastPosition.current = scrollerPosition;
if (isLocked.current) {
isLocked.current = false;
return;
}
isLocked.current = true;
scrollbar[scrollProperty] = scrollerPosition;
});
const handleScrollbarScroll = (0, _useEventCallback.default)(scrollbar => {
const scroller = scrollerRef.current;
if (!scroller) {
return;
}
if (isLocked.current) {
isLocked.current = false;
return;
}
isLocked.current = true;
scroller[scrollProperty] = scrollbar[scrollProperty];
});
return (0, _useRefCallback.default)(scrollbar => {
refSetter(scrollbar);
updateDimensions();
const scroller = scrollerRef.current;
if (!scroller) {
return () => {
refSetter(null);
};
}
const onScrollerScroll = () => handleScrollerScroll(scrollbar);
const onScrollbarScroll = () => handleScrollbarScroll(scrollbar);
const options = {
passive: true
};
scroller.addEventListener('scroll', onScrollerScroll, options);
scrollbar.addEventListener('scroll', onScrollbarScroll, options);
return () => {
scroller.removeEventListener('scroll', onScrollerScroll);
scrollbar.removeEventListener('scroll', onScrollbarScroll);
refSetter(null);
};
});
}
function cssAdd(a, b) {
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
}
return `calc(${valueToCSSString(a)} + ${valueToCSSString(b)})`;
}
function cssMax(a, b) {
if (typeof a === 'number' && typeof b === 'number') {
return Math.max(a, b);
}
return `max(${valueToCSSString(a)}, ${valueToCSSString(b)})`;
}
function valueToCSSString(value) {
if (typeof value === 'string') {
return value;
}
if (typeof value === 'undefined') {
return '0';
}
return `${value}px`;
}
@@ -0,0 +1,245 @@
'use client';
import * as React from 'react';
import useForkRef from '@mui/utils/useForkRef';
import useEventCallback from '@mui/utils/useEventCallback';
import { platform } from '@base-ui/utils/platform';
import { createSelectorMemoized } from '@mui/x-internals/store';
import { Dimensions } from "../dimensions.mjs";
import { Virtualization } from "./virtualization.mjs";
import useRefCallback from "../../utils/useRefCallback.mjs";
/* eslint-disable react-hooks/rules-of-hooks */
export class Layout {
static elements = ['scroller', 'container'];
constructor(refs) {
this.refs = refs;
}
refSetter(name) {
return node => {
if (this.refs[name].current !== node) {
this.refs[name].current = node;
}
};
}
}
export class LayoutDataGrid extends Layout {
static elements = ['scroller', 'container', 'content', 'positioner', 'scrollbarVertical', 'scrollbarHorizontal'];
use(store, _params, api, layoutParams) {
const {
scrollerRef,
containerRef
} = layoutParams;
const scrollbarVerticalRef = useScrollbarRefCallback(this.refs.scroller, this.refSetter('scrollbarVertical'), 'scrollTop', api.updateDimensions);
const scrollbarHorizontalRef = useScrollbarRefCallback(this.refs.scroller, this.refSetter('scrollbarHorizontal'), 'scrollLeft', api.updateDimensions);
store.state.virtualization.context = {
scrollerRef,
containerRef,
scrollbarVerticalRef,
scrollbarHorizontalRef
};
}
static selectors = {
containerProps: createSelectorMemoized(Virtualization.selectors.context, context => ({
ref: context.containerRef
})),
scrollerProps: createSelectorMemoized(Virtualization.selectors.context, Dimensions.selectors.autoHeight, Dimensions.selectors.needsHorizontalScrollbar, (context, autoHeight, needsHorizontalScrollbar) => ({
ref: context.scrollerRef,
style: {
// TODO: fall back to overflow: 'auto' if no overflowX or overflowY is set?
overflowX: !needsHorizontalScrollbar ? 'hidden' : undefined,
overflowY: autoHeight ? 'hidden' : undefined
// TODO: should include display: 'flex', flexDirection: 'column' since the Content has flexBasis and flexShrink?
},
role: 'presentation',
// `tabIndex` shouldn't be used along role=presentation, but it fixes a Firefox bug
// https://github.com/mui/mui-x/pull/13891#discussion_r1683416024
tabIndex: platform.engine.gecko ? -1 : undefined
})),
scrollerContentProps: createSelectorMemoized(Virtualization.selectors.layoutMode, Dimensions.selectors.dimensions, Dimensions.selectors.needsVerticalScrollbar, Dimensions.selectors.needsHorizontalScrollbar, (layoutMode, dimensions, needsVerticalScrollbar, needsHorizontalScrollbar) => {
let style;
if (layoutMode === 'controlled') {
const {
contentSize,
scrollbarSize,
topContainerHeight,
bottomContainerHeight,
minimalContentHeight,
columnsTotalWidth,
viewportOuterSize
} = dimensions;
const verticalScrollbarSize = needsVerticalScrollbar ? scrollbarSize : 0;
const horizontalScrollbarSize = needsHorizontalScrollbar ? scrollbarSize : 0;
const contentHeight = contentSize.height === 0 ? minimalContentHeight : contentSize.height;
const width = needsHorizontalScrollbar ? verticalScrollbarSize + columnsTotalWidth : 'auto';
const height = cssAdd(cssAdd(cssAdd(contentHeight, topContainerHeight), bottomContainerHeight), horizontalScrollbarSize);
style = {
width: cssMax(width, viewportOuterSize.width - verticalScrollbarSize),
height: cssMax(height, viewportOuterSize.height - horizontalScrollbarSize),
flex: '0 0 auto'
};
}
return {
style,
role: 'presentation'
};
}),
viewportProps: createSelectorMemoized(Dimensions.selectors.dimensions, dimensions => ({
style: {
width: dimensions.viewportOuterSize.width,
height: dimensions.viewportOuterSize.height
},
role: 'presentation'
})),
contentProps: createSelectorMemoized(Dimensions.selectors.contentHeight, Dimensions.selectors.minimalContentHeight, Dimensions.selectors.columnsTotalWidth, Dimensions.selectors.needsHorizontalScrollbar, (contentHeight, minimalContentHeight, columnsTotalWidth, needsHorizontalScrollbar) => ({
style: {
width: needsHorizontalScrollbar ? columnsTotalWidth : 'auto',
height: contentHeight === 0 ? minimalContentHeight : contentHeight,
flex: '0 0 auto'
},
role: 'presentation'
})),
positionerProps: createSelectorMemoized(Virtualization.selectors.layoutMode, Virtualization.selectors.offsetTop, Virtualization.selectors.scrollPosition, (layoutMode, offsetTop, scrollPosition) => ({
style: {
transform: layoutMode === 'uncontrolled' ? `translate3d(0, ${offsetTop}px, 0)` : `translate3d(${-scrollPosition.current.left}px, ${offsetTop - scrollPosition.current.top}px, 0)`
}
})),
containerVerticalProps: createSelectorMemoized(Virtualization.selectors.layoutMode, Virtualization.selectors.scrollPosition, (layoutMode, scrollPosition) => layoutMode === 'uncontrolled' ? undefined : {
style: {
transform: `translate3d(${-scrollPosition.current.left}px, 0, 0)`
}
}),
scrollbarHorizontalProps: createSelectorMemoized(Virtualization.selectors.context, Virtualization.selectors.scrollPosition, (context, scrollPosition) => ({
ref: context.scrollbarHorizontalRef,
scrollPosition
})),
scrollbarVerticalProps: createSelectorMemoized(Virtualization.selectors.context, Virtualization.selectors.scrollPosition, (context, scrollPosition) => ({
ref: context.scrollbarVerticalRef,
scrollPosition
})),
scrollAreaProps: createSelectorMemoized(Virtualization.selectors.scrollPosition, scrollPosition => ({
scrollPosition
}))
};
}
export class LayoutList extends Layout {
static elements = ['scroller', 'container', 'content', 'positioner'];
use(store, _params, _api, layoutParams) {
const {
scrollerRef,
containerRef
} = layoutParams;
const mergedRef = useForkRef(scrollerRef, containerRef);
store.state.virtualization.context = {
mergedRef
};
}
static selectors = {
containerProps: createSelectorMemoized(Virtualization.selectors.context, Dimensions.selectors.autoHeight, Dimensions.selectors.needsHorizontalScrollbar, (context, autoHeight, needsHorizontalScrollbar) => ({
ref: context.mergedRef,
style: {
overflowX: !needsHorizontalScrollbar ? 'hidden' : undefined,
overflowY: autoHeight ? 'hidden' : undefined,
position: 'relative'
},
role: 'presentation',
// `tabIndex` shouldn't be used along role=presentation, but it fixes a Firefox bug
// https://github.com/mui/mui-x/pull/13891#discussion_r1683416024
tabIndex: platform.engine.gecko ? -1 : undefined
})),
contentProps: createSelectorMemoized(Dimensions.selectors.contentHeight, contentHeight => ({
style: {
position: 'absolute',
display: 'inline-block',
width: '100%',
height: contentHeight,
top: 0,
left: 0,
zIndex: -1
},
role: 'presentation'
})),
positionerProps: createSelectorMemoized(Virtualization.selectors.offsetTop, offsetTop => ({
style: {
height: offsetTop
}
}))
};
}
function useScrollbarRefCallback(scrollerRef, refSetter, scrollProperty, updateDimensions) {
const isLocked = React.useRef(false);
const lastPosition = React.useRef(0);
const handleScrollerScroll = useEventCallback(scrollbar => {
const scroller = scrollerRef.current;
if (!scroller) {
return;
}
const scrollerPosition = scroller[scrollProperty];
if (scrollerPosition === lastPosition.current) {
return;
}
lastPosition.current = scrollerPosition;
if (isLocked.current) {
isLocked.current = false;
return;
}
isLocked.current = true;
scrollbar[scrollProperty] = scrollerPosition;
});
const handleScrollbarScroll = useEventCallback(scrollbar => {
const scroller = scrollerRef.current;
if (!scroller) {
return;
}
if (isLocked.current) {
isLocked.current = false;
return;
}
isLocked.current = true;
scroller[scrollProperty] = scrollbar[scrollProperty];
});
return useRefCallback(scrollbar => {
refSetter(scrollbar);
updateDimensions();
const scroller = scrollerRef.current;
if (!scroller) {
return () => {
refSetter(null);
};
}
const onScrollerScroll = () => handleScrollerScroll(scrollbar);
const onScrollbarScroll = () => handleScrollbarScroll(scrollbar);
const options = {
passive: true
};
scroller.addEventListener('scroll', onScrollerScroll, options);
scrollbar.addEventListener('scroll', onScrollbarScroll, options);
return () => {
scroller.removeEventListener('scroll', onScrollerScroll);
scrollbar.removeEventListener('scroll', onScrollbarScroll);
refSetter(null);
};
});
}
function cssAdd(a, b) {
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
}
return `calc(${valueToCSSString(a)} + ${valueToCSSString(b)})`;
}
function cssMax(a, b) {
if (typeof a === 'number' && typeof b === 'number') {
return Math.max(a, b);
}
return `max(${valueToCSSString(a)}, ${valueToCSSString(b)})`;
}
function valueToCSSString(value) {
if (typeof value === 'string') {
return value;
}
if (typeof value === 'undefined') {
return '0';
}
return `${value}px`;
}
@@ -0,0 +1,105 @@
import * as React from 'react';
import type { integer } from '@mui/x-internals/types';
import { Store } from '@mui/x-internals/store';
import type { CellColSpanInfo } from "../../models/colspan.mjs";
import { Dimensions } from "../dimensions.mjs";
import type { BaseState, ParamsWithDefaults } from "../../useVirtualizer.mjs";
import type { Layout } from "./layout.mjs";
import { RenderContext, ColumnsRenderContext, ColumnWithWidth, RowId, ScrollPosition } from "../../models/index.mjs";
export type VirtualizationParams = {
/** @default false */
isRtl?: boolean;
/** The row buffer in pixels to render before and after the viewport.
* @default 150 */
rowBufferPx?: number;
/** The column buffer in pixels to render before and after the viewport.
* @default 150 */
columnBufferPx?: number;
/**
* Controls how the container and render zones are positioned:
* - 'uncontrolled': uses CSS sticky positioning (default)
* - 'controlled': uses CSS absolute positioning with JS-computed offsets
* @default 'uncontrolled'
*/
layoutMode?: 'controlled' | 'uncontrolled';
};
export type VirtualizationState<K extends string = string> = {
enabled: boolean;
enabledForRows: boolean;
enabledForColumns: boolean;
renderContext: RenderContext;
props: Record<K, Record<string, any>>;
context: Record<string, any>;
scrollPosition: {
current: ScrollPosition;
};
layoutMode: 'controlled' | 'uncontrolled';
};
export declare const EMPTY_RENDER_CONTEXT: {
firstRowIndex: number;
lastRowIndex: number;
firstColumnIndex: number;
lastColumnIndex: number;
};
export declare const Virtualization: {
initialize: typeof initializeState;
use: typeof useVirtualization;
selectors: {
store: (state: BaseState) => VirtualizationState<string>;
renderContext: (state: BaseState) => RenderContext;
enabledForRows: (state: BaseState) => boolean;
enabledForColumns: (state: BaseState) => boolean;
offsetTop: (args_0: Virtualization.State<Layout<{
scroller: React.RefObject<HTMLElement | null>;
container: React.RefObject<HTMLElement | null>;
} & Record<string, React.RefObject<HTMLElement | null>>>> & Dimensions.State) => number;
context: (state: BaseState) => Record<string, any>;
layoutMode: (state: BaseState) => "controlled" | "uncontrolled";
scrollPosition: (state: BaseState) => {
current: ScrollPosition;
};
pinnedLeftOffsetSelector: (args_0: Virtualization.State<Layout<{
scroller: React.RefObject<HTMLElement | null>;
container: React.RefObject<HTMLElement | null>;
} & Record<string, React.RefObject<HTMLElement | null>>>> & Dimensions.State) => number;
pinnedRightOffsetSelector: (args_0: Virtualization.State<Layout<{
scroller: React.RefObject<HTMLElement | null>;
container: React.RefObject<HTMLElement | null>;
} & Record<string, React.RefObject<HTMLElement | null>>>> & Dimensions.State) => number;
};
};
export declare namespace Virtualization {
type State<L extends Layout> = {
virtualization: VirtualizationState<L extends Layout<infer E> ? keyof E : string>;
getters: ReturnType<typeof useVirtualization>['getters'];
};
type API = ReturnType<typeof useVirtualization>;
}
declare function initializeState(params: ParamsWithDefaults): Virtualization.State<Layout<{
scroller: React.RefObject<HTMLElement | null>;
container: React.RefObject<HTMLElement | null>;
} & Record<string, React.RefObject<HTMLElement | null>>>>;
/** APIs to override for colspan/rowspan */
type AbstractAPI = {
getCellColSpanInfo: (rowId: RowId, columnIndex: integer) => CellColSpanInfo;
calculateColSpan: (rowId: RowId, minFirstColumn: integer, maxLastColumn: integer, columns: ColumnWithWidth[]) => void;
getHiddenCellsOrigin: () => Record<RowId, Record<number, number>>;
};
type RequiredAPI = Dimensions.API & AbstractAPI;
export type VirtualizationLayoutParams = {
containerRef: (node: HTMLDivElement | null) => void;
scrollerRef: (node: HTMLDivElement | null) => void;
};
declare function useVirtualization(store: Store<BaseState>, params: ParamsWithDefaults, api: RequiredAPI): {
getCellColSpanInfo: (rowId: RowId, columnIndex: integer) => CellColSpanInfo;
calculateColSpan: (rowId: RowId, minFirstColumn: integer, maxLastColumn: integer, columns: ColumnWithWidth[]) => void;
getHiddenCellsOrigin: () => Record<RowId, Record<number, number>>;
getters: any;
setPanels: React.Dispatch<React.SetStateAction<Readonly<Map<any, React.ReactNode>>>>;
forceUpdateRenderContext: () => void;
scheduleUpdateRenderContext: () => void;
};
export declare function areRenderContextsEqual(context1: RenderContext, context2: RenderContext): boolean;
export declare function computeOffsetLeft(columnPositions: number[], renderContext: ColumnsRenderContext, pinnedLeftLength: number, layoutMode?: VirtualizationState['layoutMode']): number;
export declare function roundToDecimalPlaces(value: number, decimals: number): number;
export {};
@@ -0,0 +1,105 @@
import * as React from 'react';
import type { integer } from '@mui/x-internals/types';
import { Store } from '@mui/x-internals/store';
import type { CellColSpanInfo } from "../../models/colspan.js";
import { Dimensions } from "../dimensions.js";
import type { BaseState, ParamsWithDefaults } from "../../useVirtualizer.js";
import type { Layout } from "./layout.js";
import { RenderContext, ColumnsRenderContext, ColumnWithWidth, RowId, ScrollPosition } from "../../models/index.js";
export type VirtualizationParams = {
/** @default false */
isRtl?: boolean;
/** The row buffer in pixels to render before and after the viewport.
* @default 150 */
rowBufferPx?: number;
/** The column buffer in pixels to render before and after the viewport.
* @default 150 */
columnBufferPx?: number;
/**
* Controls how the container and render zones are positioned:
* - 'uncontrolled': uses CSS sticky positioning (default)
* - 'controlled': uses CSS absolute positioning with JS-computed offsets
* @default 'uncontrolled'
*/
layoutMode?: 'controlled' | 'uncontrolled';
};
export type VirtualizationState<K extends string = string> = {
enabled: boolean;
enabledForRows: boolean;
enabledForColumns: boolean;
renderContext: RenderContext;
props: Record<K, Record<string, any>>;
context: Record<string, any>;
scrollPosition: {
current: ScrollPosition;
};
layoutMode: 'controlled' | 'uncontrolled';
};
export declare const EMPTY_RENDER_CONTEXT: {
firstRowIndex: number;
lastRowIndex: number;
firstColumnIndex: number;
lastColumnIndex: number;
};
export declare const Virtualization: {
initialize: typeof initializeState;
use: typeof useVirtualization;
selectors: {
store: (state: BaseState) => VirtualizationState<string>;
renderContext: (state: BaseState) => RenderContext;
enabledForRows: (state: BaseState) => boolean;
enabledForColumns: (state: BaseState) => boolean;
offsetTop: (args_0: Virtualization.State<Layout<{
scroller: React.RefObject<HTMLElement | null>;
container: React.RefObject<HTMLElement | null>;
} & Record<string, React.RefObject<HTMLElement | null>>>> & Dimensions.State) => number;
context: (state: BaseState) => Record<string, any>;
layoutMode: (state: BaseState) => "controlled" | "uncontrolled";
scrollPosition: (state: BaseState) => {
current: ScrollPosition;
};
pinnedLeftOffsetSelector: (args_0: Virtualization.State<Layout<{
scroller: React.RefObject<HTMLElement | null>;
container: React.RefObject<HTMLElement | null>;
} & Record<string, React.RefObject<HTMLElement | null>>>> & Dimensions.State) => number;
pinnedRightOffsetSelector: (args_0: Virtualization.State<Layout<{
scroller: React.RefObject<HTMLElement | null>;
container: React.RefObject<HTMLElement | null>;
} & Record<string, React.RefObject<HTMLElement | null>>>> & Dimensions.State) => number;
};
};
export declare namespace Virtualization {
type State<L extends Layout> = {
virtualization: VirtualizationState<L extends Layout<infer E> ? keyof E : string>;
getters: ReturnType<typeof useVirtualization>['getters'];
};
type API = ReturnType<typeof useVirtualization>;
}
declare function initializeState(params: ParamsWithDefaults): Virtualization.State<Layout<{
scroller: React.RefObject<HTMLElement | null>;
container: React.RefObject<HTMLElement | null>;
} & Record<string, React.RefObject<HTMLElement | null>>>>;
/** APIs to override for colspan/rowspan */
type AbstractAPI = {
getCellColSpanInfo: (rowId: RowId, columnIndex: integer) => CellColSpanInfo;
calculateColSpan: (rowId: RowId, minFirstColumn: integer, maxLastColumn: integer, columns: ColumnWithWidth[]) => void;
getHiddenCellsOrigin: () => Record<RowId, Record<number, number>>;
};
type RequiredAPI = Dimensions.API & AbstractAPI;
export type VirtualizationLayoutParams = {
containerRef: (node: HTMLDivElement | null) => void;
scrollerRef: (node: HTMLDivElement | null) => void;
};
declare function useVirtualization(store: Store<BaseState>, params: ParamsWithDefaults, api: RequiredAPI): {
getCellColSpanInfo: (rowId: RowId, columnIndex: integer) => CellColSpanInfo;
calculateColSpan: (rowId: RowId, minFirstColumn: integer, maxLastColumn: integer, columns: ColumnWithWidth[]) => void;
getHiddenCellsOrigin: () => Record<RowId, Record<number, number>>;
getters: any;
setPanels: React.Dispatch<React.SetStateAction<Readonly<Map<any, React.ReactNode>>>>;
forceUpdateRenderContext: () => void;
scheduleUpdateRenderContext: () => void;
};
export declare function areRenderContextsEqual(context1: RenderContext, context2: RenderContext): boolean;
export declare function computeOffsetLeft(columnPositions: number[], renderContext: ColumnsRenderContext, pinnedLeftLength: number, layoutMode?: VirtualizationState['layoutMode']): number;
export declare function roundToDecimalPlaces(value: number, decimals: number): number;
export {};
@@ -0,0 +1,901 @@
"use strict";
'use client';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Virtualization = exports.EMPTY_RENDER_CONTEXT = void 0;
exports.areRenderContextsEqual = areRenderContextsEqual;
exports.computeOffsetLeft = computeOffsetLeft;
exports.roundToDecimalPlaces = roundToDecimalPlaces;
var _formatErrorMessage2 = _interopRequireDefault(require("@mui/x-internals/formatErrorMessage"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var ReactDOM = _interopRequireWildcard(require("react-dom"));
var _useLazyRef = _interopRequireDefault(require("@mui/utils/useLazyRef"));
var _useTimeout = _interopRequireDefault(require("@mui/utils/useTimeout"));
var _useEventCallback = _interopRequireDefault(require("@mui/utils/useEventCallback"));
var _useEnhancedEffect = _interopRequireDefault(require("@mui/utils/useEnhancedEffect"));
var _platform = require("@base-ui/utils/platform");
var _useRunOnce = require("@mui/x-internals/useRunOnce");
var _store = require("@mui/x-internals/store");
var _useRefCallback = _interopRequireDefault(require("../../utils/useRefCallback"));
var _core = require("../../models/core");
var _dimensions = require("../dimensions");
var _models = require("../../models");
/* eslint-disable import/export, @typescript-eslint/no-redeclare */
const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
const MINIMUM_COLUMN_WIDTH = 50;
const EMPTY_SCROLL_POSITION = {
top: 0,
left: 0
};
const EMPTY_DETAIL_PANELS = Object.freeze(new Map());
const EMPTY_RENDER_CONTEXT = exports.EMPTY_RENDER_CONTEXT = {
firstRowIndex: 0,
lastRowIndex: 0,
firstColumnIndex: 0,
lastColumnIndex: 0
};
const selectors = (() => {
const firstRowIndexSelector = (0, _store.createSelector)(state => state.virtualization.renderContext.firstRowIndex);
const scrollPositionSelector = (0, _store.createSelector)(state => state.virtualization.scrollPosition);
const layoutModeSelector = (0, _store.createSelector)(state => state.virtualization.layoutMode);
return {
store: (0, _store.createSelector)(state => state.virtualization),
renderContext: (0, _store.createSelector)(state => state.virtualization.renderContext),
enabledForRows: (0, _store.createSelector)(state => state.virtualization.enabledForRows),
enabledForColumns: (0, _store.createSelector)(state => state.virtualization.enabledForColumns),
offsetTop: (0, _store.createSelector)(layoutModeSelector, _dimensions.Dimensions.selectors.dimensions, _dimensions.Dimensions.selectors.rowPositions, firstRowIndexSelector, (layoutMode, dimensions, rowPositions, firstRowIndex) => {
return (layoutMode === 'uncontrolled' ? dimensions.topContainerHeight : 0) + (rowPositions[firstRowIndex] ?? 0);
}),
context: (0, _store.createSelector)(state => state.virtualization.context),
layoutMode: layoutModeSelector,
scrollPosition: scrollPositionSelector,
pinnedLeftOffsetSelector: (0, _store.createSelector)(scrollPositionSelector, scrollPosition => scrollPosition.current.left),
pinnedRightOffsetSelector: (0, _store.createSelector)(scrollPositionSelector, _dimensions.Dimensions.selectors.dimensions, _dimensions.Dimensions.selectors.columnsTotalWidth, _dimensions.Dimensions.selectors.needsVerticalScrollbar, (scrollPosition, dimensions, columnsTotalWidth, needsVerticalScrollbar) => {
return Math.max(columnsTotalWidth, dimensions.viewportOuterSize.width) - dimensions.viewportOuterSize.width - scrollPosition.current.left + (needsVerticalScrollbar ? dimensions.scrollbarSize : 0);
})
};
})();
const Virtualization = exports.Virtualization = {
initialize: initializeState,
use: useVirtualization,
selectors
};
function initializeState(params) {
const {
enabled,
enabledForRows,
enabledForColumns
} = params.initialState?.virtualization ?? {};
// When virtualization is fully disabled, pre-compute the render context to
// cover all rows/columns. This matches what `computeRenderContext` returns
// for the disabled case, so the first `forceUpdateRenderContext` after mount
// detects no change and skips the store notification, which avoids a nested
// re-render.
const renderContext = enabled === false && enabledForRows === false && enabledForColumns === false ? {
firstRowIndex: 0,
lastRowIndex: params.rows.length,
firstColumnIndex: 0,
lastColumnIndex: params.columns?.length ?? 0
} : EMPTY_RENDER_CONTEXT;
const state = {
virtualization: (0, _extends2.default)({
enabled: !_platform.platform.env.jsdom,
enabledForRows: !_platform.platform.env.jsdom,
enabledForColumns: !_platform.platform.env.jsdom,
renderContext,
props: params.layout.constructor.elements.reduce((acc, key) => (acc[key], acc), {}),
context: {},
scrollPosition: {
current: _models.ScrollPosition.EMPTY
},
layoutMode: params.virtualization.layoutMode ?? 'uncontrolled'
}, params.initialState?.virtualization),
// FIXME: refactor once the state shape is settled
getters: null
};
return state;
}
/** APIs to override for colspan/rowspan */
function useVirtualization(store, params, api) {
const {
layout,
dimensions: {
rowHeight,
columnsTotalWidth = 0
},
virtualization: {
isRtl = false,
rowBufferPx = 150,
columnBufferPx = 150
},
colspan,
initialState,
rows,
range,
columns,
pinnedRows = _core.PinnedRows.EMPTY,
pinnedColumns = _core.PinnedColumns.EMPTY,
onWheel,
onTouchMove,
onRenderContextChange,
onScrollChange,
scrollReset,
renderRow,
renderInfiniteLoadingTrigger
} = params;
const hasBottomPinnedRows = pinnedRows.bottom.length > 0;
const [panels, setPanels] = React.useState(EMPTY_DETAIL_PANELS);
const isUpdateScheduled = React.useRef(false);
const isRenderContextReady = React.useRef(false);
const renderContext = (0, _store.useStore)(store, selectors.renderContext);
const enabledForRows = (0, _store.useStore)(store, selectors.enabledForRows);
const enabledForColumns = (0, _store.useStore)(store, selectors.enabledForColumns);
const layoutMode = (0, _store.useStore)(store, selectors.layoutMode);
const contentHeight = (0, _store.useStore)(store, _dimensions.Dimensions.selectors.contentHeight);
/*
* Scroll context logic
* ====================
* We only render the cells contained in the `renderContext`. However, when the user starts scrolling the grid
* in a direction, we want to render as many cells as possible in that direction, as to avoid presenting white
* areas if the user scrolls too fast/far and the viewport ends up in a region we haven't rendered yet. To render
* more cells, we store some offsets to add to the viewport in `scrollCache.buffer`. Those offsets make the render
* context wider in the direction the user is going, but also makes the buffer around the viewport `0` for the
* dimension (horizontal or vertical) in which the user is not scrolling. So if the normal viewport is 8 columns
* wide, with a 1 column buffer (10 columns total), then we want it to be exactly 8 columns wide during vertical
* scroll.
* However, we don't want the rows in the old context to re-render from e.g. 10 columns to 8 columns, because that's
* work that's not necessary. Thus we store the context at the start of the scroll in `frozenContext`, and the rows
* that are part of this old context will keep their same render context as to avoid re-rendering.
*/
const scrollPosition = React.useRef(initialState?.scroll ?? EMPTY_SCROLL_POSITION);
const ignoreNextScrollEvent = React.useRef(false);
const previousContextScrollPosition = React.useRef(EMPTY_SCROLL_POSITION);
const previousRowContext = React.useRef(EMPTY_RENDER_CONTEXT);
const scrollTimeout = (0, _useTimeout.default)();
const frozenContext = React.useRef(undefined);
const scrollCache = (0, _useLazyRef.default)(() => createScrollCache(isRtl, rowBufferPx, columnBufferPx, rowHeight * 15, MINIMUM_COLUMN_WIDTH * 6, layoutMode)).current;
const updateRenderContext = React.useCallback(nextRenderContext => {
if (!areRenderContextsEqual(nextRenderContext, store.state.virtualization.renderContext)) {
store.set('virtualization', (0, _extends2.default)({}, store.state.virtualization, {
renderContext: nextRenderContext,
scrollPosition: {
current: (0, _extends2.default)({}, scrollPosition.current)
}
}));
}
// The lazy-loading hook is listening to `renderedRowsIntervalChange`,
// but only does something if we already have a render context, because
// otherwise we would call an update directly on mount
const isReady = _dimensions.Dimensions.selectors.dimensions(store.state).isReady;
const didRowsIntervalChange = nextRenderContext.firstRowIndex !== previousRowContext.current.firstRowIndex || nextRenderContext.lastRowIndex !== previousRowContext.current.lastRowIndex;
if (isReady && didRowsIntervalChange) {
previousRowContext.current = nextRenderContext;
onRenderContextChange?.(nextRenderContext);
}
previousContextScrollPosition.current = scrollPosition.current;
}, [store, onRenderContextChange]);
const triggerUpdateRenderContext = (0, _useEventCallback.default)(() => {
const scroller = layout.refs.scroller.current;
if (!scroller) {
return undefined;
}
const dimensions = _dimensions.Dimensions.selectors.dimensions(store.state);
const maxScrollTop = Math.ceil(dimensions.contentSize.height - dimensions.viewportInnerSize.height);
const maxScrollLeft = Math.ceil(dimensions.contentSize.width - dimensions.viewportInnerSize.width);
// Clamp the scroll position to the viewport to avoid re-calculating the render context for scroll bounce
const newScroll = {
top: clamp(scroller.scrollTop, 0, maxScrollTop),
left: isRtl ? clamp(scroller.scrollLeft, -Math.abs(maxScrollLeft), 0) : clamp(scroller.scrollLeft, 0, maxScrollLeft)
};
const dx = newScroll.left - scrollPosition.current.left;
const dy = newScroll.top - scrollPosition.current.top;
const isScrolling = dx !== 0 || dy !== 0;
scrollPosition.current = newScroll;
const direction = isScrolling ? _models.ScrollDirection.forDelta(dx, dy) : _models.ScrollDirection.NONE;
// Since previous render, we have scrolled...
const rowScroll = Math.abs(scrollPosition.current.top - previousContextScrollPosition.current.top);
const columnScroll = Math.abs(scrollPosition.current.left - previousContextScrollPosition.current.left);
// PERF: use the computed minimum column width instead of a static one
const didCrossThreshold = rowScroll >= rowHeight || columnScroll >= MINIMUM_COLUMN_WIDTH;
const didChangeDirection = scrollCache.direction !== direction;
const shouldUpdate = didCrossThreshold || didChangeDirection;
if (!shouldUpdate) {
store.set('virtualization', (0, _extends2.default)({}, store.state.virtualization, {
scrollPosition: {
current: (0, _extends2.default)({}, scrollPosition.current)
}
}));
return renderContext;
}
// Render a new context
if (didChangeDirection) {
switch (direction) {
case _models.ScrollDirection.NONE:
case _models.ScrollDirection.LEFT:
case _models.ScrollDirection.RIGHT:
frozenContext.current = undefined;
break;
default:
frozenContext.current = renderContext;
break;
}
}
scrollCache.direction = direction;
scrollCache.buffer = bufferForDirection(isRtl, direction, rowBufferPx, columnBufferPx, rowHeight * 15, MINIMUM_COLUMN_WIDTH * 6, layoutMode);
const inputs = inputsSelector(store, params, api, enabledForRows, enabledForColumns, layoutMode);
const nextRenderContext = computeRenderContext(inputs, scrollPosition.current, scrollCache);
if (!areRenderContextsEqual(nextRenderContext, renderContext)) {
// Prevents batching render context changes
ReactDOM.flushSync(() => {
updateRenderContext(nextRenderContext);
});
if (layoutMode === 'uncontrolled') {
scrollTimeout.start(1000, triggerUpdateRenderContext);
}
} else {
store.set('virtualization', (0, _extends2.default)({}, store.state.virtualization, {
scrollPosition: {
current: (0, _extends2.default)({}, scrollPosition.current)
}
}));
}
return nextRenderContext;
});
const forceUpdateRenderContext = () => {
// skip update if dimensions are not ready and virtualization is enabled
if (!_dimensions.Dimensions.selectors.dimensions(store.state).isReady && (enabledForRows || enabledForColumns)) {
return;
}
const inputs = inputsSelector(store, params, api, enabledForRows, enabledForColumns, layoutMode);
const nextRenderContext = computeRenderContext(inputs, scrollPosition.current, scrollCache);
// Reset the frozen context when the render context changes, see the illustration in https://github.com/mui/mui-x/pull/12353
frozenContext.current = undefined;
updateRenderContext(nextRenderContext);
};
const forceUpdateRenderContextCallback = (0, _useEventCallback.default)(forceUpdateRenderContext);
(0, _store.useStoreEffect)(store, _dimensions.Dimensions.selectors.dimensions, (previous, next) => {
if (next.isReady) {
forceUpdateRenderContext();
}
});
(0, _useEnhancedEffect.default)(() => {
if (isUpdateScheduled.current) {
forceUpdateRenderContext();
isUpdateScheduled.current = false;
}
});
const scheduleUpdateRenderContext = () => {
isUpdateScheduled.current = true;
};
const handleScroll = (0, _useEventCallback.default)(() => {
if (ignoreNextScrollEvent.current) {
ignoreNextScrollEvent.current = false;
return;
}
const nextRenderContext = triggerUpdateRenderContext();
if (nextRenderContext) {
onScrollChange?.(scrollPosition.current, nextRenderContext);
}
});
/**
* HACK: unstable_rowTree fixes the issue described below, but does it by tightly coupling this
* section of code to the DataGrid's rowTree model. The `unstable_rowTree` param is a temporary
* solution to decouple the code.
*/
const getRows = (rowParams = {}, unstable_rowTree) => {
if (!rowParams.rows && !range) {
return [];
}
let baseRenderContext = renderContext;
if (rowParams.renderContext) {
baseRenderContext = rowParams.renderContext;
baseRenderContext.firstColumnIndex = renderContext.firstColumnIndex;
baseRenderContext.lastColumnIndex = renderContext.lastColumnIndex;
}
const isLastSection = !hasBottomPinnedRows && rowParams.position === undefined || hasBottomPinnedRows && rowParams.position === 'bottom';
const isPinnedSection = rowParams.position !== undefined;
let rowIndexOffset;
switch (rowParams.position) {
case 'top':
rowIndexOffset = 0;
break;
case 'bottom':
rowIndexOffset = pinnedRows.top.length + rows.length;
break;
case undefined:
default:
rowIndexOffset = pinnedRows.top.length;
break;
}
const rowModels = rowParams.rows ?? rows;
const firstRowToRender = baseRenderContext.firstRowIndex;
const lastRowToRender = Math.min(baseRenderContext.lastRowIndex, rowModels.length);
const rowIndexes = rowParams.rows ? createRange(0, rowParams.rows.length) : createRange(firstRowToRender, lastRowToRender);
let virtualRowIndex = -1;
const focusedVirtualCell = params.focusedVirtualCell?.();
if (!isPinnedSection && focusedVirtualCell) {
if (focusedVirtualCell.rowIndex < firstRowToRender && focusedVirtualCell.rowIndex >= 0 && focusedVirtualCell.rowIndex < rowModels.length) {
rowIndexes.unshift(focusedVirtualCell.rowIndex);
virtualRowIndex = focusedVirtualCell.rowIndex;
}
if (focusedVirtualCell.rowIndex > lastRowToRender && focusedVirtualCell.rowIndex < rowModels.length) {
rowIndexes.push(focusedVirtualCell.rowIndex);
virtualRowIndex = focusedVirtualCell.rowIndex;
}
}
const rowElements = [];
const columnPositions = _dimensions.Dimensions.selectors.columnPositions(store.state, columns);
rowIndexes.forEach(rowIndexInPage => {
const {
id,
model
} = rowModels[rowIndexInPage];
// In certain cases, the state might already be updated and `params.rows` (which sets `rowModels`)
// contains stale data.
// In that case, skip any further row processing.
// See:
// - https://github.com/mui/mui-x/issues/16638
// - https://github.com/mui/mui-x/issues/17022
if (unstable_rowTree && !unstable_rowTree[id]) {
return;
}
const rowIndex = (range?.firstRowIndex || 0) + rowIndexOffset + rowIndexInPage;
// NOTE: This is an expensive feature, the colSpan code could be optimized.
if (colspan?.enabled) {
const minFirstColumn = pinnedColumns.left.length;
const maxLastColumn = columns.length - pinnedColumns.right.length;
api.calculateColSpan(id, minFirstColumn, maxLastColumn, columns);
if (pinnedColumns.left.length > 0) {
api.calculateColSpan(id, 0, pinnedColumns.left.length, columns);
}
if (pinnedColumns.right.length > 0) {
api.calculateColSpan(id, columns.length - pinnedColumns.right.length, columns.length, columns);
}
}
const baseRowHeight = !api.rowsMeta.rowHasAutoHeight(id) ? api.rowsMeta.getRowHeight(id) : 'auto';
let isFirstVisible = false;
if (rowParams.position === undefined) {
isFirstVisible = rowIndexInPage === 0;
}
let isLastVisible = false;
const isLastVisibleInSection = rowIndexInPage === rowModels.length - 1;
if (isLastSection) {
if (!isPinnedSection) {
const lastIndex = rows.length - 1;
const isLastVisibleRowIndex = rowIndexInPage === lastIndex;
if (isLastVisibleRowIndex) {
isLastVisible = true;
}
} else {
isLastVisible = isLastVisibleInSection;
}
}
let currentRenderContext = baseRenderContext;
if (frozenContext.current && rowIndexInPage >= frozenContext.current.firstRowIndex && rowIndexInPage < frozenContext.current.lastRowIndex) {
currentRenderContext = frozenContext.current;
}
const isVirtualFocusRow = rowIndexInPage === virtualRowIndex;
const isVirtualFocusColumn = focusedVirtualCell?.rowIndex === rowIndex;
const offsetLeft = computeOffsetLeft(columnPositions, currentRenderContext, pinnedColumns.left.length, layoutMode);
const showBottomBorder = isLastVisibleInSection && rowParams.position === 'top';
const firstColumnIndex = currentRenderContext.firstColumnIndex;
const lastColumnIndex = currentRenderContext.lastColumnIndex;
rowElements.push(renderRow({
id,
model,
rowIndex,
offsetLeft,
columnsTotalWidth,
baseRowHeight,
firstColumnIndex,
lastColumnIndex,
focusedColumnIndex: isVirtualFocusColumn ? focusedVirtualCell.columnIndex : undefined,
isFirstVisible,
isLastVisible,
isVirtualFocusRow,
showBottomBorder
}));
if (isVirtualFocusRow) {
return;
}
const panel = panels.get(id);
if (panel) {
rowElements.push(panel);
}
if (rowParams.position === undefined && isLastVisibleInSection && renderInfiniteLoadingTrigger) {
rowElements.push(renderInfiniteLoadingTrigger(id));
}
});
return rowElements;
};
const scrollRestoreCallback = React.useRef(null);
(0, _useEnhancedEffect.default)(() => {
if (!isRenderContextReady.current) {
return;
}
forceUpdateRenderContextCallback();
}, [enabledForColumns, enabledForRows, forceUpdateRenderContextCallback]);
(0, _useEnhancedEffect.default)(() => {
if (layout.refs.scroller.current) {
layout.refs.scroller.current.scrollLeft = 0;
}
}, [layout.refs.scroller, scrollReset]);
(0, _useRunOnce.useRunOnce)(renderContext !== EMPTY_RENDER_CONTEXT, () => {
onScrollChange?.(scrollPosition.current, renderContext);
isRenderContextReady.current = true;
if (initialState?.scroll && layout.refs.scroller.current) {
const scroller = layout.refs.scroller.current;
const {
top,
left
} = initialState.scroll;
const isScrollRestored = {
top: !(top > 0),
left: !(left > 0)
};
if (!isScrollRestored.left && columnsTotalWidth) {
scroller.scrollLeft = left;
isScrollRestored.left = true;
ignoreNextScrollEvent.current = true;
}
// To restore the vertical scroll, we need to wait until the rows are available in the DOM (otherwise
// there's nowhere to scroll). We still set the scrollTop to the initial value at this point in case
// there already are rows rendered in the DOM, but we only confirm `isScrollRestored.top = true` in the
// asynchronous callback below.
if (!isScrollRestored.top && contentHeight) {
scroller.scrollTop = top;
ignoreNextScrollEvent.current = true;
}
if (!isScrollRestored.top || !isScrollRestored.left) {
scrollRestoreCallback.current = (columnsTotalWidthCurrent, contentHeightCurrent) => {
if (!isScrollRestored.left && columnsTotalWidthCurrent) {
scroller.scrollLeft = left;
isScrollRestored.left = true;
ignoreNextScrollEvent.current = true;
}
if (!isScrollRestored.top && contentHeightCurrent) {
scroller.scrollTop = top;
isScrollRestored.top = true;
ignoreNextScrollEvent.current = true;
}
if (isScrollRestored.left && isScrollRestored.top) {
scrollRestoreCallback.current = null;
}
};
}
}
});
(0, _store.useStoreEffect)(store, _dimensions.Dimensions.selectors.dimensions, forceUpdateRenderContext);
(0, _useEnhancedEffect.default)(() => {
if (layout.refs.scroller) {
scrollRestoreCallback.current?.(columnsTotalWidth, contentHeight);
}
}, [layout.refs.scroller, columnsTotalWidth, contentHeight]);
const isFirstSizing = React.useRef(true);
const containerRef = (0, _useRefCallback.default)(node => {
layout.refs.container.current = node;
const unsubscribe = (0, _dimensions.observeRootNode)(node, store, rootSize => {
if (rootSize.width === 0 && rootSize.height === 0 && store.state.rootSize.height !== 0 && store.state.rootSize.width !== 0) {
return;
}
store.state.rootSize = rootSize;
if (isFirstSizing.current || !api.debouncedUpdateDimensions) {
// We want to initialize the grid dimensions as soon as possible to avoid flickering
api.updateDimensions(isFirstSizing.current);
isFirstSizing.current = false;
} else {
api.debouncedUpdateDimensions();
}
});
return () => {
unsubscribe?.();
layout.refs.container.current = null;
};
});
const scrollerRef = (0, _useRefCallback.default)(node => {
layout.refs.scroller.current = node;
const opts = {
passive: true
};
node.addEventListener('scroll', handleScroll, opts);
node.addEventListener('wheel', onWheel, opts);
node.addEventListener('touchmove', onTouchMove, opts);
return () => {
node.removeEventListener('scroll', handleScroll, opts);
node.removeEventListener('wheel', onWheel, opts);
node.removeEventListener('touchmove', onTouchMove, opts);
layout.refs.scroller.current = null;
};
});
const layoutParams = {
containerRef,
scrollerRef
};
const layoutAPI = layout.use(store, params, api, layoutParams);
const getters = (0, _extends2.default)({
setPanels,
getRows,
rows: params.rows
}, layoutAPI);
return (0, _extends2.default)({
getters,
setPanels,
forceUpdateRenderContext,
scheduleUpdateRenderContext
}, createSpanningAPI());
}
function inputsSelector(store, params, api, enabledForRows, enabledForColumns, layoutMode) {
const dimensions = _dimensions.Dimensions.selectors.dimensions(store.state);
const rows = params.rows;
const range = params.range;
const columns = params.columns;
const hiddenCellsOriginMap = api.getHiddenCellsOrigin();
const lastRowId = params.rows.at(-1)?.id;
const lastColumn = columns.at(-1);
return {
api,
enabledForRows,
enabledForColumns,
autoHeight: dimensions.autoHeight,
rowBufferPx: params.virtualization.rowBufferPx,
columnBufferPx: params.virtualization.columnBufferPx,
leftPinnedWidth: dimensions.leftPinnedWidth,
rightPinnedWidth: dimensions.rightPinnedWidth,
columnsTotalWidth: dimensions.columnsTotalWidth,
viewportInnerWidth: dimensions.viewportInnerSize.width,
viewportInnerHeight: dimensions.viewportInnerSize.height,
lastRowHeight: lastRowId !== undefined ? api.rowsMeta.getRowHeight(lastRowId) : 0,
lastColumnWidth: lastColumn?.computedWidth ?? 0,
rowsMeta: _dimensions.Dimensions.selectors.rowsMeta(store.state),
columnPositions: _dimensions.Dimensions.selectors.columnPositions(store.state, params.columns),
rows,
range,
pinnedColumns: params.pinnedColumns,
columns,
hiddenCellsOriginMap,
virtualizeColumnsWithAutoRowHeight: params.virtualizeColumnsWithAutoRowHeight,
layoutMode
};
}
function computeRenderContext(inputs, scrollPosition, scrollCache) {
const renderContext = {
firstRowIndex: 0,
lastRowIndex: inputs.rows.length,
firstColumnIndex: 0,
lastColumnIndex: inputs.columns.length
};
const {
top,
left
} = scrollPosition;
const realLeft = Math.abs(left) + inputs.leftPinnedWidth;
if (inputs.enabledForRows) {
// Clamp the value because the search may return an index out of bounds.
// In the last index, this is not needed because Array.slice doesn't include it.
let firstRowIndex = Math.min(getNearestIndexToRender(inputs, top, {
atStart: true,
lastPosition: inputs.rowsMeta.positions[inputs.rowsMeta.positions.length - 1] + inputs.lastRowHeight
}), inputs.rowsMeta.positions.length - 1);
// If any of the cells in the `firstRowIndex` is hidden due to an extended row span,
// Make sure the row from where the rowSpan is originated is visible.
const rowSpanHiddenCellOrigin = inputs.hiddenCellsOriginMap[firstRowIndex];
if (rowSpanHiddenCellOrigin) {
const minSpannedRowIndex = Math.min(...Object.values(rowSpanHiddenCellOrigin));
firstRowIndex = Math.min(firstRowIndex, minSpannedRowIndex);
}
const lastRowIndex = inputs.autoHeight ? firstRowIndex + inputs.rows.length : getNearestIndexToRender(inputs, top + inputs.viewportInnerHeight);
renderContext.firstRowIndex = firstRowIndex;
renderContext.lastRowIndex = lastRowIndex;
}
// XXX
// if (inputs.listView) {
// return {
// ...renderContext,
// lastColumnIndex: 1,
// };
// }
if (inputs.enabledForColumns) {
let firstColumnIndex = 0;
let lastColumnIndex = inputs.columnPositions.length;
let hasRowWithAutoHeight = false;
const [firstRowToRender, lastRowToRender] = getIndexesToRender({
firstIndex: renderContext.firstRowIndex,
lastIndex: renderContext.lastRowIndex,
minFirstIndex: 0,
maxLastIndex: inputs.rows.length,
bufferBefore: scrollCache.buffer.rowBefore,
bufferAfter: scrollCache.buffer.rowAfter,
positions: inputs.rowsMeta.positions,
lastSize: inputs.lastRowHeight
});
if (!inputs.virtualizeColumnsWithAutoRowHeight) {
for (let i = firstRowToRender; i < lastRowToRender && !hasRowWithAutoHeight; i += 1) {
const row = inputs.rows[i];
hasRowWithAutoHeight = inputs.api.rowsMeta.rowHasAutoHeight(row.id);
}
}
if (!hasRowWithAutoHeight || inputs.virtualizeColumnsWithAutoRowHeight) {
firstColumnIndex = binarySearch(realLeft, inputs.columnPositions, {
atStart: true,
lastPosition: inputs.columnsTotalWidth
});
const rightBound = inputs.layoutMode === 'controlled' ? realLeft + inputs.viewportInnerWidth - inputs.rightPinnedWidth : realLeft + inputs.viewportInnerWidth;
lastColumnIndex = binarySearch(rightBound, inputs.columnPositions);
}
renderContext.firstColumnIndex = firstColumnIndex;
renderContext.lastColumnIndex = lastColumnIndex;
}
const actualRenderContext = deriveRenderContext(inputs, renderContext, scrollCache);
return actualRenderContext;
}
function getNearestIndexToRender(inputs, offset, options) {
const lastMeasuredIndexRelativeToAllRows = inputs.api.rowsMeta.getLastMeasuredRowIndex();
let allRowsMeasured = lastMeasuredIndexRelativeToAllRows === Infinity;
if (inputs.range?.lastRowIndex && !allRowsMeasured) {
// Check if all rows in this page are already measured
allRowsMeasured = lastMeasuredIndexRelativeToAllRows >= inputs.range.lastRowIndex;
}
const lastMeasuredIndexRelativeToCurrentPage = clamp(lastMeasuredIndexRelativeToAllRows - (inputs.range?.firstRowIndex || 0), 0, inputs.rowsMeta.positions.length);
if (allRowsMeasured || inputs.rowsMeta.positions[lastMeasuredIndexRelativeToCurrentPage] >= offset) {
// If all rows were measured (when no row has "auto" as height) or all rows before the offset
// were measured, then use a binary search because it's faster.
return binarySearch(offset, inputs.rowsMeta.positions, options);
}
// Otherwise, use an exponential search.
// If rows have "auto" as height, their positions will be based on estimated heights.
// In this case, we can skip several steps until we find a position higher than the offset.
// Inspired by https://github.com/bvaughn/react-virtualized/blob/master/source/Grid/utils/CellSizeAndPositionManager.js
return exponentialSearch(offset, inputs.rowsMeta.positions, lastMeasuredIndexRelativeToCurrentPage, options);
}
/**
* Accepts as input a raw render context (the area visible in the viewport) and adds
* computes the actual render context based on pinned elements, buffer dimensions and
* spanning.
*/
function deriveRenderContext(inputs, nextRenderContext, scrollCache) {
const [firstRowToRender, lastRowToRender] = getIndexesToRender({
firstIndex: nextRenderContext.firstRowIndex,
lastIndex: nextRenderContext.lastRowIndex,
minFirstIndex: 0,
maxLastIndex: inputs.rows.length,
bufferBefore: scrollCache.buffer.rowBefore,
bufferAfter: scrollCache.buffer.rowAfter,
positions: inputs.rowsMeta.positions,
lastSize: inputs.lastRowHeight
});
const [initialFirstColumnToRender, lastColumnToRender] = getIndexesToRender({
firstIndex: nextRenderContext.firstColumnIndex,
lastIndex: nextRenderContext.lastColumnIndex,
minFirstIndex: inputs.pinnedColumns?.left.length ?? 0,
maxLastIndex: inputs.columns.length - (inputs.pinnedColumns?.right.length ?? 0),
bufferBefore: scrollCache.buffer.columnBefore,
bufferAfter: scrollCache.buffer.columnAfter,
positions: inputs.columnPositions,
lastSize: inputs.lastColumnWidth
});
const firstColumnToRender = getFirstNonSpannedColumnToRender({
api: inputs.api,
firstColumnToRender: initialFirstColumnToRender,
firstRowToRender,
lastRowToRender,
visibleRows: inputs.rows
});
return {
firstRowIndex: firstRowToRender,
lastRowIndex: lastRowToRender,
firstColumnIndex: firstColumnToRender,
lastColumnIndex: lastColumnToRender
};
}
/**
* Use binary search to avoid looping through all possible positions.
* The `options.atStart` provides the possibility to match for the first element that
* intersects the screen, even if said element's start position is before `offset`. In
* other words, we search for `offset + width`.
*/
function binarySearch(offset, positions, options = undefined, sliceStart = 0, sliceEnd = positions.length) {
if (positions.length <= 0) {
return -1;
}
if (sliceStart >= sliceEnd) {
return sliceStart;
}
const pivot = sliceStart + Math.floor((sliceEnd - sliceStart) / 2);
const position = positions[pivot];
let isBefore;
if (options?.atStart) {
const width = (pivot === positions.length - 1 ? options.lastPosition : positions[pivot + 1]) - position;
isBefore = offset - width < position;
} else {
isBefore = offset <= position;
}
return isBefore ? binarySearch(offset, positions, options, sliceStart, pivot) : binarySearch(offset, positions, options, pivot + 1, sliceEnd);
}
function exponentialSearch(offset, positions, index, options = undefined) {
let interval = 1;
while (index < positions.length && Math.abs(positions[index]) < offset) {
index += interval;
interval *= 2;
}
return binarySearch(offset, positions, options, Math.floor(index / 2), Math.min(index, positions.length));
}
function getIndexesToRender({
firstIndex,
lastIndex,
bufferBefore,
bufferAfter,
minFirstIndex,
maxLastIndex,
positions,
lastSize
}) {
const firstPosition = positions[firstIndex] - bufferBefore;
const lastPosition = positions[lastIndex] + bufferAfter;
const firstIndexPadded = binarySearch(firstPosition, positions, {
atStart: true,
lastPosition: positions[positions.length - 1] + lastSize
});
const lastIndexPadded = binarySearch(lastPosition, positions) + 1;
return [clamp(firstIndexPadded, minFirstIndex, maxLastIndex), clamp(lastIndexPadded, minFirstIndex, maxLastIndex)];
}
function areRenderContextsEqual(context1, context2) {
if (context1 === context2) {
return true;
}
return context1.firstRowIndex === context2.firstRowIndex && context1.lastRowIndex === context2.lastRowIndex && context1.firstColumnIndex === context2.firstColumnIndex && context1.lastColumnIndex === context2.lastColumnIndex;
}
function computeOffsetLeft(columnPositions, renderContext, pinnedLeftLength, layoutMode = 'uncontrolled') {
let offset = columnPositions[renderContext.firstColumnIndex] ?? 0;
/* CSS sticky leaves elements in the normal flow of the DOM, so we
* don't need to add the offset of the pinned columns. */
if (layoutMode === 'uncontrolled') {
offset -= columnPositions[pinnedLeftLength] ?? 0;
}
return Math.abs(offset);
}
const EMPTY_BUFFER = {
rowAfter: 0,
rowBefore: 0,
columnAfter: 0,
columnBefore: 0
};
function bufferForDirection(isRtl, direction, rowBufferPx, columnBufferPx, verticalBuffer, horizontalBuffer, layoutMode = 'uncontrolled') {
if (layoutMode === 'controlled') {
return EMPTY_BUFFER;
}
if (isRtl) {
switch (direction) {
case _models.ScrollDirection.LEFT:
direction = _models.ScrollDirection.RIGHT;
break;
case _models.ScrollDirection.RIGHT:
direction = _models.ScrollDirection.LEFT;
break;
default:
}
}
switch (direction) {
case _models.ScrollDirection.NONE:
return {
rowAfter: rowBufferPx,
rowBefore: rowBufferPx,
columnAfter: columnBufferPx,
columnBefore: columnBufferPx
};
case _models.ScrollDirection.LEFT:
return {
rowAfter: 0,
rowBefore: 0,
columnAfter: 0,
columnBefore: horizontalBuffer
};
case _models.ScrollDirection.RIGHT:
return {
rowAfter: 0,
rowBefore: 0,
columnAfter: horizontalBuffer,
columnBefore: 0
};
case _models.ScrollDirection.UP:
return {
rowAfter: 0,
rowBefore: verticalBuffer,
columnAfter: 0,
columnBefore: 0
};
case _models.ScrollDirection.DOWN:
return {
rowAfter: verticalBuffer,
rowBefore: 0,
columnAfter: 0,
columnBefore: 0
};
default:
// eslint unable to figure out enum exhaustiveness
throw /* minify-error-disabled */new Error('unreachable');
}
}
function createScrollCache(isRtl, rowBufferPx, columnBufferPx, verticalBuffer, horizontalBuffer, layoutMode = 'uncontrolled') {
return {
direction: _models.ScrollDirection.NONE,
buffer: bufferForDirection(isRtl, _models.ScrollDirection.NONE, rowBufferPx, columnBufferPx, verticalBuffer, horizontalBuffer, layoutMode)
};
}
function createRange(from, to) {
return Array.from({
length: to - from
}).map((_, i) => from + i);
}
function getFirstNonSpannedColumnToRender({
api,
firstColumnToRender,
firstRowToRender,
lastRowToRender,
visibleRows
}) {
let firstNonSpannedColumnToRender = firstColumnToRender;
let foundStableColumn = false;
// Keep checking columns until we find one that's not spanned in any visible row
while (!foundStableColumn && firstNonSpannedColumnToRender >= 0) {
foundStableColumn = true;
for (let i = firstRowToRender; i < lastRowToRender; i += 1) {
const row = visibleRows[i];
if (row) {
const rowId = visibleRows[i].id;
const cellColSpanInfo = api.getCellColSpanInfo(rowId, firstNonSpannedColumnToRender);
if (cellColSpanInfo && cellColSpanInfo.spannedByColSpan && cellColSpanInfo.leftVisibleCellIndex < firstNonSpannedColumnToRender) {
firstNonSpannedColumnToRender = cellColSpanInfo.leftVisibleCellIndex;
foundStableColumn = false;
break; // Check the new column index against the visible rows, because it might be spanned
}
}
}
}
return firstNonSpannedColumnToRender;
}
/** Placeholder API functions for colspan & rowspan to re-implement */
function createSpanningAPI() {
const getCellColSpanInfo = () => {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X: Unimplemented: colspan feature is required' : (0, _formatErrorMessage2.default)(200));
};
const calculateColSpan = () => {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X: Unimplemented: colspan feature is required' : (0, _formatErrorMessage2.default)(200));
};
const getHiddenCellsOrigin = () => {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X: Unimplemented: rowspan feature is required' : (0, _formatErrorMessage2.default)(201));
};
return {
getCellColSpanInfo,
calculateColSpan,
getHiddenCellsOrigin
};
}
function roundToDecimalPlaces(value, decimals) {
return Math.round(value * 10 ** decimals) / 10 ** decimals;
}
@@ -0,0 +1,892 @@
'use client';
import _formatErrorMessage from "@mui/x-internals/formatErrorMessage";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import useLazyRef from '@mui/utils/useLazyRef';
import useTimeout from '@mui/utils/useTimeout';
import useEventCallback from '@mui/utils/useEventCallback';
import useEnhancedEffect from '@mui/utils/useEnhancedEffect';
import { platform } from '@base-ui/utils/platform';
import { useRunOnce } from '@mui/x-internals/useRunOnce';
import { createSelector, useStore, useStoreEffect } from '@mui/x-internals/store';
import useRefCallback from "../../utils/useRefCallback.mjs";
import { PinnedRows, PinnedColumns } from "../../models/core.mjs";
import { Dimensions, observeRootNode } from "../dimensions.mjs";
import { ScrollPosition, ScrollDirection } from "../../models/index.mjs";
/* eslint-disable import/export, @typescript-eslint/no-redeclare */
const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
const MINIMUM_COLUMN_WIDTH = 50;
const EMPTY_SCROLL_POSITION = {
top: 0,
left: 0
};
const EMPTY_DETAIL_PANELS = Object.freeze(new Map());
export const EMPTY_RENDER_CONTEXT = {
firstRowIndex: 0,
lastRowIndex: 0,
firstColumnIndex: 0,
lastColumnIndex: 0
};
const selectors = (() => {
const firstRowIndexSelector = createSelector(state => state.virtualization.renderContext.firstRowIndex);
const scrollPositionSelector = createSelector(state => state.virtualization.scrollPosition);
const layoutModeSelector = createSelector(state => state.virtualization.layoutMode);
return {
store: createSelector(state => state.virtualization),
renderContext: createSelector(state => state.virtualization.renderContext),
enabledForRows: createSelector(state => state.virtualization.enabledForRows),
enabledForColumns: createSelector(state => state.virtualization.enabledForColumns),
offsetTop: createSelector(layoutModeSelector, Dimensions.selectors.dimensions, Dimensions.selectors.rowPositions, firstRowIndexSelector, (layoutMode, dimensions, rowPositions, firstRowIndex) => {
return (layoutMode === 'uncontrolled' ? dimensions.topContainerHeight : 0) + (rowPositions[firstRowIndex] ?? 0);
}),
context: createSelector(state => state.virtualization.context),
layoutMode: layoutModeSelector,
scrollPosition: scrollPositionSelector,
pinnedLeftOffsetSelector: createSelector(scrollPositionSelector, scrollPosition => scrollPosition.current.left),
pinnedRightOffsetSelector: createSelector(scrollPositionSelector, Dimensions.selectors.dimensions, Dimensions.selectors.columnsTotalWidth, Dimensions.selectors.needsVerticalScrollbar, (scrollPosition, dimensions, columnsTotalWidth, needsVerticalScrollbar) => {
return Math.max(columnsTotalWidth, dimensions.viewportOuterSize.width) - dimensions.viewportOuterSize.width - scrollPosition.current.left + (needsVerticalScrollbar ? dimensions.scrollbarSize : 0);
})
};
})();
export const Virtualization = {
initialize: initializeState,
use: useVirtualization,
selectors
};
function initializeState(params) {
const {
enabled,
enabledForRows,
enabledForColumns
} = params.initialState?.virtualization ?? {};
// When virtualization is fully disabled, pre-compute the render context to
// cover all rows/columns. This matches what `computeRenderContext` returns
// for the disabled case, so the first `forceUpdateRenderContext` after mount
// detects no change and skips the store notification, which avoids a nested
// re-render.
const renderContext = enabled === false && enabledForRows === false && enabledForColumns === false ? {
firstRowIndex: 0,
lastRowIndex: params.rows.length,
firstColumnIndex: 0,
lastColumnIndex: params.columns?.length ?? 0
} : EMPTY_RENDER_CONTEXT;
const state = {
virtualization: _extends({
enabled: !platform.env.jsdom,
enabledForRows: !platform.env.jsdom,
enabledForColumns: !platform.env.jsdom,
renderContext,
props: params.layout.constructor.elements.reduce((acc, key) => (acc[key], acc), {}),
context: {},
scrollPosition: {
current: ScrollPosition.EMPTY
},
layoutMode: params.virtualization.layoutMode ?? 'uncontrolled'
}, params.initialState?.virtualization),
// FIXME: refactor once the state shape is settled
getters: null
};
return state;
}
/** APIs to override for colspan/rowspan */
function useVirtualization(store, params, api) {
const {
layout,
dimensions: {
rowHeight,
columnsTotalWidth = 0
},
virtualization: {
isRtl = false,
rowBufferPx = 150,
columnBufferPx = 150
},
colspan,
initialState,
rows,
range,
columns,
pinnedRows = PinnedRows.EMPTY,
pinnedColumns = PinnedColumns.EMPTY,
onWheel,
onTouchMove,
onRenderContextChange,
onScrollChange,
scrollReset,
renderRow,
renderInfiniteLoadingTrigger
} = params;
const hasBottomPinnedRows = pinnedRows.bottom.length > 0;
const [panels, setPanels] = React.useState(EMPTY_DETAIL_PANELS);
const isUpdateScheduled = React.useRef(false);
const isRenderContextReady = React.useRef(false);
const renderContext = useStore(store, selectors.renderContext);
const enabledForRows = useStore(store, selectors.enabledForRows);
const enabledForColumns = useStore(store, selectors.enabledForColumns);
const layoutMode = useStore(store, selectors.layoutMode);
const contentHeight = useStore(store, Dimensions.selectors.contentHeight);
/*
* Scroll context logic
* ====================
* We only render the cells contained in the `renderContext`. However, when the user starts scrolling the grid
* in a direction, we want to render as many cells as possible in that direction, as to avoid presenting white
* areas if the user scrolls too fast/far and the viewport ends up in a region we haven't rendered yet. To render
* more cells, we store some offsets to add to the viewport in `scrollCache.buffer`. Those offsets make the render
* context wider in the direction the user is going, but also makes the buffer around the viewport `0` for the
* dimension (horizontal or vertical) in which the user is not scrolling. So if the normal viewport is 8 columns
* wide, with a 1 column buffer (10 columns total), then we want it to be exactly 8 columns wide during vertical
* scroll.
* However, we don't want the rows in the old context to re-render from e.g. 10 columns to 8 columns, because that's
* work that's not necessary. Thus we store the context at the start of the scroll in `frozenContext`, and the rows
* that are part of this old context will keep their same render context as to avoid re-rendering.
*/
const scrollPosition = React.useRef(initialState?.scroll ?? EMPTY_SCROLL_POSITION);
const ignoreNextScrollEvent = React.useRef(false);
const previousContextScrollPosition = React.useRef(EMPTY_SCROLL_POSITION);
const previousRowContext = React.useRef(EMPTY_RENDER_CONTEXT);
const scrollTimeout = useTimeout();
const frozenContext = React.useRef(undefined);
const scrollCache = useLazyRef(() => createScrollCache(isRtl, rowBufferPx, columnBufferPx, rowHeight * 15, MINIMUM_COLUMN_WIDTH * 6, layoutMode)).current;
const updateRenderContext = React.useCallback(nextRenderContext => {
if (!areRenderContextsEqual(nextRenderContext, store.state.virtualization.renderContext)) {
store.set('virtualization', _extends({}, store.state.virtualization, {
renderContext: nextRenderContext,
scrollPosition: {
current: _extends({}, scrollPosition.current)
}
}));
}
// The lazy-loading hook is listening to `renderedRowsIntervalChange`,
// but only does something if we already have a render context, because
// otherwise we would call an update directly on mount
const isReady = Dimensions.selectors.dimensions(store.state).isReady;
const didRowsIntervalChange = nextRenderContext.firstRowIndex !== previousRowContext.current.firstRowIndex || nextRenderContext.lastRowIndex !== previousRowContext.current.lastRowIndex;
if (isReady && didRowsIntervalChange) {
previousRowContext.current = nextRenderContext;
onRenderContextChange?.(nextRenderContext);
}
previousContextScrollPosition.current = scrollPosition.current;
}, [store, onRenderContextChange]);
const triggerUpdateRenderContext = useEventCallback(() => {
const scroller = layout.refs.scroller.current;
if (!scroller) {
return undefined;
}
const dimensions = Dimensions.selectors.dimensions(store.state);
const maxScrollTop = Math.ceil(dimensions.contentSize.height - dimensions.viewportInnerSize.height);
const maxScrollLeft = Math.ceil(dimensions.contentSize.width - dimensions.viewportInnerSize.width);
// Clamp the scroll position to the viewport to avoid re-calculating the render context for scroll bounce
const newScroll = {
top: clamp(scroller.scrollTop, 0, maxScrollTop),
left: isRtl ? clamp(scroller.scrollLeft, -Math.abs(maxScrollLeft), 0) : clamp(scroller.scrollLeft, 0, maxScrollLeft)
};
const dx = newScroll.left - scrollPosition.current.left;
const dy = newScroll.top - scrollPosition.current.top;
const isScrolling = dx !== 0 || dy !== 0;
scrollPosition.current = newScroll;
const direction = isScrolling ? ScrollDirection.forDelta(dx, dy) : ScrollDirection.NONE;
// Since previous render, we have scrolled...
const rowScroll = Math.abs(scrollPosition.current.top - previousContextScrollPosition.current.top);
const columnScroll = Math.abs(scrollPosition.current.left - previousContextScrollPosition.current.left);
// PERF: use the computed minimum column width instead of a static one
const didCrossThreshold = rowScroll >= rowHeight || columnScroll >= MINIMUM_COLUMN_WIDTH;
const didChangeDirection = scrollCache.direction !== direction;
const shouldUpdate = didCrossThreshold || didChangeDirection;
if (!shouldUpdate) {
store.set('virtualization', _extends({}, store.state.virtualization, {
scrollPosition: {
current: _extends({}, scrollPosition.current)
}
}));
return renderContext;
}
// Render a new context
if (didChangeDirection) {
switch (direction) {
case ScrollDirection.NONE:
case ScrollDirection.LEFT:
case ScrollDirection.RIGHT:
frozenContext.current = undefined;
break;
default:
frozenContext.current = renderContext;
break;
}
}
scrollCache.direction = direction;
scrollCache.buffer = bufferForDirection(isRtl, direction, rowBufferPx, columnBufferPx, rowHeight * 15, MINIMUM_COLUMN_WIDTH * 6, layoutMode);
const inputs = inputsSelector(store, params, api, enabledForRows, enabledForColumns, layoutMode);
const nextRenderContext = computeRenderContext(inputs, scrollPosition.current, scrollCache);
if (!areRenderContextsEqual(nextRenderContext, renderContext)) {
// Prevents batching render context changes
ReactDOM.flushSync(() => {
updateRenderContext(nextRenderContext);
});
if (layoutMode === 'uncontrolled') {
scrollTimeout.start(1000, triggerUpdateRenderContext);
}
} else {
store.set('virtualization', _extends({}, store.state.virtualization, {
scrollPosition: {
current: _extends({}, scrollPosition.current)
}
}));
}
return nextRenderContext;
});
const forceUpdateRenderContext = () => {
// skip update if dimensions are not ready and virtualization is enabled
if (!Dimensions.selectors.dimensions(store.state).isReady && (enabledForRows || enabledForColumns)) {
return;
}
const inputs = inputsSelector(store, params, api, enabledForRows, enabledForColumns, layoutMode);
const nextRenderContext = computeRenderContext(inputs, scrollPosition.current, scrollCache);
// Reset the frozen context when the render context changes, see the illustration in https://github.com/mui/mui-x/pull/12353
frozenContext.current = undefined;
updateRenderContext(nextRenderContext);
};
const forceUpdateRenderContextCallback = useEventCallback(forceUpdateRenderContext);
useStoreEffect(store, Dimensions.selectors.dimensions, (previous, next) => {
if (next.isReady) {
forceUpdateRenderContext();
}
});
useEnhancedEffect(() => {
if (isUpdateScheduled.current) {
forceUpdateRenderContext();
isUpdateScheduled.current = false;
}
});
const scheduleUpdateRenderContext = () => {
isUpdateScheduled.current = true;
};
const handleScroll = useEventCallback(() => {
if (ignoreNextScrollEvent.current) {
ignoreNextScrollEvent.current = false;
return;
}
const nextRenderContext = triggerUpdateRenderContext();
if (nextRenderContext) {
onScrollChange?.(scrollPosition.current, nextRenderContext);
}
});
/**
* HACK: unstable_rowTree fixes the issue described below, but does it by tightly coupling this
* section of code to the DataGrid's rowTree model. The `unstable_rowTree` param is a temporary
* solution to decouple the code.
*/
const getRows = (rowParams = {}, unstable_rowTree) => {
if (!rowParams.rows && !range) {
return [];
}
let baseRenderContext = renderContext;
if (rowParams.renderContext) {
baseRenderContext = rowParams.renderContext;
baseRenderContext.firstColumnIndex = renderContext.firstColumnIndex;
baseRenderContext.lastColumnIndex = renderContext.lastColumnIndex;
}
const isLastSection = !hasBottomPinnedRows && rowParams.position === undefined || hasBottomPinnedRows && rowParams.position === 'bottom';
const isPinnedSection = rowParams.position !== undefined;
let rowIndexOffset;
switch (rowParams.position) {
case 'top':
rowIndexOffset = 0;
break;
case 'bottom':
rowIndexOffset = pinnedRows.top.length + rows.length;
break;
case undefined:
default:
rowIndexOffset = pinnedRows.top.length;
break;
}
const rowModels = rowParams.rows ?? rows;
const firstRowToRender = baseRenderContext.firstRowIndex;
const lastRowToRender = Math.min(baseRenderContext.lastRowIndex, rowModels.length);
const rowIndexes = rowParams.rows ? createRange(0, rowParams.rows.length) : createRange(firstRowToRender, lastRowToRender);
let virtualRowIndex = -1;
const focusedVirtualCell = params.focusedVirtualCell?.();
if (!isPinnedSection && focusedVirtualCell) {
if (focusedVirtualCell.rowIndex < firstRowToRender && focusedVirtualCell.rowIndex >= 0 && focusedVirtualCell.rowIndex < rowModels.length) {
rowIndexes.unshift(focusedVirtualCell.rowIndex);
virtualRowIndex = focusedVirtualCell.rowIndex;
}
if (focusedVirtualCell.rowIndex > lastRowToRender && focusedVirtualCell.rowIndex < rowModels.length) {
rowIndexes.push(focusedVirtualCell.rowIndex);
virtualRowIndex = focusedVirtualCell.rowIndex;
}
}
const rowElements = [];
const columnPositions = Dimensions.selectors.columnPositions(store.state, columns);
rowIndexes.forEach(rowIndexInPage => {
const {
id,
model
} = rowModels[rowIndexInPage];
// In certain cases, the state might already be updated and `params.rows` (which sets `rowModels`)
// contains stale data.
// In that case, skip any further row processing.
// See:
// - https://github.com/mui/mui-x/issues/16638
// - https://github.com/mui/mui-x/issues/17022
if (unstable_rowTree && !unstable_rowTree[id]) {
return;
}
const rowIndex = (range?.firstRowIndex || 0) + rowIndexOffset + rowIndexInPage;
// NOTE: This is an expensive feature, the colSpan code could be optimized.
if (colspan?.enabled) {
const minFirstColumn = pinnedColumns.left.length;
const maxLastColumn = columns.length - pinnedColumns.right.length;
api.calculateColSpan(id, minFirstColumn, maxLastColumn, columns);
if (pinnedColumns.left.length > 0) {
api.calculateColSpan(id, 0, pinnedColumns.left.length, columns);
}
if (pinnedColumns.right.length > 0) {
api.calculateColSpan(id, columns.length - pinnedColumns.right.length, columns.length, columns);
}
}
const baseRowHeight = !api.rowsMeta.rowHasAutoHeight(id) ? api.rowsMeta.getRowHeight(id) : 'auto';
let isFirstVisible = false;
if (rowParams.position === undefined) {
isFirstVisible = rowIndexInPage === 0;
}
let isLastVisible = false;
const isLastVisibleInSection = rowIndexInPage === rowModels.length - 1;
if (isLastSection) {
if (!isPinnedSection) {
const lastIndex = rows.length - 1;
const isLastVisibleRowIndex = rowIndexInPage === lastIndex;
if (isLastVisibleRowIndex) {
isLastVisible = true;
}
} else {
isLastVisible = isLastVisibleInSection;
}
}
let currentRenderContext = baseRenderContext;
if (frozenContext.current && rowIndexInPage >= frozenContext.current.firstRowIndex && rowIndexInPage < frozenContext.current.lastRowIndex) {
currentRenderContext = frozenContext.current;
}
const isVirtualFocusRow = rowIndexInPage === virtualRowIndex;
const isVirtualFocusColumn = focusedVirtualCell?.rowIndex === rowIndex;
const offsetLeft = computeOffsetLeft(columnPositions, currentRenderContext, pinnedColumns.left.length, layoutMode);
const showBottomBorder = isLastVisibleInSection && rowParams.position === 'top';
const firstColumnIndex = currentRenderContext.firstColumnIndex;
const lastColumnIndex = currentRenderContext.lastColumnIndex;
rowElements.push(renderRow({
id,
model,
rowIndex,
offsetLeft,
columnsTotalWidth,
baseRowHeight,
firstColumnIndex,
lastColumnIndex,
focusedColumnIndex: isVirtualFocusColumn ? focusedVirtualCell.columnIndex : undefined,
isFirstVisible,
isLastVisible,
isVirtualFocusRow,
showBottomBorder
}));
if (isVirtualFocusRow) {
return;
}
const panel = panels.get(id);
if (panel) {
rowElements.push(panel);
}
if (rowParams.position === undefined && isLastVisibleInSection && renderInfiniteLoadingTrigger) {
rowElements.push(renderInfiniteLoadingTrigger(id));
}
});
return rowElements;
};
const scrollRestoreCallback = React.useRef(null);
useEnhancedEffect(() => {
if (!isRenderContextReady.current) {
return;
}
forceUpdateRenderContextCallback();
}, [enabledForColumns, enabledForRows, forceUpdateRenderContextCallback]);
useEnhancedEffect(() => {
if (layout.refs.scroller.current) {
layout.refs.scroller.current.scrollLeft = 0;
}
}, [layout.refs.scroller, scrollReset]);
useRunOnce(renderContext !== EMPTY_RENDER_CONTEXT, () => {
onScrollChange?.(scrollPosition.current, renderContext);
isRenderContextReady.current = true;
if (initialState?.scroll && layout.refs.scroller.current) {
const scroller = layout.refs.scroller.current;
const {
top,
left
} = initialState.scroll;
const isScrollRestored = {
top: !(top > 0),
left: !(left > 0)
};
if (!isScrollRestored.left && columnsTotalWidth) {
scroller.scrollLeft = left;
isScrollRestored.left = true;
ignoreNextScrollEvent.current = true;
}
// To restore the vertical scroll, we need to wait until the rows are available in the DOM (otherwise
// there's nowhere to scroll). We still set the scrollTop to the initial value at this point in case
// there already are rows rendered in the DOM, but we only confirm `isScrollRestored.top = true` in the
// asynchronous callback below.
if (!isScrollRestored.top && contentHeight) {
scroller.scrollTop = top;
ignoreNextScrollEvent.current = true;
}
if (!isScrollRestored.top || !isScrollRestored.left) {
scrollRestoreCallback.current = (columnsTotalWidthCurrent, contentHeightCurrent) => {
if (!isScrollRestored.left && columnsTotalWidthCurrent) {
scroller.scrollLeft = left;
isScrollRestored.left = true;
ignoreNextScrollEvent.current = true;
}
if (!isScrollRestored.top && contentHeightCurrent) {
scroller.scrollTop = top;
isScrollRestored.top = true;
ignoreNextScrollEvent.current = true;
}
if (isScrollRestored.left && isScrollRestored.top) {
scrollRestoreCallback.current = null;
}
};
}
}
});
useStoreEffect(store, Dimensions.selectors.dimensions, forceUpdateRenderContext);
useEnhancedEffect(() => {
if (layout.refs.scroller) {
scrollRestoreCallback.current?.(columnsTotalWidth, contentHeight);
}
}, [layout.refs.scroller, columnsTotalWidth, contentHeight]);
const isFirstSizing = React.useRef(true);
const containerRef = useRefCallback(node => {
layout.refs.container.current = node;
const unsubscribe = observeRootNode(node, store, rootSize => {
if (rootSize.width === 0 && rootSize.height === 0 && store.state.rootSize.height !== 0 && store.state.rootSize.width !== 0) {
return;
}
store.state.rootSize = rootSize;
if (isFirstSizing.current || !api.debouncedUpdateDimensions) {
// We want to initialize the grid dimensions as soon as possible to avoid flickering
api.updateDimensions(isFirstSizing.current);
isFirstSizing.current = false;
} else {
api.debouncedUpdateDimensions();
}
});
return () => {
unsubscribe?.();
layout.refs.container.current = null;
};
});
const scrollerRef = useRefCallback(node => {
layout.refs.scroller.current = node;
const opts = {
passive: true
};
node.addEventListener('scroll', handleScroll, opts);
node.addEventListener('wheel', onWheel, opts);
node.addEventListener('touchmove', onTouchMove, opts);
return () => {
node.removeEventListener('scroll', handleScroll, opts);
node.removeEventListener('wheel', onWheel, opts);
node.removeEventListener('touchmove', onTouchMove, opts);
layout.refs.scroller.current = null;
};
});
const layoutParams = {
containerRef,
scrollerRef
};
const layoutAPI = layout.use(store, params, api, layoutParams);
const getters = _extends({
setPanels,
getRows,
rows: params.rows
}, layoutAPI);
return _extends({
getters,
setPanels,
forceUpdateRenderContext,
scheduleUpdateRenderContext
}, createSpanningAPI());
}
function inputsSelector(store, params, api, enabledForRows, enabledForColumns, layoutMode) {
const dimensions = Dimensions.selectors.dimensions(store.state);
const rows = params.rows;
const range = params.range;
const columns = params.columns;
const hiddenCellsOriginMap = api.getHiddenCellsOrigin();
const lastRowId = params.rows.at(-1)?.id;
const lastColumn = columns.at(-1);
return {
api,
enabledForRows,
enabledForColumns,
autoHeight: dimensions.autoHeight,
rowBufferPx: params.virtualization.rowBufferPx,
columnBufferPx: params.virtualization.columnBufferPx,
leftPinnedWidth: dimensions.leftPinnedWidth,
rightPinnedWidth: dimensions.rightPinnedWidth,
columnsTotalWidth: dimensions.columnsTotalWidth,
viewportInnerWidth: dimensions.viewportInnerSize.width,
viewportInnerHeight: dimensions.viewportInnerSize.height,
lastRowHeight: lastRowId !== undefined ? api.rowsMeta.getRowHeight(lastRowId) : 0,
lastColumnWidth: lastColumn?.computedWidth ?? 0,
rowsMeta: Dimensions.selectors.rowsMeta(store.state),
columnPositions: Dimensions.selectors.columnPositions(store.state, params.columns),
rows,
range,
pinnedColumns: params.pinnedColumns,
columns,
hiddenCellsOriginMap,
virtualizeColumnsWithAutoRowHeight: params.virtualizeColumnsWithAutoRowHeight,
layoutMode
};
}
function computeRenderContext(inputs, scrollPosition, scrollCache) {
const renderContext = {
firstRowIndex: 0,
lastRowIndex: inputs.rows.length,
firstColumnIndex: 0,
lastColumnIndex: inputs.columns.length
};
const {
top,
left
} = scrollPosition;
const realLeft = Math.abs(left) + inputs.leftPinnedWidth;
if (inputs.enabledForRows) {
// Clamp the value because the search may return an index out of bounds.
// In the last index, this is not needed because Array.slice doesn't include it.
let firstRowIndex = Math.min(getNearestIndexToRender(inputs, top, {
atStart: true,
lastPosition: inputs.rowsMeta.positions[inputs.rowsMeta.positions.length - 1] + inputs.lastRowHeight
}), inputs.rowsMeta.positions.length - 1);
// If any of the cells in the `firstRowIndex` is hidden due to an extended row span,
// Make sure the row from where the rowSpan is originated is visible.
const rowSpanHiddenCellOrigin = inputs.hiddenCellsOriginMap[firstRowIndex];
if (rowSpanHiddenCellOrigin) {
const minSpannedRowIndex = Math.min(...Object.values(rowSpanHiddenCellOrigin));
firstRowIndex = Math.min(firstRowIndex, minSpannedRowIndex);
}
const lastRowIndex = inputs.autoHeight ? firstRowIndex + inputs.rows.length : getNearestIndexToRender(inputs, top + inputs.viewportInnerHeight);
renderContext.firstRowIndex = firstRowIndex;
renderContext.lastRowIndex = lastRowIndex;
}
// XXX
// if (inputs.listView) {
// return {
// ...renderContext,
// lastColumnIndex: 1,
// };
// }
if (inputs.enabledForColumns) {
let firstColumnIndex = 0;
let lastColumnIndex = inputs.columnPositions.length;
let hasRowWithAutoHeight = false;
const [firstRowToRender, lastRowToRender] = getIndexesToRender({
firstIndex: renderContext.firstRowIndex,
lastIndex: renderContext.lastRowIndex,
minFirstIndex: 0,
maxLastIndex: inputs.rows.length,
bufferBefore: scrollCache.buffer.rowBefore,
bufferAfter: scrollCache.buffer.rowAfter,
positions: inputs.rowsMeta.positions,
lastSize: inputs.lastRowHeight
});
if (!inputs.virtualizeColumnsWithAutoRowHeight) {
for (let i = firstRowToRender; i < lastRowToRender && !hasRowWithAutoHeight; i += 1) {
const row = inputs.rows[i];
hasRowWithAutoHeight = inputs.api.rowsMeta.rowHasAutoHeight(row.id);
}
}
if (!hasRowWithAutoHeight || inputs.virtualizeColumnsWithAutoRowHeight) {
firstColumnIndex = binarySearch(realLeft, inputs.columnPositions, {
atStart: true,
lastPosition: inputs.columnsTotalWidth
});
const rightBound = inputs.layoutMode === 'controlled' ? realLeft + inputs.viewportInnerWidth - inputs.rightPinnedWidth : realLeft + inputs.viewportInnerWidth;
lastColumnIndex = binarySearch(rightBound, inputs.columnPositions);
}
renderContext.firstColumnIndex = firstColumnIndex;
renderContext.lastColumnIndex = lastColumnIndex;
}
const actualRenderContext = deriveRenderContext(inputs, renderContext, scrollCache);
return actualRenderContext;
}
function getNearestIndexToRender(inputs, offset, options) {
const lastMeasuredIndexRelativeToAllRows = inputs.api.rowsMeta.getLastMeasuredRowIndex();
let allRowsMeasured = lastMeasuredIndexRelativeToAllRows === Infinity;
if (inputs.range?.lastRowIndex && !allRowsMeasured) {
// Check if all rows in this page are already measured
allRowsMeasured = lastMeasuredIndexRelativeToAllRows >= inputs.range.lastRowIndex;
}
const lastMeasuredIndexRelativeToCurrentPage = clamp(lastMeasuredIndexRelativeToAllRows - (inputs.range?.firstRowIndex || 0), 0, inputs.rowsMeta.positions.length);
if (allRowsMeasured || inputs.rowsMeta.positions[lastMeasuredIndexRelativeToCurrentPage] >= offset) {
// If all rows were measured (when no row has "auto" as height) or all rows before the offset
// were measured, then use a binary search because it's faster.
return binarySearch(offset, inputs.rowsMeta.positions, options);
}
// Otherwise, use an exponential search.
// If rows have "auto" as height, their positions will be based on estimated heights.
// In this case, we can skip several steps until we find a position higher than the offset.
// Inspired by https://github.com/bvaughn/react-virtualized/blob/master/source/Grid/utils/CellSizeAndPositionManager.js
return exponentialSearch(offset, inputs.rowsMeta.positions, lastMeasuredIndexRelativeToCurrentPage, options);
}
/**
* Accepts as input a raw render context (the area visible in the viewport) and adds
* computes the actual render context based on pinned elements, buffer dimensions and
* spanning.
*/
function deriveRenderContext(inputs, nextRenderContext, scrollCache) {
const [firstRowToRender, lastRowToRender] = getIndexesToRender({
firstIndex: nextRenderContext.firstRowIndex,
lastIndex: nextRenderContext.lastRowIndex,
minFirstIndex: 0,
maxLastIndex: inputs.rows.length,
bufferBefore: scrollCache.buffer.rowBefore,
bufferAfter: scrollCache.buffer.rowAfter,
positions: inputs.rowsMeta.positions,
lastSize: inputs.lastRowHeight
});
const [initialFirstColumnToRender, lastColumnToRender] = getIndexesToRender({
firstIndex: nextRenderContext.firstColumnIndex,
lastIndex: nextRenderContext.lastColumnIndex,
minFirstIndex: inputs.pinnedColumns?.left.length ?? 0,
maxLastIndex: inputs.columns.length - (inputs.pinnedColumns?.right.length ?? 0),
bufferBefore: scrollCache.buffer.columnBefore,
bufferAfter: scrollCache.buffer.columnAfter,
positions: inputs.columnPositions,
lastSize: inputs.lastColumnWidth
});
const firstColumnToRender = getFirstNonSpannedColumnToRender({
api: inputs.api,
firstColumnToRender: initialFirstColumnToRender,
firstRowToRender,
lastRowToRender,
visibleRows: inputs.rows
});
return {
firstRowIndex: firstRowToRender,
lastRowIndex: lastRowToRender,
firstColumnIndex: firstColumnToRender,
lastColumnIndex: lastColumnToRender
};
}
/**
* Use binary search to avoid looping through all possible positions.
* The `options.atStart` provides the possibility to match for the first element that
* intersects the screen, even if said element's start position is before `offset`. In
* other words, we search for `offset + width`.
*/
function binarySearch(offset, positions, options = undefined, sliceStart = 0, sliceEnd = positions.length) {
if (positions.length <= 0) {
return -1;
}
if (sliceStart >= sliceEnd) {
return sliceStart;
}
const pivot = sliceStart + Math.floor((sliceEnd - sliceStart) / 2);
const position = positions[pivot];
let isBefore;
if (options?.atStart) {
const width = (pivot === positions.length - 1 ? options.lastPosition : positions[pivot + 1]) - position;
isBefore = offset - width < position;
} else {
isBefore = offset <= position;
}
return isBefore ? binarySearch(offset, positions, options, sliceStart, pivot) : binarySearch(offset, positions, options, pivot + 1, sliceEnd);
}
function exponentialSearch(offset, positions, index, options = undefined) {
let interval = 1;
while (index < positions.length && Math.abs(positions[index]) < offset) {
index += interval;
interval *= 2;
}
return binarySearch(offset, positions, options, Math.floor(index / 2), Math.min(index, positions.length));
}
function getIndexesToRender({
firstIndex,
lastIndex,
bufferBefore,
bufferAfter,
minFirstIndex,
maxLastIndex,
positions,
lastSize
}) {
const firstPosition = positions[firstIndex] - bufferBefore;
const lastPosition = positions[lastIndex] + bufferAfter;
const firstIndexPadded = binarySearch(firstPosition, positions, {
atStart: true,
lastPosition: positions[positions.length - 1] + lastSize
});
const lastIndexPadded = binarySearch(lastPosition, positions) + 1;
return [clamp(firstIndexPadded, minFirstIndex, maxLastIndex), clamp(lastIndexPadded, minFirstIndex, maxLastIndex)];
}
export function areRenderContextsEqual(context1, context2) {
if (context1 === context2) {
return true;
}
return context1.firstRowIndex === context2.firstRowIndex && context1.lastRowIndex === context2.lastRowIndex && context1.firstColumnIndex === context2.firstColumnIndex && context1.lastColumnIndex === context2.lastColumnIndex;
}
export function computeOffsetLeft(columnPositions, renderContext, pinnedLeftLength, layoutMode = 'uncontrolled') {
let offset = columnPositions[renderContext.firstColumnIndex] ?? 0;
/* CSS sticky leaves elements in the normal flow of the DOM, so we
* don't need to add the offset of the pinned columns. */
if (layoutMode === 'uncontrolled') {
offset -= columnPositions[pinnedLeftLength] ?? 0;
}
return Math.abs(offset);
}
const EMPTY_BUFFER = {
rowAfter: 0,
rowBefore: 0,
columnAfter: 0,
columnBefore: 0
};
function bufferForDirection(isRtl, direction, rowBufferPx, columnBufferPx, verticalBuffer, horizontalBuffer, layoutMode = 'uncontrolled') {
if (layoutMode === 'controlled') {
return EMPTY_BUFFER;
}
if (isRtl) {
switch (direction) {
case ScrollDirection.LEFT:
direction = ScrollDirection.RIGHT;
break;
case ScrollDirection.RIGHT:
direction = ScrollDirection.LEFT;
break;
default:
}
}
switch (direction) {
case ScrollDirection.NONE:
return {
rowAfter: rowBufferPx,
rowBefore: rowBufferPx,
columnAfter: columnBufferPx,
columnBefore: columnBufferPx
};
case ScrollDirection.LEFT:
return {
rowAfter: 0,
rowBefore: 0,
columnAfter: 0,
columnBefore: horizontalBuffer
};
case ScrollDirection.RIGHT:
return {
rowAfter: 0,
rowBefore: 0,
columnAfter: horizontalBuffer,
columnBefore: 0
};
case ScrollDirection.UP:
return {
rowAfter: 0,
rowBefore: verticalBuffer,
columnAfter: 0,
columnBefore: 0
};
case ScrollDirection.DOWN:
return {
rowAfter: verticalBuffer,
rowBefore: 0,
columnAfter: 0,
columnBefore: 0
};
default:
// eslint unable to figure out enum exhaustiveness
throw /* minify-error-disabled */new Error('unreachable');
}
}
function createScrollCache(isRtl, rowBufferPx, columnBufferPx, verticalBuffer, horizontalBuffer, layoutMode = 'uncontrolled') {
return {
direction: ScrollDirection.NONE,
buffer: bufferForDirection(isRtl, ScrollDirection.NONE, rowBufferPx, columnBufferPx, verticalBuffer, horizontalBuffer, layoutMode)
};
}
function createRange(from, to) {
return Array.from({
length: to - from
}).map((_, i) => from + i);
}
function getFirstNonSpannedColumnToRender({
api,
firstColumnToRender,
firstRowToRender,
lastRowToRender,
visibleRows
}) {
let firstNonSpannedColumnToRender = firstColumnToRender;
let foundStableColumn = false;
// Keep checking columns until we find one that's not spanned in any visible row
while (!foundStableColumn && firstNonSpannedColumnToRender >= 0) {
foundStableColumn = true;
for (let i = firstRowToRender; i < lastRowToRender; i += 1) {
const row = visibleRows[i];
if (row) {
const rowId = visibleRows[i].id;
const cellColSpanInfo = api.getCellColSpanInfo(rowId, firstNonSpannedColumnToRender);
if (cellColSpanInfo && cellColSpanInfo.spannedByColSpan && cellColSpanInfo.leftVisibleCellIndex < firstNonSpannedColumnToRender) {
firstNonSpannedColumnToRender = cellColSpanInfo.leftVisibleCellIndex;
foundStableColumn = false;
break; // Check the new column index against the visible rows, because it might be spanned
}
}
}
}
return firstNonSpannedColumnToRender;
}
/** Placeholder API functions for colspan & rowspan to re-implement */
function createSpanningAPI() {
const getCellColSpanInfo = () => {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X: Unimplemented: colspan feature is required' : _formatErrorMessage(200));
};
const calculateColSpan = () => {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X: Unimplemented: colspan feature is required' : _formatErrorMessage(200));
};
const getHiddenCellsOrigin = () => {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI X: Unimplemented: rowspan feature is required' : _formatErrorMessage(201));
};
return {
getCellColSpanInfo,
calculateColSpan,
getHiddenCellsOrigin
};
}
export function roundToDecimalPlaces(value, decimals) {
return Math.round(value * 10 ** decimals) / 10 ** decimals;
}
+4
View File
@@ -0,0 +1,4 @@
export * from "./models/index.mjs";
export * from "./features/index.mjs";
export * from "./constants.mjs";
export * from "./useVirtualizer.mjs";
+4
View File
@@ -0,0 +1,4 @@
export * from "./models/index.js";
export * from "./features/index.js";
export * from "./constants.js";
export * from "./useVirtualizer.js";
+56
View File
@@ -0,0 +1,56 @@
/**
* @mui/x-virtualizer v0.6.3
*
* @license MIT
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _models = require("./models");
Object.keys(_models).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _models[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _models[key];
}
});
});
var _features = require("./features");
Object.keys(_features).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _features[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _features[key];
}
});
});
var _constants = require("./constants");
Object.keys(_constants).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _constants[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _constants[key];
}
});
});
var _useVirtualizer = require("./useVirtualizer");
Object.keys(_useVirtualizer).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _useVirtualizer[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _useVirtualizer[key];
}
});
});
+11
View File
@@ -0,0 +1,11 @@
/**
* @mui/x-virtualizer v0.6.3
*
* @license MIT
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export * from "./models/index.mjs";
export * from "./features/index.mjs";
export * from "./constants.mjs";
export * from "./useVirtualizer.mjs";
+13
View File
@@ -0,0 +1,13 @@
import { float, integer } from '@mui/x-internals/types';
export type ColumnIndex = number;
export type CellColSpanInfo = {
spannedByColSpan: true;
rightVisibleCellIndex: ColumnIndex;
leftVisibleCellIndex: ColumnIndex;
} | {
spannedByColSpan: false;
cellProps: {
colSpan: integer;
width: float;
};
};
+13
View File
@@ -0,0 +1,13 @@
import { float, integer } from '@mui/x-internals/types';
export type ColumnIndex = number;
export type CellColSpanInfo = {
spannedByColSpan: true;
rightVisibleCellIndex: ColumnIndex;
leftVisibleCellIndex: ColumnIndex;
} | {
spannedByColSpan: false;
cellProps: {
colSpan: integer;
width: float;
};
};
+5
View File
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
+1
View File
@@ -0,0 +1 @@
export {};
+85
View File
@@ -0,0 +1,85 @@
export type Size = {
width: number;
height: number;
};
export declare const Size: {
EMPTY: {
width: number;
height: number;
};
equals: (a: Size, b: Size) => boolean;
};
export type Row = {
[key: string | symbol]: any;
};
export type Column = {
[key: string | symbol]: any;
};
export type ColumnWithWidth = {
computedWidth: number;
} & Column;
export type RowId = any;
export type RowEntry = {
id: any;
model: Row;
};
export type PinnedRows = {
top: RowEntry[];
bottom: RowEntry[];
};
export declare const PinnedRows: {
EMPTY: PinnedRows;
};
export type PinnedColumns = {
left: Column[];
right: Column[];
};
export declare const PinnedColumns: {
EMPTY: PinnedColumns;
};
export type FocusedCell = {
rowIndex: number;
columnIndex: number;
id?: any;
field?: string;
};
export interface ColumnsRenderContext {
firstColumnIndex: number;
lastColumnIndex: number;
}
export interface RenderContext extends ColumnsRenderContext {
firstRowIndex: number;
lastRowIndex: number;
}
export interface GridScrollParams {
left: number;
top: number;
renderContext?: RenderContext;
}
export type GridScrollFn = (v: GridScrollParams) => void;
export type PinnedRowPosition = keyof PinnedRows;
export type ScrollPosition = {
top: number;
left: number;
};
export declare const ScrollPosition: {
EMPTY: {
top: number;
left: number;
};
equals: (a: ScrollPosition, b: ScrollPosition) => boolean;
};
export declare enum ScrollDirection {
NONE = 0,
UP = 1,
DOWN = 2,
LEFT = 3,
RIGHT = 4,
}
export declare namespace ScrollDirection {
function forDelta(dx: number, dy: number): ScrollDirection;
}
export type RowRange = {
firstRowIndex: number;
lastRowIndex: number;
};
+85
View File
@@ -0,0 +1,85 @@
export type Size = {
width: number;
height: number;
};
export declare const Size: {
EMPTY: {
width: number;
height: number;
};
equals: (a: Size, b: Size) => boolean;
};
export type Row = {
[key: string | symbol]: any;
};
export type Column = {
[key: string | symbol]: any;
};
export type ColumnWithWidth = {
computedWidth: number;
} & Column;
export type RowId = any;
export type RowEntry = {
id: any;
model: Row;
};
export type PinnedRows = {
top: RowEntry[];
bottom: RowEntry[];
};
export declare const PinnedRows: {
EMPTY: PinnedRows;
};
export type PinnedColumns = {
left: Column[];
right: Column[];
};
export declare const PinnedColumns: {
EMPTY: PinnedColumns;
};
export type FocusedCell = {
rowIndex: number;
columnIndex: number;
id?: any;
field?: string;
};
export interface ColumnsRenderContext {
firstColumnIndex: number;
lastColumnIndex: number;
}
export interface RenderContext extends ColumnsRenderContext {
firstRowIndex: number;
lastRowIndex: number;
}
export interface GridScrollParams {
left: number;
top: number;
renderContext?: RenderContext;
}
export type GridScrollFn = (v: GridScrollParams) => void;
export type PinnedRowPosition = keyof PinnedRows;
export type ScrollPosition = {
top: number;
left: number;
};
export declare const ScrollPosition: {
EMPTY: {
top: number;
left: number;
};
equals: (a: ScrollPosition, b: ScrollPosition) => boolean;
};
export declare enum ScrollDirection {
NONE = 0,
UP = 1,
DOWN = 2,
LEFT = 3,
RIGHT = 4,
}
export declare namespace ScrollDirection {
function forDelta(dx: number, dy: number): ScrollDirection;
}
export type RowRange = {
firstRowIndex: number;
lastRowIndex: number;
};
+68
View File
@@ -0,0 +1,68 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Size = exports.ScrollPosition = exports.ScrollDirection = exports.PinnedRows = exports.PinnedColumns = void 0;
/* eslint-disable @typescript-eslint/no-redeclare */
const Size = exports.Size = {
EMPTY: {
width: 0,
height: 0
},
equals: (a, b) => a.width === b.width && a.height === b.height
};
// TODO
const PinnedRows = exports.PinnedRows = {
EMPTY: {
top: [],
bottom: []
}
};
const PinnedColumns = exports.PinnedColumns = {
EMPTY: {
left: [],
right: []
}
};
const ScrollPosition = exports.ScrollPosition = {
EMPTY: {
top: 0,
left: 0
},
equals: (a, b) => a.top === b.top && a.left === b.left
};
let ScrollDirection = exports.ScrollDirection = /*#__PURE__*/function (ScrollDirection) {
ScrollDirection[ScrollDirection["NONE"] = 0] = "NONE";
ScrollDirection[ScrollDirection["UP"] = 1] = "UP";
ScrollDirection[ScrollDirection["DOWN"] = 2] = "DOWN";
ScrollDirection[ScrollDirection["LEFT"] = 3] = "LEFT";
ScrollDirection[ScrollDirection["RIGHT"] = 4] = "RIGHT";
return ScrollDirection;
}({});
(function (_ScrollDirection) {
function forDelta(dx, dy) {
if (dx === 0 && dy === 0) {
return ScrollDirection.NONE;
}
/* eslint-disable */
if (Math.abs(dy) >= Math.abs(dx)) {
if (dy > 0) {
return ScrollDirection.DOWN;
} else {
return ScrollDirection.UP;
}
} else {
if (dx > 0) {
return ScrollDirection.RIGHT;
} else {
return ScrollDirection.LEFT;
}
}
/* eslint-enable */
}
_ScrollDirection.forDelta = forDelta;
})(ScrollDirection || (exports.ScrollDirection = ScrollDirection = {}));
+62
View File
@@ -0,0 +1,62 @@
/* eslint-disable @typescript-eslint/no-redeclare */
export const Size = {
EMPTY: {
width: 0,
height: 0
},
equals: (a, b) => a.width === b.width && a.height === b.height
};
// TODO
export const PinnedRows = {
EMPTY: {
top: [],
bottom: []
}
};
export const PinnedColumns = {
EMPTY: {
left: [],
right: []
}
};
export const ScrollPosition = {
EMPTY: {
top: 0,
left: 0
},
equals: (a, b) => a.top === b.top && a.left === b.left
};
export let ScrollDirection = /*#__PURE__*/function (ScrollDirection) {
ScrollDirection[ScrollDirection["NONE"] = 0] = "NONE";
ScrollDirection[ScrollDirection["UP"] = 1] = "UP";
ScrollDirection[ScrollDirection["DOWN"] = 2] = "DOWN";
ScrollDirection[ScrollDirection["LEFT"] = 3] = "LEFT";
ScrollDirection[ScrollDirection["RIGHT"] = 4] = "RIGHT";
return ScrollDirection;
}({});
(function (_ScrollDirection) {
function forDelta(dx, dy) {
if (dx === 0 && dy === 0) {
return ScrollDirection.NONE;
}
/* eslint-disable */
if (Math.abs(dy) >= Math.abs(dx)) {
if (dy > 0) {
return ScrollDirection.DOWN;
} else {
return ScrollDirection.UP;
}
} else {
if (dx > 0) {
return ScrollDirection.RIGHT;
} else {
return ScrollDirection.LEFT;
}
}
/* eslint-enable */
}
_ScrollDirection.forDelta = forDelta;
})(ScrollDirection || (ScrollDirection = {}));
+109
View File
@@ -0,0 +1,109 @@
import { Size } from "./core.mjs";
export interface DimensionsState {
/**
* Indicates that the dimensions have been initialized.
*/
isReady: boolean;
/**
* The root container size.
*/
root: Size;
/**
* The viewport size including scrollbars.
*/
viewportOuterSize: Size;
/**
* The viewport size not including scrollbars.
*/
viewportInnerSize: Size;
/**
* The size of the main content (unpinned rows & columns).
*/
contentSize: Size;
/**
* The minimum size to display the grid, including all pinned sections and headers.
*/
minimumSize: Size;
/**
* Indicates if a scroll is currently needed to go from the beginning of the first column to the end of the last column.
*/
hasScrollX: boolean;
/**
* Indicates if a scroll is currently needed to go from the beginning of the first row to the end of the last row.
*/
hasScrollY: boolean;
/**
* Size of the scrollbar used to scroll the rows in pixel.
* It is defined even when the scrollbar is currently not needed.
*/
scrollbarSize: number;
/**
* Width of a row. At least as wide as `viewportOuterSize.width`.
*/
rowWidth: number;
/**
* Height of a row.
*/
rowHeight: number;
/**
* Size of all the columns.
*/
columnsTotalWidth: number;
/**
* Size of left pinned columns.
*/
leftPinnedWidth: number;
/**
* Size of right pinned columns.
*/
rightPinnedWidth: number;
/**
* Size of the top container.
*/
topContainerHeight: number;
/**
* Size of the bottom container.
*/
bottomContainerHeight: number;
/**
* Indicates that the container takes the height of its content.
*/
autoHeight: boolean;
/**
* Minimal height to display the content area.
*/
minimalContentHeight: string | number | undefined;
}
/**
* The rows total height and positions.
*/
export interface RowsMetaState {
/**
* The grid rows positions.
*/
positions: number[];
/**
* The sum of all visible grid rows in the current rows.
*/
currentPageTotalHeight: number;
/**
* The total height of the pinned top rows.
*/
pinnedTopRowsTotalHeight: number;
/**
* The total height of the pinned bottom rows.
*/
pinnedBottomRowsTotalHeight: number;
}
export interface RowSpacing {
top?: number;
bottom?: number;
}
export type HeightEntry = {
content: number;
spacingTop: number;
spacingBottom: number;
detail: number;
autoHeight: boolean;
needsFirstMeasurement: boolean;
};
+109
View File
@@ -0,0 +1,109 @@
import { Size } from "./core.js";
export interface DimensionsState {
/**
* Indicates that the dimensions have been initialized.
*/
isReady: boolean;
/**
* The root container size.
*/
root: Size;
/**
* The viewport size including scrollbars.
*/
viewportOuterSize: Size;
/**
* The viewport size not including scrollbars.
*/
viewportInnerSize: Size;
/**
* The size of the main content (unpinned rows & columns).
*/
contentSize: Size;
/**
* The minimum size to display the grid, including all pinned sections and headers.
*/
minimumSize: Size;
/**
* Indicates if a scroll is currently needed to go from the beginning of the first column to the end of the last column.
*/
hasScrollX: boolean;
/**
* Indicates if a scroll is currently needed to go from the beginning of the first row to the end of the last row.
*/
hasScrollY: boolean;
/**
* Size of the scrollbar used to scroll the rows in pixel.
* It is defined even when the scrollbar is currently not needed.
*/
scrollbarSize: number;
/**
* Width of a row. At least as wide as `viewportOuterSize.width`.
*/
rowWidth: number;
/**
* Height of a row.
*/
rowHeight: number;
/**
* Size of all the columns.
*/
columnsTotalWidth: number;
/**
* Size of left pinned columns.
*/
leftPinnedWidth: number;
/**
* Size of right pinned columns.
*/
rightPinnedWidth: number;
/**
* Size of the top container.
*/
topContainerHeight: number;
/**
* Size of the bottom container.
*/
bottomContainerHeight: number;
/**
* Indicates that the container takes the height of its content.
*/
autoHeight: boolean;
/**
* Minimal height to display the content area.
*/
minimalContentHeight: string | number | undefined;
}
/**
* The rows total height and positions.
*/
export interface RowsMetaState {
/**
* The grid rows positions.
*/
positions: number[];
/**
* The sum of all visible grid rows in the current rows.
*/
currentPageTotalHeight: number;
/**
* The total height of the pinned top rows.
*/
pinnedTopRowsTotalHeight: number;
/**
* The total height of the pinned bottom rows.
*/
pinnedBottomRowsTotalHeight: number;
}
export interface RowSpacing {
top?: number;
bottom?: number;
}
export type HeightEntry = {
content: number;
spacingTop: number;
spacingBottom: number;
detail: number;
autoHeight: boolean;
needsFirstMeasurement: boolean;
};
+5
View File
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
+1
View File
@@ -0,0 +1 @@
export {};
+4
View File
@@ -0,0 +1,4 @@
export * from "./core.mjs";
export * from "./colspan.mjs";
export * from "./dimensions.mjs";
export * from "./rowspan.mjs";
+4
View File
@@ -0,0 +1,4 @@
export * from "./core.js";
export * from "./colspan.js";
export * from "./dimensions.js";
export * from "./rowspan.js";
+49
View File
@@ -0,0 +1,49 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _core = require("./core");
Object.keys(_core).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _core[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _core[key];
}
});
});
var _colspan = require("./colspan");
Object.keys(_colspan).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _colspan[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _colspan[key];
}
});
});
var _dimensions = require("./dimensions");
Object.keys(_dimensions).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _dimensions[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _dimensions[key];
}
});
});
var _rowspan = require("./rowspan");
Object.keys(_rowspan).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (key in exports && exports[key] === _rowspan[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _rowspan[key];
}
});
});
+4
View File
@@ -0,0 +1,4 @@
export * from "./core.mjs";
export * from "./colspan.mjs";
export * from "./dimensions.mjs";
export * from "./rowspan.mjs";
+17
View File
@@ -0,0 +1,17 @@
import { RowId, RowRange } from "./core.mjs";
type ColumnIndex = number;
export interface RowSpanningCaches {
spannedCells: Record<RowId, Record<ColumnIndex, number>>;
hiddenCells: Record<RowId, Record<ColumnIndex, boolean>>;
/**
* For each hidden cell, it contains the row index corresponding to the cell that is
* the origin of the hidden cell. i.e. the cell which is spanned.
* Used by the virtualization to properly keep the spanned cells in view.
*/
hiddenCellOriginMap: Record<number, Record<ColumnIndex, number>>;
}
export interface RowSpanningState {
caches: RowSpanningCaches;
processedRange: RowRange;
}
export {};
+17
View File
@@ -0,0 +1,17 @@
import { RowId, RowRange } from "./core.js";
type ColumnIndex = number;
export interface RowSpanningCaches {
spannedCells: Record<RowId, Record<ColumnIndex, number>>;
hiddenCells: Record<RowId, Record<ColumnIndex, boolean>>;
/**
* For each hidden cell, it contains the row index corresponding to the cell that is
* the origin of the hidden cell. i.e. the cell which is spanned.
* Used by the virtualization to properly keep the spanned cells in view.
*/
hiddenCellOriginMap: Record<number, Record<ColumnIndex, number>>;
}
export interface RowSpanningState {
caches: RowSpanningCaches;
processedRange: RowRange;
}
export {};
+5
View File
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
+1
View File
@@ -0,0 +1 @@
export {};
+107
View File
@@ -0,0 +1,107 @@
{
"name": "@mui/x-virtualizer",
"version": "0.6.3",
"author": "MUI Team",
"description": "MUI virtualization library",
"license": "MIT",
"bugs": {
"url": "https://github.com/mui/mui-x/issues"
},
"homepage": "https://mui.com",
"sideEffects": false,
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/mui-org"
},
"publishConfig": {
"access": "public"
},
"keywords": [
"react",
"react-component",
"virtualization"
],
"repository": {
"type": "git",
"url": "git+https://github.com/mui/mui-x.git",
"directory": "packages/x-virtualizer"
},
"dependencies": {
"@babel/runtime": "^7.29.7",
"@base-ui/utils": "^0.3.1",
"@mui/utils": "^9.3.0",
"@mui/x-internals": "^9.11.0"
},
"peerDependencies": {
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0"
},
"engines": {
"node": ">=14.0.0"
},
"type": "commonjs",
"exports": {
"./package.json": "./package.json",
".": {
"import": {
"types": "./index.d.mts",
"default": "./index.mjs"
},
"require": {
"types": "./index.d.ts",
"default": "./index.js"
},
"default": {
"types": "./index.d.mts",
"default": "./index.mjs"
}
},
"./useVirtualizer": {
"import": {
"types": "./useVirtualizer.d.mts",
"default": "./useVirtualizer.mjs"
},
"require": {
"types": "./useVirtualizer.d.ts",
"default": "./useVirtualizer.js"
},
"default": {
"types": "./useVirtualizer.d.mts",
"default": "./useVirtualizer.mjs"
}
},
"./features": {
"import": {
"types": "./features/index.d.mts",
"default": "./features/index.mjs"
},
"require": {
"types": "./features/index.d.ts",
"default": "./features/index.js"
},
"default": {
"types": "./features/index.d.mts",
"default": "./features/index.mjs"
}
},
"./models": {
"import": {
"types": "./models/index.d.mts",
"default": "./models/index.mjs"
},
"require": {
"types": "./models/index.d.ts",
"default": "./models/index.js"
},
"default": {
"types": "./models/index.d.mts",
"default": "./models/index.mjs"
}
}
},
"imports": {
"#formatErrorMessage": "@mui/x-internals/formatErrorMessage"
},
"main": "./index.js",
"types": "./index.d.ts"
}
+135
View File
@@ -0,0 +1,135 @@
import * as React from 'react';
import { integer } from '@mui/x-internals/types';
import { Store } from '@mui/x-internals/store';
import { Colspan } from "./features/colspan.mjs";
import { Dimensions } from "./features/dimensions.mjs";
import { Rowspan } from "./features/rowspan.mjs";
import { Virtualization } from "./features/virtualization/index.mjs";
import type { Layout } from "./features/virtualization/layout.mjs";
import type { HeightEntry, RowSpacing } from "./models/dimensions.mjs";
import type { ColspanParams } from "./features/colspan.mjs";
import type { DimensionsParams } from "./features/dimensions.mjs";
import type { VirtualizationParams } from "./features/virtualization/index.mjs";
import { ColumnWithWidth, FocusedCell, Size, PinnedRows, PinnedColumns, RenderContext, Row, RowEntry } from "./models/index.mjs";
export type Virtualizer = ReturnType<typeof useVirtualizer>;
export type VirtualScrollerCompat<L extends Layout = Layout> = Virtualization.State<L>['getters'];
export type BaseState<L extends Layout = Layout> = Virtualization.State<L> & Dimensions.State;
export type VirtualizerParams<L extends Layout = Layout> = {
layout: L;
dimensions: DimensionsParams;
virtualization: VirtualizationParams;
colspan?: ColspanParams;
initialState?: {
scroll?: {
top: number;
left: number;
};
rowSpanning?: Rowspan.State['rowSpanning'];
virtualization?: Partial<Virtualization.State<L>['virtualization']>;
};
/** current page rows */
rows: RowEntry[];
/** current page range */
range: {
firstRowIndex: integer;
lastRowIndex: integer;
} | null;
rowCount: integer;
columns?: ColumnWithWidth[];
pinnedRows?: PinnedRows;
pinnedColumns?: PinnedColumns;
disableHorizontalScroll?: boolean;
disableVerticalScroll?: boolean;
getRowHeight?: (row: RowEntry) => number | null | undefined | 'auto';
/**
* Function that returns the estimated height for a row.
* Only works if dynamic row height is used.
* Once the row height is measured this value is discarded.
* @param rowEntry
* @returns The estimated row height value. If `null` or `undefined` then the default row height, based on the density, is applied.
*/
getEstimatedRowHeight?: (rowEntry: RowEntry) => number | null;
/**
* Function that allows to specify the spacing between rows.
* @param rowEntry
* @returns The row spacing values.
*/
getRowSpacing?: (rowEntry: RowEntry) => RowSpacing;
/** Update the row height values before they're used.
* Used to add detail panel heights.
* @param entry
* @param rowEntry
*/
applyRowHeight?: (entry: HeightEntry, rowEntry: RowEntry) => void;
virtualizeColumnsWithAutoRowHeight?: boolean;
resizeThrottleMs?: number;
onResize?: (lastSize: Size) => void;
onWheel?: (event: React.WheelEvent) => void;
onTouchMove?: (event: React.TouchEvent) => void;
onRenderContextChange?: (c: RenderContext) => void;
onScrollChange?: (scrollPosition: {
top: number;
left: number;
}, nextRenderContext: RenderContext) => void;
focusedVirtualCell?: () => FocusedCell | null;
scrollReset?: any;
renderRow: (params: {
id: any;
model: Row;
rowIndex: number;
offsetLeft: number;
columnsTotalWidth: number;
baseRowHeight: number | 'auto';
firstColumnIndex: number;
lastColumnIndex: number;
focusedColumnIndex: number | undefined;
isFirstVisible: boolean;
isLastVisible: boolean;
isVirtualFocusRow: boolean;
showBottomBorder: boolean;
}) => React.ReactElement;
renderInfiniteLoadingTrigger?: (id: any) => React.ReactElement;
};
type RequiredFields<T, K extends keyof T> = T & Required<Pick<T, K>>;
export type ParamsWithDefaults = RequiredFields<VirtualizerParams, 'resizeThrottleMs' | 'columns'> & {
dimensions: RequiredFields<VirtualizerParams['dimensions'], 'columnsTotalWidth' | 'leftPinnedWidth' | 'rightPinnedWidth' | 'topPinnedHeight' | 'bottomPinnedHeight' | 'autoHeight'>;
virtualization: RequiredFields<VirtualizerParams['virtualization'], 'isRtl' | 'rowBufferPx' | 'columnBufferPx'>;
};
export declare const useVirtualizer: <L extends Layout = Layout<{
scroller: React.RefObject<HTMLElement | null>;
container: React.RefObject<HTMLElement | null>;
} & Record<string, React.RefObject<HTMLElement | null>>>>(params: VirtualizerParams<L>) => {
store: Store<Dimensions.State & Virtualization.State<L> & Colspan.State & Rowspan.State>;
api: {
updateDimensions: (firstUpdate?: boolean) => void;
debouncedUpdateDimensions: (((firstUpdate?: boolean) => void) & import("@mui/x-internals/throttle").Cancelable) | undefined;
rowsMeta: {
getRowHeight: (rowId: import("./models/index.mjs").RowId) => any;
setLastMeasuredRowIndex: (index: number) => void;
storeRowHeightMeasurement: (id: import("./models/index.mjs").RowId, height: number) => void;
hydrateRowsMeta: () => void;
observeRowHeight: (element: Element, rowId: import("./models/index.mjs").RowId) => () => void | undefined;
rowHasAutoHeight: (id: import("./models/index.mjs").RowId) => any;
getRowHeightEntry: (rowId: import("./models/index.mjs").RowId) => any;
getLastMeasuredRowIndex: () => number;
resetRowHeights: () => void;
};
} & {
getCellColSpanInfo: (rowId: import("./models/index.mjs").RowId, columnIndex: integer) => import("./models/index.mjs").CellColSpanInfo;
calculateColSpan: (rowId: import("./models/index.mjs").RowId, minFirstColumn: integer, maxLastColumn: integer, columns: ColumnWithWidth[]) => void;
getHiddenCellsOrigin: () => Record<import("./models/index.mjs").RowId, Record<number, number>>;
getters: any;
setPanels: React.Dispatch<React.SetStateAction<Readonly<Map<any, React.ReactNode>>>>;
forceUpdateRenderContext: () => void;
scheduleUpdateRenderContext: () => void;
} & {
resetColSpan: () => void;
getCellColSpanInfo: (rowId: import("./models/index.mjs").RowId, columnIndex: integer) => import("./models/index.mjs").CellColSpanInfo | undefined;
calculateColSpan: (rowId: import("./models/index.mjs").RowId, minFirstColumn: integer, maxLastColumn: integer, columns: ColumnWithWidth[]) => void;
} & {
getHiddenCellsOrigin: () => Record<number, Record<number, number>>;
} & {
getViewportPageSize: () => number;
};
};
export {};
+135
View File
@@ -0,0 +1,135 @@
import * as React from 'react';
import { integer } from '@mui/x-internals/types';
import { Store } from '@mui/x-internals/store';
import { Colspan } from "./features/colspan.js";
import { Dimensions } from "./features/dimensions.js";
import { Rowspan } from "./features/rowspan.js";
import { Virtualization } from "./features/virtualization/index.js";
import type { Layout } from "./features/virtualization/layout.js";
import type { HeightEntry, RowSpacing } from "./models/dimensions.js";
import type { ColspanParams } from "./features/colspan.js";
import type { DimensionsParams } from "./features/dimensions.js";
import type { VirtualizationParams } from "./features/virtualization/index.js";
import { ColumnWithWidth, FocusedCell, Size, PinnedRows, PinnedColumns, RenderContext, Row, RowEntry } from "./models/index.js";
export type Virtualizer = ReturnType<typeof useVirtualizer>;
export type VirtualScrollerCompat<L extends Layout = Layout> = Virtualization.State<L>['getters'];
export type BaseState<L extends Layout = Layout> = Virtualization.State<L> & Dimensions.State;
export type VirtualizerParams<L extends Layout = Layout> = {
layout: L;
dimensions: DimensionsParams;
virtualization: VirtualizationParams;
colspan?: ColspanParams;
initialState?: {
scroll?: {
top: number;
left: number;
};
rowSpanning?: Rowspan.State['rowSpanning'];
virtualization?: Partial<Virtualization.State<L>['virtualization']>;
};
/** current page rows */
rows: RowEntry[];
/** current page range */
range: {
firstRowIndex: integer;
lastRowIndex: integer;
} | null;
rowCount: integer;
columns?: ColumnWithWidth[];
pinnedRows?: PinnedRows;
pinnedColumns?: PinnedColumns;
disableHorizontalScroll?: boolean;
disableVerticalScroll?: boolean;
getRowHeight?: (row: RowEntry) => number | null | undefined | 'auto';
/**
* Function that returns the estimated height for a row.
* Only works if dynamic row height is used.
* Once the row height is measured this value is discarded.
* @param rowEntry
* @returns The estimated row height value. If `null` or `undefined` then the default row height, based on the density, is applied.
*/
getEstimatedRowHeight?: (rowEntry: RowEntry) => number | null;
/**
* Function that allows to specify the spacing between rows.
* @param rowEntry
* @returns The row spacing values.
*/
getRowSpacing?: (rowEntry: RowEntry) => RowSpacing;
/** Update the row height values before they're used.
* Used to add detail panel heights.
* @param entry
* @param rowEntry
*/
applyRowHeight?: (entry: HeightEntry, rowEntry: RowEntry) => void;
virtualizeColumnsWithAutoRowHeight?: boolean;
resizeThrottleMs?: number;
onResize?: (lastSize: Size) => void;
onWheel?: (event: React.WheelEvent) => void;
onTouchMove?: (event: React.TouchEvent) => void;
onRenderContextChange?: (c: RenderContext) => void;
onScrollChange?: (scrollPosition: {
top: number;
left: number;
}, nextRenderContext: RenderContext) => void;
focusedVirtualCell?: () => FocusedCell | null;
scrollReset?: any;
renderRow: (params: {
id: any;
model: Row;
rowIndex: number;
offsetLeft: number;
columnsTotalWidth: number;
baseRowHeight: number | 'auto';
firstColumnIndex: number;
lastColumnIndex: number;
focusedColumnIndex: number | undefined;
isFirstVisible: boolean;
isLastVisible: boolean;
isVirtualFocusRow: boolean;
showBottomBorder: boolean;
}) => React.ReactElement;
renderInfiniteLoadingTrigger?: (id: any) => React.ReactElement;
};
type RequiredFields<T, K extends keyof T> = T & Required<Pick<T, K>>;
export type ParamsWithDefaults = RequiredFields<VirtualizerParams, 'resizeThrottleMs' | 'columns'> & {
dimensions: RequiredFields<VirtualizerParams['dimensions'], 'columnsTotalWidth' | 'leftPinnedWidth' | 'rightPinnedWidth' | 'topPinnedHeight' | 'bottomPinnedHeight' | 'autoHeight'>;
virtualization: RequiredFields<VirtualizerParams['virtualization'], 'isRtl' | 'rowBufferPx' | 'columnBufferPx'>;
};
export declare const useVirtualizer: <L extends Layout = Layout<{
scroller: React.RefObject<HTMLElement | null>;
container: React.RefObject<HTMLElement | null>;
} & Record<string, React.RefObject<HTMLElement | null>>>>(params: VirtualizerParams<L>) => {
store: Store<Dimensions.State & Virtualization.State<L> & Colspan.State & Rowspan.State>;
api: {
updateDimensions: (firstUpdate?: boolean) => void;
debouncedUpdateDimensions: (((firstUpdate?: boolean) => void) & import("@mui/x-internals/throttle").Cancelable) | undefined;
rowsMeta: {
getRowHeight: (rowId: import("./models/index.js").RowId) => any;
setLastMeasuredRowIndex: (index: number) => void;
storeRowHeightMeasurement: (id: import("./models/index.js").RowId, height: number) => void;
hydrateRowsMeta: () => void;
observeRowHeight: (element: Element, rowId: import("./models/index.js").RowId) => () => void | undefined;
rowHasAutoHeight: (id: import("./models/index.js").RowId) => any;
getRowHeightEntry: (rowId: import("./models/index.js").RowId) => any;
getLastMeasuredRowIndex: () => number;
resetRowHeights: () => void;
};
} & {
getCellColSpanInfo: (rowId: import("./models/index.js").RowId, columnIndex: integer) => import("./models/index.js").CellColSpanInfo;
calculateColSpan: (rowId: import("./models/index.js").RowId, minFirstColumn: integer, maxLastColumn: integer, columns: ColumnWithWidth[]) => void;
getHiddenCellsOrigin: () => Record<import("./models/index.js").RowId, Record<number, number>>;
getters: any;
setPanels: React.Dispatch<React.SetStateAction<Readonly<Map<any, React.ReactNode>>>>;
forceUpdateRenderContext: () => void;
scheduleUpdateRenderContext: () => void;
} & {
resetColSpan: () => void;
getCellColSpanInfo: (rowId: import("./models/index.js").RowId, columnIndex: integer) => import("./models/index.js").CellColSpanInfo | undefined;
calculateColSpan: (rowId: import("./models/index.js").RowId, minFirstColumn: integer, maxLastColumn: integer, columns: ColumnWithWidth[]) => void;
} & {
getHiddenCellsOrigin: () => Record<number, Record<number, number>>;
} & {
getViewportPageSize: () => number;
};
};
export {};
+50
View File
@@ -0,0 +1,50 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useVirtualizer = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _useLazyRef = _interopRequireDefault(require("@mui/utils/useLazyRef"));
var _store = require("@mui/x-internals/store");
var _colspan = require("./features/colspan");
var _dimensions = require("./features/dimensions");
var _keyboard = require("./features/keyboard");
var _rowspan = require("./features/rowspan");
var _virtualization = require("./features/virtualization");
var _constants = require("./constants");
/* eslint-disable jsdoc/require-param-type */
/* eslint-disable jsdoc/require-param-description */
/* eslint-disable jsdoc/require-returns-type */
const FEATURES = [_dimensions.Dimensions, _virtualization.Virtualization, _colspan.Colspan, _rowspan.Rowspan, _keyboard.Keyboard];
const useVirtualizer = params => {
const paramsWithDefault = mergeDefaults(params, _constants.DEFAULT_PARAMS);
const store = (0, _useLazyRef.default)(() => {
return new _store.Store(FEATURES.map(f => f.initialize(paramsWithDefault)).reduce((state, partial) => Object.assign(state, partial), {}));
}).current;
const api = {};
for (const feature of FEATURES) {
Object.assign(api, feature.use(store, paramsWithDefault, api));
}
return {
store,
api
};
};
exports.useVirtualizer = useVirtualizer;
function mergeDefaults(params, defaults) {
const result = (0, _extends2.default)({}, params);
for (const key in defaults) {
if (Object.hasOwn(defaults, key)) {
const value = defaults[key];
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
result[key] = mergeDefaults(params[key] ?? {}, value);
} else {
result[key] = params[key] ?? value;
}
}
}
return result;
}
+43
View File
@@ -0,0 +1,43 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import useLazyRef from '@mui/utils/useLazyRef';
import { Store } from '@mui/x-internals/store';
import { Colspan } from "./features/colspan.mjs";
import { Dimensions } from "./features/dimensions.mjs";
import { Keyboard } from "./features/keyboard.mjs";
import { Rowspan } from "./features/rowspan.mjs";
import { Virtualization } from "./features/virtualization/index.mjs";
import { DEFAULT_PARAMS } from "./constants.mjs";
/* eslint-disable jsdoc/require-param-type */
/* eslint-disable jsdoc/require-param-description */
/* eslint-disable jsdoc/require-returns-type */
const FEATURES = [Dimensions, Virtualization, Colspan, Rowspan, Keyboard];
export const useVirtualizer = params => {
const paramsWithDefault = mergeDefaults(params, DEFAULT_PARAMS);
const store = useLazyRef(() => {
return new Store(FEATURES.map(f => f.initialize(paramsWithDefault)).reduce((state, partial) => Object.assign(state, partial), {}));
}).current;
const api = {};
for (const feature of FEATURES) {
Object.assign(api, feature.use(store, paramsWithDefault, api));
}
return {
store,
api
};
};
function mergeDefaults(params, defaults) {
const result = _extends({}, params);
for (const key in defaults) {
if (Object.hasOwn(defaults, key)) {
const value = defaults[key];
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
result[key] = mergeDefaults(params[key] ?? {}, value);
} else {
result[key] = params[key] ?? value;
}
}
}
return result;
}
+1
View File
@@ -0,0 +1 @@
export default function useRefCallback(fn: (node: HTMLDivElement) => (() => void) | undefined): (node: HTMLDivElement | null) => (() => void | undefined) | undefined;
+1
View File
@@ -0,0 +1 @@
export default function useRefCallback(fn: (node: HTMLDivElement) => (() => void) | undefined): (node: HTMLDivElement | null) => (() => void | undefined) | undefined;
+28
View File
@@ -0,0 +1,28 @@
"use strict";
'use client';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useRefCallback;
var React = _interopRequireWildcard(require("react"));
var _useEventCallback = _interopRequireDefault(require("@mui/utils/useEventCallback"));
var _reactMajor = _interopRequireDefault(require("@mui/x-internals/reactMajor"));
function useRefCallback(fn) {
const refCleanup = React.useRef(undefined);
const refCallback = (0, _useEventCallback.default)(node => {
if (!node) {
// Cleanup for R18
refCleanup.current?.();
return;
}
refCleanup.current = fn(node);
if (_reactMajor.default >= 19) {
/* eslint-disable-next-line consistent-return */
return refCleanup.current;
}
});
return refCallback;
}
+21
View File
@@ -0,0 +1,21 @@
'use client';
import * as React from 'react';
import useEventCallback from '@mui/utils/useEventCallback';
import reactMajor from '@mui/x-internals/reactMajor';
export default function useRefCallback(fn) {
const refCleanup = React.useRef(undefined);
const refCallback = useEventCallback(node => {
if (!node) {
// Cleanup for R18
refCleanup.current?.();
return;
}
refCleanup.current = fn(node);
if (reactMajor >= 19) {
/* eslint-disable-next-line consistent-return */
return refCleanup.current;
}
});
return refCallback;
}