Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 2 additions & 18 deletions docs/backlog.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,22 +49,6 @@ instead of reaching the top or the bottom. Clamp to 0..1 instead.
or an empty string would be better. Whatever changes, `createFullSectionData`
must keep spreading unknown fields of `stickyHeaderIndicesWithData` through.

### The dots' thumb goes back to the first dot each time the bar shows

[FastScrollSectionDots.tsx:230](../src/FastScrollSectionDots/FastScrollSectionDots.tsx#L230):
the bar is unmounted while hidden (`{visible && ...}`), so:

- `onViewableIndexChanged` is dropped while the bar is hidden, because
`fastScrollSectionDotsBarRef.current` is `null`
([line 149](../src/FastScrollSectionDots/FastScrollSectionDots.tsx#L149)).
- When the bar mounts again, `pointStylePositionY` starts at 0, so the thumb
sits on the first dot.

Apps show the bar from `onScroll` but usually debounce `onViewableIndexChanged`
until the list stops, so during a fling the thumb may point at the first section
the whole time. Not confirmed on a device yet. The fix is the one in "The dots
bar remounts every time it shows" below.

## Performance

None of these grows memory over time: they cost CPU and short-lived garbage.
Expand Down Expand Up @@ -139,8 +123,8 @@ per dot, and a `measure` call. Meanwhile `useHideFlatBar` springs
hide, but nothing reads it.

Possible fix: keep the bar mounted and slide it with `translateFastScrollBarX`
(or drop that shared value). This also fixes "The dots' thumb goes back to the
first dot each time the bar shows" above.
(or drop that shared value). The thumb no longer depends on it: the dots keep
the last active section and the bar starts on it when it mounts.

### Unstable props rebuild the gestures

Expand Down
1 change: 1 addition & 0 deletions example/src/ExamplesScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export const ExamplesScreen = () => {
{ title: 'StaleCallback', destination: 'StaleCallback' },
{ title: 'DotsLayout', destination: 'DotsLayout' },
{ title: 'MemoryLeak', destination: 'MemoryLeak' },
{ title: 'ReplaceSections', destination: 'ReplaceSections' },
];
return (
<>
Expand Down
2 changes: 2 additions & 0 deletions example/src/NavigationTree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import Performance from './performance/Performance';
import StaleCallback from './staleCallback/StaleCallback';
import DotsLayout from './dotsLayout/DotsLayout';
import MemoryLeak from './memoryLeak/MemoryLeak';
import ReplaceSections from './replaceSections/ReplaceSections';

const Stack = createStackNavigator<RootStackParamList>();

Expand All @@ -23,6 +24,7 @@ const NavigationTree = () => {
<Stack.Screen name="StaleCallback" component={StaleCallback} />
<Stack.Screen name="DotsLayout" component={DotsLayout} />
<Stack.Screen name="MemoryLeak" component={MemoryLeak} />
<Stack.Screen name="ReplaceSections" component={ReplaceSections} />
</Stack.Group>

<Stack.Group screenOptions={{ presentation: 'modal' }}>
Expand Down
19 changes: 13 additions & 6 deletions example/src/category/Categories.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback, useRef } from 'react';
import React, { useCallback, useEffect, useRef } from 'react';
import { CategoryItemData, data, Header, Product } from './data/categories';

import {
Expand Down Expand Up @@ -129,15 +129,22 @@ const Categories = () => {
});
}, []);

// Like the production app, report the first visible item to the dots only
// once the list has settled for 500 ms.
const viewableIndexDebounce = useRef<ReturnType<typeof setTimeout>>();
useEffect(() => () => clearTimeout(viewableIndexDebounce.current), []);
const onViewableItemsChanged = (info: {
viewableItems: ViewToken[];
changed: ViewToken[];
}) => {
if (info.viewableItems[0]?.index != null) {
fastScrollSectionDotsRef.current?.onViewableIndexChanged(
info.viewableItems[0].index
);
}
clearTimeout(viewableIndexDebounce.current);
viewableIndexDebounce.current = setTimeout(() => {
if (info.viewableItems[0]?.index != null) {
fastScrollSectionDotsRef.current?.onViewableIndexChanged(
info.viewableItems[0].index
);
}
}, 500);
};

const onScrollToIndex = (index: number) => {
Expand Down
192 changes: 192 additions & 0 deletions example/src/replaceSections/ReplaceSections.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import {
NativeScrollEvent,
NativeSyntheticEvent,
Pressable,
StyleSheet,
Text,
View,
} from 'react-native';
import { FlashList, ViewToken } from '@shopify/flash-list';
import { FastScrollSectionDots, Section } from 'react-native-fast-scroll';

/**
* The app replaces the dots' sections while the dots are hidden: a filter
* keeps only the first sections. When the dots show again, before the list
* reports its first visible item (debounced 500 ms, like production), the
* thumb must sit on one of the dots that are left.
*/

const SECTION_COUNT = 12;
const FILTERED_SECTION_COUNT = 4;
const ROWS_PER_SECTION = 10;
const HEADER_HEIGHT = 64;

type Row = { type: 'header' | 'row'; title: string };

const buildList = (sectionCount: number) => {
const data: Row[] = [];
const sections: Section[] = [];
for (let s = 1; s <= sectionCount; s++) {
sections.push({ index: data.length, text: `Section ${s}` });
data.push({ type: 'header', title: `Section ${s}` });
for (let r = 1; r <= ROWS_PER_SECTION; r++) {
data.push({ type: 'row', title: `Product ${s}.${r}` });
}
}
return { data, sections };
};

const ALL = buildList(SECTION_COUNT);
const FILTERED = buildList(FILTERED_SECTION_COUNT);

const ReplaceSections = () => {
const [filtered, setFiltered] = useState(false);
const { data, sections } = filtered ? FILTERED : ALL;

const flashListRef = useRef<FlashList<Row> | null>(null);
const dotsRef = useRef<React.ElementRef<typeof FastScrollSectionDots> | null>(
null
);

const onScroll = useCallback(
(_event: NativeSyntheticEvent<NativeScrollEvent>) => {
dotsRef.current?.onScrollToOffsetPercentage(0);
},
[]
);

// Like the production app, report the first visible item to the dots only
// once the list has settled for 500 ms.
const viewableIndexDebounce = useRef<ReturnType<typeof setTimeout>>();
useEffect(() => () => clearTimeout(viewableIndexDebounce.current), []);
const onViewableItemsChanged = useCallback(
(info: { viewableItems: ViewToken[] }) => {
clearTimeout(viewableIndexDebounce.current);
viewableIndexDebounce.current = setTimeout(() => {
const first = info.viewableItems[0]?.index;
if (first != null) {
dotsRef.current?.onViewableIndexChanged(first);
}
}, 500);
},
[]
);

const onScrollToIndex = useCallback((index: number) => {
flashListRef.current?.scrollToIndex({ index, animated: true });
}, []);

const contentContainerStyle = useMemo(
() => ({ paddingTop: HEADER_HEIGHT }),
[]
);

return (
<View style={styles.container}>
<FlashList
ref={flashListRef}
data={data}
estimatedItemSize={56}
overrideItemLayout={(layout, item) => {
layout.size = item.type === 'header' ? 40 : 56;
}}
getItemType={(item) => item.type}
contentContainerStyle={contentContainerStyle}
onScroll={onScroll}
onViewableItemsChanged={onViewableItemsChanged}
viewabilityConfig={{ itemVisiblePercentThreshold: 20 }}
renderItem={({ item }) =>
item.type === 'header' ? (
<View style={styles.sectionHeader}>
<Text style={styles.sectionHeaderText}>{item.title}</Text>
</View>
) : (
<View style={styles.row}>
<Text style={styles.rowText}>{item.title}</Text>
</View>
)
}
/>

<View style={styles.header}>
<Text style={styles.headerTitle}>
Sections: {sections.length} of {SECTION_COUNT}
</Text>
<Pressable
style={styles.button}
onPress={() => setFiltered((f) => !f)}
testID="toggle-filter"
>
<Text style={styles.buttonText}>
{filtered ? 'Show all' : `Only 1–${FILTERED_SECTION_COUNT}`}
</Text>
</Pressable>
</View>

<View style={styles.dots} pointerEvents={'box-none'}>
<FastScrollSectionDots
ref={dotsRef}
side={'left'}
hideFastScrollIndicatorTimeout={2000}
stickyHeaderIndicesWithData={sections}
onScrollToIndex={onScrollToIndex}
/>
</View>
</View>
);
};

const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: 'white' },
header: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: HEADER_HEIGHT,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingHorizontal: 12,
backgroundColor: '#1F3A5F',
},
headerTitle: { color: 'white', fontSize: 16, fontWeight: '700' },
button: {
backgroundColor: 'white',
borderRadius: 6,
paddingHorizontal: 10,
paddingVertical: 6,
},
buttonText: { color: '#1F3A5F', fontWeight: '700' },
sectionHeader: {
height: 40,
justifyContent: 'center',
paddingLeft: 60,
backgroundColor: 'darkred',
},
sectionHeaderText: { color: 'white', fontSize: 18, fontWeight: '700' },
row: {
height: 56,
justifyContent: 'center',
paddingLeft: 60,
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#DDD',
},
rowText: { fontSize: 16 },
dots: {
position: 'absolute',
top: HEADER_HEIGHT + 20,
bottom: 20,
left: 0,
right: 0,
},
});

