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 TextInputInstance,
10 type ViewProps,
11} from "react-native";
12
13import { AppText as Text } from "../../components/AppText";
14import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
15import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
16import {
17 getNativeTerminalHardwareKeyRevision,
18 resolveNativeTerminalSurfaceView,
19} from "./nativeTerminalModule";
20import {
21 buildGhosttyThemeConfig,
22 getMobileTerminalTheme,
23 type TerminalTheme,
24} from "./terminalTheme";
25import { terminalDebugLog } from "./terminalDebugLog";
26
27interface TerminalInputEvent {
28 readonly data: string;
29}
30
31interface TerminalResizeEvent {
32 readonly cols: number;
33 readonly rows: number;
34}
35
36interface TerminalSurfaceProps extends ViewProps {
37 readonly terminalKey: string;
38 readonly buffer: string;
39 readonly fontSize?: number;
40 readonly isRunning: boolean;
41 readonly autoFocus?: boolean;
42 readonly keyboardFocusRequest?: number;
43 readonly captureRequest?: number;
44 readonly onCapture?: (text: string) => void;
45 readonly theme?: TerminalTheme;
46 readonly onInput: (data: string) => void;
47 readonly onResize: (size: { readonly cols: number; readonly rows: number }) => void;
48}
49
50function estimateGridSize(input: {
51 readonly width: number;
52 readonly height: number;
53 readonly fontSize: number;
54}): { readonly cols: number; readonly rows: number } {
55 const cellWidth = input.fontSize * 0.62;
56 const cellHeight = input.fontSize * 1.35;
57 return {
58 cols: Math.max(20, Math.min(400, Math.floor(input.width / cellWidth))),
59 rows: Math.max(5, Math.min(200, Math.floor(input.height / cellHeight))),
60 };
61}
62
63const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: TerminalSurfaceProps) {
64 const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;
65 const inputRef = useRef<TextInputInstance>(null);
66 const { themeAppearance, themeId } = useAppearancePreferences();
67 const theme = props.theme ?? getMobileTerminalTheme(themeId, themeAppearance);
68 const statusLabel = props.isRunning
69 ? "Native terminal unavailable. Using text fallback."
70 : "Open terminal to start a shell.";
71
72 const handleLayout = (event: LayoutChangeEvent) => {
73 const { width, height } = event.nativeEvent.layout;
74 props.onResize(estimateGridSize({ width, height, fontSize }));
75 };
76
77 useEffect(() => {
78 if ((props.keyboardFocusRequest ?? 0) > 0) {
79 inputRef.current?.blur();
80 const focusFrame = requestAnimationFrame(() => inputRef.current?.focus());
81 return () => cancelAnimationFrame(focusFrame);
82 }
83
84 return undefined;
85 }, [props.keyboardFocusRequest]);
86
87 return (
88 <View
89 className="flex-1"
90 style={[
91 {
92 backgroundColor: theme.background,
93 borderRadius: 8,
94 overflow: "hidden",
95 },
96 props.style,
97 ]}
98 onLayout={handleLayout}
99 >
100 <View className="flex-1 px-2.5 py-2">
101 <Text
102 className="pb-2 text-2xs"
103 style={{
104 color: theme.mutedForeground,
105 }}
106 >
107 {statusLabel}
108 </Text>
109 <ScrollView
110 className="flex-1"
111 contentContainerClassName="pb-3"
112 showsVerticalScrollIndicator={false}
113 >
114 <Text
115 selectable
116 style={{
117 color: theme.foreground,
118 fontFamily: "Menlo",
119 fontSize,
120 lineHeight: Math.round(fontSize * 1.35),
121 }}
122 >
123 {props.buffer || "$ "}
124 </Text>
125 </ScrollView>
126 </View>
127 <View
128 className="flex-row items-center gap-2 border-t p-2"
129 style={{
130 borderTopColor: theme.border,
131 }}
132 >
133 <TextInput
134 ref={inputRef}
135 autoCapitalize="none"
136 autoCorrect={false}
137 blurOnSubmit={false}
138 editable={props.isRunning}
139 placeholder="type and press return"
140 placeholderTextColor={theme.mutedForeground}
141 returnKeyType="send"
142 className="text-sm"
143 style={{
144 color: theme.foreground,
145 flex: 1,
146 fontFamily: "Menlo",
147 padding: 0,
148 }}
149 onSubmitEditing={(event) => {
150 const text = event.nativeEvent.text;
151 if (text.length > 0) {
152 // Terminal Enter is CR. LF is Ctrl+J and raw-mode TUIs can treat it as J.
153 props.onInput(`${text}\r`);
154 }
155 }}
156 />
157 <Pressable
158 disabled={!props.isRunning}
159 style={({ pressed }) => ({
160 opacity: !props.isRunning ? 0.35 : pressed ? 0.65 : 1,
161 paddingHorizontal: 10,
162 paddingVertical: 6,
163 borderRadius: 8,
164 backgroundColor: theme.border,
165 })}
166 onPress={() => props.onInput("\u0003")}
167 >
168 <Text className="text-2xs font-t3-bold" style={{ color: theme.foreground }}>
169 Ctrl-C
170 </Text>
171 </Pressable>
172 </View>
173 </View>
174 );
175});
176
177export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) {
178 const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;
179 const { themeAppearance, themeId } = useAppearancePreferences();
180 const theme = props.theme ?? getMobileTerminalTheme(themeId, themeAppearance);
181 const { onInput, onResize } = props;
182 const NativeTerminalSurfaceView = resolveNativeTerminalSurfaceView();
183 const hasNativeSurface = Boolean(NativeTerminalSurfaceView);
184
185 useEffect(() => {
186 terminalDebugLog("native:surface", {
187 terminalKey: props.terminalKey,
188 native: hasNativeSurface,
189 // null = installed binary predates native hardware-key handling (rebuild needed).
190 hardwareKeyRevision: getNativeTerminalHardwareKeyRevision(),
191 bufferLen: props.buffer.length,
192 isRunning: props.isRunning,
193 });
194 }, [hasNativeSurface, props.buffer.length, props.isRunning, props.terminalKey]);
195 const handleNativeInput = useCallback(
196 (event: NativeSyntheticEvent<TerminalInputEvent>) => {
197 if (!props.isRunning) {
198 return;
199 }
200 terminalDebugLog("native:onInput", {
201 codes: Array.from(event.nativeEvent.data, (char) => char.codePointAt(0)),
202 });
203 onInput(event.nativeEvent.data);
204 },
205 [onInput, props.isRunning],
206 );
207 const handleNativeResize = useCallback(
208 (event: NativeSyntheticEvent<TerminalResizeEvent>) => {
209 onResize({
210 cols: event.nativeEvent.cols,
211 rows: event.nativeEvent.rows,
212 });
213 },
214 [onResize],
215 );
216
217 if (NativeTerminalSurfaceView) {
218 return (
219 <View style={props.style}>
220 <NativeTerminalSurfaceView
221 appearanceScheme={themeAppearance}
222 autoFocus={props.autoFocus ?? true}
223 backgroundColor={theme.background}
224 focusRequest={props.isRunning ? (props.keyboardFocusRequest ?? 0) : 0}
225 foregroundColor={theme.foreground}
226 mutedForegroundColor={theme.mutedForeground}
227 terminalKey={props.terminalKey}
228 initialBuffer={props.buffer}
229 fontSize={fontSize}
230 style={{ flex: 1 }}
231 themeConfig={buildGhosttyThemeConfig(theme)}
232 onInput={handleNativeInput}
233 onResize={handleNativeResize}
234 captureRequest={props.captureRequest}
235 onCapture={(event) => props.onCapture?.(event.nativeEvent.text)}
236 />
237 </View>
238 );
239 }
240
241 return <FallbackTerminalSurface {...props} fontSize={fontSize} theme={theme} />;
242});