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
13 changes: 9 additions & 4 deletions __tests__/src/components/Toast.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
Toast as ToastType,
ToastType as ToastingType,
resolveValue,
DismissReason,
} from '../../../src/core/types';
import { toast as toasting } from '../../../src/headless';
import { View, Text } from 'react-native';
Expand Down Expand Up @@ -92,10 +93,14 @@ describe('<Toast />', () => {
toast={{ ...defaultProps.toast, visible: false }}
/>
);
expect(onToastHide).toHaveBeenCalledWith({
...defaultProps.toast,
visible: false,
});
expect(onToastHide).toHaveBeenCalledTimes(1);
expect(onToastHide).toHaveBeenCalledWith(
{
...defaultProps.toast,
visible: false,
},
DismissReason.PROGRAMMATIC
);
});

it('handles press events', () => {
Expand Down
9 changes: 7 additions & 2 deletions __tests__/src/core/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ import {
reducer,
useStore,
} from '../../../src/core/store';
import { renderHook, act } from '@testing-library/react-native';
import { ToastPosition, ToastType } from '../../../src/core/types';
import { act, renderHook } from '@testing-library/react-native';
import {
DismissReason,
ToastPosition,
ToastType,
} from '../../../src/core/types';

describe('Toast Store', () => {
const initialState = { toasts: [], pausedAt: undefined };
Expand Down Expand Up @@ -76,6 +80,7 @@ describe('Toast Store', () => {
const updatedState = reducer(stateWithToast, {
type: ActionType.DISMISS_TOAST,
toastId: '1',
reason: DismissReason.TIMEOUT,
});

expect(updatedState.toasts[0]?.visible).toBe(false);
Expand Down
36 changes: 34 additions & 2 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,38 @@ export default function App() {
</Text>
</Pressable>

<Pressable
style={{ marginTop: 16 }}
onPress={() => {
toast(Math.floor(Math.random() * 1000).toString(), {
position,
duration,
height,
width,
providerKey: 'PERSISTS',
onPress: (toast) => {
console.log('Toast pressed: ', toast);
},
onShow: (toast) => {
console.log('Toast shown: ', toast);
},
onHide: (toast, reason) => {
console.log('Toast hidden: ', toast, reason);
},
});
}}
>
<Text
style={{
fontSize: 16,
fontWeight: 'bold',
color: isDarkMode ? colors.textDark : colors.textLight,
}}
>
Toast With Handlers
</Text>
</Pressable>

<Pressable
style={{ marginTop: 16 }}
onPress={() => {
Expand Down Expand Up @@ -294,8 +326,8 @@ export default function App() {
onToastShow={(t) => {
console.log('SHOW: ', t);
}}
onToastHide={(t) => {
console.log('HIDE: ', t);
onToastHide={(t, reason) => {
console.log('HIDE: ', t, reason);
}}
onToastPress={(t) => {
console.log('PRESS: ', t);
Expand Down
33 changes: 24 additions & 9 deletions src/components/Toast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
GestureDetector,
} from 'react-native-gesture-handler';

import type { ExtraInsets, Toast as ToastType } from '../core/types';
import { DismissReason, ExtraInsets, Toast as ToastType } from '../core/types';
import { resolveValue, Toast as T, ToastPosition } from '../core/types';
import { colors, ConstructShadow, useVisibilityChange } from '../utils';
import { toast as toasting } from '../headless';
Expand All @@ -45,7 +45,7 @@ type Props = {
customRenderer?: (toast: ToastType) => React.ReactNode;
overrideDarkMode?: boolean;
onToastShow?: (toast: T) => void;
onToastHide?: (toast: T) => void;
onToastHide?: (toast: T, reason?: DismissReason) => void;
onToastPress?: (toast: T) => void;
extraInsets?: ExtraInsets;
keyboardVisible?: boolean;
Expand Down Expand Up @@ -136,10 +136,18 @@ export const Toast: FC<Props> = ({
const position = useSharedValue(startY);
const offsetY = useSharedValue(startY);

const onPress = () => onToastPress?.(toast);
const onPress = useCallback(() => {
if (toast.onPress) {
toast.onPress(toast);
}

if (onToastPress) {
onToastPress(toast);
}
}, [toast, onToastPress]);

const dismiss = useCallback((id: string) => {
toasting.dismiss(id);
const dismiss = useCallback((id: string, reason: DismissReason) => {
toasting.dismiss(id, reason);
}, []);

const getSwipeDirection = useCallback(() => {
Expand Down Expand Up @@ -240,7 +248,7 @@ export const Toast: FC<Props> = ({
offsetY.value = withTiming(startY, {
duration: toast?.animationConfig?.flingPositionReturnDuration ?? 40,
});
runOnJS(dismiss)(toast.id);
runOnJS(dismiss)(toast.id, DismissReason.SWIPE);
});

return toast.isSwipeable
Expand All @@ -260,12 +268,19 @@ export const Toast: FC<Props> = ({

useVisibilityChange(
() => {
if (toast.onShow) {
toast.onShow(toast);
}
onToastShow?.(toast);
},
() => {
onToastHide?.(toast);
(reason) => {
if (toast.onHide) {
toast.onHide(toast, reason || DismissReason.PROGRAMMATIC);
}
onToastHide?.(toast, reason || DismissReason.PROGRAMMATIC);
},
toast.visible
toast.visible,
toast.dismissReason
);

useEffect(() => {
Expand Down
3 changes: 2 additions & 1 deletion src/components/Toasts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
useSafeAreaFrame,
} from 'react-native-safe-area-context';
import {
DismissReason,
ExtraInsets,
ToastAnimationConfig,
ToastAnimationType,
Expand All @@ -25,7 +26,7 @@ type Props = {
overrideDarkMode?: boolean;
extraInsets?: ExtraInsets;
onToastShow?: (toast: T) => void;
onToastHide?: (toast: T) => void;
onToastHide?: (toast: T, reason?: DismissReason) => void;
onToastPress?: (toast: T) => void;
providerKey?: string;
preventScreenReaderFromHiding?: boolean;
Expand Down
14 changes: 9 additions & 5 deletions src/core/store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import type { DefaultToastOptions, Toast, ToastType } from './types';
import { DefaultToastOptions, DismissReason, Toast, ToastType } from './types';

const TOAST_LIMIT = 20;

Expand Down Expand Up @@ -29,10 +29,12 @@ export type Action =
| {
type: ActionType.DISMISS_TOAST;
toastId?: string;
reason: DismissReason;
}
| {
type: ActionType.REMOVE_TOAST;
toastId?: string;
reason?: DismissReason;
}
| {
type: ActionType.START_PAUSE;
Expand All @@ -50,7 +52,7 @@ interface State {

const toastTimeouts = new Map<Toast['id'], ReturnType<typeof setTimeout>>();

const addToRemoveQueue = (toastId: string) => {
const addToRemoveQueue = (toastId: string, reason: DismissReason) => {
if (toastTimeouts.has(toastId)) {
return;
}
Expand All @@ -60,6 +62,7 @@ const addToRemoveQueue = (toastId: string) => {
dispatch({
type: ActionType.REMOVE_TOAST,
toastId: toastId,
reason,
});
}, 1000);

Expand Down Expand Up @@ -101,14 +104,14 @@ export const reducer = (state: State, action: Action): State => {
: reducer(state, { type: ActionType.ADD_TOAST, toast });

case ActionType.DISMISS_TOAST:
const { toastId } = action;
const { toastId, reason } = action;

// ! Side effects ! - This could be execrated into a dismissToast() action, but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId);
addToRemoveQueue(toastId, reason);
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id);
addToRemoveQueue(toast.id, reason);
});
}

Expand All @@ -119,6 +122,7 @@ export const reducer = (state: State, action: Action): State => {
? {
...t,
visible: false,
dismissReason: reason,
}
: t
),
Expand Down
7 changes: 6 additions & 1 deletion src/core/toast.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
DefaultToastOptions,
DismissReason,
Element,
resolveValue,
Toast,
Expand Down Expand Up @@ -55,10 +56,14 @@ toast.error = createHandler('error');
toast.success = createHandler('success');
toast.loading = createHandler('loading');

toast.dismiss = (toastId?: string) => {
toast.dismiss = (
toastId?: string,
reason: DismissReason = DismissReason.PROGRAMMATIC
) => {
dispatch({
type: ActionType.DISMISS_TOAST,
toastId,
reason,
});
};

Expand Down
14 changes: 14 additions & 0 deletions src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ export enum ToastPosition {

export type Element = JSX.Element | string | null;

export enum DismissReason {
TIMEOUT = 'timeout',
SWIPE = 'swipe',
PROGRAMMATIC = 'programmatic',
TAP = 'tap',
}

export interface IconTheme {
primary: string;
secondary: string;
Expand Down Expand Up @@ -55,6 +62,10 @@ export interface Toast {
height?: number;
width?: number;
maxWidth?: number;
onPress?: (toast: Toast) => void;
onHide?: (toast: Toast, reason: DismissReason) => void;
onShow?: (toast: Toast) => void;
dismissReason?: DismissReason;
styles?: {
pressable?: ViewStyle;
view?: ViewStyle;
Expand Down Expand Up @@ -86,6 +97,9 @@ export type ToastOptions = Partial<
| 'animationConfig'
| 'animationType'
| 'maxWidth'
| 'onPress'
| 'onHide'
| 'onShow'
>
>;

Expand Down
14 changes: 11 additions & 3 deletions src/core/use-toaster.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { useEffect, useMemo } from 'react';
import { ActionType, dispatch, useStore } from './store';
import { toast } from './toast';
import type { DefaultToastOptions, Toast, ToastPosition } from './types';
import {
DefaultToastOptions,
DismissReason,
Toast,
ToastPosition,
} from './types';

export const useToaster = (toastOptions?: DefaultToastOptions) => {
const { toasts, pausedAt } = useStore(toastOptions);
Expand All @@ -22,11 +27,14 @@ export const useToaster = (toastOptions?: DefaultToastOptions) => {

if (durationLeft < 0) {
if (t.visible) {
toast.dismiss(t.id);
toast.dismiss(t.id, DismissReason.TIMEOUT);
}
return;
}
return setTimeout(() => toast.dismiss(t.id), durationLeft);
return setTimeout(
() => toast.dismiss(t.id, DismissReason.TIMEOUT),
durationLeft
);
});

return () => {
Expand Down
10 changes: 6 additions & 4 deletions src/utils/useVisibilityChange.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { useEffect, useState } from 'react';
import { DismissReason } from '../core/types';

export const useVisibilityChange = (
onShow: () => void,
onHide: () => void,
visible: boolean
onHide: (reason?: DismissReason) => void,
visible: boolean,
dismissReason?: DismissReason
) => {
const [mounted, setMounted] = useState(false);

Expand All @@ -15,9 +17,9 @@ export const useVisibilityChange = (

if (mounted && !visible) {
setMounted(false);
onHide();
onHide(dismissReason);
}
}, [visible, mounted, onShow, onHide]);
}, [visible, mounted, dismissReason, onShow, onHide]);

return undefined;
};
Loading