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