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

NativeTerminalSurface.tsx

283 lines9.7 KB

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