Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

notificationNavigation.ts

50 lines1.8 KB

1import { useEffect, useLayoutEffect, useRef } from "react";
2import * as Notifications from "expo-notifications";
3import { useLinkTo } from "@react-navigation/native";
4​
5import { setAndroidThreadOnScreen } from "./androidNotifications";
6import { foregroundNotificationBehavior } from "./foregroundNotificationBehavior";
7import { routeAgentNotificationResponseOnce, threadDeepLinkOnScreen } from "./notificationPayload";
8import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
9​
10export function useAgentNotificationNavigation(pathname: string): void {
11 const linkTo = useLinkTo();
12 const handledResponseIds = useRef(new Set<string>());
13 const deepLinkOnScreen = useRef<string | null>(null);
14 useLayoutEffect(() => {
15 const thread = threadDeepLinkOnScreen(pathname);
16 deepLinkOnScreen.current = thread;
17 setAndroidThreadOnScreen(thread);
18 }, [pathname]);
19​
20 useEffect(() => {
21 Notifications.setNotificationHandler({
22 handleNotification: (notification) =>
23 Promise.resolve(foregroundNotificationBehavior(notification, deepLinkOnScreen.current)),
24 });
25 return () => {
26 Notifications.setNotificationHandler(null);
27 };
28 }, []);
29​
30 useEffect(() => {
31 const handleResponse = (response: Notifications.NotificationResponse): void => {
32 routeAgentNotificationResponseOnce({
33 handledResponseIds: handledResponseIds.current,
34 response,
35 navigate: linkTo,
36 });
37 };
38​
39 const subscription = Notifications.addNotificationResponseReceivedListener(handleResponse);
40 void consumeLastAgentNotificationResponse({
41 getLastResponse: () => Notifications.getLastNotificationResponseAsync(),
42 clearLastResponse: () => Notifications.clearLastNotificationResponseAsync(),
43 handleResponse,
44 });
45​
46 return () => {
47 subscription.remove();
48 };
49 }, [linkTo]);