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
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ jobs:
- name: Typecheck files
run: yarn typecheck

- name: Typecheck example
run: yarn example exec tsc --noEmit

test:
runs-on: ubuntu-latest

Expand Down
3 changes: 2 additions & 1 deletion example/src/app/custom-refresh-control-2.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import Animated, {
useAnimatedStyle,
useFrameCallback,
useSharedValue,
type SharedValue,
} from 'react-native-reanimated';
import { RefreshShowcaseScreen } from '@/components/RefreshShowcaseScreen';

Expand Down Expand Up @@ -51,7 +52,7 @@ function CommandTile({
}: {
index: number;
label: string;
clock: Animated.SharedValue<number>;
clock: SharedValue<number>;
}) {
const refresh = useRefreshControl();

Expand Down
10 changes: 9 additions & 1 deletion example/src/app/refresh-control-edge-cases.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,13 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context';
*/
export default function Screen() {
const [refreshing, setRefreshing] = React.useState(false);
const [refreshCount, setRefreshCount] = React.useState(0);
const [enabled, setEnabled] = React.useState(true);
const [controlMounted, setControlMounted] = React.useState(true);
const [tab, setTab] = React.useState<'a' | 'b'>('a');

const onRefresh = React.useCallback(() => {
setRefreshCount((count) => count + 1);
setRefreshing(true);
setTimeout(() => setRefreshing(false), 2500);
}, []);
Expand Down Expand Up @@ -78,7 +80,7 @@ export default function Screen() {
];

return (
<HeaderMotion>
<HeaderMotion progressThreshold={0}>
<HeaderMotion.Bridge>
{(value) => (
<Stack.Screen
Expand All @@ -87,6 +89,7 @@ export default function Screen() {
<HeaderMotion.NavigationBridge value={value}>
<ReadoutHeader
enabled={enabled}
refreshCount={refreshCount}
controlMounted={controlMounted}
tab={tab}
/>
Expand Down Expand Up @@ -123,10 +126,12 @@ export default function Screen() {

function ReadoutHeader({
enabled,
refreshCount,
controlMounted,
tab,
}: {
enabled: boolean;
refreshCount: number;
controlMounted: boolean;
tab: 'a' | 'b';
}) {
Expand Down Expand Up @@ -190,6 +195,9 @@ function ReadoutHeader({
<Text style={styles.readout} testID="refresh-progress-readout">
progress: {progressLabel}
</Text>
<Text style={styles.readout} testID="refresh-count-readout">
refresh callbacks: {refreshCount}
</Text>
<Text style={styles.readout} testID="refresh-config-readout">
enabled: {String(enabled)} | control:{' '}
{controlMounted ? 'mounted' : 'unmounted'} | tab: {tab.toUpperCase()}
Expand Down
7 changes: 5 additions & 2 deletions example/src/components/PresetShowcaseScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export function PresetShowcaseScreen({
return (
<Collapsible preset={preset}>
<Collapsible.NavigationHeader
style={[styles.header, { paddingTop: insets.top }]}
style={[styles.header, withPinnedTitle && { paddingTop: insets.top }]}
render={(header) => <Stack.Screen options={{ header: () => header }} />}
>
{withPinnedTitle ? (
Expand All @@ -43,7 +43,10 @@ export function PresetShowcaseScreen({
</Collapsible.Pinned>
) : null}
<Collapsible.Dynamic
style={styles.dynamic}
style={[
styles.dynamic,
!withPinnedTitle && { paddingTop: insets.top + 12 },
]}
contentStyle={styles.dynamicContent}
>
{withPinnedTitle ? null : (
Expand Down
2 changes: 1 addition & 1 deletion example/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"extends": "../tsconfig",
"include": ["src/**/*"],
"include": ["src/**/*", "../src/types/**/*.d.ts"],
"exclude": [],
"compilerOptions": {
"baseUrl": ".",
Expand Down
15 changes: 10 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"types": "./lib/typescript/src/index.d.ts",
"exports": {
".": {
"source": "./src/index.tsx",
"source": "./src/index.ts",
"types": "./lib/typescript/src/index.d.ts",
"default": "./lib/module/index.js"
},
Expand All @@ -18,18 +18,21 @@
"android",
"ios",
"cpp",
"*.podspec",
"react-native.config.js",
"/react-native-header-motion.podspec",
"/react-native.config.js",
"!ios/build",
"!android/build",
"!android/gradle",
"!android/gradlew",
"!android/gradlew.bat",
"!android/local.properties",
"!**/__tests__",
"!**/*.test.*",
"!**/__fixtures__",
"!**/__mocks__",
"!**/.*"
"!**/.*",
"!/.claude/**",
"!/.tmp/**"
],
"scripts": {
"example": "yarn workspace react-native-header-motion-example",
Expand Down Expand Up @@ -146,7 +149,9 @@
],
"modulePathIgnorePatterns": [
"<rootDir>/example/node_modules",
"<rootDir>/lib/"
"<rootDir>/lib/",
"<rootDir>/.claude/",
"<rootDir>/.tmp/"
]
},
"commitlint": {
Expand Down
14 changes: 8 additions & 6 deletions src/collapsible/Collapsible.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { NavigationBridge } from '../components/NavigationBridge';
import { ScrollView } from '../components/ScrollView';
import { useMotionProgress } from '../hooks/useMotionProgress';
import type { HeaderDynamicProps } from '../types';
import { SCROLL_OFFSET_TOLERANCE } from '../utils/defaults';
import {
CollapsiblePresetsContext,
CollapsibleTabsContext,
Expand All @@ -46,9 +47,6 @@ type DistributiveOmit<T, K extends keyof any> = T extends any
? Omit<T, K>
: never;

const EXPANDED_EDGE = 0.001;
const COLLAPSED_EDGE = 0.999;

/** @experimental */
export interface CollapsibleProps<T extends string = string>
extends HeaderMotionProps<T> {
Expand All @@ -72,7 +70,7 @@ function CollapsibleStateObserver({
}: {
onStateChange: (state: CollapsibleHeaderState) => void;
}) {
const { progress } = useMotionProgress();
const { progress, progressThreshold } = useMotionProgress();
const callbackRef = useRef(onStateChange);
useEffect(() => {
callbackRef.current = onStateChange;
Expand All @@ -88,10 +86,14 @@ function CollapsibleStateObserver({
() => progress.get(),
(value) => {
const previous = lastState.get();
if (value >= COLLAPSED_EDGE && previous !== 'collapsed') {
const tolerance = Math.min(
0.5,
SCROLL_OFFSET_TOLERANCE / Math.max(1, progressThreshold.get())
);
if (value >= 1 - tolerance && previous !== 'collapsed') {
lastState.set('collapsed');
scheduleOnRN(emit, 'collapsed');
} else if (value <= EXPANDED_EDGE && previous !== 'expanded') {
} else if (value <= tolerance && previous !== 'expanded') {
lastState.set('expanded');
scheduleOnRN(emit, 'expanded');
}
Expand Down
64 changes: 64 additions & 0 deletions src/collapsible/__tests__/Collapsible.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,70 @@ describe('Collapsible', () => {
expect(element.props.children.props.children[0]).not.toBeNull();
});

it.each([40, 120, 1000])(
'reports terminal states within half a point at threshold %s',
(threshold) => {
const reanimated = require('react-native-reanimated');
const worklets = require('react-native-worklets');
let progress = (threshold - 0.6) / threshold;
let reactToProgress: () => void;
const reactionSpy: jest.SpyInstance = jest.spyOn(
reanimated,
'useAnimatedReaction'
);
reactionSpy.mockImplementation(
(prepare: () => number, react: (value: number) => void) => {
reactToProgress = () => react(prepare());
}
);
const scheduleSpy: jest.SpyInstance = jest.spyOn(
worklets,
'scheduleOnRN'
);
scheduleSpy.mockImplementation(
(callback: (...args: any[]) => void, ...args: any[]) =>
callback(...args)
);
mockUseMotionProgress.mockReturnValue({
progress: { get: () => progress },
progressThreshold: createSharedValue(threshold),
});
const onStateChange = jest.fn();
const root = Collapsible({
onStateChange,
children: null,
}) as React.ReactElement<any>;
const observer = root.props.children.props.children[0];

try {
observer.type(observer.props);
reactToProgress!();
expect(onStateChange).not.toHaveBeenCalled();

progress = (threshold - 0.4) / threshold;
reactToProgress!();
reactToProgress!();
expect(onStateChange.mock.calls).toEqual([['collapsed']]);

progress = 0.5;
reactToProgress!();
expect(onStateChange).toHaveBeenCalledTimes(1);

progress = 0.6 / threshold;
reactToProgress!();
expect(onStateChange).toHaveBeenCalledTimes(1);

progress = 0.4 / threshold;
reactToProgress!();
reactToProgress!();
expect(onStateChange.mock.calls).toEqual([['collapsed'], ['expanded']]);
} finally {
reactionSpy.mockRestore();
scheduleSpy.mockRestore();
}
}
);

it('Header slides up by the collapse distance', () => {
const userStyle = { backgroundColor: 'red' };
const element = Collapsible.Header({
Expand Down
16 changes: 16 additions & 0 deletions src/collapsible/__tests__/pagerAdapters.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,22 @@ describe('DefaultCollapsibleTabsPagerAdapter', () => {
expect(onIndexChange).toHaveBeenCalledWith(2);
});

it('scrolls the attached pager when the controller changes the page', () => {
const { element, controllerRef } = render();
const scrollTo = jest.fn();
element.props.ref({ scrollTo });

controllerRef.current!.setIndex(2);

expect(scrollTo).toHaveBeenCalledWith({
x: windowWidth * 2,
animated: true,
});
element.props.ref(null);
controllerRef.current!.setIndex(0);
expect(scrollTo).toHaveBeenCalledTimes(1);
});

it('exposes a controller that does not crash before the ref attaches', () => {
const { controllerRef } = render();

Expand Down
27 changes: 26 additions & 1 deletion src/collapsible/__tests__/useCollapsibleHeader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,32 @@ describe('useCollapsibleHeader', () => {
createContext({ scrollTo: null });

expect(() => useCollapsibleHeader().collapse()).not.toThrow();
expect(scheduleOnUISpy).not.toHaveBeenCalled();
expect(scheduleOnUISpy).toHaveBeenCalledTimes(1);
});

it('reads the scroll command on the UI runtime after scheduling', () => {
const { ctxValue } = createContext({ scrollTo: null });
const scrollTo = jest.fn();
scheduleOnUISpy.mockImplementationOnce((worklet: () => void) => {
ctxValue.scrollToRef.current = scrollTo;
worklet();
});

useCollapsibleHeader().collapse();

expect(scrollTo).toHaveBeenCalledWith(120, {
isValueDelta: false,
animated: true,
});
});

it.each([0, Infinity])('does not scroll with threshold %s', (threshold) => {
const { ctxValue, scrollTo } = createContext();
ctxValue.progressThreshold = createSharedValue(threshold);

useCollapsibleHeader().collapse();

expect(scrollTo).not.toHaveBeenCalled();
});

it('exposes the motion progress values', () => {
Expand Down
17 changes: 9 additions & 8 deletions src/collapsible/pagerAdapters.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
useImperativeHandle,
useRef,
useState,
type ComponentRef,
type ComponentType,
type ReactNode,
type Ref,
Expand Down Expand Up @@ -97,7 +96,9 @@ export function DefaultCollapsibleTabsPagerAdapter({
const { width: windowWidth } = useWindowDimensions();
const [pageWidth, setPageWidth] = useState(windowWidth);
const pageWidthRef = useRef(pageWidth);
const scrollRef = useRef<ComponentRef<typeof ScrollView>>(null);
const scrollRef = useRef<{
scrollTo: (options: { x: number; animated: boolean }) => void;
} | null>(null);

useEffect(() => {
pageWidthRef.current = pageWidth;
Expand Down Expand Up @@ -137,7 +138,9 @@ export function DefaultCollapsibleTabsPagerAdapter({

return (
<ScrollView
ref={scrollRef}
ref={(instance) => {
scrollRef.current = instance;
}}
horizontal
pagingEnabled
nestedScrollEnabled
Expand Down Expand Up @@ -165,11 +168,9 @@ export interface CollapsiblePagerViewLikeProps {
ref?: Ref<any>;
style?: StyleProp<ViewStyle>;
initialPage?: number;
onPageSelected?: (event: {
nativeEvent: {
position: number;
};
}) => void;
onPageSelected?: (
event: NativeSyntheticEvent<Readonly<{ position: number }>>
) => void;
children?: ReactNode;
}

Expand Down
Loading
Loading