Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rm width/height props, use ResizeObserver to get the grid's content dimensions #2130

Merged
merged 3 commits into from
Aug 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## `alpha` to `canary`
- **Added:**
- **Props:**
- `className`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to support the style prop?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add it if there's demand for it, see my opening comment.

- `onSelectedCellChange`
- ⚠️ This replaces the `onCellSelected` and `onCellDeSelected` props
- `enableFilters`
Expand Down Expand Up @@ -34,6 +35,8 @@
- **Packages:**
- ⚠️ `react-data-grid-addons`
- **Props:**
- ⚠️ `width`
- ⚠️ `height`
- ⚠️ `cellContentRenderer`
- ⚠️ `contextMenu`
<!-- TODO: fill link to storybook -->
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ See [documentation](https://babeljs.io/docs/en/)
import 'core-js/stable';
```
- Babel's `env` preset, if configured correctly, will transform this import so only the necessary polyfills are included in your bundle.
- Polyfilling the [`ResizeObserver`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) API is required for older browsers.
- Optional: we also recommend using the [`babel-plugin-optimize-clsx` plugin](https://www.npmjs.com/package/babel-plugin-optimize-clsx).
</details>

Expand Down
2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@
"@types/react": "^16.9.44",
"@types/react-dom": "^16.9.8",
"@types/react-select": "^3.0.15",
"@types/react-virtualized": "^9.21.10",
"@typescript-eslint/eslint-plugin": "^3.7.1",
"@typescript-eslint/parser": "^3.7.1",
"babel-loader": "^8.1.0",
Expand Down Expand Up @@ -84,7 +83,6 @@
"react-dom": "^16.13.1",
"react-popper": "^2.2.3",
"react-select": "^3.1.0",
"react-virtualized": "^9.21.2",
"ts-jest": "^26.1.4",
"ts-loader": "^8.0.2",
"typescript": "~4.0.2"
Expand Down
29 changes: 8 additions & 21 deletions src/DataGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import React, {
} from 'react';
import clsx from 'clsx';

import { useGridWidth, useViewportColumns } from './hooks';
import { useGridDimensions, useViewportColumns } from './hooks';
import EventBus from './EventBus';
import HeaderRow from './HeaderRow';
import FilterRow from './FilterRow';
Expand All @@ -19,7 +19,6 @@ import SummaryRow from './SummaryRow';
import {
assertIsValidKey,
getColumnScrollPosition,
getScrollbarSize,
getVerticalRangeToRender,
getNextSelectedCellPosition,
isSelectedCellEditable,
Expand Down Expand Up @@ -103,10 +102,6 @@ export interface DataGridProps<R, K extends keyof R, SR = unknown> extends Share
/**
* Dimensions props
*/
/** The width of the grid in pixels */
width?: number;
/** The height of the grid in pixels */
height?: number;
/** The height of each row in pixels */
rowHeight?: number;
/** The height of the header row in pixels */
Expand Down Expand Up @@ -165,6 +160,7 @@ export interface DataGridProps<R, K extends keyof R, SR = unknown> extends Share
*/
/** The node where the editor portal should mount. */
editorPortalTarget?: Element;
className?: string;
rowClass?: (row: R) => string | undefined;
}

Expand All @@ -184,8 +180,6 @@ function DataGrid<R, K extends keyof R, SR>({
onRowsUpdate,
onRowsChange,
// Dimensions props
width,
height = 350,
rowHeight = 35,
headerRowHeight = rowHeight,
headerFiltersHeight = 45,
Expand Down Expand Up @@ -214,6 +208,7 @@ function DataGrid<R, K extends keyof R, SR>({
cellNavigationMode = CellNavigationMode.NONE,
// Miscellaneous
editorPortalTarget = document.body,
className,
rowClass,
// ARIA
'aria-label': ariaLabel,
Expand Down Expand Up @@ -248,27 +243,21 @@ function DataGrid<R, K extends keyof R, SR>({
/**
* computed values
*/
const [gridRef, gridWidth] = useGridWidth(width);
const viewportWidth = gridWidth - 2; // 2 for border width;
const [gridRef, gridWidth, gridHeight] = useGridDimensions();
const headerRowsCount = enableFilters ? 2 : 1;
const summaryRowsCount = summaryRows?.length ?? 0;
const totalHeaderHeight = headerRowHeight + (enableFilters ? headerFiltersHeight : 0);
const clientHeight = gridHeight - totalHeaderHeight - summaryRowsCount * rowHeight;
const isSelectable = selectedRows !== undefined && onSelectedRowsChange !== undefined;

const { columns, viewportColumns, totalColumnWidth, lastFrozenColumnIndex } = useViewportColumns({
columns: rawColumns,
columnWidths,
scrollLeft,
viewportWidth,
viewportWidth: gridWidth,
defaultColumnOptions
});

const totalHeaderHeight = headerRowHeight + (enableFilters ? headerFiltersHeight : 0);
const clientHeight = height
- 2 // border width
- totalHeaderHeight
- summaryRowsCount * rowHeight
- (totalColumnWidth > viewportWidth ? getScrollbarSize() : 0);

const [rowOverscanStartIdx, rowOverscanEndIdx] = getVerticalRangeToRender(
clientHeight,
rowHeight,
Expand Down Expand Up @@ -787,10 +776,8 @@ function DataGrid<R, K extends keyof R, SR>({
aria-multiselectable={isSelectable ? true : undefined}
aria-colcount={columns.length}
aria-rowcount={headerRowsCount + rows.length + summaryRowsCount}
className={clsx('rdg', { 'rdg-viewport-dragging': isDragging })}
className={clsx('rdg', { 'rdg-viewport-dragging': isDragging }, className)}
style={{
width,
height,
'--header-row-height': `${headerRowHeight}px`,
'--filter-row-height': `${headerFiltersHeight}px`,
'--row-width': `${totalColumnWidth}px`,
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export * from './useCombinedRefs';
export * from './useClickOutside';
export * from './useGridWidth';
export * from './useGridDimensions';
export * from './useViewportColumns';
41 changes: 41 additions & 0 deletions src/hooks/useGridDimensions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { useRef, useState, useLayoutEffect } from 'react';

// https://github.com/microsoft/TypeScript/issues/37861
interface ResizeObserverEntry {
contentRect: {
width: number;
height: number;
};
}

type ResizeObserver = new (callback: (entries: readonly ResizeObserverEntry[]) => void) => {
observe: (target: Element) => void;
disconnect: () => void;
};

export function useGridDimensions(): [React.RefObject<HTMLDivElement>, number, number] {
const gridRef = useRef<HTMLDivElement>(null);
const [gridWidth, setGridWidth] = useState(1);
const [gridHeight, setGridHeight] = useState(1);
Comment on lines +18 to +19
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've set to 1 by default just to avoid divisions by zero possibly breaking things.


useLayoutEffect(() => {
const { ResizeObserver } = window as typeof window & { ResizeObserver: ResizeObserver };
Copy link
Contributor Author

@nstepien nstepien Aug 25, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's fair to ask devs to use a polyfill to get the grid working, though that'd only be on IE11/old Edge/Safari 13.
Chrome and Firefox have had it for a long time now.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May be we can add a note on the readme file that a polyfill is required for old browsers. Something like https://reactjs.org/docs/javascript-environment-requirements.html

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added a line in the readme.


// don't break in jest/jsdom and browsers that don't support ResizeObserver
if (ResizeObserver == null) return;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So in this case we render an empty grid? I wonder if we should throw an exception

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Almost.

image

We could log something with console.error, but it'd spam jest tests as well.


const resizeObserver = new ResizeObserver(entries => {
const { width, height } = entries[0].contentRect;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can now properly support css-only dimensions, custom border sizes for the grid, and custom scrollbar sizes as well.

setGridWidth(width);
setGridHeight(height);
});

resizeObserver.observe(gridRef.current!);

return () => {
resizeObserver.disconnect();
};
}, []);

return [gridRef, gridWidth, gridHeight];
}
51 changes: 0 additions & 51 deletions src/hooks/useGridWidth.ts

This file was deleted.

3 changes: 1 addition & 2 deletions src/utils/columnUtils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Column, CalculatedColumn, FormatterProps, Omit } from '../types';
import { getScrollbarSize } from './domUtils';

interface Metrics<R, SR> {
columns: readonly Column<R, SR>[];
Expand Down Expand Up @@ -45,7 +44,7 @@ export function getColumnMetrics<R, SR>(metrics: Metrics<R, SR>): ColumnMetrics<
}
}

const unallocatedWidth = metrics.viewportWidth - allocatedWidths - getScrollbarSize();
const unallocatedWidth = metrics.viewportWidth - allocatedWidths;
const unallocatedColumnWidth = Math.max(
Math.floor(unallocatedWidth / unassignedColumnsCount),
metrics.minColumnWidth
Expand Down
20 changes: 0 additions & 20 deletions src/utils/domUtils.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,3 @@
let size: number | undefined;

export function getScrollbarSize(): number {
if (size === undefined) {
const scrollDiv = document.createElement('div');

scrollDiv.style.position = 'absolute';
scrollDiv.style.top = '-9999px';
scrollDiv.style.width = '50px';
scrollDiv.style.height = '50px';
scrollDiv.style.overflow = 'scroll';

document.body.appendChild(scrollDiv);
size = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We won't manually trigger layout/reflow in the middle of rendering now 👌 👌 👌

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👏

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nstepien
Could you explain a little bit why we needed this originally? Is it for the scenario when the scroll bar appears and we need to get the new demension?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We needed it to know what the scrollbar size was so we could correctly calculate the actual vertical/horizontal viewport.

}

return size;
}

export function preventDefault(event: React.SyntheticEvent) {
event.preventDefault();
}
Expand Down
22 changes: 22 additions & 0 deletions stories/demos/AllFeatures.less
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
.all-features {
display: flex;
flex-direction: column;
height: 100%;

> .rdg {
flex: 1;
}
}

.highlight .rdg-cell {
background-color: #9370DB;
color: white;
Expand All @@ -6,3 +16,15 @@
.highlight:hover .rdg-cell {
background-color: #800080;
}

.load-more-rows-tag {
width: 180px;
padding: 8px 16px;
position: absolute;
bottom: 8px;
right: 8px;

color: white;
line-height: 35px;
background: rgba(0, 0, 0, 0.6);
}
45 changes: 18 additions & 27 deletions stories/demos/AllFeatures.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import faker from 'faker';
import React, { useState, useMemo, useCallback, useRef } from 'react';
import { AutoSizer } from 'react-virtualized';
import DataGrid, { Column, SelectColumn, UpdateActions, DataGridHandle, RowsUpdateEvent, CalculatedColumn } from '../../src';
import DropDownEditor from './components/Editors/DropDownEditor';
import { ImageFormatter } from './components/Formatters';
Expand Down Expand Up @@ -222,32 +221,24 @@ export default function AllFeatures() {
}

return (
<>
<div className="all-features">
<Toolbar onAddRow={handleAddRow} numberOfRows={rows.length} />
<AutoSizer>
{({ height, width }) => (
<>
<DataGrid
ref={gridRef}
columns={columns}
rows={rows}
rowKey="id"
onRowsUpdate={handleRowUpdate}
onRowClick={handleRowClick}
rowHeight={30}
width={width}
height={height - 40}
selectedRows={selectedRows}
onScroll={handleScroll}
onSelectedRowsChange={setSelectedRows}
rowClass={row => row.id.includes('7') ? 'highlight' : undefined}
enableCellCopyPaste
enableCellDragAndDrop
/>
{isLoading && <div className="load-more-rows-tag" style={{ left: width - 230 }}>Loading more rows...</div>}
</>
)}
</AutoSizer>
</>
<DataGrid
ref={gridRef}
columns={columns}
rows={rows}
rowKey="id"
onRowsUpdate={handleRowUpdate}
onRowClick={handleRowClick}
rowHeight={30}
selectedRows={selectedRows}
onScroll={handleScroll}
onSelectedRowsChange={setSelectedRows}
rowClass={row => row.id.includes('7') ? 'highlight' : undefined}
enableCellCopyPaste
enableCellDragAndDrop
/>
{isLoading && <div className="load-more-rows-tag">Loading more rows...</div>}
</div>
);
}
18 changes: 6 additions & 12 deletions stories/demos/CellActions.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React, { useState } from 'react';
import { AutoSizer } from 'react-virtualized';
import faker from 'faker';

import DataGrid, { Column } from '../../src';
Expand Down Expand Up @@ -148,16 +147,11 @@ export default function CellActions() {
const [rows] = useState(createRows);

return (
<AutoSizer>
{({ height, width }) => (
<DataGrid<Row, 'id'>
columns={columns}
rows={rows}
width={width}
height={height}
rowHeight={55}
/>
)}
</AutoSizer>
<DataGrid<Row, 'id'>
columns={columns}
rows={rows}
rowHeight={55}
className="fill-grid"
/>
);
}
Loading