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

backHandler.ts

26 lines1.3 KB

1import { useIsFocused } from "@react-navigation/native";
2import { use, useEffect, useEffectEvent } from "react";
3import { BackHandler } from "react-native";
4​
5import { usePaneRole } from "../components/ui/Pane";
6import { NativeWorkspaceTabActivityContext } from "../native/v5-workspace-context";
7​
8/**
9 * Android hardware back while `active` and the owning screen is focused.
10 * Keyed on those alone, not `onBack`: BackHandler calls the newest listener
11 * first, so re-registering per render lets a covered screen consume Back.
12 */
13export function useHardwareBack(active: boolean, onBack: () => boolean) {
14 // The sidebar's route stays unfocused under the page beside it.
15 const inSidebar = usePaneRole() === "sidebar";
16 // A retained tab stays mounted while another tab is shown.
17 const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true;
18 const focused = (useIsFocused() || inSidebar) && tabActive;
19 const handleBack = useEffectEvent(onBack);
20 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to BackHandler for the focused screen's lifetime
21 useEffect(() => {
22 if (!active || !focused) return;
23 const subscription = BackHandler.addEventListener("hardwareBackPress", () => handleBack());
24 return () => subscription.remove();
25 }, [active, focused]);