200 lines
6.3 KiB
TypeScript
200 lines
6.3 KiB
TypeScript
import React, {
|
|
createContext,
|
|
useCallback,
|
|
useContext,
|
|
useEffect,
|
|
useRef,
|
|
useState,
|
|
} from "react";
|
|
import * as Notifications from "expo-notifications";
|
|
import { registerForPushNotificationsAsync } from "./notif-register";
|
|
import { useRouter } from "expo-router";
|
|
import { NotificationToast } from "../toaster";
|
|
import { NOTIF_PERMISSION_DENIED } from "common-ui/src/lib/const-strs";
|
|
import type { ReactParentComponent } from '@packages/shared';
|
|
import { useStaffAuth } from "@/components/context/staff-auth-context";
|
|
import { setPendingHref } from "./pending-navigation";
|
|
|
|
const DASHBOARD_HREF = "/(drawer)/dashboard";
|
|
const COMPLAINTS_HREF = "/(drawer)/dashboard/complaints";
|
|
|
|
const orderDetailsHref = (orderId: string) =>
|
|
`/(drawer)/dashboard/manage-orders/order-details/${orderId}`;
|
|
|
|
/** Push payload ids are numeric; ignore anything else. */
|
|
function toNumericId(value: unknown): string | null {
|
|
if (value === null || value === undefined) return null;
|
|
const id = String(value);
|
|
return /^\d+$/.test(id) ? id : null;
|
|
}
|
|
|
|
interface NotificationContextType {
|
|
expoPushToken: string | null;
|
|
notification: Notifications.Notification | null;
|
|
error: Error | null;
|
|
notifPermission: 'pending' | 'granted' | 'denied'
|
|
}
|
|
|
|
export const NotificationContext = createContext<
|
|
NotificationContextType | undefined
|
|
>(undefined);
|
|
|
|
export const useNotification = () => {
|
|
const context = useContext(NotificationContext);
|
|
if (context === undefined) {
|
|
throw new Error(
|
|
"useNotification must be used within a NotificationProvider"
|
|
);
|
|
}
|
|
return context;
|
|
};
|
|
|
|
export const NotificationProvider: React.FC<ReactParentComponent> = ({
|
|
children,
|
|
}) => {
|
|
const [expoPushToken, setExpoPushToken] = useState<string | null>(null);
|
|
const [notification, setNotification] =
|
|
useState<Notifications.Notification | null>(null);
|
|
const [error, setError] = useState<Error | null>(null);
|
|
const [notifPermission, setNotifPermission] = React.useState<NotificationContextType["notifPermission"]>("pending");
|
|
|
|
const notificationListener = useRef<any>(null);
|
|
const responseListener = useRef<any>(null);
|
|
const router = useRouter();
|
|
|
|
// Auth state is read through a ref so the response listener (registered once)
|
|
// always sees the current session, and a tap that arrives while the session is
|
|
// being restored is not mistaken for a signed-out tap.
|
|
const { isLoading, isLoggedIn } = useStaffAuth();
|
|
const isLoggedInRef = useRef(isLoggedIn);
|
|
const handledResponses = useRef<Set<string>>(new Set());
|
|
/**
|
|
* Response that launched the app. `getLastNotificationResponseAsync` resolves
|
|
* before the auth provider finishes restoring the session, so it is held here
|
|
* until `isLoading` turns false.
|
|
*/
|
|
const [launchResponse, setLaunchResponse] =
|
|
useState<Notifications.NotificationResponse | null>(null);
|
|
|
|
useEffect(() => {
|
|
isLoggedInRef.current = isLoggedIn;
|
|
}, [isLoggedIn]);
|
|
|
|
const openFromNotification = useCallback(
|
|
(response: Notifications.NotificationResponse) => {
|
|
// The launch response and the live listener can deliver the same tap.
|
|
const responseId = response.notification.request.identifier;
|
|
if (responseId) {
|
|
if (handledResponses.current.has(responseId)) return;
|
|
handledResponses.current.add(responseId);
|
|
}
|
|
|
|
const data = response.notification.request.content.data;
|
|
const orderId = toNumericId(data?.orderId);
|
|
const complaintId = toNumericId(data?.complaintId);
|
|
|
|
// An order-specific push opens that order; a general complaint opens the
|
|
// complaints list.
|
|
const target = orderId
|
|
? orderDetailsHref(orderId)
|
|
: complaintId
|
|
? COMPLAINTS_HREF
|
|
: null;
|
|
|
|
if (!target) {
|
|
if (isLoggedInRef.current) {
|
|
router.push(DASHBOARD_HREF as any);
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (isLoggedInRef.current) {
|
|
router.push(target as any);
|
|
return;
|
|
}
|
|
|
|
// Signed out: remember the destination so login can land on it.
|
|
setPendingHref(target);
|
|
},
|
|
[router]
|
|
);
|
|
|
|
useEffect(() => {
|
|
registerForPushNotificationsAsync()
|
|
.then((token) => {
|
|
setExpoPushToken(token);
|
|
setNotifPermission("granted");
|
|
})
|
|
.catch((errorRaw) => {
|
|
const err = String(errorRaw).slice(7); // strip leading "Error: "
|
|
if (err === NOTIF_PERMISSION_DENIED) {
|
|
setNotifPermission("denied");
|
|
}
|
|
});
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
notificationListener.current =
|
|
Notifications.addNotificationReceivedListener((notification) => {
|
|
setNotification(notification);
|
|
const content = notification.request?.content;
|
|
if (content) {
|
|
NotificationToast(
|
|
content.title || "Notification",
|
|
content.body || "",
|
|
content.data || {}
|
|
);
|
|
}
|
|
});
|
|
|
|
responseListener.current =
|
|
Notifications.addNotificationResponseReceivedListener(
|
|
openFromNotification
|
|
);
|
|
|
|
return () => {
|
|
if (notificationListener.current) {
|
|
Notifications.removeNotificationSubscription(
|
|
notificationListener.current
|
|
);
|
|
}
|
|
if (responseListener.current) {
|
|
Notifications.removeNotificationSubscription(responseListener.current);
|
|
}
|
|
};
|
|
}, [openFromNotification]);
|
|
|
|
// Tapping a push while the app is terminated never reaches the listener
|
|
// above; Expo replays it through the "last response" API instead.
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
|
|
Notifications.getLastNotificationResponseAsync()
|
|
.then((response) => {
|
|
if (cancelled || !response) return;
|
|
setLaunchResponse(response);
|
|
return Notifications.clearLastNotificationResponseAsync();
|
|
})
|
|
.catch(() => undefined);
|
|
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, []);
|
|
|
|
// Open the launch response only once the session is known, so the tap is not
|
|
// treated as signed out while the provider is still restoring it.
|
|
useEffect(() => {
|
|
if (isLoading || !launchResponse) return;
|
|
setLaunchResponse(null);
|
|
openFromNotification(launchResponse);
|
|
}, [isLoading, launchResponse, openFromNotification]);
|
|
|
|
return (
|
|
<NotificationContext.Provider
|
|
value={{ expoPushToken, notification, error, notifPermission }}
|
|
>
|
|
{children}
|
|
</NotificationContext.Provider>
|
|
);
|
|
};
|