export default ReplaceSections;
1 change: 1 addition & 0 deletions example/src/screens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ export type RootStackParamList = {
StaleCallback: undefined;
DotsLayout: undefined;
MemoryLeak: undefined;
ReplaceSections: undefined;
};
20 changes: 19 additions & 1 deletion src/FastScrollSectionDots/FastScrollSectionDots.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,15 @@ const FastScrollSectionDots = React.forwardRef(
});
}, [stickyHeaderIndices, stickyHeaderIndicesWithData]);

// The bar unmounts while hidden, and apps show it from onScroll but usually
// report the first visible item only once the list stops. The last section
// reported or dragged to is kept here so the thumb starts on it each time
// the bar mounts again. It holds a list index, not the section's ordinal,
// and is matched against the sections when the bar mounts: the app may
// replace the sections meanwhile, and an old ordinal could then point past
// the last dot.
const activeListIndexRef = useRef<number | undefined>(undefined);

React.useImperativeHandle(
forwardedRef,
(): FastScrollSectionDotsHandle => ({
Expand All @@ -145,8 +154,9 @@ const FastScrollSectionDots = React.forwardRef(
},

onViewableIndexChanged(index: number) {
activeListIndexRef.current = index;
const section = findNearestActiveSection(sections, index);
if (section && fastScrollSectionDotsBarRef.current) {
if (section) {
fastScrollSectionDotsBarRef.current?.onSectionChange(section);
}
},
Expand Down Expand Up @@ -205,6 +215,7 @@ const FastScrollSectionDots = React.forwardRef(
const onSectionChange = useCallback(
(section: SectionFullData) => {
debouncedScrollToIndexRef.current(section.index);
activeListIndexRef.current = section.index;

if (section) {
// locing the panel as we are opening the full list
Expand Down Expand Up @@ -235,6 +246,12 @@ const FastScrollSectionDots = React.forwardRef(
return null;
}

const initialSectionIndex =
activeListIndexRef.current === undefined
? undefined
: findNearestActiveSection(sections, activeListIndexRef.current)
?.sectionIndex;

return (
<View style={[styles.container]} pointerEvents={'box-none'}>
{visible && (
Expand All @@ -255,6 +272,7 @@ const FastScrollSectionDots = React.forwardRef(
onSectionChange={onSectionChange}
onFingerDown={holdSectionList}
onFingerUp={releaseSectionList}
initialSectionIndex={initialSectionIndex}
/>
</Animated.View>
)}
Expand Down
Loading
Loading