Open History to see the last commit
1import { memo, useCallback, useEffect, useRef } from "react";
2import {
3 Pressable,
4 ScrollView,
5 TextInput,
6 View,
7 type LayoutChangeEvent,
8 type NativeSyntheticEvent,
9 type ViewProps,
10 useColorScheme,
11} from "react-native";
12
13import { AppText as Text } from "../../components/AppText";
14import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
15import { resolveNativeTerminalSurfaceView } from "./nativeTerminalModule";
16import {
17 buildGhosttyThemeConfig,
18 getPierreTerminalTheme,
19 type TerminalTheme,
20} from "./terminalTheme";
21import { terminalDebugLog } from "./terminalDebugLog";
22
23interface TerminalInputEvent {
24 readonly data: string;
25}
26
27interface TerminalResizeEvent {
28 readonly cols: number;
29 readonly rows: number;
30}
31
32interface TerminalSurfaceProps extends ViewProps {
33 readonly terminalKey: string;
34 readonly buffer: string;
35 readonly fontSize?: number;
36 readonly isRunning: boolean;
37 readonly keyboardFocusRequest?: number;
38 readonly theme?: TerminalTheme;
39 readonly onInput: (data: string) => void;
40 readonly onResize: (size: { readonly cols: number; readonly rows: number }) => void;
41}
42
43function estimateGridSize(input: {
44 readonly width: number;
45 readonly height: number;
46 readonly fontSize: number;
47}): { readonly cols: number; readonly rows: number } {
48 const cellWidth = input.fontSize * 0.62;
49 const cellHeight = input.fontSize * 1.35;
50 return {
51 cols: Math.max(20, Math.min(400, Math.floor(input.width / cellWidth))),
52 rows: Math.max(5, Math.min(200, Math.floor(input.height / cellHeight))),
53 };
54}
55
56const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: TerminalSurfaceProps) {
57 const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;
58 const inputRef = useRef<TextInput>(null);
59 const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
60 const theme = props.theme ?? getPierreTerminalTheme(appearanceScheme);
61 const statusLabel = props.isRunning
62 ? "Native terminal unavailable. Using text fallback."
63 : "Open terminal to start a shell.";
64
65 const handleLayout = (event: LayoutChangeEvent) => {
66 const { width, height } = event.nativeEvent.layout;
67 props.onResize(estimateGridSize({ width, height, fontSize }));
68 };
69
70 useEffect(() => {
71 if ((props.keyboardFocusRequest ?? 0) > 0) {
72 inputRef.current?.blur();
73 const focusFrame = requestAnimationFrame(() => inputRef.current?.focus());
74 return () => cancelAnimationFrame(focusFrame);
75 }
76
77 return undefined;
78 }, [props.keyboardFocusRequest]);
79
80 return (
81 <View
82 style={[
83 {
84 flex: 1,
85 backgroundColor: theme.background,
86 borderRadius: 8,
87 overflow: "hidden",
88 },
89 props.style,
90 ]}
91 onLayout={handleLayout}
92 >
93 <View style={{ flex: 1, paddingHorizontal: 10, paddingVertical: 8 }}>
94 <Text
95 style={{
96 color: theme.mutedForeground,
97 fontSize: MOBILE_TYPOGRAPHY.caption.fontSize,
98 paddingBottom: 8,
99 }}
100 >
101 {statusLabel}
102 </Text>
103 <ScrollView
104 style={{ flex: 1 }}
105 contentContainerStyle={{ paddingBottom: 12 }}
106 showsVerticalScrollIndicator={false}
107 >
108 <Text
109 selectable
110 style={{
111 color: theme.foreground,
112 fontFamily: "Menlo",
113 fontSize,
114 lineHeight: Math.round(fontSize * 1.35),
115 }}
116 >
117 {props.buffer || "$ "}
118 </Text>
119 </ScrollView>
120 </View>
121 <View
122 style={{
123 borderTopWidth: 1,
124 borderTopColor: theme.border,
125 flexDirection: "row",
126 alignItems: "center",
127 gap: 8,
128 padding: 8,
129 }}
130 >
131 <TextInput
132 ref={inputRef}
133 autoCapitalize="none"
134 autoCorrect={false}
135 blurOnSubmit={false}
136 editable={props.isRunning}
137 placeholder="type and press return"
138 placeholderTextColor={theme.mutedForeground}
139 returnKeyType="send"
140 style={{
141 color: theme.foreground,
142 flex: 1,
143 fontFamily: "Menlo",
144 fontSize: MOBILE_TYPOGRAPHY.footnote.fontSize,
145 padding: 0,
146 }}
147 onSubmitEditing={(event) => {
148 const text = event.nativeEvent.text;
149 if (text.length > 0) {
150 props.onInput(`${text}\n`);
151 }
152 }}
153 />
154 <Pressable
155 disabled={!props.isRunning}
156 style={({ pressed }) => ({
157 opacity: !props.isRunning ? 0.35 : pressed ? 0.65 : 1,
158 paddingHorizontal: 10,
159 paddingVertical: 6,
160 borderRadius: 8,
161 backgroundColor: theme.border,
162 })}
163 onPress={() => props.onInput("\u0003")}
164 >
165 <Text
166 style={{
167 color: theme.foreground,
168 fontFamily: "DMSans_700Bold",
169 fontSize: MOBILE_TYPOGRAPHY.caption.fontSize,
170 }}
171 >
172 Ctrl-C
173 </Text>
174 </Pressable>
175 </View>
176 </View>
177 );
178});
179
180export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) {
181 const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;
182 const keyboardInputRef = useRef<TextInput>(null);
183 const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
184 const theme = props.theme ?? getPierreTerminalTheme(appearanceScheme);
185 const { onInput, onResize } = props;
186 const NativeTerminalSurfaceView = resolveNativeTerminalSurfaceView();
187 const hasNativeSurface = Boolean(NativeTerminalSurfaceView);
188
189 useEffect(() => {
190 terminalDebugLog("native:surface", {
191 terminalKey: props.terminalKey,
192 native: hasNativeSurface,
193 bufferLen: props.buffer.length,
194 isRunning: props.isRunning,
195 });
196 }, [hasNativeSurface, props.buffer.length, props.isRunning, props.terminalKey]);
197 const handleNativeInput = useCallback(
198 (event: NativeSyntheticEvent<TerminalInputEvent>) => {
199 onInput(event.nativeEvent.data);
200 },
201 [onInput],
202 );
203 const handleNativeResize = useCallback(
204 (event: NativeSyntheticEvent<TerminalResizeEvent>) => {
205 onResize({
206 cols: event.nativeEvent.cols,
207 rows: event.nativeEvent.rows,
208 });
209 },
210 [onResize],
211 );
212
213 // Reopen focus through React and forward input normally; this avoids a native focus-command bridge.
214 useEffect(() => {
215 if (!NativeTerminalSurfaceView || (props.keyboardFocusRequest ?? 0) <= 0) {
216 return undefined;
217 }
218
219 keyboardInputRef.current?.blur();
220 const focusFrame = requestAnimationFrame(() => keyboardInputRef.current?.focus());
221 return () => cancelAnimationFrame(focusFrame);
222 }, [NativeTerminalSurfaceView, props.keyboardFocusRequest]);
223
224 const handleKeyboardInput = useCallback(
225 (data: string) => {
226 if (data.length > 0) {
227 onInput(data);
228 keyboardInputRef.current?.clear();
229 }
230 },
231 [onInput],
232 );
233
234 if (NativeTerminalSurfaceView) {
235 return (
236 <View style={props.style}>
237 <NativeTerminalSurfaceView
238 appearanceScheme={appearanceScheme}
239 backgroundColor={theme.background}
240 foregroundColor={theme.foreground}
241 mutedForegroundColor={theme.mutedForeground}
242 terminalKey={props.terminalKey}
243 initialBuffer={props.buffer}
244 fontSize={fontSize}
245 style={{ flex: 1 }}
246 themeConfig={buildGhosttyThemeConfig(theme)}
247 onInput={handleNativeInput}
248 onResize={handleNativeResize}
249 />
250 <TextInput
251 ref={keyboardInputRef}
252 autoCapitalize="none"
253 autoCorrect={false}
254 blurOnSubmit={false}
255 caretHidden
256 editable={props.isRunning}
257 keyboardType="ascii-capable"
258 style={{ bottom: 0, height: 1, left: 0, opacity: 0.01, position: "absolute", width: 1 }}
259 onChangeText={handleKeyboardInput}
260 onKeyPress={(event) => {
261 if (event.nativeEvent.key === "Backspace") {
262 onInput("\u007f");
263 }
264 }}
265 onSubmitEditing={() => onInput("\n")}
266 />
267 </View>
268 );
269 }
270
271 return <FallbackTerminalSurface {...props} fontSize={fontSize} theme={theme} />;
272});