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
5 changes: 5 additions & 0 deletions internal/playground/src/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ export const baseRouter = [
name: 'date-picker 日期选择器',
path: '/date-picker',
},
{
element: getDemos(import.meta.glob('~/virtual-list/demo/*.tsx')),
name: 'virtual-list 虚拟列表',
path: '/virtual-list',
},
/*insert target*/
];

Expand Down
1 change: 1 addition & 0 deletions packages/components/src/index.scss
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@
@import './input-popover';
@import './picker';
@import './date-picker';
@import './virtual-list';
1 change: 1 addition & 0 deletions packages/components/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,4 @@ export * from './calendar';
export * from './input-popover';
export * from './picker';
export * from './date-picker';
export * from './virtual-list';
1 change: 1 addition & 0 deletions packages/components/src/namespace.scss
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,4 @@ $input-skin: '#{Var.$prefix}input-skin';
$input-popover: '#{Var.$prefix}input-popover';
$picker: '#{Var.$prefix}picker';
$date-picker: '#{Var.$prefix}date-picker';
$virtual-list: '#{Var.$prefix}virtual-list';
177 changes: 177 additions & 0 deletions packages/components/src/virtual-list/VirtualList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import React, { useEffect, Children, useState, useMemo, useRef } from 'react';
import type { VirtualListProps } from './virtual-list.types';
import { getClassNames, getSafeNum } from '@tool-pack/basic';
import { useForwardRef, getClasses } from '@pkg/shared';
import type { RequiredPart } from '@tool-pack/types';

const cls = getClasses('virtual-list', ['items', 'wrapper'], []);
const defaultProps = {
tag: 'div',
} satisfies Partial<VirtualListProps>;

type Offsets = [start: number, end: number];

export const VirtualList: React.FC<VirtualListProps> = React.forwardRef<
HTMLElement,
VirtualListProps
>((props, ref) => {
const {
attrs = {},
children,
tag,
} = props as RequiredPart<VirtualListProps, keyof typeof defaultProps>;
const itemsElRef = useRef<HTMLDivElement>(null);
const wrapperElRef = useRef<HTMLDivElement>(null);
const rootElRef = useForwardRef(ref);

const containerItemsLenRef = useRef(0);
const translateYRef = useRef(0);
const scrollHandlerLockerRef = useRef(false);
const autoFillLayoutRef = useRef(true);
const scrollTopRef = useRef(0);
const [offsets, setOffsets] = useState<Offsets>([0, 0]);
const childList = useMemo(() => Children.toArray(children), [children]);

const _children = useMemo(() => {
const [start, end] = offsets;
return childList.slice(start, end);
}, [childList, offsets]);

useEffect(() => {
if (!autoFillLayoutRef.current) return;
const [start, end] = offsets;
const len = childList.length;
if (end >= childList.length) {
autoFillLayoutRef.current = false;
return;
}
const wrapperEL = itemsElRef.current;
const itemsEl = itemsElRef.current;
const rootEl = rootElRef.current;
if (wrapperEL && itemsEl && rootEl) {
const { offsetHeight } = itemsEl;
if (offsetHeight > rootEl.offsetHeight) {
const firstChild = itemsEl.children[0] as HTMLElement | null;
if (firstChild) {
wrapperEL.style.height =
offsetHeight + (len - end) * firstChild.offsetHeight + 'px';
}
autoFillLayoutRef.current = false;
return;
}
}
containerItemsLenRef.current++;
setOffsets([start, end + 1]);
});

useEffect(() => {
scrollHandlerLockerRef.current = false;
}, [offsets]);

return React.createElement(
tag,
{
...attrs,
className: getClassNames(cls.root, attrs.className),
onScroll: _onScroll,
ref: rootElRef,
},
<div className={cls.__.wrapper} ref={wrapperElRef}>
<div
style={{ transform: `translateY(${translateYRef.current}px)` }}
className={cls.__.items}
ref={itemsElRef}
>
{_children}
</div>
</div>,
);

function _onScroll(e: React.UIEvent<HTMLDivElement>) {
if (scrollHandlerLockerRef.current) return;
const target = e.currentTarget;
const itemsEl = itemsElRef.current;

if (!itemsEl) return;

const children = itemsEl.children;
if (!children || !children.length) return;

const { scrollTop } = target;

const direct = scrollTop > scrollTopRef.current ? 'bottom' : 'top';
scrollTopRef.current = scrollTop;

let [start, end] = offsets;
const firstChild = children[0] as HTMLElement;
const lastChild = children[children.length - 1] as HTMLElement;
console.log(direct, scrollTop);

if (direct === 'top') {
if (start > 0 && isScrollOnTopOfFirstChild(firstChild)) {
start--;
}
if (isScrollOnTopOfLastChild(lastChild)) {
end--;
}
setSafeOffsets(start, end, firstChild);
return;
}

/* ---- direct === 'bottom' ---- */

if (isScrollAtBottomOfFirstChild(firstChild)) {
start++;
}
if (isScrollAtBottomOfLastChild(lastChild)) {
end++;
}
setSafeOffsets(start, end, firstChild);
}
function isScrollOnTopOfFirstChild(firstChild: HTMLElement): boolean {
return scrollTopRef.current < firstChild.offsetTop + translateYRef.current;
}
function isScrollAtBottomOfFirstChild(firstChild: HTMLElement): boolean {
return (
scrollTopRef.current >
firstChild.offsetHeight + firstChild.offsetTop + translateYRef.current
);
}
function isScrollAtBottomOfLastChild(lastChild: HTMLElement): boolean {
return (
scrollTopRef.current + (rootElRef.current?.offsetHeight || 0) >
lastChild.offsetHeight + lastChild.offsetTop + translateYRef.current
);
}
function isScrollOnTopOfLastChild(lastChild: HTMLElement): boolean {
return (
scrollTopRef.current + (rootElRef.current?.offsetHeight || 0) <
lastChild.offsetTop + translateYRef.current
);
}
function setSafeOffsets(
start: number,
end: number,
firstChild: HTMLElement,
): void {
const maxIndex = childList.length;
start = getSafeNum(start, 0, maxIndex);
end = getSafeNum(end, 0, maxIndex);

const [_start, _end] = offsets;

if (end - start < containerItemsLenRef.current) return;
if (start === _start && end === _end) return;

if (start !== _start) {
translateYRef.current +=
firstChild.offsetHeight * (start > _start ? 1 : -1);
}

scrollHandlerLockerRef.current = true;
setOffsets([start, end]);
}
});

