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

useShownThreadRouteTarget.ts

31 lines1.3 KB

1import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2import { useMatches } from "@tanstack/react-router";
3import { useState } from "react";
4​
5import {
6 getAppModalReturnThreadTarget,
7 isAppModalPage,
8} from "../components/sidebar/mainAppLocation";
9import type { ThreadRouteTarget } from "../threadRoutes";
10import { useThreadRouteTarget } from "./useThreadRouteTarget";
11​
12function threadRouteTargetKey(target: ThreadRouteTarget | null) {
13 if (!target) return null;
14 return target.kind === "server" ? scopedThreadKey(target.threadRef) : target.draftId;
16​
17/** Settings and Usage render over the thread that opened them; that thread stays the shown one. */
18export function useShownThreadRouteTarget() {
19 const routeTarget = useThreadRouteTarget();
20 // Read matches, not location, so this agrees with the params useThreadRouteTarget reads.
21 const modalOpen = useMatches({
22 select: (matches) => matches.some((match) => isAppModalPage(match.pathname)),
23 });
24 const [backgroundTarget, setBackgroundTarget] = useState(() =>
25 modalOpen ? getAppModalReturnThreadTarget() : routeTarget,
26 );
27 if (!modalOpen && threadRouteTargetKey(backgroundTarget) !== threadRouteTargetKey(routeTarget)) {
28 setBackgroundTarget(routeTarget);
29 }
30 return { shownTarget: modalOpen ? backgroundTarget : routeTarget, modalOpen };