import type { TerminalGrid, TerminalOutputState } from "@t3tools/client-runtime/state/terminal";
import { memo, useEffect, useImperativeHandle, useMemo, useRef, useState, type Ref } from "react";
import {
Pressable,
ScrollView,
TextInput,
View,
type LayoutChangeEvent,
type NativeSyntheticEvent,
type TextInputInstance,
type ViewProps,
} from "react-native";
import { AppText as Text } from "../../components/ui/AppText";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import {
resolveNativeTerminalSurfaceView,
supportsNativeTerminalOutput,
type NativeTerminalSurfaceHandle,
} from "./nativeTerminalModule";
import {
buildGhosttyThemeConfig,
getMobileTerminalTheme,
type TerminalTheme,
} from "./terminalTheme";
import { useTerminalSurfaceBuffer } from "./useTerminalSurfaceBuffer";
import { createTerminalOutputWriter } from "./terminalOutputWriter";
interface TerminalInputEvent {
readonly data: string;
}
interface TerminalResizeEvent {
readonly cols: number;
readonly rows: number;
}
export interface TerminalSurfaceHandle {
/** The text fallback focuses its input; the native view follows `keyboardFocusRequest`. */
readonly focusKeyboard: () => void;
/** Drops the native field's IME context after input that bypassed it. */
readonly resetInput: () => void;
}
interface TerminalSurfaceProps extends ViewProps {
readonly ref?: Ref<TerminalSurfaceHandle>;
readonly terminalKey: string;
readonly buffer: string | null;
readonly output: TerminalOutputState | null;
readonly fontSize?: number;
readonly grid?: TerminalGrid | null;
readonly isRunning: boolean;
readonly readOnly?: boolean;
readonly autoFocus?: boolean;
readonly keyboardFocusRequest?: number;
readonly captureRequest?: number;
readonly onCapture?: (text: string) => void;
readonly theme?: TerminalTheme;
readonly onInput: (data: string) => void;
readonly onResize: (size: { readonly cols: number; readonly rows: number }) => void;
}
type ReadyTerminalSurfaceProps = Omit<TerminalSurfaceProps, "buffer"> & {
readonly buffer: string;
};
function estimateGridSize(input: {
readonly width: number;
readonly height: number;
readonly fontSize: number;
}): { readonly cols: number; readonly rows: number } {
const cellWidth = input.fontSize * 0.62;
const cellHeight = input.fontSize * 1.35;
return {
cols: Math.max(20, Math.min(400, Math.floor(input.width / cellWidth))),
rows: Math.max(5, Math.min(200, Math.floor(input.height / cellHeight))),
};
}
const FallbackTerminalSurface = memo(function FallbackTerminalSurface({
ref,
...props
}: ReadyTerminalSurfaceProps) {
const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;
const inputRef = useRef<TextInputInstance>(null);
const { themeAppearance, themeId } = useAppearancePreferences();
const theme = props.theme ?? getMobileTerminalTheme(themeId, themeAppearance);
const statusLabel = props.readOnly
? "Viewing terminal output."
: props.isRunning
? "Native terminal unavailable. Using text fallback."
: "Open terminal to start a shell.";
const handleLayout = (event: LayoutChangeEvent) => {
const { width, height } = event.nativeEvent.layout;
props.onResize(estimateGridSize({ width, height, fontSize }));
};
useImperativeHandle(ref, () => ({
focusKeyboard: () => {
if (props.readOnly) return;
// Blur first so a focused input still raises the keyboard; focus lands after the blur commits.
inputRef.current?.blur();
requestAnimationFrame(() => inputRef.current?.focus());
},
resetInput: () => {},
}));
return (
<View
className="flex-1"
style={[
{
backgroundColor: theme.background,
borderRadius: 8,
overflow: "hidden",
},
props.style,
]}
onLayout={handleLayout}
>
<View className="flex-1 px-2.5 py-2">
<Text
className="pb-2 text-2xs"
style={{
color: theme.mutedForeground,
}}
>
{statusLabel}
</Text>
<ScrollView
className="flex-1"
contentContainerClassName="pb-3"
showsVerticalScrollIndicator={false}
>
<Text
selectable
style={{
color: theme.foreground,
fontFamily: "Menlo",
fontSize,
lineHeight: Math.round(fontSize * 1.35),
}}
>
{props.buffer || "$ "}
</Text>
</ScrollView>
</View>
<View
className="flex-row items-center gap-2 border-t p-2"
style={{
borderTopColor: theme.border,
}}
>
<TextInput
ref={inputRef}
autoCapitalize="none"
autoCorrect={false}
blurOnSubmit={false}
editable={props.isRunning && !props.readOnly}
placeholder="type and press return"
placeholderTextColor={theme.mutedForeground}
returnKeyType="send"
className="text-sm"
style={{
color: theme.foreground,
flex: 1,
fontFamily: "Menlo",
padding: 0,
}}
onSubmitEditing={(event) => {
const text = event.nativeEvent.text;
if (text.length > 0) {
// Terminal Enter is CR. LF is Ctrl+J and raw-mode TUIs can treat it as J.
props.onInput(`${text}\r`);
}
}}
/>
<Pressable
disabled={!props.isRunning || props.readOnly}
style={({ pressed }) => ({
opacity: !props.isRunning || props.readOnly ? 0.35 : pressed ? 0.65 : 1,
paddingHorizontal: 10,
paddingVertical: 6,
borderRadius: 8,
backgroundColor: theme.border,
})}
onPress={() => props.onInput("\u0003")}
>
<Text className="text-2xs font-t3-bold" style={{ color: theme.foreground }}>
Ctrl-C
</Text>
</Pressable>
</View>
</View>
);
});
export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) {
const buffer = useTerminalSurfaceBuffer(props);
return <ReadyTerminalSurface key={props.terminalKey} {...props} buffer={buffer} />;
});
const ReadyTerminalSurface = memo(function ReadyTerminalSurface({
ref,
grid,
...props
}: ReadyTerminalSurfaceProps) {
const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;
const { themeAppearance, themeId } = useAppearancePreferences();
const theme = props.theme ?? getMobileTerminalTheme(themeId, themeAppearance);
const { onInput, onResize } = props;
const NativeTerminalSurfaceView = resolveNativeTerminalSurfaceView();
const gridCols = grid?.cols;
const gridRows = grid?.rows;
const sharedGrid = useMemo(
() => (gridCols !== undefined && gridRows !== undefined ? [gridCols, gridRows] : []),
[gridCols, gridRows],
);
const streaming = supportsNativeTerminalOutput();
const nativeRef = useRef<NativeTerminalSurfaceHandle>(null);
const writerRef = useRef<ReturnType<typeof createTerminalOutputWriter> | null>(null);
const [nativeReady, setNativeReady] = useState(false);
// The fallback surface binds the same ref itself.
useImperativeHandle(NativeTerminalSurfaceView ? ref : undefined, () => ({
focusKeyboard: () => {},
resetInput: () => {
void nativeRef.current?.resetInput?.().catch((error: unknown) => {
console.error("Terminal input reset failed", error);
});
},
}));
// 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
useEffect(() => {
const view = nativeRef.current;
if (!streaming || !nativeReady || view === null) return;
const writer = createTerminalOutputWriter((data, reset) => view.writeOutput(data, reset));
writerRef.current = writer;
return () => {
writerRef.current = null;
writer.dispose();
};
}, [nativeReady, streaming]);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- streams new terminal output into the native terminal view through its writer
useEffect(() => {
if (!streaming || !nativeReady || props.output === null) return;
void writerRef.current?.write(props.output).catch((error: unknown) => {
console.error("Terminal output delivery failed", error);
});
}, [nativeReady, props.output, streaming]);
const handleNativeInput = (event: NativeSyntheticEvent<TerminalInputEvent>) => {
if (!props.isRunning || props.readOnly) {
return;
}
onInput(event.nativeEvent.data);
};
const handleNativeResize = (event: NativeSyntheticEvent<TerminalResizeEvent>) => {
// The first grid event comes from the mounted native surface, after registration.
setNativeReady(true);
onResize({
cols: event.nativeEvent.cols,
rows: event.nativeEvent.rows,
});
};
if (NativeTerminalSurfaceView) {
return (
<View style={props.style}>
{/* oxlint-disable-next-line react/static-components -- The resolver returns a cached native component with stable identity. */}
<NativeTerminalSurfaceView
ref={nativeRef}
appearanceScheme={themeAppearance}
autoFocus={!props.readOnly && (props.autoFocus ?? true)}
readOnly={props.readOnly ?? false}
backgroundColor={theme.background}
focusRequest={props.isRunning && !props.readOnly ? (props.keyboardFocusRequest ?? 0) : 0}
foregroundColor={theme.foreground}
mutedForegroundColor={theme.mutedForeground}
terminalKey={props.terminalKey}
initialBuffer={streaming ? "" : props.buffer}
fontSize={fontSize}
sharedGrid={sharedGrid}
style={{ flex: 1 }}
themeConfig={buildGhosttyThemeConfig(theme)}
onInput={handleNativeInput}
onResize={handleNativeResize}
captureRequest={props.captureRequest}
onCapture={(event) => props.onCapture?.(event.nativeEvent.text)}
/>
</View>
);
}
return <FallbackTerminalSurface {...props} ref={ref} fontSize={fontSize} theme={theme} />;
});