|
| 1 | +import type { ScopedThreadRef } from "@t3tools/contracts"; |
| 2 | +import { useEffect, useMemo, useState } from "react"; |
| 3 | + |
| 4 | +import { useAppActive } from "../../lib/appState"; |
| 5 | +import { scopedThreadKey } from "../../lib/scopedEntities"; |
| 6 | +import { nextThreadViewState, type ThreadViewState } from "./threadViewInterruption"; |
| 7 | + |
| 8 | +/** How long a thread shows, synced and in the foreground, after a resume or sync before it counts as read. */ |
| 9 | +const THREAD_READ_DWELL_MS = 2_000; |
| 10 | + |
| 11 | +/** |
| 12 | + * The thread while it counts as viewed, otherwise null. Opening a synced thread counts at once. |
| 13 | + * After the app leaves the foreground or the environment syncs, a run that finished meanwhile |
| 14 | + * may land before the user has looked, so the view counts again only once the thread has shown, |
| 15 | + * synced and in the foreground, for a moment; backing out sooner keeps it unread. |
| 16 | + */ |
| 17 | +export function useSettledThreadView( |
| 18 | + ref: ScopedThreadRef | null, |
| 19 | + synchronizing: boolean, |
| 20 | +): ScopedThreadRef | null { |
| 21 | + const active = useAppActive(); |
| 22 | + const key = ref === null ? null : scopedThreadKey(ref.environmentId, ref.threadId); |
| 23 | + const visible = active && !synchronizing && key !== null; |
| 24 | + const [opened, setOpened] = useState<ThreadViewState | null>(null); |
| 25 | + const next = nextThreadViewState(opened, key, visible); |
| 26 | + if (next !== opened) setOpened(next); |
| 27 | + const interrupted = next?.interrupted ?? false; |
| 28 | + // A fresh view each time the thread becomes visible again, so the wait restarts even if no |
| 29 | + // timer ran while the app was in the background. |
| 30 | + const view = useMemo(() => (visible && key !== null ? { key } : null), [visible, key]); |
| 31 | + const [settled, setSettled] = useState<{ readonly key: string } | null>(null); |
| 32 | + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- times how long a resumed or synced thread has shown in the foreground |
| 33 | + useEffect(() => { |
| 34 | + if (view === null || !interrupted) return; |
| 35 | + const timer = setTimeout(() => setSettled(view), THREAD_READ_DWELL_MS); |
| 36 | + return () => clearTimeout(timer); |
| 37 | + }, [view, interrupted]); |
| 38 | + if (view === null) return null; |
| 39 | + return !interrupted || settled === view ? ref : null; |
| 40 | +} |
0 commit comments