The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 315 lines 10.7 KB
Raw
1 import {
2 terminalOutputText,
3 type TerminalGrid,
4 type TerminalOutputState,
5 } from "@t3tools/client-runtime/state/terminal";
6 import { useGT } from "gt-react-native";
7 import { memo, useEffect, useImperativeHandle, useMemo, useRef, useState, type Ref } from "react";
8 import {
9 Pressable,
10 ScrollView,
11 TextInput,
12 View,
13 type LayoutChangeEvent,
14 type NativeSyntheticEvent,
15 type TextInputInstance,
16 type ViewProps,
17 } from "react-native";
18
19 import { AppText as Text } from "../../components/ui/AppText";
20 import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
21 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
22 import {
23 resolveNativeTerminalSurfaceView,
24 supportsNativeTerminalOutput,
25 type NativeTerminalSurfaceHandle,
26 } from "./nativeTerminalModule";
27 import {
28 buildGhosttyThemeConfig,
29 getMobileTerminalTheme,
30 type TerminalTheme,
31 } from "./terminalTheme";
32 import { useTerminalSurfaceBuffer } from "./useTerminalSurfaceBuffer";
33 import { createTerminalOutputWriter } from "./terminalOutputWriter";
34
35 interface TerminalInputEvent {
36 readonly data: string;
37 }
38
39 interface TerminalResizeEvent {
40 readonly cols: number;
41 readonly rows: number;
42 }
43
44 export interface TerminalSurfaceHandle {
45 /** The text fallback focuses its input; the native view follows `keyboardFocusRequest`. */
46 readonly focusKeyboard: () => void;
47 /** Drops the native field's IME context after input that bypassed it. */
48 readonly resetInput: () => void;
49 }
50
51 interface TerminalSurfaceProps extends ViewProps {
52 readonly ref?: Ref<TerminalSurfaceHandle>;
53 readonly terminalKey: string;
54 readonly buffer: string | null;
55 readonly output: TerminalOutputState | null;
56 readonly fontSize?: number;
57 readonly grid?: TerminalGrid | null;
58 readonly isRunning: boolean;
59 readonly readOnly?: boolean;
60 readonly autoFocus?: boolean;
61 readonly keyboardFocusRequest?: number;
62 readonly captureRequest?: number;
63 readonly onCapture?: (text: string) => void;
64 readonly theme?: TerminalTheme;
65 readonly onInput: (data: string) => void;
66 readonly onPaste?: (text: string) => void;
67 readonly onResize: (size: { readonly cols: number; readonly rows: number }) => void;
68 }
69
70 type ReadyTerminalSurfaceProps = Omit<TerminalSurfaceProps, "buffer"> & {
71 readonly buffer: string;
72 };
73
74 function estimateGridSize(input: {
75 readonly width: number;
76 readonly height: number;
77 readonly fontSize: number;
78 }): { readonly cols: number; readonly rows: number } {
79 const cellWidth = input.fontSize * 0.62;
80 const cellHeight = input.fontSize * 1.35;
81 return {
82 cols: Math.max(20, Math.min(400, Math.floor(input.width / cellWidth))),
83 rows: Math.max(5, Math.min(200, Math.floor(input.height / cellHeight))),
84 };
85 }
86
87 const FallbackTerminalSurface = memo(function FallbackTerminalSurface({
88 ref,
89 ...props
90 }: ReadyTerminalSurfaceProps) {
91 const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;
92 const gt = useGT();
93 const inputRef = useRef<TextInputInstance>(null);
94 const { themeAppearance, themeId } = useAppearancePreferences();
95 const theme = props.theme ?? getMobileTerminalTheme(themeId, themeAppearance);
96 const statusLabel = props.readOnly
97 ? gt("Viewing terminal output.")
98 : props.isRunning
99 ? gt("Native terminal unavailable. Using text fallback.")
100 : gt("Open terminal to start a shell.");
101
102 const handleLayout = (event: LayoutChangeEvent) => {
103 const { width, height } = event.nativeEvent.layout;
104 props.onResize(estimateGridSize({ width, height, fontSize }));
105 };
106
107 useImperativeHandle(ref, () => ({
108 focusKeyboard: () => {
109 if (props.readOnly) return;
110 // Blur first so a focused input still raises the keyboard; focus lands after the blur commits.
111 inputRef.current?.blur();
112 requestAnimationFrame(() => inputRef.current?.focus());
113 },
114 resetInput: () => {},
115 }));
116
117 return (
118 <View
119 className="flex-1"
120 style={[
121 {
122 backgroundColor: theme.background,
123 borderRadius: 8,
124 overflow: "hidden",
125 },
126 props.style,
127 ]}
128 onLayout={handleLayout}
129 >
130 <View className="flex-1 px-2.5 py-2">
131 <Text
132 className="pb-2 text-2xs"
133 style={{
134 color: theme.mutedForeground,
135 }}
136 >
137 {statusLabel}
138 </Text>
139 <ScrollView
140 className="flex-1"
141 contentContainerClassName="pb-3"
142 showsVerticalScrollIndicator={false}
143 >
144 <Text
145 selectable
146 style={{
147 color: theme.foreground,
148 fontFamily: "Menlo",
149 fontSize,
150 lineHeight: Math.round(fontSize * 1.35),
151 }}
152 >
153 {props.buffer || "$ "}
154 </Text>
155 </ScrollView>
156 </View>
157 <View
158 className="flex-row items-center gap-2 border-t p-2"
159 style={{
160 borderTopColor: theme.border,
161 }}
162 >
163 <TextInput
164 ref={inputRef}
165 autoCapitalize="none"
166 autoCorrect={false}
167 blurOnSubmit={false}
168 editable={props.isRunning && !props.readOnly}
169 placeholder={gt("type and press return")}
170 placeholderTextColor={theme.mutedForeground}
171 returnKeyType="send"
172 className="text-sm"
173 style={{
174 color: theme.foreground,
175 flex: 1,
176 fontFamily: "Menlo",
177 padding: 0,
178 }}
179 onSubmitEditing={(event) => {
180 const text = event.nativeEvent.text;
181 if (text.length > 0) {
182 // Terminal Enter is CR. LF is Ctrl+J and raw-mode TUIs can treat it as J.
183 props.onInput(`${text}\r`);
184 }
185 }}
186 />
187 <Pressable
188 disabled={!props.isRunning || props.readOnly}
189 style={({ pressed }) => ({
190 opacity: !props.isRunning || props.readOnly ? 0.35 : pressed ? 0.65 : 1,
191 paddingHorizontal: 10,
192 paddingVertical: 6,
193 borderRadius: 8,
194 backgroundColor: theme.border,
195 })}
196 onPress={() => props.onInput("\u0003")}
197 >
198 <Text className="text-2xs font-t3-bold" style={{ color: theme.foreground }}>
199 Ctrl-C
200 </Text>
201 </Pressable>
202 </View>
203 </View>
204 );
205 });
206
207 export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) {
208 // The text fallback draws escape sequences literally, so it gets displayed text, not the replay.
209 const buffer = useTerminalSurfaceBuffer(
210 resolveNativeTerminalSurfaceView() || props.output === null
211 ? props
212 : { terminalKey: props.terminalKey, buffer: terminalOutputText(props.output) },
213 );
214 return <ReadyTerminalSurface key={props.terminalKey} {...props} buffer={buffer} />;
215 });
216
217 const ReadyTerminalSurface = memo(function ReadyTerminalSurface({
218 ref,
219 grid,
220 ...props
221 }: ReadyTerminalSurfaceProps) {
222 const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;
223 const { themeAppearance, themeId } = useAppearancePreferences();
224 const theme = props.theme ?? getMobileTerminalTheme(themeId, themeAppearance);
225 const { onInput, onResize } = props;
226 const NativeTerminalSurfaceView = resolveNativeTerminalSurfaceView();
227 const gridCols = grid?.cols;
228 const gridRows = grid?.rows;
229 const sharedGrid = useMemo(
230 () => (gridCols !== undefined && gridRows !== undefined ? [gridCols, gridRows] : []),
231 [gridCols, gridRows],
232 );
233 const streaming = supportsNativeTerminalOutput();
234 const nativeRef = useRef<NativeTerminalSurfaceHandle>(null);
235 const writerRef = useRef<ReturnType<typeof createTerminalOutputWriter> | null>(null);
236 const [nativeReady, setNativeReady] = useState(false);
237
238 // The fallback surface binds the same ref itself.
239 useImperativeHandle(NativeTerminalSurfaceView ? ref : undefined, () => ({
240 focusKeyboard: () => {},
241 resetInput: () => {
242 void nativeRef.current?.resetInput?.().catch((error: unknown) => {
243 console.error("Terminal input reset failed", error);
244 });
245 },
246 }));
247
248 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- creates the output writer for the native terminal view once it is ready and disposes it on cleanup
249 useEffect(() => {
250 const view = nativeRef.current;
251 if (!streaming || !nativeReady || view === null) return;
252 const writer = createTerminalOutputWriter((data, reset) => view.writeOutput(data, reset));
253 writerRef.current = writer;
254 return () => {
255 writerRef.current = null;
256 writer.dispose();
257 };
258 }, [nativeReady, streaming]);
259
260 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- streams new terminal output into the native terminal view through its writer
261 useEffect(() => {
262 if (!streaming || !nativeReady || props.output === null) return;
263 void writerRef.current?.write(props.output).catch((error: unknown) => {
264 console.error("Terminal output delivery failed", error);
265 });
266 }, [nativeReady, props.output, streaming]);
267
268 const handleNativeInput = (event: NativeSyntheticEvent<TerminalInputEvent>) => {
269 if (!props.isRunning || props.readOnly) {
270 return;
271 }
272 onInput(event.nativeEvent.data);
273 };
274 const handleNativeResize = (event: NativeSyntheticEvent<TerminalResizeEvent>) => {
275 // The first grid event comes from the mounted native surface, after registration.
276 setNativeReady(true);
277 onResize({
278 cols: event.nativeEvent.cols,
279 rows: event.nativeEvent.rows,
280 });
281 };
282
283 if (NativeTerminalSurfaceView) {
284 return (
285 <View style={props.style}>
286 {/* oxlint-disable-next-line react/static-components -- The resolver returns a cached native component with stable identity. */}
287 <NativeTerminalSurfaceView
288 ref={nativeRef}
289 appearanceScheme={themeAppearance}
290 autoFocus={!props.readOnly && (props.autoFocus ?? true)}
291 readOnly={props.readOnly ?? false}
292 backgroundColor={theme.background}
293 focusRequest={props.isRunning && !props.readOnly ? (props.keyboardFocusRequest ?? 0) : 0}
294 foregroundColor={theme.foreground}
295 mutedForegroundColor={theme.mutedForeground}
296 terminalKey={props.terminalKey}
297 initialBuffer={streaming ? "" : props.buffer}
298 fontSize={fontSize}
299 sharedGrid={sharedGrid}
300 style={{ flex: 1 }}
301 themeConfig={buildGhosttyThemeConfig(theme)}
302 onInput={handleNativeInput}
303 onPaste={(event) => {
304 if (props.isRunning && !props.readOnly) props.onPaste?.(event.nativeEvent.text);
305 }}
306 onResize={handleNativeResize}
307 captureRequest={props.captureRequest}
308 onCapture={(event) => props.onCapture?.(event.nativeEvent.text)}
309 />
310 </View>
311 );
312 }
313
314 return <FallbackTerminalSurface {...props} ref={ref} fontSize={fontSize} theme={theme} />;
315 });