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

[#38] Improve preview pages #39

Merged
merged 8 commits into from
Nov 23, 2024
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
19 changes: 16 additions & 3 deletions preview/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,28 @@
import './asset/Style.scss';
import Preview from './Preview';
import GithubIcon from './asset/GithubIcon.svg';
import NpmIcon from './asset/NpmIcon.svg';

const App = () => {
return <>
<header className='Preview-Header'>
<h1>react-window-infinite-scroll preview</h1>
<div className='Icons'>
<a
className='IconLink'
href='https://github.com/dlguswo333/react-window-infinite-scroll'>
<img src={GithubIcon} />
</a>
<a
className='IconLink'
href='https://www.npmjs.com/package/react-window-infinite-scroll'>
<img src={NpmIcon} />
</a>
</div>
</header>
<main className='Preview-Main'>
<Preview type={1} />
<Preview type={2} />
<Preview type={3} />
<Preview />
<Preview />
</main>
</>;
};
Expand Down
92 changes: 92 additions & 0 deletions preview/src/Config.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
export type Configs = {
NumItemsToLoadAtOnce: 1 | 3 | 5;
Threshold: number,
ScrollOffset: number,
InfiniteScrollDirection: 'start' | 'end' | 'both',
}
type SetState<T> = React.Dispatch<React.SetStateAction<T>>

type Props = {
numItemsToLoadAtOnce: Configs['NumItemsToLoadAtOnce'];
threshold: Configs['Threshold'],
scrollOffset: Configs['ScrollOffset'],
infiniteScrollDirection: Configs['InfiniteScrollDirection'],
setNumItemsToLoadAtOnce: SetState<Configs['NumItemsToLoadAtOnce']>;
setThreshold: SetState<Configs['Threshold']>,
setScrollOffset: SetState<Configs['ScrollOffset']>,
setInfiniteScrollDirection: SetState<Configs['InfiniteScrollDirection']>,
resetData: () => void;
}

const Config = ({
numItemsToLoadAtOnce,
threshold,
scrollOffset,
infiniteScrollDirection,
setNumItemsToLoadAtOnce,
setThreshold,
setScrollOffset,
setInfiniteScrollDirection,
resetData,
}: Props) => {
return <div className='Preview-Config'>
<div>
<h3>Number of Items to Load At Once: <code>{numItemsToLoadAtOnce}</code></h3>
<select
value={numItemsToLoadAtOnce}
onChange={(e) => {
const value = Number(e.target.value);
if (value === 1 || value === 3 || value === 5) {
setNumItemsToLoadAtOnce(value);
}
}}
>
<option value={1}>1</option>
<option value={3}>3</option>
<option value={5}>5</option>
</select>
</div>
<div>
<h3>threshold: <code>{threshold}</code></h3>
<input type='number' defaultValue={threshold} onChange={(e) => {
const value = Number(e.target.value);
if (Number.isInteger(value) && 0 <= value && value <= 5) {
setThreshold(value);
}
}} />
(<code>0</code> ~ <code>5</code>)
</div>
<div>
<h3>Infinite Scroll Direction: <code>{infiniteScrollDirection}</code></h3>
<select
value={infiniteScrollDirection}
onChange={(e) => {
const value = e.target.value;
if (value === 'start' || value === 'end' || value === 'both') {
setInfiniteScrollDirection(value);
}
}}
>
<option value='start'>start</option>
<option value='end'>end</option>
<option value='both'>both</option>
</select>
</div>
<div>
<h3>Scroll Offset: <code>{scrollOffset}</code></h3>
<input type='number' defaultValue={scrollOffset} onChange={(e) => {
const value = Number(e.target.value);
if (Number.isInteger(value) && 0 <= value && value <= 30) {
setScrollOffset(value);
}
}} />
(<code>0</code> ~ <code>30</code>)
</div>
<div>
<h3>Reset Data</h3>
<button onClick={resetData}>reset</button>
</div>
</div>;
};

export default Config;
39 changes: 29 additions & 10 deletions preview/src/Preview.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,48 @@
import InfiniteScroll from 'react-window-infinite-scroll';
import useReactWindow from './useReactWindow';
import {FixedSizeList} from 'react-window';
import {CSSProperties, useRef} from 'react';
import {CSSProperties, useRef, useState} from 'react';
import Config, {Configs} from './Config';

type Props = {
type: Parameters<typeof useReactWindow>[0]
}
const defaultValues = {
numItemsToLoadAtOnce: 1,
threshold: 1,
scrollOffset: 30,
infiniteScrollDirection: 'end',
} as const;

const Preview = ({type}: Props) => {
const {data, loadMoreItems, isItemsLoaded, itemCount} = useReactWindow(type);
const Preview = () => {
const [numItemsToLoadAtOnce, setNumItemsToLoadAtOnce] = useState<Configs['NumItemsToLoadAtOnce']>(defaultValues.numItemsToLoadAtOnce);
const [threshold, setThreshold] = useState<Configs['Threshold']>(defaultValues.threshold);
const [scrollOffset, setScrollOffset] = useState<Configs['ScrollOffset']>(defaultValues.scrollOffset);
const [infiniteScrollDirection, setInfiniteScrollDirection] = useState<Configs['InfiniteScrollDirection']>(defaultValues.infiniteScrollDirection);
const {data, loadMoreItems, isItemsLoaded, itemCount, resetData} = useReactWindow({numItemsToLoadAtOnce, infiniteScrollDirection});
const outerRef = useRef<HTMLElement>(null);

const Row = ({index, style}: {index: number, style: CSSProperties}) => (
<div style={style}>{data[index]}</div>
);

return <>
return <div>
<Config
numItemsToLoadAtOnce={numItemsToLoadAtOnce}
threshold={threshold}
scrollOffset={scrollOffset}
infiniteScrollDirection={infiniteScrollDirection}
setNumItemsToLoadAtOnce={setNumItemsToLoadAtOnce}
setThreshold={setThreshold}
setScrollOffset={setScrollOffset}
setInfiniteScrollDirection={setInfiniteScrollDirection}
resetData={resetData}
/>
<InfiniteScroll
data={data}
loadMoreItems={loadMoreItems}
isItemLoaded={isItemsLoaded}
itemCount={itemCount}
threshold={1}
threshold={threshold}
outerRef={outerRef}
scrollOffset={30}
scrollOffset={scrollOffset}
>
{({onItemsRendered}) => <FixedSizeList
height={300}
Expand All @@ -37,7 +56,7 @@ const Preview = ({type}: Props) => {
{Row}
</FixedSizeList>}
</InfiniteScroll>
</>;
</div>;
};

export default Preview;
1 change: 1 addition & 0 deletions preview/src/asset/GithubIcon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions preview/src/asset/NpmIcon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
52 changes: 52 additions & 0 deletions preview/src/asset/Style.scss
Original file line number Diff line number Diff line change
@@ -1,23 +1,75 @@
$big-screen: 800px;

:root {
font-size: 17px;
}
* {
box-sizing: border-box;
}
.Preview-Header {
@media (max-width: $big-screen) {
text-align: center;
}
h1 {
display: inline-block;
margin-top: 8px;
margin-right: 14px;
}
.Icons {
display: inline-block;
& > * {
margin-right: 10px;
}
.IconLink {
display: inline-block;
width: 26px;
height: 26px;
@media (hover: hover) and (pointer: fine) {
&:hover {
filter: brightness(2.5);
}
}
img {
width: 100%;
height: 100%;
}
}
}
}
.Preview-Main {
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
gap: 6px;
@media (min-width: $big-screen) {
flex-direction: row;
align-items: flex-start;
}
& > div {
flex: 1;
}
.Outer {
border: 1px solid gray;
}
}
.Preview-Config {
display: flex;
flex-direction: column;
margin-bottom: 20px;
h3 {
margin-top: 16px;
margin-bottom: 6px;
}
input, select {
min-width: 80px;
field-sizing: content;
font-size: 0.9rem;
margin-right: 10px;
}
code {
background-color: #f0f0f0;
padding: 3px;
border-radius: 2px;
}
}
99 changes: 38 additions & 61 deletions preview/src/useReactWindow.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import {useCallback, useMemo, useRef, useState} from 'react';
import {sleep} from './util';
import {Configs} from './Config';

const MAX_LENGTH = 500;
const SLEEP_MS = 100;

const useReactWindow = (type: 1 | 2 | 3) => {
const [data, setData] = useState<string[]>(() => {
switch (type) {
case 1:
return [];
case 2:
return ['data 150'];
case 3:
return ['data 500'];
}
});
type Props = {
numItemsToLoadAtOnce: Configs['NumItemsToLoadAtOnce'];
infiniteScrollDirection: Configs['InfiniteScrollDirection'],
}

const useReactWindow = ({
numItemsToLoadAtOnce,
infiniteScrollDirection,
}: Props) => {
const [data, setData] = useState<string[]>(() => ['data 0']);
const resetData = useCallback(() => setData(['data 0']), []);
const isFetching = useRef<boolean>(false);
const itemCount = useMemo(() => data.length + (data.length < MAX_LENGTH ? 1 : 0), [data.length]);

Expand All @@ -27,64 +28,40 @@ const useReactWindow = (type: 1 | 2 | 3) => {
return;
}
isFetching.current = true;
switch (type) {
case 1: {
const newValue = `data ${data.length}`;
await sleep(SLEEP_MS);
setData(data => {
if (data.length >= MAX_LENGTH) {
// This must not be reached.
throw Error(`data length exceeds MAX_LENGTH:${MAX_LENGTH}`);
}
return data.concat([newValue]);
});
isFetching.current = false;
break;
}
case 2: {
const newValue = direction === 'end' ?
`data ${Number(/(-?\d+)/.exec(data[data.length - 1])![1]) + 1}` :
`data ${Number(/(-?\d+)/.exec(data[0])![1]) - 1}`;
await sleep(SLEEP_MS);
setData(data => {
if (data.length >= MAX_LENGTH) {
const getNewItems = () => {
if (data.length >= MAX_LENGTH) {
// This must not be reached.
throw Error(`data length exceeds MAX_LENGTH:${MAX_LENGTH}`);
}
return direction === 'end' ? [...data, newValue] : [newValue, ...data];
});
isFetching.current = false;
break;
}
case 3: {
const newValue = `data ${Number(/(-?\d+)/.exec(data[0])![1]) - 1}`;
await sleep(SLEEP_MS);
setData(data => {
if (data.length >= MAX_LENGTH) {
// This must not be reached.
throw Error(`data length exceeds MAX_LENGTH:${MAX_LENGTH}`);
}
return [newValue, ...data];
});
isFetching.current = false;
break;
}
}
}, [data, type]);
throw Error(`data length exceeds MAX_LENGTH:${MAX_LENGTH}`);
}
const newItems = [];
const start = direction === 'end'
? Number(/(-?\d+)/.exec(data[data.length - 1])![1]) + 1
: Number(/(-?\d+)/.exec(data[0])![1]) - numItemsToLoadAtOnce;
for (let i = 0;i < numItemsToLoadAtOnce;++i) {
newItems.push(`data ${start + i}`);
}
return direction === 'end'
? [...data, ...newItems]
: [...newItems, ...data];
};
await sleep(SLEEP_MS);
setData(getNewItems());
isFetching.current = false;
}, [data, numItemsToLoadAtOnce]);

const isItemsLoaded = useCallback((index: number) => {
switch (type) {
case 1:
return index >= MAX_LENGTH || index < data.length;
case 2:
switch (infiniteScrollDirection) {
case 'end':
return data.length >= MAX_LENGTH || index < 0;
case 'both':
return data.length >= MAX_LENGTH;
case 3:
case 'start':
return data.length >= MAX_LENGTH || index >= 0;
}
}, [data.length, type]);
}, [data.length, infiniteScrollDirection]);

return {
data, loadMoreItems, isItemsLoaded, itemCount,
data, loadMoreItems, isItemsLoaded, itemCount, resetData,
};
};

Expand Down
Loading
Loading