VirtualList.defaultProps = defaultProps;
VirtualList.displayName = 'VirtualList';
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { render } from '@testing-library/react';
import { testAttrs } from '~/testAttrs';
import { VirtualList } from '..';

describe('VirtualList', () => {
testAttrs(VirtualList);
it('basic', () => {
expect(
render(
<VirtualList>
<div>123</div>
<div>123</div>
<div>123</div>
</VirtualList>,
).container.firstChild,
).toMatchSnapshot();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`VirtualList basic 1`] = `
<div
class="t-virtual-list"
>
<div
class="t-virtual-list__wrapper"
>
<div
class="t-virtual-list__items"
style="transform: translateY(0px);"
>
<div>
123
</div>
<div>
123
</div>
<div>
123
</div>
</div>
</div>
</div>
`;
26 changes: 26 additions & 0 deletions packages/components/src/virtual-list/demo/basic.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* title: 基础用法
* description: VirtualList 基础用法。
*/

import { VirtualList, Alert } from '@tool-pack/react-ui';
import React from 'react';

const App: React.FC = () => {
return (
<VirtualList
attrs={{
style: {
backgroundColor: '#fdf3f8',
height: '200px',
},
}}
>
{Array.from({ length: 10 }).map((_, i) => (
<Alert key={i}>{i}</Alert>
))}
</VirtualList>
);
};

export default App;
11 changes: 11 additions & 0 deletions packages/components/src/virtual-list/index.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
@use '../namespace' as Name;

$r: Name.$virtual-list;

.#{$r} {
overflow: auto;
&__wrapper {
position: relative;
overflow: hidden;
}
}
2 changes: 2 additions & 0 deletions packages/components/src/virtual-list/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export type { VirtualListProps } from './virtual-list.types';
export * from './VirtualList';
29 changes: 29 additions & 0 deletions packages/components/src/virtual-list/index.zh-CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
---
category: Components
title: VirtualList 虚拟列表
atomId: VirtualList
demo:
cols: 2
group:
title: 数据展示
---

VirtualList 虚拟列表。

当列表数据量大的时候,使用该组件能够提高长列表的性能。

## 代码演示

<!-- prettier-ignore -->
<code src="./demo/basic.tsx"></code>

## API

VirtualList 的属性说明如下:

| 属性 | 说明 | 类型 | 默认值 | 版本 |
| ----- | ------------------ | -------------------------------------------- | ------ | ---- |
| tag | 组件根元素的标签名 | keyof HTMLElementTagNameMap | 'div' | -- |
| attrs | html 标签属性 | Partial\<React.HTMLAttributes\<HTMLElement>> | -- | -- |

其他说明。
5 changes: 5 additions & 0 deletions packages/components/src/virtual-list/virtual-list.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { PropsBase } from '@pkg/shared';

export interface VirtualListProps extends PropsBase<HTMLElement> {
tag?: keyof HTMLElementTagNameMap;
}