Skip to content
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
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ module.exports = {
'@typescript-eslint/no-explicit-any': 0,
'react/no-did-update-set-state': 0,
'react/no-find-dom-node': 0,
'no-dupe-class-members': 0,
},
};
87 changes: 67 additions & 20 deletions examples/basic.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
/* eslint-disable jsx-a11y/label-has-associated-control, jsx-a11y/label-has-for */
import * as React from 'react';
import List from '../src/List';

interface Item {
id: number;
}

const MyItem: React.FC<Item> = ({ id }, ref) => {
return (
<span
ref={ref}
style={{
border: '1px solid gray',
padding: '0 16px',
height: 30,
lineHeight: '30px',
boxSizing: 'border-box',
display: 'inline-block',
}}
>
{id}
</span>
);
};
const MyItem: React.FC<Item> = ({ id }, ref) => (
<span
ref={ref}
style={{
border: '1px solid gray',
padding: '0 16px',
height: 30,
lineHeight: '30px',
boxSizing: 'border-box',
display: 'inline-block',
}}
>
{id}
</span>
);

const ForwardMyItem = React.forwardRef(MyItem);

class TestItem extends React.Component<{ id: number }> {
class TestItem extends React.Component<{ id: number }, {}> {
state = {};

render() {
return <div style={{ lineHeight: '30px' }}>{this.props.id}</div>;
}
Expand All @@ -45,6 +46,7 @@ const TYPES = [

const Demo = () => {
const [type, setType] = React.useState('dom');
const listRef = React.useRef<List>(null);

return (
<React.StrictMode>
Expand All @@ -65,6 +67,7 @@ const Demo = () => {
))}

<List
ref={listRef}
data={data}
height={200}
itemHeight={30}
Expand All @@ -75,16 +78,60 @@ const Demo = () => {
}}
>
{(item, _, props) =>
type === 'dom' ? (
(type === 'dom' ? (
<ForwardMyItem {...item} {...props} />
) : (
<TestItem {...item} {...props} />
)
))
}
</List>

<button
type="button"
onClick={() => {
listRef.current.scrollTo(500);
}}
>
Scroll To 100px
</button>
<button
type="button"
onClick={() => {
listRef.current.scrollTo({
index: 50,
align: 'top',
});
}}
>
Scroll To 50 (top)
</button>
<button
type="button"
onClick={() => {
listRef.current.scrollTo({
index: 50,
align: 'bottom',
});
}}
>
Scroll To 50 (bottom)
</button>
<button
type="button"
onClick={() => {
listRef.current.scrollTo({
index: 50,
align: 'auto',
});
}}
>
Scroll To 50 (auto)
</button>
</div>
</React.StrictMode>
);
};

export default Demo;

