Repository navigation
feat(h5): support ScrollView anchor offsets #19706
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| /** Scroll only the supplied container, applying an offset to the aligned target position. */ | ||
| export function scrollIntoViewWithOffset ( | ||
| container: HTMLElement, | ||
| target: HTMLElement, | ||
| options: { | ||
| offset: number | ||
| scrollX: boolean | ||
| scrollY: boolean | ||
| alignment?: ScrollLogicalPosition | ||
| behavior: ScrollBehavior | ||
| } | ||
| ) { | ||
| const { offset, scrollX, scrollY, alignment, behavior } = options | ||
| const outer = container.getBoundingClientRect() | ||
| const inner = target.getBoundingClientRect() | ||
| const scaleX = container.offsetWidth ? outer.width / container.offsetWidth : 1 | ||
| const scaleY = container.offsetHeight ? outer.height / container.offsetHeight : 1 | ||
|
|
||
| function delta (start: number, size: number, extent: number, align: ScrollLogicalPosition) { | ||
| if (align === 'center') return start - (extent - size) / 2 | ||
| if (align === 'end') return start - extent + size | ||
| if (align === 'nearest') { | ||
| if (start >= 0 && start + size <= extent) return 0 | ||
| if (start < 0 && start + size > extent) return 0 | ||
| return (start < 0 && size <= extent) || (start >= 0 && size > extent) ? start : start + size - extent | ||
| } | ||
| return start | ||
| } | ||
|
|
||
| const position: ScrollToOptions = { behavior } | ||
| if (scrollY) { | ||
| position.top = container.scrollTop + delta( | ||
| (inner.top - outer.top) / (scaleY || 1) - container.clientTop + offset, inner.height / (scaleY || 1), container.clientHeight, alignment || 'center' | ||
| ) | ||
| } | ||
| if (scrollX) { | ||
| position.left = container.scrollLeft + delta( | ||
| (inner.left - outer.left) / (scaleX || 1) - container.clientLeft + offset, inner.width / (scaleX || 1), container.clientWidth, alignment || 'start' | ||
| ) | ||
| } | ||
| // SelectorQuery can replace the instance method with the mini-program adapter. | ||
| const nativeScrollTo = container.ownerDocument.defaultView?.HTMLElement.prototype.scrollTo | ||
| if (nativeScrollTo) nativeScrollTo.call(container, position) | ||
| else container.scrollTo(position) | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| import { scrollIntoViewWithOffset } from '@tarojs/shared' | ||
| import { render } from '@testing-library/react' | ||
| import React from 'react' | ||
|
|
||
| import ScrollView from '../src/components/scroll-view' | ||
|
|
||
| describe('controlled anchor scrolling', () => { | ||
| let scrollTo: jest.Mock | ||
| const original = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollTo') | ||
| beforeEach(() => { | ||
| jest.useFakeTimers() | ||
| scrollTo = jest.fn() | ||
| Object.defineProperty(HTMLElement.prototype, 'scrollTo', { configurable: true, writable: true, value: scrollTo }) | ||
| jest.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function () { | ||
| return { top: this.id === 'anchor' ? 150 : 0, left: 0, width: 100, height: 20 } as DOMRect | ||
| }) | ||
| }) | ||
| afterEach(() => { | ||
| jest.restoreAllMocks() | ||
| jest.useRealTimers() | ||
| if (original) Object.defineProperty(HTMLElement.prototype, 'scrollTo', original) | ||
| else Reflect.deleteProperty(HTMLElement.prototype, 'scrollTo') | ||
| }) | ||
|
|
||
| it('allows controlled coordinates after an unchanged anchor', () => { | ||
| const content = <div id='anchor' /> | ||
| const { container, rerender } = render( | ||
| <ScrollView scrollY scrollWithAnimation={false} scrollIntoView='anchor' scrollIntoViewOffset={0} scrollIntoViewAlignment='start'>{content}</ScrollView> | ||
| ) | ||
| jest.advanceTimersByTime(500) | ||
| expect(scrollTo).toHaveBeenLastCalledWith({ top: 150, behavior: 'auto' }) | ||
| scrollTo.mockClear() | ||
| rerender(<ScrollView scrollY scrollWithAnimation={false} scrollIntoView='anchor' scrollIntoViewOffset={0} scrollIntoViewAlignment='start' scrollTop={400}>{content}</ScrollView>) | ||
| jest.advanceTimersByTime(10) | ||
| expect(scrollTo).not.toHaveBeenCalled() | ||
| expect(container.firstElementChild!.scrollTop).toBe(400) | ||
| }) | ||
|
|
||
| it('falls back to controlled coordinates for an absent scoped anchor', () => { | ||
| const { container } = render( | ||
| <ScrollView scrollY scrollTop={300} scrollWithAnimation={false} scrollIntoView='missing' scrollIntoViewOffset={0} /> | ||
| ) | ||
| jest.advanceTimersByTime(500) | ||
| expect(scrollTo).not.toHaveBeenCalled() | ||
| expect(container.firstElementChild!.scrollTop).toBe(300) | ||
| }) | ||
|
|
||
| it('converges nearest alignment in scaled containers and bypasses instance overrides', () => { | ||
| const container = document.createElement('div') | ||
| const target = document.createElement('div') | ||
| Object.defineProperties(container, { | ||
| offsetHeight: { value: 100 }, offsetWidth: { value: 100 }, clientHeight: { value: 100 }, | ||
| }) | ||
| container.getBoundingClientRect = () => ({ top: 0, left: 0, width: 200, height: 200 }) as DOMRect | ||
| target.getBoundingClientRect = () => ({ | ||
| top: (300 - container.scrollTop) * 2, left: 0, width: 40, height: 40, | ||
| }) as DOMRect | ||
| scrollTo.mockImplementation(function (options) { this.scrollTop = options.top }) | ||
| container.scrollTo = jest.fn(() => { throw new Error('adapter called') }) | ||
| const options = { offset: 20, scrollY: true, scrollX: false, alignment: 'nearest' as const, behavior: 'auto' as const } | ||
| scrollIntoViewWithOffset(container, target, options) | ||
| const position = container.scrollTop | ||
| scrollIntoViewWithOffset(container, target, options) | ||
| expect(position).toBe(240) | ||
| expect(container.scrollTop).toBe(position) | ||
| expect(container.scrollTo).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('cancels delayed initialization when the offset changes', () => { | ||
| const content = <div id='anchor' /> | ||
| const { rerender } = render(<ScrollView scrollY scrollIntoView='anchor' scrollIntoViewOffset={0} scrollIntoViewAlignment='start'>{content}</ScrollView>) | ||
| jest.advanceTimersByTime(100) | ||
| rerender(<ScrollView scrollY scrollIntoView='anchor' scrollIntoViewOffset={200} scrollIntoViewAlignment='start'>{content}</ScrollView>) | ||
| jest.advanceTimersByTime(500) | ||
| expect(scrollTo).toHaveBeenCalledTimes(1) | ||
| expect(scrollTo).toHaveBeenLastCalledWith({ top: 350, behavior: 'smooth' }) | ||
| }) | ||
| }) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| import './style/index.scss' | ||
|
|
||
| import { isFunction } from '@tarojs/shared' | ||
| import { isFunction, scrollIntoViewWithOffset } from '@tarojs/shared' | ||
| import classNames from 'classnames' | ||
|
|
||
| import { ScrollElementContext } from '../../contexts/ScrollElementContext' | ||
|
|
@@ -39,8 +39,23 @@ function scrollIntoView ( | |
| animated = true, | ||
| scrollX = false, | ||
| scrollY = false, | ||
| scrollIntoViewAlignment?: ScrollLogicalPosition | ||
| scrollIntoViewAlignment?: ScrollLogicalPosition, | ||
| container?: HTMLElement | null, | ||
| offset?: number | ||
| ) { | ||
| if (container && offset !== undefined) { | ||
| const target = Array.from(container.querySelectorAll<HTMLElement>('[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', | ||
|
|
@@ -79,6 +94,7 @@ interface IProps extends React.HTMLAttributes<HTMLDivElement> { | |
| scrollLeft: number | ||
| scrollIntoView?: string | ||
| scrollIntoViewAlignment?: ScrollLogicalPosition | ||
| scrollIntoViewOffset?: number | ||
| scrollWithAnimation: boolean | ||
| enableBackToTop?: boolean | ||
| forwardedRef?: React.MutableRefObject<HTMLDivElement> | ||
|
|
@@ -107,8 +123,7 @@ function ScrollView (props: IProps) { | |
| const scrollEndTimerRef = useRef<NodeJS.Timeout | null>(null) | ||
| const isScrollingRef = useRef<boolean>(false) | ||
| const isInitializedRef = useRef<boolean>(false) | ||
| /** 与 props.scrollIntoView 比对,同 id 时只走受控 scrollTop,避免与上次锚点反复互顶 */ | ||
| const lastAppliedScrollIntoViewIdRef = useRef<string | null>(null) | ||
| const lastAppliedAnchorRef = useRef<string | null>(null) | ||
| const [containerHeight, setContainerHeight] = useState(0) | ||
| const onTouchMove = (e) => { | ||
| if (props.stopTouchMovePropagation !== false) { | ||
|
|
@@ -129,80 +144,50 @@ function ScrollView (props: IProps) { | |
| } | ||
| } | ||
|
|
||
| const handleScroll = (props: IProps, isInit = false) => { | ||
| if ( | ||
| props.scrollIntoView && | ||
| typeof props.scrollIntoView === 'string' && | ||
| document && | ||
| document.querySelector && | ||
| document.querySelector(`#${props.scrollIntoView}`) | ||
| ) { | ||
| if (isInit) { | ||
| setTimeout( | ||
| () => | ||
| scrollIntoView( | ||
| props.scrollIntoView, | ||
| props.scrollWithAnimation, | ||
| !!props.scrollX, | ||
| !!props.scrollY, | ||
| props.scrollIntoViewAlignment | ||
| ), | ||
| 500 | ||
| ) | ||
| } else { | ||
| scrollIntoView( | ||
| props.scrollIntoView, | ||
| props.scrollWithAnimation, | ||
| !!props.scrollX, | ||
| !!props.scrollY, | ||
| props.scrollIntoViewAlignment | ||
| ) | ||
| } | ||
| } else { | ||
| applyControlledScrollTopLeft(props) | ||
| } | ||
| } | ||
|
|
||
| useEffect(() => { | ||
| handleScroll(props, true) | ||
| const root = container.current as HTMLElement | null | ||
| if (!root) return | ||
| const initial = !isInitializedRef.current | ||
| isInitializedRef.current = true | ||
| }, []) | ||
|
|
||
| // scrollTop / scrollLeft / scrollIntoView 受控同步(跳过 mount 时的 init effect) | ||
| useEffect(() => { | ||
| if (!isInitializedRef.current || !container.current) return | ||
|
|
||
| const sitv = props.scrollIntoView | ||
| const sitvOk = Boolean( | ||
| sitv && | ||
| typeof sitv === 'string' && | ||
| document && | ||
| document.querySelector && | ||
| document.querySelector(`#${sitv}`) | ||
| ) | ||
| const id = props.scrollIntoView | ||
| const target = typeof id === 'string' && id | ||
| ? (props.scrollIntoViewOffset !== undefined | ||
| ? Array.from(root.querySelectorAll<HTMLElement>('[id]')).find(node => node.id === id) | ||
| : document.querySelector(`#${id}`)) | ||
| : null | ||
| if (!target) { | ||
| lastAppliedAnchorRef.current = null | ||
| applyControlledScrollTopLeft(props) | ||
| return | ||
| } | ||
|
|
||
| if (sitvOk) { | ||
| if (sitv !== lastAppliedScrollIntoViewIdRef.current) { | ||
| scrollIntoView( | ||
| sitv, | ||
| props.scrollWithAnimation, | ||
| !!props.scrollX, | ||
| !!props.scrollY, | ||
| props.scrollIntoViewAlignment | ||
| ) | ||
| lastAppliedScrollIntoViewIdRef.current = typeof sitv === 'string' ? sitv : null | ||
| } else { | ||
| applyControlledScrollTopLeft(props) | ||
| } | ||
| } else { | ||
| lastAppliedScrollIntoViewIdRef.current = null | ||
| 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( | ||
|
Comment on lines
+173
to
+174
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 新锚点生效前,需使旧的受控滚动任务失效。 当 若在 10ms 内将 应用新锚点时,需取消所有尚未执行的受控定时回调和动画帧。取消方式(保存并清除定时器 ID、为动画返回可取消句柄,或使用代次计数)可由作者选择。没有后续锚点更新时,受控滚动仍应正常完成。
|
||
| 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 | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import { h } from '@stencil/core' | ||
| import { newSpecPage } from '@stencil/core/testing' | ||
|
|
||
| import { ScrollView } from '../src/components/scroll-view/scroll-view' | ||
|
|
||
| it('scrolls the stencil container with an offset', async () => { | ||
| const page = await newSpecPage({ | ||
| components: [ScrollView], | ||
| template: () => <taro-scroll-view-core scrollY mpScrollIntoViewOffset={-20} mpScrollIntoViewAlignment='start'> | ||
| <div id='anchor'>target</div> | ||
| </taro-scroll-view-core>, | ||
| }) | ||
| const root = page.root! | ||
| const target = root.querySelector<HTMLElement>('#anchor')! | ||
| root.getBoundingClientRect = () => ({ top: 10, left: 0 }) as DOMRect | ||
| target.getBoundingClientRect = () => ({ top: 160, left: 0, width: 20, height: 20 }) as DOMRect | ||
| Object.defineProperty(root, 'clientTop', { value: 0 }) | ||
| Object.defineProperty(root, 'clientHeight', { value: 100 }) | ||
| root.scrollTop = 0 | ||
| root.scrollTo = jest.fn() | ||
| await page.rootInstance.mpScrollIntoViewMethod('anchor') | ||
| expect(root.scrollTo).toHaveBeenCalledWith({ top: 130, behavior: 'auto' }) | ||
| }) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
在去重键中区分未提供偏移与非有限偏移。
数组中的
undefined和NaN都会被JSON.stringify编码为null。因此,offset从undefined变成NaN时,键不会变化。(tc39.es)如果初次文档级查询命中了另一个容器的同名锚点,更新后虽然能找到当前容器的目标,仍会进入去重分支。Line 50 的“非有限值按0处理”不会执行,当前容器不会定位。(raw.githubusercontent.com)
请在键中加入
offset !== undefined,再记录规范化后的偏移值。这样既能区分两个定位路径,也能保留重复参数去重。