import './scroll.scss'; import {computed, createSyncHooks, designComponent, getComponentCls, onBeforeUnmount, onMounted, reactive, useClasses, useMounted, useRefs, useStyles, watch} from "@peryl/react-compose"; import {delay} from "@peryl/utils/delay"; import {debounce} from "@peryl/utils/debounce"; import {throttle} from "@peryl/utils/throttle"; import {VerticalScrollbar} from "./VerticalScrollbar"; import {HorizontalScrollbar} from "./HorizontalScrollbar"; import {ResizeDetectFuncParam, useResizeDetector} from "../../directives/ResizeDetector"; import {createScrollUtils} from "../createScrollUtils"; import {getRectAutoFormat} from "@peryl/utils/getRectAutoFormat"; export enum PLAIN_SCROLL_VERTICAL_POSITION { top = 'top', center = 'center', bottom = 'bottom' } export const Scroll = designComponent({ name: 'scroll', props: { refreshState: {}, // 监听改属性,以便自动执行refresh刷新 scrollbarSize: { type: Number }, // 滚动条大小 scrollbarColor: { type: String, default: 'rgba(144,147,153,.3)' }, // 滚动条颜色 scrollX: { type: Boolean }, // 可以横向滚动 scrollY: { type: Boolean, default: true }, // 可以纵向滚动 hideScrollbar: { type: Boolean }, // 隐藏滚动条 alwaysShowScrollbar: { type: Boolean, default: true }, // 一直显示滚动条 fitContentWidth: { type: Boolean }, // 适配内容宽度 fitContentHeight: { type: Boolean }, // 适配内容高度 fitHostWidth: { type: Boolean }, // 适配容器宽度 fitHostHeight: { type: Boolean }, // 适配容器高度 topThreshold: { type: Number, default: 20 }, // 距离顶部多少距离派发滚动到顶部事件 bottomThreshold: { type: Number, default: 20 }, // 距离底部多少距离派发滚动到底部事件 autoScrollSpeed: { type: Number, default: 400 }, // 自动滚动的时候的速度,每秒钟滚动的距离 scrollAfterDragEnd: { type: Boolean, }, // 是否拖拽结束后才刷新滚动位置 disableListTransition: { type: Boolean, }, // 是否股弄懂的时候禁用list的队列动画 disableTransitionWhenScroll: { type: Boolean }, // 是否在滚动的时候禁用内部所有元素的transition动画 horizontalScrollbarTooltip: { type: String }, // 横向滚动条tooltip显示文本 verticalScrollbarTooltip: { type: String }, // 纵向滚动条tooltip显示文本 mutationSubtree: { type: Boolean, default: true }, // 监听整个子树的节点变化 mutationChildList: { type: Boolean, default: true }, // 监听整个子树的节点新增与删除 mutationAttributes: { type: Boolean, default: false }, // 监听整个子树节点的属性变化 }, emits: { onScroll: (e: Event) => true, onVerticalScrollTop: (e: Event) => true, onVerticalScrollBottom: (e: Event) => true, onVerticalScrollCenter: (e: Event) => true, }, inheritPropsType: HTMLDivElement, slots: ['content', 'default', 'prevContent', 'nextContent'], provideRefer: true, setup({ props, event: { emit, on, off }, slots }) { const hooks = { onScroll: createSyncHooks<(top: Event) => void>() }; /*---------------------------------------ref-------------------------------------------*/ const { refs, onRef } = useRefs({ host: HTMLDivElement, wrapper: HTMLDivElement, content: HTMLDivElement, }); /*---------------------------------------state-------------------------------------------*/ const mounted = useMounted(); /*非响应式状态*/ const freezeState = { verticalPosition: PLAIN_SCROLL_VERTICAL_POSITION.top, // 当前滚动纵向位置,top,center,right wrapperScrollTop: 0, // 容器 scrollTop wrapperScrollLeft: 0, // 容器 scrollLeft emitScroll: true, // 当前是否派发scroll事件 _isDragging: false, get isDragging() { return this._isDragging; }, set isDragging(val: boolean) { this._isDragging = val; if (val) { refs.host?.setAttribute('is-dragging', ''); } else { refs.host?.removeAttribute('is-dragging'); } }, }; const state = reactive({ contentWidth: 0, // 内容宽度 contentHeight: 0, // 内容高度 hostWidth: 0, // 容器宽度 hostHeight: 0, // 容器高度 }); /*---------------------------------------computed-------------------------------------------*/ const targetScrollbarSize = computed(() => { if (!props.scrollX) { return props.scrollbarSize || 6; } else { return props.scrollbarSize || 9; } }); const classes = useClasses(() => [ getComponentCls('scroll'), { 'scroll-always-show-scroll-bar': props.alwaysShowScrollbar, } ]); const hostStyles = useStyles(style => { if (!mounted.value) return style; if (props.fitContentHeight) { style.height = `${state.contentHeight}px`; } return style; }); const wrapperStyles = useStyles(style => { if (!mounted.value) return style; if (props.fitContentHeight) { style.height = `${state.contentHeight + 17}px`; } return style; }); const contentStyles = useStyles(style => { if (!mounted.value) return style; if (!props.scrollX) { style.width = props.fitContentWidth && state.contentWidth > 0 ? `${state.contentWidth}px` : `100%`; style.overflowX = 'hidden'; } if (!props.scrollY) { style.height = props.fitContentHeight && state.contentHeight > 0 ? `${state.contentHeight}px` : `100%`; style.overflowY = 'hidden'; } if (props.fitHostHeight) { style.height = '100%'; } if (props.fitHostWidth) { style.width = '100%'; } if (props.fitContentWidth) { style.width = `${state.contentWidth}px`; } if (props.fitContentHeight) { style.height = `${state.contentHeight}px`; } return style; }); /*---------------------------------------methods-------------------------------------------*/ const scrollUtils = createScrollUtils({ getAutoScrollSpeed: () => props.autoScrollSpeed, getScrollElement: () => refs.wrapper, onStop: () => {freezeState.emitScroll = true;}, }); const methods = { refresh: async () => { await delay(); if (!refs.content!) {return;} const { scrollWidth: width1, scrollHeight: height1 } = refs.content!; handler.contentResize({ width: Math.ceil(width1), height: Math.ceil(height1), }); const { offsetWidth: width2, offsetHeight: height2 } = refs.wrapper!; handler.hostResize({ width: Math.ceil(width2), height: Math.ceil(height2), }); }, /** * 滚动到指定位置 * @author 韦胜健 * @date 2020/12/7 12:20 * @param point * @param point.x // 滚动scrollLeft值 * @param point.y // 滚动scrollTop值 * @param configOrTime // number|{ time?: number, noEmitScroll?: boolean } * @param configOrTime.time // 滚动的时间 * @param configOrTime.noEmitScroll //滚动期间不派发scroll事件 */ async scroll(point: { x?: number, y?: number }, configOrTime?: number | { time?: number, noEmitScroll?: boolean }) { const config = configOrTime == null ? {} : typeof configOrTime === "number" ? { time: configOrTime } : configOrTime; scrollUtils.scroll({ top: point.y, left: point.x, time: config.time, onBegin: () => { config.noEmitScroll && (freezeState.emitScroll = false); }, onFinish: () => { config.noEmitScroll && (freezeState.emitScroll = true); }, }); }, scrollTop(scrollTop: number, time?: number) {scrollUtils.scrollTop(scrollTop, time);}, scrollLeft(scrollLeft: number, time?: number) {scrollUtils.scrollLeft(scrollLeft, time);}, scrollEnd(point: { x: boolean, y?: boolean } = { x: true, y: true }) {scrollUtils.scrollEnd({ top: point.y, left: point.x });}, autoScrollTop() {scrollUtils.autoScrollTop();}, autoScrollBottom() {scrollUtils.autoScrollBottom();}, autoScrollLeft() {scrollUtils.autoScrollLeft();}, autoScrollRight() {scrollUtils.autoScrollRight();}, stopAutoScroll() {scrollUtils.stopAutoScroll();}, showElement: (elementSelector: string | HTMLElement): boolean => { if (!refs.host || !refs.content) {return false;} const selectElement = typeof elementSelector === "string" ? refs.content?.querySelector(elementSelector) : elementSelector; if (selectElement == null) {return false;} const selectElementRect = getRectAutoFormat(selectElement as any); const contentElementRect = getRectAutoFormat(refs.content); const hostElementRect = getRectAutoFormat(refs.host); /*vertical*/ if (selectElementRect.bottom >= hostElementRect.bottom) { /*在下面*/ const offsetTop = selectElementRect.top - contentElementRect.top; methods.scrollTop(offsetTop - (hostElementRect.height - selectElementRect.height)); } else if (selectElementRect.top <= hostElementRect.top) { /*在上面*/ const offsetTop = selectElementRect.top - contentElementRect.top; methods.scrollTop(offsetTop); } /*horizontal*/ if (selectElementRect.right >= hostElementRect.right) { /*在右边*/ const offsetLeft = selectElementRect.left - contentElementRect.left; methods.scrollLeft(offsetLeft - (hostElementRect.width - selectElementRect.width)); } else if (selectElementRect.left <= hostElementRect.left) { /*在左边*/ const offsetLeft = selectElementRect.left - contentElementRect.left; methods.scrollLeft(offsetLeft); } return true; }, /** * 禁用list的队列动画,300ms后恢复正常 * @author 韦胜健 * @date 2020/12/15 10:16 */ disableListTransition: (() => { const disabledQueueAnimation = debounce(() => refs.host?.removeAttribute('virtual-scrolling'), 300, true); return () => { refs.host?.setAttribute('virtual-scrolling', ''); disabledQueueAnimation(); }; })(), /** * 禁用内部所有过度动画,300ms后恢复正常 * @author 韦胜健 * @date 2022.10.28 21:34 */ disableInnerTransition: (() => { const disabledQueueAnimation = debounce(() => refs.host?.removeAttribute('disable-all-transition'), 300, true); return () => { refs.host?.setAttribute('disable-all-transition', ''); disabledQueueAnimation(); }; })() }; /*---------------------------------------handler-------------------------------------------*/ const handler = { windowResize: throttle(() => methods.refresh(), 500), popperOpen: () => methods.refresh(), popperShow: async () => { await delay(); methods.scroll({ y: 0 }); }, contentResize: (data: ResizeDetectFuncParam) => { if (data.width != null) state.contentWidth = data.width; if (data.height != null) state.contentHeight = data.height; }, hostResize: (data: ResizeDetectFuncParam) => { if (data.width != null) state.hostWidth = data.width - 16; if (data.height != null) state.hostHeight = data.height - 16; }, wrapperMousewheel: () => { scrollUtils.stopAutoScroll(); }, wrapperScroll: (e: any) => { const target = e.target as HTMLElement; freezeState.wrapperScrollTop = target.scrollTop; freezeState.wrapperScrollLeft = target.scrollLeft; hooks.onScroll.exec(e); if (freezeState.emitScroll) { emit.onScroll(e); } if (freezeState.verticalPosition === PLAIN_SCROLL_VERTICAL_POSITION.top && freezeState.wrapperScrollTop > props.topThreshold!) { /*进入center*/ emit.onVerticalScrollCenter(e); freezeState.verticalPosition = PLAIN_SCROLL_VERTICAL_POSITION.center; } else if (freezeState.verticalPosition === PLAIN_SCROLL_VERTICAL_POSITION.center) { // console.log(this.contentHeight - this.hostHeight - this.contentWrapperScrollTop, this.bottomScrollDuration) if (freezeState.wrapperScrollTop < props.topThreshold!) { /*进入top*/ emit.onVerticalScrollTop(e); freezeState.verticalPosition = PLAIN_SCROLL_VERTICAL_POSITION.top; } else if (state.contentHeight - state.hostHeight - freezeState.wrapperScrollTop < props.bottomThreshold!) { /*进入bottom*/ emit.onVerticalScrollBottom(e); freezeState.verticalPosition = PLAIN_SCROLL_VERTICAL_POSITION.bottom; } } else if (freezeState.verticalPosition === PLAIN_SCROLL_VERTICAL_POSITION.bottom) { if (state.contentHeight - state.hostHeight - freezeState.wrapperScrollTop > props.bottomThreshold!) { /*进入center*/ emit.onVerticalScrollCenter(e); freezeState.verticalPosition = PLAIN_SCROLL_VERTICAL_POSITION.center; } } if (props.disableListTransition) { methods.disableListTransition(); } if (props.disableTransitionWhenScroll) { methods.disableInnerTransition(); } }, }; /*---------------------------------------lifecycle-------------------------------------------*/ onMounted(() => { window.addEventListener('resize', handler.windowResize); /*if (!!popper) { popper.event.on.onOpen(handler.popperOpen) popper.event.on.onShow(handler.popperShow) }*/ }); onBeforeUnmount(() => { window.removeEventListener('resize', handler.windowResize); /*if (!!popper) { popper.event.off.onOpen(handler.popperOpen) popper.event.off.onShow(handler.popperShow) }*/ handler.windowResize.dispose(); }); watch(() => props.refreshState, methods.refresh); useResizeDetector({ elGetter: () => refs.host, onResize: handler.hostResize, mutateOption: { childList: props.mutationChildList, subtree: props.mutationSubtree, attributes: props.mutationAttributes } }); useResizeDetector({ elGetter: () => refs.content, onResize: handler.contentResize, mutateOption: { childList: props.mutationChildList, subtree: props.mutationSubtree, attributes: props.mutationAttributes }, }); return { refer: { props, on, off, targetScrollbarSize, refs, slots, handler, methods, state, freezeState, hooks, }, render: () => (