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

Use react bootstrap #13

Merged
merged 7 commits into from
Dec 3, 2023
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@
![status](https://github.com/krjakbrjak/virtualtable/workflows/React%20VirtualTable%20component%20CI/badge.svg)

An implementation of a table displaying large data sets

<img src=testApp.gif width=400 height=400 />
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@krjakbrjak/virtualtable",
"version": "1.1.4",
"version": "1.1.5",
"description": "",
"repository": {
"type": "git",
Expand All @@ -18,9 +18,12 @@
"homepage": "https://github.com/krjakbrjak/virtualtable#readme",
"main": "dist/index.js",
"dependencies": {
"@types/react-bootstrap": "^0.32.35",
"bootstrap": "^5.3.2",
"normalize.css": "^8.0.1",
"prop-types": "^15.8.1",
"react": "^18.2.0",
"react-bootstrap": "^2.9.1",
"react-dom": "^18.2.0"
},
"devDependencies": {
Expand Down
4 changes: 0 additions & 4 deletions src/VirtualTable.css

This file was deleted.

200 changes: 116 additions & 84 deletions src/VirtualTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import PropTypes from 'prop-types';
import { slideItems } from './helpers/collections';

import './base.css';
import css from './VirtualTable.css';

import { LazyPaginatedCollection } from './helpers/LazyPaginatedCollection';
import { Result, Fetcher } from './helpers/types';
import { Style, Fetcher } from './helpers/types';
import { Container, Row, Col } from 'react-bootstrap';

interface State<Type> {
scrollTop: number,
Expand All @@ -34,8 +34,9 @@ interface Action<Type> {

interface Args<Type> {
height: number;
renderer: (data: Type) => ReactNode;
renderer: (data: Type, classes: string) => ReactNode;
fetcher: Fetcher<Type>;
style?: Style;
}

/**
Expand All @@ -49,18 +50,18 @@ interface Args<Type> {
*/
function reducer<Type>(state: State<Type>, action: Action<Type>): State<Type> {
switch (action.type) {
case 'scroll':
return { ...state, ...action.data };
case 'render':
return { ...state, ...action.data };
case 'loaded':
return { ...state, ...action.data };
case 'click':
return { ...state, ...action.data };
case 'hover':
return { ...state, ...action.data };
default:
return state;
case 'scroll':
return { ...state, ...action.data };
case 'render':
return { ...state, ...action.data };
case 'loaded':
return { ...state, ...action.data };
case 'click':
return { ...state, ...action.data };
case 'hover':
return { ...state, ...action.data };
default:
return state;
}
};

Expand All @@ -87,9 +88,21 @@ function reducer<Type>(state: State<Type>, action: Action<Type>): State<Type> {
* @param {VirtualTable.Props} props Properties
* @component
*/
export default function VirtualTable<Type>({ height, renderer, fetcher }: Args<Type>): JSX.Element {
interface Rect {
x: number;
y: number;
height: number;
width: number;
}
export default function VirtualTable<Type>({ height, renderer, fetcher, style }: Args<Type>): JSX.Element {
const ref = useRef(null);
const [collection, setCollection] = useState<LazyPaginatedCollection<Type>>(new LazyPaginatedCollection<Type>(1, fetcher));
const [rect, setRect] = useState<Rect>({
x: 0,
y: 0,
height: 0,
width: 0,
});

const [state, dispatch] = useReducer(reducer<Type>, {
scrollTop: 0,
Expand All @@ -106,6 +119,12 @@ export default function VirtualTable<Type>({ height, renderer, fetcher }: Args<T
const calculatePageCount = () => 2 * Math.floor(height / state.itemHeight);

useEffect(() => {
const handler = () => {
if (ref && ref.current) {
setRect(ref.current.getBoundingClientRect());
}
};
window.addEventListener('resize', handler);
collection.slice(0, 1).then((result) => {
dispatch({
type: 'loaded',
Expand All @@ -115,6 +134,9 @@ export default function VirtualTable<Type>({ height, renderer, fetcher }: Args<T
},
});
});
return function cleanup() {
window.removeEventListener('resize', handler, true);
}
}, []);

useEffect(() => {
Expand Down Expand Up @@ -161,15 +183,16 @@ export default function VirtualTable<Type>({ height, renderer, fetcher }: Args<T
const ret = [];

for (let i = 0; i < d.length; i += 1) {
let backgroundColor = 'transparent';
if (i + offset === state.selected) {
backgroundColor = 'dimgrey';
} else if (i + offset === state.hovered) {
backgroundColor = 'silver';
let className = '';
if (style) {
className = style.item;
}
ret.push(<div key={i + offset} style={{
backgroundColor,
}}>{renderer(d[i])}</div>);
if (i + offset === state.selected && style) {
className = `${className} ${style.select}`;
} else if (i + offset === state.hovered && style) {
className = `${className} ${style.hover}`;
}
ret.push(<div key={i + offset}>{renderer(d[i], className)}</div>);
}
return ret;
};
Expand All @@ -179,6 +202,7 @@ export default function VirtualTable<Type>({ height, renderer, fetcher }: Args<T
ref.current.scrollTop = state.scrollTop % state.itemHeight;
if (ref.current.children && ref.current.children.length) {
if (ref.current.children[0].clientHeight !== state.itemHeight) {
setRect(ref.current.getBoundingClientRect());
dispatch({
type: 'render',
data: {
Expand All @@ -195,66 +219,74 @@ export default function VirtualTable<Type>({ height, renderer, fetcher }: Args<T
}

return (
<div style={{ position: 'relative' }}>
<div
ref={ref}
className={css.grid}
style={{
height, position: 'sticky', top: 0, width: '100%', overflow: 'hidden',
}}
>
{generate(currentOffset, slideItems(currentOffset, {
items: state.items,
offset: state.offset,
}))}
</div>
<div
style={{
height, overflow: 'scroll', position: 'absolute', width: '100%', top: 0,
}}
onMouseMove={(e) => {
const index = Math.floor((e.clientY + state.scrollTop - ref.current.getBoundingClientRect().top) / state.itemHeight);
const childElement = ref.current.children[index - state.offset];
if (childElement) {
const event = new Event('mouseover', { bubbles: true, cancelable: false });
childElement.dispatchEvent(event);
dispatch({
type: 'hover',
data: {
hovered: index,
},
});
}
}}
onClick={(e) => {
const index = Math.floor((e.clientY + state.scrollTop - ref.current.getBoundingClientRect().top) / state.itemHeight);
const childElement = ref.current.children[index - state.offset];
if (childElement) {
const clickEvent = new Event('click', { bubbles: true, cancelable: false });
childElement.children[0].dispatchEvent(clickEvent);
dispatch({
type: 'click',
data: {
selected: index,
},
});
}
}}
onScroll={(e) => {
dispatch({
type: 'scroll',
data: {
scrollTop: (e.target as HTMLElement).scrollTop,
},
});
}}
>
<div style={{
height: `${state.itemCount * state.itemHeight}px`, position: 'absolute', top: 0, width: '100%',
}}
/>
</div>
</div>
<Container>
<Row>
<Col>
<div
ref={ref}
className='overflow-hidden'
style={{
height,
}}
>
{generate(currentOffset, slideItems(currentOffset, {
items: state.items,
offset: state.offset,
}))}
</div>
<div
className='overflow-scroll position-absolute'
style={{
top: rect.y,
left: rect.x,
width: rect.width,
height: rect.height,
}}
onMouseMove={(e) => {
const index = Math.floor((e.clientY + state.scrollTop - ref.current.getBoundingClientRect().top) / state.itemHeight);
const childElement = ref.current.children[index - state.offset];
if (childElement) {
const event = new Event('mouseover', { bubbles: true, cancelable: false });
childElement.children[0].dispatchEvent(event);
dispatch({
type: 'hover',
data: {
hovered: index,
},
});
}
}}
onClick={(e) => {
const index = Math.floor((e.clientY + state.scrollTop - ref.current.getBoundingClientRect().top) / state.itemHeight);
const childElement = ref.current.children[index - state.offset];
if (childElement) {
const clickEvent = new Event('click', { bubbles: true, cancelable: false });
childElement.children[0].dispatchEvent(clickEvent);
dispatch({
type: 'click',
data: {
selected: index,
},
});
}
}}
onScroll={(e) => {
dispatch({
type: 'scroll',
data: {
scrollTop: (e.target as HTMLElement).scrollTop,
},
});
}}
>
<div style={{
height: `${state.itemCount * state.itemHeight}px`, width: '100%',
}}
/>
</div>
</Col>
</Row>
</Container>
);
}

Expand Down
6 changes: 6 additions & 0 deletions src/helpers/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,9 @@ export interface Result<Type> {
}

export type Fetcher<Type> = (index: number, count: number) => Promise<Result<Type>>;

export interface Style {
hover: string;
select: string;
item: string;
}
Binary file added testApp.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions testApp/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>VirtualTable</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous" />
</head>

<body>
Expand Down
10 changes: 10 additions & 0 deletions testApp/src/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.item {
}

.item.hover {
background-color: aquamarine;
}

.item.select {
background-color: red;
}
46 changes: 33 additions & 13 deletions testApp/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';

import VirtualTable from '../../src/VirtualTable';
import { Result } from '../../src/helpers/types';
import { Result, Style } from '../../src/helpers/types';
import css from './index.css';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';

const style = css as Style;
const fetchData = (index: number, count: number): Promise<Result<number>> => {
const items = [...Array(count).keys()].map((value) => value + index);
return new Promise((resolve, reject) => {
Expand All @@ -25,18 +30,33 @@ const fetchData = (index: number, count: number): Promise<Result<number>> => {

function App() {
return (
<VirtualTable<number>
renderer={(i) => <div
style={{ padding: 5 }}
onClick={(e) => {
console.log(`${i} clicked`);
}}
>
{i !== undefined ? i : 'unknown'}
</div>}
height={400}
fetcher={fetchData}
/>
<Container>
<Row style={{
height: '50px'
}}/>
<Row>
<Col/>
<Col>
<VirtualTable<number>
style={style}
renderer={(i, classes) => <div
className={`text-center border rounded-pill p-3 ${classes}`}
onClick={(e) => {
console.log(`${i} clicked`);
}}
>
{i !== undefined ? i : 'unknown'}
</div>}
height={400}
fetcher={fetchData}
/>
</Col>
<Col/>
</Row>
<Row style={{
height: '50px'
}}/>
</Container>
);
}

Expand Down
1 change: 0 additions & 1 deletion testApp/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ module.exports = (env = {}) => ({
},
{
test: /\.css$/i,
exclude: /node_modules/,
use: ['style-loader', {
loader: 'css-loader',
options: {
Expand Down
Loading