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

feat: support sticky indexes #274

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
23 changes: 12 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,24 +43,25 @@ open http://localhost:9001/
import List from 'rc-virtual-list';

<List data={[0, 1, 2]} height={200} itemHeight={30} itemKey="id">
{index => <div>{index}</div>}
{(index) => <div>{index}</div>}
</List>;
```

# API

## List

| Prop | Description | Type | Default |
| ---------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| children | Render props of item | (item, index, props) => ReactElement | - |
| component | Customize List dom element | string \| Component | div |
| data | Data list | Array | - |
| disabled | Disable scroll check. Usually used on animation control | boolean | false |
| height | List height | number | - |
| itemHeight | Item minium height | number | - |
| itemKey | Match key with item | string | - |
| styles | style | { horizontalScrollBar?: React.CSSProperties; horizontalScrollBarThumb?: React.CSSProperties; verticalScrollBar?: React.CSSProperties; verticalScrollBarThumb?: React.CSSProperties; } | - |
| Prop | Description | Type | Default |
| ------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| children | Render props of item | (item, index, props) => ReactElement | - |
| component | Customize List dom element | string \| Component | div |
| data | Data list | Array | - |
| disabled | Disable scroll check. Usually used on animation control | boolean | false |
| height | List height | number | - |
| itemHeight | Item minium height | number | - |
| itemKey | Match key with item | string | - |
| stickyIndexes | sticky indexes | number[] | - |
| styles | style | { horizontalScrollBar?: React.CSSProperties; horizontalScrollBarThumb?: React.CSSProperties; verticalScrollBar?: React.CSSProperties; verticalScrollBarThumb?: React.CSSProperties; } | - |

`children` provides additional `props` argument to support IE 11 scroll shaking.
It will set `style` to `visibility: hidden` when measuring. You can ignore this if no requirement on IE.
8 changes: 8 additions & 0 deletions docs/demo/sticky.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
title: Sticky
nav:
title: Demo
path: /demo
---

<code src="../../examples/sticky.tsx"></code>
69 changes: 69 additions & 0 deletions examples/sticky.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import * as React from 'react';
import List from '../src/List';

interface Item {
id: number;
height: number;
style?: React.CSSProperties;
}

const MyItem: React.ForwardRefRenderFunction<HTMLElement, Item> = ({ id, height, style }, ref) => {
return (
<span
ref={ref}
style={{
border: '1px solid gray',
padding: '0 16px',
height,
lineHeight: '30px',
boxSizing: 'border-box',
display: 'inline-block',
width: '100%',
...style,
...(style.position
? {
background: 'white',
}
: {}),
}}
>
{id}
</span>
);
};

const ForwardMyItem = React.forwardRef(MyItem);

const data: Item[] = [];
for (let i = 0; i < 100; i += 1) {
data.push({
id: i,
height: 30 + (i % 2 ? 70 : 0),
});
}

const Demo = () => {
return (
<React.StrictMode>
<div>
<h2>Sticky</h2>

<List
data={data}
height={500}
itemHeight={30}
itemKey="id"
stickyIndexes={[2, 4, 6]}
style={{
border: '1px solid red',
boxSizing: 'border-box',
}}
>
{(item, _, { style }) => <ForwardMyItem {...item} style={style} />}
</List>
</div>
</React.StrictMode>
);
};

export default Demo;
5 changes: 5 additions & 0 deletions src/List.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export interface ListProps<T> extends Omit<React.HTMLAttributes<any>, 'children'
* When set, `virtual` will always be enabled.
*/
scrollWidth?: number;
stickyIndexes?: number[];

styles?: {
horizontalScrollBar?: React.CSSProperties;
Expand Down Expand Up @@ -104,6 +105,7 @@ export function RawList<T>(props: ListProps<T>, ref: React.Ref<ListRef>) {
virtual,
direction,
scrollWidth,
stickyIndexes,
component: Component = 'div',
onScroll,
onVirtualScroll,
Expand Down Expand Up @@ -521,9 +523,12 @@ export function RawList<T>(props: ListProps<T>, ref: React.Ref<ListRef>) {
end,
scrollWidth,
offsetLeft,
offsetTop,
setInstanceRef,
children,
sharedConfig,
heights,
stickyIndexes,
);

let componentStyle: React.CSSProperties = null;
Expand Down
54 changes: 52 additions & 2 deletions src/hooks/useChildren.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,72 @@
import * as React from 'react';
import type { RenderFunc, SharedConfig } from '../interface';
import { Item } from '../Item';
import { generateIndexesWithSticky } from '../utils/algorithmUtil';
import type CacheMap from '../utils/CacheMap';

export default function useChildren<T>(
list: T[],
startIndex: number,
endIndex: number,
scrollWidth: number,
offsetX: number,
offsetY: number,
setNodeRef: (item: T, element: HTMLElement) => void,
renderFunc: RenderFunc<T>,
{ getKey }: SharedConfig<T>,
heights: CacheMap,
stickyIndexes: number[] = [],
) {
return list.slice(startIndex, endIndex + 1).map((item, index) => {
// Distance beyond the top of the container
const startOverContainerTop =
offsetY -
list.slice(0, startIndex).reduce((total, item) => total + heights.get(getKey(item)), 0);

const shouldStickyIndexesAndTop = stickyIndexes
.sort((a, b) => a - b)
.reduce<{ index: number; top: number }[]>((total, index) => {
// The sum of the heights of all sticky elements
const beforeStickyTotalHeight = total.reduce(
(height, item) => height + heights.get(getKey(list[item.index])),
0,
);
if (index <= startIndex) {
total.push({ index, top: startOverContainerTop + beforeStickyTotalHeight });
} else if (index > startIndex && index < endIndex) {
// Distance from top of container
const offsetContainerTop =
list.slice(0, index).reduce((height, item) => height + heights.get(getKey(item)), 0) -
(offsetY + startOverContainerTop);

if (offsetContainerTop <= beforeStickyTotalHeight) {
total.push({ index, top: startOverContainerTop + beforeStickyTotalHeight });
}
}
return total;
}, []);

return generateIndexesWithSticky(
startIndex,
endIndex,
shouldStickyIndexesAndTop.map((i) => i.index),
).map((index) => {
const item = list[index];
const eleIndex = startIndex + index;
const stickyInfo = shouldStickyIndexesAndTop.find((i) => i.index === index);
const node = renderFunc(item, eleIndex, {
style: {
width: scrollWidth,
...(scrollWidth
? {
width: scrollWidth,
}
: {}),
...(stickyInfo
? {
// Use sticky when it exists, use absolute when it disappears
position: index >= startIndex && index <= endIndex ? 'sticky' : 'absolute',
top: stickyInfo.top,
}
: {}),
},
offsetX,
}) as React.ReactElement;
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useHeights.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as React from 'react';
import { useRef, useEffect } from 'react';
import findDOMNode from 'rc-util/lib/Dom/findDOMNode';
import raf from 'rc-util/lib/raf';
import * as React from 'react';
import { useEffect, useRef } from 'react';
import type { GetKey } from '../interface';
import CacheMap from '../utils/CacheMap';

Expand Down
19 changes: 19 additions & 0 deletions src/utils/algorithmUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,22 @@ export function findListDiffIndex<T>(

return diffIndex === null ? null : { index: diffIndex, multiple };
}

export function generateIndexesWithSticky(
startIndex: number,
endIndex: number,
stickyIndexes: number[],
) {
const indexArray: number[] = [];
for (let i = startIndex; i <= endIndex; i++) {
indexArray.push(i);
}

stickyIndexes.forEach((index) => {
if (index < startIndex || index > endIndex) {
indexArray.push(index);
}
});

return indexArray.sort((a, b) => a - b);
}
Loading