/* eslint-enable */
131 changes: 125 additions & 6 deletions src/List.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ interface ListState<T> {
* # located item
* The base position item which other items position calculate base on.
*/
class List<T> extends React.Component<ListProps<T>, ListState<T>> {
class List<T = any> extends React.Component<ListProps<T>, ListState<T>> {
static defaultProps = {
itemHeight: 15,
data: [],
Expand Down Expand Up @@ -404,7 +404,7 @@ class List<T> extends React.Component<ListProps<T>, ListState<T>> {
return this.getItemKey(item, mergedProps);
};

public getItemKey = (item: T, props?: Partial<ListProps<T>>) => {
public getItemKey = (item: T, props?: Partial<ListProps<T>>): string => {
const { itemKey } = props || this.props;

return typeof itemKey === 'function' ? itemKey(item) : item[itemKey];
Expand All @@ -413,8 +413,8 @@ class List<T> extends React.Component<ListProps<T>, ListState<T>> {
/**
* Collect current rendered dom element item heights
*/
public collectItemHeights = () => {
const { startIndex, endIndex } = this.state;
public collectItemHeights = (range?: { startIndex: number; endIndex: number }) => {
const { startIndex, endIndex } = range || this.state;
const { data } = this.props;

// Record here since measure item height will get warning in `render`
Expand All @@ -429,8 +429,127 @@ class List<T> extends React.Component<ListProps<T>, ListState<T>> {
}
};

public scrollTo(scrollTop: number) {
this.listRef.current.scrollTop = scrollTop;
public scrollTo(scrollTop: number): void;

public scrollTo(config: { index: number; align?: 'top' | 'bottom' | 'auto' }): void;

public scrollTo(arg0: any) {
// Number top
if (typeof arg0 === 'object') {
const { isVirtual } = this.state;
const { height, itemHeight, data } = this.props;
const { index, align = 'auto' } = arg0;
const itemCount = Math.ceil(height / itemHeight);
const item = data[index];
if (item) {
const { clientHeight } = this.listRef.current;

if (isVirtual) {
// Calculate related data
const { itemIndex, itemOffsetPtg, startIndex, endIndex } = this.state;

const relativeLocatedItemTop = getItemRelativeTop({
itemIndex,
itemOffsetPtg,
itemElementHeights: this.itemElementHeights,
scrollPtg: getElementScrollPercentage(this.listRef.current),
clientHeight,
getItemKey: this.getIndexKey,
});

// We will force render related items to collect height for re-location
this.setState(
{
startIndex: Math.max(0, index - itemCount),
endIndex: Math.min(data.length - 1, index + itemCount),
},
() => {
this.collectItemHeights();

// Calculate related top
let relativeTop: number;
let mergedAlgin = align;

if (align === 'auto') {
let shouldChange = true;

// Check if exist in the visible range
if (Math.abs(itemIndex - index) < itemCount) {
let itemTop = relativeLocatedItemTop;
if (index < itemIndex) {
for (let i = index; i < itemIndex; i += 1) {
const eleKey = this.getIndexKey(i);
itemTop -= this.itemElementHeights[eleKey] || 0;
}
} else {
for (let i = itemIndex; i <= index; i += 1) {
const eleKey = this.getIndexKey(i);
itemTop += this.itemElementHeights[eleKey] || 0;
}
}

shouldChange = itemTop <= 0 || itemTop >= clientHeight;
}

if (shouldChange) {
// Out of range will fall back to position align
mergedAlgin = index < itemIndex ? 'top' : 'bottom';
} else {
this.setState({
startIndex,
endIndex,
});
return;
}
}

// Align with position should make scroll happen
if (mergedAlgin === 'top') {
relativeTop = 0;
} else if (mergedAlgin === 'bottom') {
const eleKey = this.getItemKey(item);

relativeTop = clientHeight - this.itemElementHeights[eleKey] || 0;
}

this.internalScrollTo({
itemIndex: index,
relativeTop,
});
},
);
} else {
// Raw list without virtual scroll set position directly
this.collectItemHeights({ startIndex: 0, endIndex: data.length - 1 });
let mergedAlgin = align;

// Collection index item position
const indexItemHeight = this.itemElementHeights[this.getIndexKey(index)];
let itemTop = 0;
for (let i = 0; i < index; i += 1) {
const eleKey = this.getIndexKey(i);
itemTop += this.itemElementHeights[eleKey] || 0;
}
const itemBottom = itemTop + indexItemHeight;

if (mergedAlgin === 'auto') {
if (itemTop < this.listRef.current.scrollTop) {
mergedAlgin = 'top';
} else if (itemBottom > this.listRef.current.scrollTop + clientHeight) {
mergedAlgin = 'bottom';
}
}

if (mergedAlgin === 'top') {
this.listRef.current.scrollTop = itemTop;
} else if (mergedAlgin === 'bottom') {
this.listRef.current.scrollTop = itemTop - (clientHeight - indexItemHeight);
}
}
}
} else {
this.listRef.current.scrollTop = arg0;
}
}

public internalScrollTo(relativeScroll: RelativeScroll): void {
Expand Down
Loading