import {computed, getComponentCls, onBeforeUnmount, onMounted, onUpdated, reactive, useClasses, useStyles, watch} from "@peryl/react-compose"; import {createCounter} from '@peryl/utils/createCounter'; import {delay} from "@peryl/utils/delay"; import './virtual-list.scss'; import Scroll from "../Scroll"; import {unit} from "@peryl/utils/unit"; import {createEnum} from "@peryl/utils/createEnum"; import {PlainObject} from "@peryl/utils/event"; import {addWindowListener} from "@peryl/utils/addWindowListener"; interface DataNode { start: number; end: number; size: number; item: any; id: string; index: number, } /** * 滚动的方向 * 纵向:start表示往上滚动,end表示往下滚动 * 横向:start表示往左滚动,end表示往右滚动 * @author 韦胜健 * @date 2024/1/10 14:37 */ const ScrollDirection = createEnum(['start', 'end', 'none'] as const); const nextRowId = createCounter('__v__'); export function useVirtualList( { dataModel, props, refs, emit, transform, }: { dataModel: { value: any[] | undefined | null }, props: { size: number, disabled?: boolean, dynamicSize?: boolean, /*纵向虚拟滚动,需要横向滚动的时候必须指定宽度*/ width?: string | number, /*横向虚拟滚动,需要纵向滚动的时候必须指定高度*/ height?: string | number, /*启用横向虚拟滚动*/ horizontal?: boolean, }, refs: { scroll?: typeof Scroll.use.class | null, content?: HTMLDivElement | null, }, emit: { onScroll: (e: Event) => void, onPageIndexChange: (data: { pageIndex: number, startIndex: number, endIndex: number }) => void, }, transform?: boolean, } ) { /*非响应式属性*/ const freezeState = { scrollValue: 0, // 实时的scrollTop值 current: { // 当前的页面信息 pageIndex: 0, startIndex: 0, endIndex: 0, }, }; /*响应式属性*/ const state = reactive({ scrollValue: 0, // 当前滚动scrollTop(非实时的) hostSize: null as null | number, // 容器高度 scrollDirection: ScrollDirection.none as typeof ScrollDirection.TYPE, id2size: {} as Record, }); const _avgSize = computed((): number => { const total = Object.values(state.id2size).reduce((prev, item) => { if (item != null) { prev.total += item; prev.count++; } return prev; }, { total: 0, count: 0 }); if (!!total.count) { return Math.floor(total.total / total.count); } else { return props.size; } }); const _pageSize = computed(() => { if (state.hostSize == null) {return null;} return Math.max(3, Math.floor(state.hostSize / _avgSize.value)); }); const idMap = new WeakMap(); let prevEnd = 0; const nodes = computed((): iVirtualNode[] => { prevEnd = 0; return (dataModel.value || []).map((item, index): DataNode => { let id = idMap.get(item); if (!id) { id = nextRowId(); idMap.set(item, id); } const size: number = state.id2size[id] || _avgSize.value; let start = prevEnd; let end = start + size; prevEnd = end; return { id: id!, item, size, start, end, index }; }); }); /** * 计算得到的在虚拟列表当前要渲染的数组数据 * @author 韦胜健 * @date 2020/11/15 9:28 */ const offsetData = computed((): { list: { item: any, id: string, index: number }[], startPageIndex: number, startIndex: number } => { const pageSize = _pageSize.value; const { scrollValue } = state; if (!pageSize) { return { list: [], startPageIndex: 0, startIndex: 0 }; } if (props.disabled) { return { list: nodes.value, startIndex: 0, startPageIndex: 0, }; } const { startIndex, endIndex, pageIndex } = utils.getPageIndex(scrollValue); return { list: nodes.value.slice(startIndex, endIndex), startPageIndex: pageIndex, startIndex, }; }); /*---------------------------------------style-------------------------------------------*/ /** * 跟节点Scroll的class * @author 韦胜健 * @date 2020/12/16 10:48 */ const classes = useClasses(() => [ getComponentCls('virtual-list'), { 'virtual-list-disabled': props.disabled, 'virtual-list-horizontal': props.horizontal, }, ]); /** * 占位节点strut的样式 * @author 韦胜健 * @date 2020/12/16 10:48 */ const strutStyles = useStyles(style => { if (!_pageSize.value) { return; } if (props.disabled) { return; } if (!props.horizontal) { /*纵向*/ if (!!props.width) { style.width = unit(props.width); style.minWidth = '100%'; } if (!props.dynamicSize) { style.height = `${(dataModel.value || []).length * props.size}px`; } else { style.height = !nodes.value.length ? 0 : `${nodes.value[nodes.value.length - 1].end}px`; } } else { /*横向*/ if (!!props.height) { style.height = unit(props.height); style.minHeight = '100%'; } if (!props.dynamicSize) { style.width = `${(dataModel.value || []).length * props.size}px`; } else { style.width = !nodes.value.length ? 0 : `${nodes.value[nodes.value.length - 1].end}px`; } } }); /** * 内容(位移)节点的样式 * @author 韦胜健 * @date 2020/12/16 10:48 */ const contentStyles = useStyles(style => { if (!_pageSize.value) { return; } if (props.disabled) { return; } const { startIndex } = offsetData.value; let start; if (!props.dynamicSize) { start = startIndex * props.size; } else { start = nodes.value[startIndex]?.start ?? 0; } if (!props.horizontal) { /*纵向定位*/ if (transform !== false) { /*transform定位*/ style.transform = `translateY(${start}px)`; } else { /*top定位*/ style.top = `${start}px`; } } else { /*横向定位*/ if (transform !== false) { /*transform定位*/ style.transform = `translateX(${start}px)`; } else { /*top定位*/ style.left = `${start}px`; } } }); /*---------------------------------------utils-------------------------------------------*/ const utils = { /** * 根据top值,对比DataNodes中节点的top以及bottom得到在data nodes中的位置索引 * @author 韦胜健 * @date 2020/11/15 9:29 */ getIndex: (scrollValue: number) => { if (!props.dynamicSize) { // console.log('not dynamic》》》getIndex', top / props.size) return Math.floor(scrollValue / props.size); } else { const _nodes = nodes.value; let start = 0; let end = _nodes.length - 1; let temp = 0; while (start <= end) { let middle = Math.floor((start + end) / 2); let middleBottom = _nodes[middle].end; if (middleBottom === scrollValue) { return middle + 1; } else if (middleBottom < scrollValue) { start = middle + 1; } else if (middleBottom > scrollValue) { if (!temp || temp > middle) { temp = middle; } end = middle - 1; } } // console.log('is dynamic》》》getIndex', temp) return temp; } }, /** * 根据scrollTop以及pageSize获取当前的pageIndex * @author 韦胜健 * @date 2020/12/14 22:44 */ getPageIndex: (scrollValue: number) => { if (scrollValue < 0) { scrollValue = 0; } const pageSize = _pageSize.value; const data = dataModel.value || []; if (pageSize == null) { return { data, startIndex: 0, endIndex: 0, pageIndex: 0, }; } /*当前scrollTop对应的数据中数据的索引*/ let scrollIndex = utils.getIndex(scrollValue); let pageIndex = Math.floor(scrollIndex / pageSize); let startIndex = (() => { if (state.scrollDirection === 'none') { return scrollIndex - Math.floor(pageSize * 0.5); } else if (state.scrollDirection === ScrollDirection.start) { /*这里多减去2,避免出现空白的间隙*/ return scrollIndex - (pageSize - 2); } else { return scrollIndex; } })(); let endIndex = startIndex + pageSize * 2; startIndex -= 1; endIndex += 1; if (startIndex < 0) { endIndex -= startIndex; startIndex = 0; } /*console.log({ scrollIndex, pageIndex, start, end, pageSize, scrollDirection: state.scrollDirection });*/ const exceed = endIndex - data.length; if (exceed > 0) { endIndex = data.length; startIndex -= exceed; if (startIndex < 0) { startIndex = 0; } } pageIndex = Math.floor(startIndex / pageSize); return { data, startIndex, endIndex, pageIndex, }; }, resetHostSize: () => { const hostEl = refs.scroll?.refs.host; if (!hostEl) {return;} let hostSize = hostEl[props.horizontal ? 'offsetWidth' : 'offsetHeight']; const headEl = hostEl.querySelector('[data-virtual-head]') as undefined | HTMLDivElement; const footEl = hostEl.querySelector('[data-virtual-foot]') as undefined | HTMLDivElement; if (!!headEl) {hostSize -= headEl[props.horizontal ? 'offsetWidth' : 'offsetHeight'];} if (!!footEl) {hostSize -= footEl[props.horizontal ? 'offsetWidth' : 'offsetHeight'];} if (state.hostSize != hostSize) {state.hostSize = hostSize;} }, }; /*---------------------------------------handler-------------------------------------------*/ const handler = { onScroll: (e: Event) => { emit.onScroll(e); if (props.disabled) { return; } const newScrollValue = (e.target as HTMLDivElement)[props.horizontal ? 'scrollLeft' : 'scrollTop']; state.scrollDirection = newScrollValue > freezeState.scrollValue ? ScrollDirection.end : ScrollDirection.start; freezeState.scrollValue = newScrollValue; const current = utils.getPageIndex((e.target as HTMLDivElement).scrollTop); state.scrollValue = (e.target as HTMLDivElement)[props.horizontal ? 'scrollLeft' : 'scrollTop']; freezeState.current = current; emit.onPageIndexChange(current); } }; watch(() => dataModel.value || [], (data: any[]) => { delay().then(() => { utils.resetHostSize(); }); if (props.disabled) { return; } if (!props.dynamicSize) { return; } // !!refs.scroll && refs.scroll.methods.scrollTop(0, 0); }); onMounted(async () => { await delay(23); utils.resetHostSize(); }); onBeforeUnmount( addWindowListener('resize', () => delay(23).then(utils.resetHostSize)) ); onUpdated(async () => { if (props.disabled) { return; } if (!props.dynamicSize) { return; } await delay(); // console.log('dynamic scan height') const elNodes = (refs.content?.querySelectorAll('[data-vid],[vid]') || []) as HTMLElement[]; for (let i = 0; i < elNodes.length; i++) { const el = elNodes[i]; const size = el[props.horizontal ? 'offsetWidth' : 'offsetHeight']; let vid = el.getAttribute('vid') || el.getAttribute('data-vid') as null | number | string; if (vid == null) { throw new Error('Each item of the virtual-list must have an attribute named "vid", please set :vid="index" or :data-vid="index"'); } if (state.id2size[vid] != size) { state.id2size[vid] = size; } } }); return { virtual: { offsetData, classes, strutStyles, contentStyles, handler, freezeState, state, nodes, } }; } export type iVirtualList = ReturnType['virtual'] export interface iVirtualNode { id: string, item: T, size: number, start: number, end: number, index: number }