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