import './style/index.scss' import { isFunction, scrollIntoViewWithOffset } from '@tarojs/shared' import classNames from 'classnames' import { ScrollElementContext } from '../../contexts/ScrollElementContext' import { createForwardRefComponent, throttle } from '../../utils' import { useEffect, useRef, useState } from '../../utils/hooks' import type React from 'react' function easeOutScroll (from = 0, to = 0, callback) { if (from === to || typeof from !== 'number') { return } const change = to - from const dur = 500 const sTime = +new Date() function linear (t, b, c, d) { return (c * t) / d + b } const isLarger = to >= from function step () { from = linear(+new Date() - sTime, from, change, dur) if ((isLarger && from >= to) || (!isLarger && to >= from)) { callback(to) return } callback(from) requestAnimationFrame(step) } step() } /** 未开启的滚动轴使用 nearest 避免原生 scrollIntoView 沿该轴滚动整页 */ function scrollIntoView ( id = '', animated = true, scrollX = false, scrollY = false, scrollIntoViewAlignment?: ScrollLogicalPosition, container?: HTMLElement | null, offset?: number ) { if (container && offset !== undefined) { const target = Array.from(container.querySelectorAll('[id]')).find(node => node.id === id) if (target) { scrollIntoViewWithOffset(container, target, { offset: Number.isFinite(offset) ? offset : 0, scrollX, scrollY, alignment: scrollIntoViewAlignment, behavior: animated ? 'smooth' : 'auto', }) } return } document.querySelector(`#${id}`)?.scrollIntoView({ behavior: animated ? 'smooth' : 'auto', block: scrollY ? (scrollIntoViewAlignment || 'center') : 'nearest', inline: scrollX ? (scrollIntoViewAlignment || 'start') : 'nearest' }) } function scrollVertical (container, scrollTop, top, isAnimation) { if (isAnimation) { easeOutScroll(scrollTop.current, top, pos => { if (container.current) container.current.scrollTop = pos }) } else { if (container.current) container.current.scrollTop = top } scrollTop.current = top } function scrollHorizontal (container, scrollLeft, left, isAnimation) { if (isAnimation) { easeOutScroll(scrollLeft.current, left, pos => { if (container.current) container.current.scrollLeft = pos }) } else { if (container.current) container.current.scrollLeft = left } scrollLeft.current = left } interface IProps extends React.HTMLAttributes { scrollX: boolean scrollY: boolean upperThreshold: number lowerThreshold: number scrollTop: number scrollLeft: number scrollIntoView?: string scrollIntoViewAlignment?: ScrollLogicalPosition scrollIntoViewOffset?: number scrollWithAnimation: boolean enableBackToTop?: boolean forwardedRef?: React.MutableRefObject onScrollToUpper: (e: React.SyntheticEvent) => void onScrollToLower: (e: React.SyntheticEvent) => void onScroll: (e: React.SyntheticEvent) => void onScrollStart?: (e: React.SyntheticEvent) => void onScrollEnd?: (e: React.SyntheticEvent) => void onTouchMove: (e: React.SyntheticEvent) => void onTouchStart?: (e: React.SyntheticEvent) => void onTouchEnd?: (e: React.SyntheticEvent) => void stopTouchMovePropagation?: boolean showScrollbar?: boolean // 新增参数,默认true enhanced?: boolean // 新增参数,默认false /** 嵌套滚动:内容在滚动容器中的起始偏移(固定头部等场景) */ startOffset?: number } /** H5 等环境下 scrollTop 为整数,与带亚像素的受控值比较时允许该误差,避免反复 set scrollTop 与 scrollIntoView 打架 */ const CONTROLLED_SCROLL_EPSILON = 0.5 function ScrollView (props: IProps) { const _scrollTop = useRef(null) const _scrollLeft = useRef(null) const container = useRef(null) const scrollEndTimerRef = useRef(null) const isScrollingRef = useRef(false) const isInitializedRef = useRef(false) const lastAppliedAnchorRef = useRef(null) const [containerHeight, setContainerHeight] = useState(0) const onTouchMove = (e) => { if (props.stopTouchMovePropagation !== false) { e.stopPropagation() } } const applyControlledScrollTopLeft = (p: IProps) => { const isAnimation = !!p.scrollWithAnimation const eps = CONTROLLED_SCROLL_EPSILON if (p.scrollY && typeof p.scrollTop === 'number' && (_scrollTop.current === null || Math.abs(p.scrollTop - _scrollTop.current) >= eps)) { setTimeout(() => scrollVertical(container, _scrollTop, p.scrollTop, isAnimation), 10) } if (p.scrollX && typeof p.scrollLeft === 'number' && (_scrollLeft.current === null || Math.abs(p.scrollLeft - _scrollLeft.current) >= eps)) { setTimeout(() => scrollHorizontal(container, _scrollLeft, p.scrollLeft, isAnimation), 10) } } useEffect(() => { const root = container.current as HTMLElement | null if (!root) return const initial = !isInitializedRef.current isInitializedRef.current = true const id = props.scrollIntoView const target = typeof id === 'string' && id ? (props.scrollIntoViewOffset !== undefined ? Array.from(root.querySelectorAll('[id]')).find(node => node.id === id) : document.querySelector(`#${id}`)) : null if (!target) { lastAppliedAnchorRef.current = null applyControlledScrollTopLeft(props) return } const key = JSON.stringify([ id, props.scrollIntoViewOffset, props.scrollIntoViewAlignment, props.scrollWithAnimation, props.scrollX, props.scrollY, ]) if (lastAppliedAnchorRef.current === key) { applyControlledScrollTopLeft(props) return } const applyAnchor = () => { scrollIntoView( id, props.scrollWithAnimation, !!props.scrollX, !!props.scrollY, props.scrollIntoViewAlignment, root, props.scrollIntoViewOffset ) lastAppliedAnchorRef.current = key } if (initial) { const timer = setTimeout(applyAnchor, 500) return () => clearTimeout(timer) } applyAnchor() }, [ props.scrollTop, props.scrollLeft, props.scrollIntoView, props.scrollIntoViewAlignment, props.scrollIntoViewOffset, props.scrollWithAnimation, props.scrollX, props.scrollY ]) const { className, style = {}, onScroll, onScrollToUpper, onScrollToLower, scrollX, scrollY, showScrollbar = true, // 默认显示滚动条 enhanced = false // 默认不增强 } = props let { upperThreshold = 50, lowerThreshold = 50 } = props const cls = classNames( 'taro-scroll', { 'taro-scroll-view__scroll-x': scrollX, 'taro-scroll-view__scroll-y': scrollY, 'taro-scroll--hidebar': enhanced === true && showScrollbar === false, 'taro-scroll--enhanced': enhanced === true }, className ) upperThreshold = Number(upperThreshold) lowerThreshold = Number(lowerThreshold) const upperAndLower = e => { if (!container.current) return const { offsetWidth, offsetHeight, scrollLeft, scrollTop, scrollHeight, scrollWidth } = container.current if ( onScrollToLower && ((props.scrollY && offsetHeight + scrollTop + lowerThreshold >= scrollHeight) || (props.scrollX && offsetWidth + scrollLeft + lowerThreshold >= scrollWidth)) ) { onScrollToLower(e) } if ( onScrollToUpper && ((props.scrollY && scrollTop <= upperThreshold) || (props.scrollX && scrollLeft <= upperThreshold)) ) { onScrollToUpper(e) } } const upperAndLowerThrottle = throttle(upperAndLower, 200) const _onScroll = e => { const { scrollLeft, scrollTop, scrollHeight, scrollWidth } = container.current _scrollLeft.current = scrollLeft _scrollTop.current = scrollTop Object.defineProperty(e, 'detail', { enumerable: true, writable: true, value: { scrollLeft, scrollTop, scrollHeight, scrollWidth } }) // 处理滚动开始 if (!isScrollingRef.current) { isScrollingRef.current = true if (props.onScrollStart) { props.onScrollStart(e) } } // 清除滚动结束定时器 if (scrollEndTimerRef.current) { clearTimeout(scrollEndTimerRef.current) scrollEndTimerRef.current = null } // 设置滚动结束定时器(150ms 无滚动事件后触发) if (props.onScrollEnd) { scrollEndTimerRef.current = setTimeout(() => { if (isScrollingRef.current) { isScrollingRef.current = false props.onScrollEnd?.(e) } scrollEndTimerRef.current = null }, 150) } upperAndLowerThrottle(e) onScroll && onScroll(e) } const _onTouchMove = e => { isFunction(props.onTouchMove) ? props.onTouchMove(e) : onTouchMove(e) } const _onTouchStart = e => { if (isFunction(props.onTouchStart)) { props.onTouchStart(e) } } const _onTouchEnd = e => { if (isFunction(props.onTouchEnd)) { props.onTouchEnd(e) } } // 清理定时器 useEffect(() => { return () => { if (scrollEndTimerRef.current) { clearTimeout(scrollEndTimerRef.current) scrollEndTimerRef.current = null } } }, []) // ScrollElementContext:嵌套滚动时向子组件提供 scrollRef、containerHeight、startOffset useEffect(() => { const el = container.current if (!el) return const update = () => { if (container.current) { setContainerHeight(container.current.clientHeight) } } update() const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(update) : null if (ro) { ro.observe(el) return () => ro.disconnect() } }, []) const scrollElementContextValue = { scrollRef: container, containerHeight, startOffset: props.startOffset ?? 0, } return (
{ if (e) { container.current = e if (props.forwardedRef) props.forwardedRef.current = e } }} style={style} className={cls} onScroll={_onScroll} onTouchMove={_onTouchMove} onTouchStart={_onTouchStart} onTouchEnd={_onTouchEnd} > {props.children}
) } export default createForwardRefComponent(ScrollView)