import { dimensions } from "../kit/internal/dimensions.ts" import type { Device } from "../Native.ts" import type { NativeNode } from "../NativeHost.ts" import { mounted } from "./node.ts" import { observe } from "./observe.ts" /** * Tracks the focused view and the soft keyboard's height while shown. * Clears the view on blur or when it leaves the tree. * `unreliable` is set on Android before API 30, whose keyboard events can be * missing, so the keyboard counts as possibly shown, as in React Native. * * @internal */ export const focus: { node: NativeNode | undefined keyboard: number | undefined unreliable: boolean } = { node: undefined, keyboard: undefined, unreliable: false } /** * Blurs the focused view if it's still mounted, which hides the keyboard. * * @internal */ export const blurFocused = (): void => { const node = focus.node if (node !== undefined && mounted(node)) node.host.command(node, "blur") } /** * iOS can report dismissal as a frame change without a hide event. * * @internal */ export const offScreen = (device: Device, frame: any): boolean => { const screen = dimensions(device).get().screen.height return frame == null || frame.height <= 0 || (screen > 0 && frame.screenY >= screen) } const tracked = new WeakSet() /** Follows the device's keyboard events. @internal */ export const trackKeyboard = (device: Device): void => { if (tracked.has(device)) return tracked.add(device) for ( const event of [ "keyboardWillShow", "keyboardDidShow", "keyboardWillChangeFrame", "keyboardDidChangeFrame", "keyboardWillHide", "keyboardDidHide" ] ) { const shown = event.endsWith("Show") const moved = event.endsWith("Frame") observe(device, "KeyboardObserver", event, (e) => { const frame = e?.endCoordinates // A zero-height show event still counts as shown. focus.keyboard = shown ? frame?.height ?? 0 : moved && !offScreen(device, frame) ? frame.height : undefined }) } if (device.os === "android") { focus.unreliable = device.module("PlatformConstants")?.getConstants?.().Version < 30 } }