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

ProviderAuthTerminal.tsx

78 lines2.8 KB

1import type { ProviderAuthResponse } from "@t3tools/contracts";
2import { useEffect, useRef, useState } from "react";
3import { GhosttyTerminalSurface } from "../../terminal/ghostty/surface";
4import { ensureLocalApi } from "../../localApi";
5import { useStableCallback } from "../../hooks/useStableCallback";
6import { terminalThemeFromApp } from "../ThreadTerminalDrawer";
7​
8export default function ProviderAuthTerminal({
9 output,
10 outputOffset,
11 onResponse,
12}: {
13 readonly output: string;
14 readonly outputOffset?: number | undefined;
15 readonly onResponse: (response: Extract<ProviderAuthResponse, { type: "terminal" }>) => void;
16}) {
17 const [surface, setSurface] = useState<GhosttyTerminalSurface | null>(null);
18 const written = useRef(0);
19 const [error, setError] = useState<string | null>(null);
20 // The surface captures its callbacks once at creation.
21 const respond = useStableCallback(onResponse);
22 const offset = outputOffset ?? output.length;
23 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes new auth output into the imperative Ghostty terminal surface
24 useEffect(() => {
25 if (!surface) return;
26 const delta = offset - written.current;
27 if (delta > 0 && delta <= output.length) surface.write(output.slice(-delta));
28 else if (delta !== 0) surface.resetAndWrite(output);
29 written.current = offset;
30 }, [surface, output, offset]);
31 const mountSurface = (element: HTMLDivElement) => {
32 let disposed = false;
33 let created: GhosttyTerminalSurface | null = null;
34 void GhosttyTerminalSurface.create(element, {
35 theme: terminalThemeFromApp(element),
36 font: { size: 13 },
37 onData: (data) => respond({ type: "terminal", data }),
38 onResize: (cols, rows) => respond({ type: "terminal", data: "", size: { cols, rows } }),
39 onSelectionChange: () => {},
40 beforeKey: (event) => event.key !== "Tab",
41 onLinkActivate: (url) => {
42 if (/^https?:\/\//i.test(url))
43 void ensureLocalApi()
44 .shell.openExternal(url)
45 .catch(() => setError("Could not open the provider link."));
46 },
47 })
48 .then((terminal) => {
49 if (disposed) {
50 terminal.dispose();
51 return;
52 }
53 created = terminal;
54 written.current = 0;
55 setSurface(terminal);
56 })
57 .catch(() => setError("Could not load the sign-in terminal. Cancel and retry sign-in."));
58 return () => {
59 disposed = true;
60 created?.dispose();
61 setSurface(null);
62 };
63 };
64 return (
65 <>
66 <div
67 ref={mountSurface}
68 aria-label="Provider sign-in terminal"
69 className="relative h-64 overflow-hidden rounded-md border border-border"
70 />
71 {error ? (
72 <p role="alert" className="text-destructive">
73 {error}
74 </p>
75 ) : null}
76 </>
77 );