diff --git a/docs/backlog.md b/docs/backlog.md index 290a457..dbf1b19 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -22,18 +22,6 @@ re-render change touches that path. ## Bugs -### The section list may not center the active section when it opens - -[FastScrollSectionFullList.tsx:103-125](../src/FastScrollSectionDots/FastScrollSectionFullList.tsx#L103-L125): -`show()` only scrolls when `flatListRef.current` is set, but the list renders -`null` while hidden. On the first `show()` the list is not mounted yet, so -neither the `scrollToIndex` nor the 1 s retry runs. During a drag the next calls -fix it; a quick tap on the dots may leave the list at its top. Not confirmed on -a device yet. - -Possible fix: scroll once the list has mounted (for example `initialScrollIndex` -or an effect on the active section), instead of in `show()`. - ### Sections built from `stickyHeaderIndices` all read "1" [utils.ts:232](../src/utils.ts#L232): `createFullSectionData` gives each section diff --git a/src/FastScrollSectionDots/FastScrollSectionFullList.tsx b/src/FastScrollSectionDots/FastScrollSectionFullList.tsx index 6852963..ae527d9 100644 --- a/src/FastScrollSectionDots/FastScrollSectionFullList.tsx +++ b/src/FastScrollSectionDots/FastScrollSectionFullList.tsx @@ -10,6 +10,7 @@ import React, { import { ColorValue, FlatList, + LayoutChangeEvent, ListRenderItemInfo, StyleSheet, } from 'react-native'; @@ -128,49 +129,111 @@ const FastScrollSectionFullList = React.forwardRef( [] ); - // Read when the list lays out, which can be before the state update that - // set the active section has rendered. - const activeSectionRef = useRef(null); + /** Centers the row of `section` in the list, when the list is on screen. */ + const centerSection = useCallback( + (section: SectionFullData, animated?: boolean) => { + flatListRef.current?.scrollToIndex({ + index: section.sectionIndex, + viewPosition: 0.5, + animated, + }); + }, + [] + ); - /** - * Centers the active section's row, then again a second later: rows the - * list had not measured yet cannot be scrolled to on the first attempt. - */ - const centerActiveSection = useCallback(() => { - const section = activeSectionRef.current; - if (!flatListRef.current || !section) { + // The section to center waits here until its row is laid out. The list + // renders nothing while closed, so the touch that opens it has no list to + // scroll yet; then it renders its first rows and the rest a batch at a + // time, each batch growing its content, so a row far down is laid out + // only later. + const sectionToCenter = useRef(null); + // Why the last attempt did not center its row: the row was not laid out + // yet ('estimated': it jumped near it from the rows that were), or no row + // was ('unmeasured': there was nothing to estimate from). + const centerMiss = useRef<'estimated' | 'unmeasured' | null>(null); + + // The list can report its content size before it lays its rows out, and + // laying them out need not change that size again, so a section that + // found no row to estimate from is tried again shortly, until the retry a + // second after show() takes over. + const centerRetryTimeout = useRef(null); + const cancelCenterRetry = useCallback(() => { + if (centerRetryTimeout.current) { + clearTimeout(centerRetryTimeout.current); + centerRetryTimeout.current = null; + } + }, []); + + // Without an animation: on Android, an animated scroll started while the + // list is still laying out its rows does not move it. + const centerPendingSection = useCallback(() => { + cancelCenterRetry(); + if (!sectionToCenter.current || !flatListRef.current) { return; } - flatListRef.current.scrollToIndex({ - index: section.sectionIndex, - viewPosition: 0.5, - }); - if (rescrollTimeout.current) { - clearTimeout(rescrollTimeout.current); - rescrollTimeout.current = null; + centerMiss.current = null; + centerSection(sectionToCenter.current, false); + if (!centerMiss.current) { + sectionToCenter.current = null; + } else if (centerMiss.current === 'unmeasured') { + centerRetryTimeout.current = setTimeout(centerPendingSection, 50); } - rescrollTimeout.current = setTimeout(() => { - if (flatListRef.current) { - flatListRef.current.scrollToIndex({ - index: section.sectionIndex, - viewPosition: 0.5, - }); - } - }, 1000); + }, [cancelCenterRetry, centerSection]); + + // A screen can close before a retry runs. + useEffect(() => cancelCenterRetry, [cancelCenterRetry]); + + const listHeight = useRef(0); + const onLayout = useCallback((event: LayoutChangeEvent) => { + listHeight.current = event.nativeEvent.layout.height; }, []); + // Called when the row is not laid out yet. Once some rows are, jump to + // where it should be from their average height: that renders the rows + // around it, and the next content size change centers it exactly. + const onScrollToIndexFailed = useCallback( + ({ + index, + averageItemLength, + }: { + index: number; + averageItemLength: number; + }) => { + if (averageItemLength === 0) { + centerMiss.current = 'unmeasured'; + return; + } + centerMiss.current = 'estimated'; + flatListRef.current?.scrollToOffset({ + offset: Math.max( + 0, + averageItemLength * (index + 0.5) - listHeight.current / 2 + ), + animated: false, + }); + }, + [] + ); + React.useImperativeHandle( forwardedRef, (): FastScrollSectionFullListHandle => ({ show(section: SectionFullData) { setActiveIndexVisible(true); setActiveSection(section); - activeSectionRef.current = section; startShowActiveIndexVisibleTimer(); - // When show() opens the list, it is not mounted yet: it centers the - // section once it lays out (onLayout below). The dots only call - // show() again when the finger reaches another dot. - centerActiveSection(); + sectionToCenter.current = section; + centerPendingSection(); + // Again a second later, in case the list has not centered it by then. + if (rescrollTimeout.current) { + clearTimeout(rescrollTimeout.current); + rescrollTimeout.current = null; + } + rescrollTimeout.current = setTimeout(() => { + rescrollTimeout.current = null; + cancelCenterRetry(); + centerSection(section); + }, 1000); }, hold(isHeld: boolean) { held.current = isHeld; @@ -209,10 +272,9 @@ const FastScrollSectionFullList = React.forwardRef( ref={setFlatListRef} style={styles.list} contentContainerStyle={styles.listContainer} - onLayout={centerActiveSection} - onScrollToIndexFailed={() => { - // just ignore to avoid errors/crashes - }} + onLayout={onLayout} + onScrollToIndexFailed={onScrollToIndexFailed} + onContentSizeChange={centerPendingSection} onScroll={() => { startShowActiveIndexVisibleTimer(); }} diff --git a/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx b/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx index 9de5914..2970fa2 100644 --- a/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx +++ b/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx @@ -761,19 +761,90 @@ describe('FastScrollSectionDots', () => { expect(isAnythingShown()).toBe(false); }); - // The touch opens the list, so it is not there yet to scroll when the touch - // reports its section, and the finger only reports again on another dot. - it('centers the section a touch opens the section list on, while the finger stays on its dot', () => { + // The section list renders nothing while closed, so the touch that opens it + // finds no list to scroll: it has to center once its rows are laid out. + it('centers the section under the finger when a touch opens the section list', () => { renderDots({ hideFastScrollIndicatorTimeout: 0 }); - const finger = touchDown(FINGER_ON.dairy); + + touchDown(FINGER_ON.dairy); layoutSectionList({ visibleHeight: 40, rowHeight: 30 }); - const scrollTo: jest.Mock = getSectionListScrollView().instance.scrollTo; + const scrollView = getSectionListScrollView(); + const scrollTo: jest.Mock = scrollView.instance.scrollTo; + expect(scrollTo).not.toHaveBeenCalled(); + // The list reports the size of its rows once they are laid out. + fireEvent(scrollView, 'contentSizeChange', 100, 90); - finger.moveTo(FINGER_ON.dairy + 2); + // Dairy's row spans 60..90; centered in a 40px list, the list shows 55..95. + expect(scrollTo.mock.calls).toEqual([[{ y: 55, animated: false }]]); + + // The retry covers rows that were not measured yet on the first attempt. act(() => jest.advanceTimersByTime(1000)); + expect(scrollTo.mock.calls).toEqual([ + [{ y: 55, animated: false }], + [{ y: 55 }], + ]); + }); + + // The list can report its content size before it lays its rows out, and + // laying them out need not change that size again. + it('centers the section under the finger when the section list lays its rows out after reporting its size', () => { + renderDots({ hideFastScrollIndicatorTimeout: 0 }); + + touchDown(FINGER_ON.dairy); + const scrollView = getSectionListScrollView(); + const scrollTo: jest.Mock = scrollView.instance.scrollTo; + fireEvent(scrollView, 'contentSizeChange', 100, 90); + layoutSectionList({ visibleHeight: 40, rowHeight: 30 }); + expect(scrollTo).not.toHaveBeenCalled(); // Dairy's row spans 60..90; centered in a 40px list, the list shows 55..95. - expect(scrollTo.mock.calls).toEqual([[{ y: 55 }]]); + act(() => jest.advanceTimersByTime(50)); + expect(scrollTo.mock.calls).toEqual([[{ y: 55, animated: false }]]); + }); + + // A list renders its first rows at once and the rest a batch at a time, so a + // section far down has no laid out row to center yet when the list opens. + it('jumps near a section whose row is not laid out yet when a touch opens the section list, then centers it', () => { + renderDots({ + hideFastScrollIndicatorTimeout: 0, + sections: Array.from({ length: 30 }, (_, i) => ({ + index: i * 10, + text: `Aisle ${i}`, + })), + }); + + // Aisle 25's dot starts at 12 * 26 + 10 * 25 = 562. + touchDown(565); + const scrollView = getSectionListScrollView(); + const layout = (y: number, height: number) => ({ + nativeEvent: { layout: { x: 0, y, width: 100, height } }, + }); + fireEvent(scrollView, 'layout', layout(0, 100)); + // The first 10 rows are 30px tall, the others 40px. + const rowTop = (i: number) => (i < 10 ? i * 30 : 300 + (i - 10) * 40); + /** The list renders a batch of 10 rows, and they are laid out. */ + const layoutBatch = (first: number) => { + act(() => jest.advanceTimersByTime(100)); + Array.from({ length: 10 }, (_, i) => first + i).forEach((i) => + fireEvent( + screen.getByText(`Aisle ${i}`), + 'layout', + layout(rowTop(i), rowTop(i + 1) - rowTop(i)) + ) + ); + fireEvent(scrollView, 'contentSizeChange', 100, rowTop(first + 10)); + }; + const scrollTo: jest.Mock = scrollView.instance.scrollTo; + + layoutBatch(0); + // Rows average 30px so far, so Aisle 25's row should be about 750..780; + // centered in a 100px list, the list shows about 715..815. + expect(scrollTo.mock.calls).toEqual([[{ y: 715, animated: false }]]); + + layoutBatch(10); + layoutBatch(20); + // Aisle 25's row is laid out at 900..940: centered, the list shows 870..970. + expect(scrollTo).toHaveBeenLastCalledWith({ y: 870, animated: false }); }); it('scrolls the open section list to center the section under the finger, and again a second later', () => { @@ -787,12 +858,15 @@ describe('FastScrollSectionDots', () => { touchDown(FINGER_ON.dairy); // Dairy's row spans 60..90; centered in a 40px list, the list shows 55..95. - expect(scrollTo.mock.calls).toEqual([[{ y: 55 }]]); + expect(scrollTo.mock.calls).toEqual([[{ y: 55, animated: false }]]); // The retry covers rows that were not measured yet on the first attempt. act(() => jest.advanceTimersByTime(999)); expect(scrollTo).toHaveBeenCalledTimes(1); act(() => jest.advanceTimersByTime(1)); - expect(scrollTo.mock.calls).toEqual([[{ y: 55 }], [{ y: 55 }]]); + expect(scrollTo.mock.calls).toEqual([ + [{ y: 55, animated: false }], + [{ y: 55 }], + ]); }); });