TypeScript
fix(mobile): iOS terminal accepts Chinese, Japanese and Korean input (#30546)
Julius Marminge71f251d4cf81
diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.ktindex 703bcdf361b..2734b0ceaa0 100644--- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt+++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt@@ -19,6 +19,9 @@ class T3TerminalModule : Module() {view.writeOutput(data, reset)}+ // The Android input field already clears after every change.+ AsyncFunction("resetInput") { _: T3TerminalView -> }+Prop("terminalKey") { view: T3TerminalView, terminalKey: String ->view.terminalKey = terminalKey}diff --git a/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift b/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swiftindex d68e46a5416..e2770ba5386 100644--- a/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift+++ b/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift@@ -16,6 +16,10 @@ public class T3TerminalModule: Module {view.writeOutput(data, reset: reset)}+ AsyncFunction("resetInput") { (view: T3TerminalView) in+ view.resetInputField()+ }+Prop("terminalKey") { (view: T3TerminalView, terminalKey: String) inview.terminalKey = terminalKey}diff --git a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swiftindex 0ae146bb124..fad1199a4a4 100644--- a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift+++ b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift@@ -133,12 +133,16 @@ private final class TerminalInputField: UITextField {action: #selector(handleHardwareKeyCommand(_:)))+ // While an IME composes, arrows, Tab and Escape pick or cancel candidates instead.override var keyCommands: [UIKeyCommand]? {- Self.hardwareKeyCommands+ markedTextRange == nil ? Self.hardwareKeyCommands : nil}override func deleteBackward() {- onDeleteBackward?()+ // Backspace edits marked or committed field text first; the field diff sends that DEL.+ if markedTextRange == nil, !hasText {+ onDeleteBackward?()+ }super.deleteBackward()}@@ -198,6 +202,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {private var lastAppliedBuffer = ""private var streamedOutput: TerminalOutputBuffer?private var pendingVerticalScrollPoints: CGFloat = 0+ private var sentInput = ""private var app: ghostty_app_t?private var surface: ghostty_surface_t?private var isCreatingSurface = false@@ -348,19 +353,22 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {inputField.spellCheckingType = .noinputField.smartDashesType = .noinputField.smartQuotesType = .no+ inputField.smartInsertDeleteType = .noinputField.returnKeyType = .send- inputField.keyboardType = .asciiCapable+ inputField.keyboardType = .defaultinputField.enablesReturnKeyAutomatically = falseinputField.translatesAutoresizingMaskIntoConstraints = falseinputField.alpha = 0.02inputField.isAccessibilityElement = falseinputField.accessibilityElementsHidden = trueinputField.addTarget(self, action: #selector(handleInputEditingDidBegin), for: .editingDidBegin)+ inputField.addTarget(self, action: #selector(handleInputEditingChanged), for: .editingChanged)inputField.onDeleteBackward = { [weak self] inself?.emitInput("\u{7F}")}inputField.onInsert = { [weak self] data inself?.emitInput(data)+ self?.resetInputField()}focusTapGesture.addTarget(self, action: #selector(handleViewportTap))@@ -417,21 +425,11 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {}}- public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {- if !string.isEmpty {- // Some software keyboards deliver Return through this delegate instead of- // textFieldShouldReturn, so normalize that path too.- emitInput(TerminalInputSequence.normalizingReturn(string))- return false- }-- emitInput("\u{7F}")- return false- }-public func textFieldShouldReturn(_ textField: UITextField) -> Bool {+ // Return during a composition commits it; that is not Enter.+ guard textField.markedTextRange == nil else { return false }emitInput(TerminalInputSequence.carriageReturn)- textField.text = ""+ resetInputField()return false}@@ -480,11 +478,44 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {}}+ // Korean keyboards build a syllable by replacing the committed character before the cursor,+ // so the field keeps what was sent and each change goes out as DELs plus the new suffix.+ // Scalars, not Characters: a Thai or Indic mark joins the previous grapheme, and resending+ // that grapheme after one DEL would leave its base twice in a code-point line editor.+ @objc+ private func handleInputEditingChanged() {+ guard inputField.markedTextRange == nil else { return }+ let text = inputField.text ?? ""+ let fieldScalars = text.unicodeScalars+ let sentScalars = sentInput.unicodeScalars+ let commonCount = zip(fieldScalars, sentScalars).prefix { $0.0 == $0.1 }.count+ let unsent = String(String.UnicodeScalarView(sentScalars.dropFirst(commonCount)))+ let added = String(String.UnicodeScalarView(fieldScalars.dropFirst(commonCount)))+ // Some software keyboards deliver Return as an inserted newline instead of textFieldShouldReturn.+ emitInput(String(repeating: "\u{7F}", count: unsent.count) + TerminalInputSequence.normalizingReturn(added))+ sentInput = text+ // A Hangul syllable never spans whitespace; past the cap, keep the last character to compose onto.+ if text.last?.isWhitespace == true {+ resetInputField()+ } else if text.count > 64 {+ let last = String(text.suffix(1))+ inputField.text = last+ sentInput = last+ }+ }+@objcprivate func handleInputEditingDidBegin() {+ // A composition abandoned by losing focus must not reach the PTY with the next keystroke.+ resetInputField()textInputModeDidChange()}+ func resetInputField() {+ inputField.text = ""+ sentInput = ""+ }+private func createSurfaceIfPossible() {guard surface == nil, app == nil, !isCreatingSurface, !surfaceCreationFailed else { return }guard terminalViewport.bounds.width > 0, terminalViewport.bounds.height > 0 else { return }diff --git a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsxindex a1957aa1242..877ab40582b 100644--- a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx+++ b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx@@ -39,6 +39,8 @@ interface TerminalResizeEvent {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 {@@ -102,6 +104,7 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface({inputRef.current?.blur();requestAnimationFrame(() => inputRef.current?.focus());},+ resetInput: () => {},}));return (@@ -199,14 +202,18 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfreturn <ReadyTerminalSurface key={props.terminalKey} {...props} buffer={buffer} />;});-const ReadyTerminalSurface = memo(function ReadyTerminalSurface(props: ReadyTerminalSurfaceProps) {+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 = props.grid?.cols;- const gridRows = props.grid?.rows;+ const gridCols = grid?.cols;+ const gridRows = grid?.rows;const sharedGrid = useMemo(() => (gridCols !== undefined && gridRows !== undefined ? [gridCols, gridRows] : []),[gridCols, gridRows],@@ -216,6 +223,16 @@ const ReadyTerminalSurface = memo(function ReadyTerminalSurface(props: ReadyTermconst 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 cleanupuseEffect(() => {const view = nativeRef.current;@@ -279,5 +296,5 @@ const ReadyTerminalSurface = memo(function ReadyTerminalSurface(props: ReadyTerm);}- return <FallbackTerminalSurface {...props} fontSize={fontSize} theme={theme} />;+ return <FallbackTerminalSurface {...props} ref={ref} fontSize={fontSize} theme={theme} />;});diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsxindex 19a8685fe36..74ae491786d 100644--- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx+++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx@@ -751,6 +751,9 @@ function ThreadTerminal(props: {return;}+ // Toolbar input bypasses the native field, so a syllable it holds must not be recomposed.+ surfaceRef.current?.resetInput();+if (action.kind === "clear") {handleClearTerminal();return;diff --git a/apps/mobile/src/features/terminal/nativeTerminalModule.ts b/apps/mobile/src/features/terminal/nativeTerminalModule.tsindex cb5d79e2109..1f0702453a9 100644--- a/apps/mobile/src/features/terminal/nativeTerminalModule.ts+++ b/apps/mobile/src/features/terminal/nativeTerminalModule.ts@@ -44,6 +44,8 @@ export interface NativeTerminalSurfaceProps extends ViewProps {export interface NativeTerminalSurfaceHandle {readonly writeOutput: (data: string, reset: boolean) => Promise<void>;+ /** Absent on native builds that predate it. */+ readonly resetInput?: () => Promise<void>;}let cachedNativeTerminalSurfaceView: ComponentType<NativeTerminalSurfaceProps> | undefined;