1import { useIsFocused } from "@react-navigation/native";
2import { secondTick } from "@t3tools/client-runtime/clock";
3import { useSyncExternalStore } from "react";
4
5import { useAppActive } from "../../lib/appState";
6import { usePaneRole } from "../../components/ui/Pane";
7
8const subscribeNever = () => () => undefined;
9
10/**
11 * Retained routes stay mounted when hidden, so an ungated tick would keep
12 * re-rendering them. Every visible label shares one module-level tick.
13 */
14export function useVisibleSecondClock(enabled: boolean): number {
15 const focused = useIsFocused();
16 // The sidebar's route stays unfocused under the page beside it.
17 const inSidebar = usePaneRole() === "sidebar";
18 const appActive = useAppActive();
19 const ticking = enabled && (focused || inSidebar) && appActive;
20 // While paused the snapshot still reads the shared tick, so resuming shows
21 // the current second rather than the one the clock stopped on.
22 return useSyncExternalStore(
23 ticking ? secondTick.subscribe : subscribeNever,
24 secondTick.getSnapshot,
25 secondTick.getSnapshot,
26 );
27}