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