Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NativeTerminalSurface.tsx

313 lines10.6 KB

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