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

ThreadLinkPrompt.tsx

50 lines1.9 KB

1import type { ScopedThreadRef } from "@t3tools/contracts";
2import { parseThreadLinkPrompt, withoutPromptLinkParams } from "@t3tools/shared/promptLinks";
3import { useLocation, useNavigate } from "@tanstack/react-router";
4import { useEffect } from "react";
5​
6import { isThreadRoutePathname } from "../../threadRoutes";
7import { stackedThreadToast, toastManager } from "../ui/toast";
8import { placeLinkedPrompt } from "./linkedPrompt";
9​
10const handledLinkKeys = new Set<string>();
11​
12export function ThreadLinkPrompt({ threadRef }: { readonly threadRef: ScopedThreadRef }) {
13 const navigate = useNavigate();
14 const location = useLocation({
15 select: (current) => ({
16 key: current.state.__TSR_key ?? current.href,
17 pathname: current.pathname,
18 search: current.searchStr,
19 }),
20 structuralSharing: true,
21 });
22​
23 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- places a ?prompt link into the composer once per location and strips it from the URL via the router
24 useEffect(() => {
25 // A pending navigation shows the next location while the params still name this thread.
26 if (!isThreadRoutePathname(location.pathname, threadRef)) return;
27 if (!new URLSearchParams(location.search).has("prompt")) return;
28 if (!handledLinkKeys.has(location.key)) {
29 handledLinkKeys.add(location.key);
30 const parsed = parseThreadLinkPrompt(location.search);
31 if (!parsed.ok) {
32 toastManager.add(
33 stackedThreadToast({
34 type: "error",
35 title: "Could not open the linked prompt",
36 description: parsed.error,
37 }),
38 );
39 } else if (parsed.value !== null) {
40 placeLinkedPrompt(threadRef, parsed.value);
41 }
42 }
43 void navigate({
44 href: `${location.pathname}${withoutPromptLinkParams(location.search)}`,
45 replace: true,
46 });
47 }, [location, navigate, threadRef]);
48​
49 return null;