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

ProviderAuthTerminal.tsx

77 lines2.6 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 useEffect(() => {
24 if (!surface) return;
25 const delta = offset - written.current;
26 if (delta > 0 && delta <= output.length) surface.write(output.slice(-delta));
27 else if (delta !== 0) surface.resetAndWrite(output);
28 written.current = offset;
29 }, [surface, output, offset]);
30 const mountSurface = (element: HTMLDivElement) => {
31 let disposed = false;
32 let created: GhosttyTerminalSurface | null = null;
33 void GhosttyTerminalSurface.create(element, {
34 theme: terminalThemeFromApp(element),
35 font: { size: 13 },
36 onData: (data) => respond({ type: "terminal", data }),
37 onResize: (cols, rows) => respond({ type: "terminal", data: "", size: { cols, rows } }),
38 onSelectionChange: () => {},
39 beforeKey: (event) => event.key !== "Tab",
40 onLinkActivate: (url) => {
41 if (/^https?:\/\//i.test(url))
42 void ensureLocalApi()
43 .shell.openExternal(url)
44 .catch(() => setError("Could not open the provider link."));
45 },
46 })
47 .then((terminal) => {
48 if (disposed) {
49 terminal.dispose();
50 return;
51 }
52 created = terminal;
53 written.current = 0;
54 setSurface(terminal);
55 })
56 .catch(() => setError("Could not load the sign-in terminal. Cancel and retry sign-in."));
57 return () => {
58 disposed = true;
59 created?.dispose();
60 setSurface(null);
61 };
62 };
63 return (
64 <>
65 <div
66 ref={mountSurface}
67 aria-label="Provider sign-in terminal"
68 className="relative h-64 overflow-hidden rounded-md border border-border"
69 />
70 {error ? (
71 <p role="alert" className="text-destructive">
72 {error}
73 </p>
74 ) : null}
75 </>
76 );