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

useT3ChatLink.ts

76 lines2.5 KB

1import { findErrorTraceId } from "@t3tools/client-runtime/errors";
2import {
3 isAtomCommandInterrupted,
4 squashAtomCommandFailure,
5} from "@t3tools/client-runtime/state/runtime";
6import { useState } from "react";
7​
8import {
9 createManagedRelayT3ChatLinkRequestCommand,
10 unlinkManagedRelayT3ChatCommand,
11 useManagedRelayT3ChatLink,
12} from "../../cloud/managedRelayState";
13import { readLocalApi } from "../../localApi";
14import { useAtomCommand } from "../../state/use-atom-command";
15import { toastManager } from "../ui/toast";
16​
17function reportFailure(title: string, cause: unknown) {
18 const traceId = findErrorTraceId(cause);
19 toastManager.add({
20 type: "error",
21 title,
22 description: cause instanceof Error ? cause.message : "Try again.",
23 data: traceId
24 ? {
25 secondaryActionProps: {
26 children: "Copy trace ID",
27 onClick: () => void navigator.clipboard?.writeText(traceId),
28 },
29 }
30 : undefined,
31 });
33​
34/** Starts and removes the T3 Chat link that raises the T3 Connect tunnel cap. */
35export function useT3ChatLink() {
36 const linkState = useManagedRelayT3ChatLink();
37 const createLinkRequest = useAtomCommand(createManagedRelayT3ChatLinkRequestCommand, {
38 reportFailure: false,
39 });
40 const unlinkCommand = useAtomCommand(unlinkManagedRelayT3ChatCommand, { reportFailure: false });
41 const [pending, setPending] = useState<"link" | "unlink" | null>(null);
42 // Kept so a blocked popup still leaves the user a link to open.
43 const [linkUrl, setLinkUrl] = useState<string | null>(null);
44​
45 const link = async () => {
46 const accountId = linkState.accountId;
47 if (!accountId || pending) return;
48 setPending("link");
49 const result = await createLinkRequest({ accountId });
50 if (result._tag === "Success") {
51 setLinkUrl(result.value);
52 await readLocalApi()
53 ?.shell.openExternal(result.value)
54 .catch(() => undefined);
55 } else if (!isAtomCommandInterrupted(result)) {
56 reportFailure("Could not start linking", squashAtomCommandFailure(result));
57 }
58 setPending(null);
59 };
60​
61 const unlink = async () => {
62 const accountId = linkState.accountId;
63 if (!accountId || pending) return;
64 setPending("unlink");
65 const result = await unlinkCommand({ accountId });
66 if (result._tag === "Success") {
67 setLinkUrl(null);
68 linkState.refresh();
69 } else if (!isAtomCommandInterrupted(result)) {
70 reportFailure("Could not unlink T3 Chat", squashAtomCommandFailure(result));
71 }
72 setPending(null);
73 };
74​
75 return { linkState, pending, linkUrl, link, unlink };