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

ProviderAuthTerminal.tsx

80 lines2.9 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 onBinary: (data) => respond({ type: "terminal", data, binary: true }),
39 onReply: (data) => respond({ type: "terminal", data }),
40 onResize: (cols, rows) => respond({ type: "terminal", data: "", size: { cols, rows } }),
41 onSelectionChange: () => {},
42 beforeKey: (event) => event.key !== "Tab",
43 onLinkActivate: (url) => {
44 if (/^https?:\/\//i.test(url))
45 void ensureLocalApi()
46 .shell.openExternal(url)
47 .catch(() => setError("Could not open the provider link."));
48 },
49 })
50 .then((terminal) => {
51 if (disposed) {
52 terminal.dispose();
53 return;
54 }
55 created = terminal;
56 written.current = 0;
57 setSurface(terminal);
58 })
59 .catch(() => setError("Could not load the sign-in terminal. Cancel and retry sign-in."));
60 return () => {
61 disposed = true;
62 created?.dispose();
63 setSurface(null);
64 };
65 };
66 return (
67 <>
68 <div
69 ref={mountSurface}
70 aria-label="Provider sign-in terminal"
71 className="relative h-64 overflow-hidden rounded-md border border-border"
72 />
73 {error ? (
74 <p role="alert" className="text-destructive">
75 {error}
76 </p>
77 ) : null}
78 </>
79 );