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

NativeTerminalSurface.tsx

241 lines7.5 KB

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