Files
openchamber/packages/ui/src/lib/hardwareKeyboard.ts
T
Serhii DziupinandSerhii Dziupin 86e6a2ae76 Remove verified dead declarations (#2714)
* chore: remove verified dead declarations

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* chore: narrow unused internal exports

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* chore: remove newly exposed dead helpers

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* chore: remove unused deep-link serializer

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* test: drop two tests that assert on copies of the code

mainLayoutMobileSidebarMount read MainLayout.tsx and SessionSidebar.tsx as
strings and asserted on source substrings down to exact indentation, so it
failed on formatting rather than behaviour. useProjectSessionSelection.test
reimplemented the hook's visitNodes logic inside the test file and asserted
against that copy, so it could not observe the hook at all.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* test: repair sync suites that had rotted while unrunnable

No runner executed packages/ui, so these drifted from the source unnoticed:
two imported helpers that are no longer exported, one directory-store stub
predated the session field routeMessage reads, and the WebSocket fake missed
the mandatory url-token mint plus the close event the socket wrapper reads.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* test: stop the web suite failing on timeouts and a hand-copied mock

The Git suites drive a real git binary, so the 5s default made a valid suite
fail differently per run. The gitApiHttp mock listed ~70 export names by hand
and fell behind the source; it now derives every stub from the real module,
which the added shared-UI aliases make resolvable.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* test: run every suite from one command and in CI

packages/ui (232 files) and packages/vscode (22) had no test script at all, CI
ran neither, and 9 vscode files could never run because Node cannot resolve
their extensionless TypeScript imports. Three electron files sat outside every
script list, one of them importing vitest, which that package does not depend
on. A runner gives each file its own process, since these suites keep
module-level singletons and fail by load order when sharing one.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* chore: delete a superseded repro harness and a completed plan

The issue-2638 harness needed lsof, overrode process.platform and spawned real
servers, and nothing referenced it; event-stream/rebind.test.js now covers the
same hub-pinned-to-the-old-port behaviour. The pairing v2 plan described relay
and the pairing UI as out of scope, both of which shipped.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* docs: point at the theme tools and record the github barrel invariant

convert-vscode-theme and harmonize-theme were referenced nowhere, so the
theme-authoring reference now names them. The github barrel is loaded through
await import('./index.js') and destructured per route, which no static report
can see; documenting that is what stops the next cleanup from deleting it.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* test: repair merge drift in bridge and route-registry mocks

upstream/main gained upsertProviderConfig on bridge-system-runtime and a
PATCH scheduled-task route after this branch forked. Their test doubles
were never updated to match:
- bridge-system-runtime.test.js: add upsertProviderConfig to the
  opencodeConfig mock so the import resolves.
- sse-routes.test.js: add app.patch to the route registry stub.

---------

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>
2026-08-13 15:30:54 +03:00

158 lines
5.7 KiB
TypeScript

/**
* "Is a hardware keyboard attached?" — the input the mobile layout uses to
* decide whether a soft keyboard will ever eat the screen.
*
* Two sources, in priority order:
*
* 1. The native answer. On iOS the shell reads `GCKeyboard` and stamps
* `window.__OPENCHAMBER_HARDWARE_KEYBOARD__` at document start, then keeps it
* live via `oc:hardware-keyboard` (see BridgeViewController). This is
* authoritative and — crucially — known BEFORE the user focuses anything, so
* the draft screen and composer start in the right shape instead of
* re-laying-out after the first focus.
* 2. Inference, for runtimes with no native answer (Android, hosted mobile).
* A `keyboardWillShow` with a real height means there IS a soft keyboard; a
* tiny height means only iOS' shortcut strip; focus with no event at all
* within a short window means nothing was presented. Inference is ignored
* entirely once the native source has spoken.
*
* Everything else stays `false`, which is the safe default: the layout then
* behaves exactly as it does on a phone.
*
* In memory only — a keyboard can be attached and detached while the app runs,
* and both sources re-answer the question continuously.
*/
import React from 'react';
/** Below this the "keyboard" is only iOS' shortcut bar, not a real keyboard. */
const SOFTWARE_KEYBOARD_MIN_HEIGHT_PX = 120;
/** iOS starts its keyboard animation well inside this window after focus. */
const KEYBOARD_EVENT_GRACE_MS = 600;
declare global {
interface Window {
__OPENCHAMBER_HARDWARE_KEYBOARD__?: boolean;
}
}
// Read at module init, not just from the bridge effect: the stamp exists from
// document start, and the very first render of the draft screen / composer must
// already see it — otherwise the layout still settles one frame late.
const initialNativeAnswer = typeof window !== 'undefined'
&& typeof window.__OPENCHAMBER_HARDWARE_KEYBOARD__ === 'boolean'
? window.__OPENCHAMBER_HARDWARE_KEYBOARD__
: null;
let hardwareKeyboardAttached = initialNativeAnswer === true;
let hasNativeAnswer = initialNativeAnswer !== null;
let focusProbeTimer: number | null = null;
let bridgeStarted = false;
const subscribers = new Set<() => void>();
if (hardwareKeyboardAttached && typeof document !== 'undefined') {
document.documentElement.classList.add('oc-hardware-keyboard');
}
const clearFocusProbe = (): void => {
if (focusProbeTimer === null) return;
window.clearTimeout(focusProbeTimer);
focusProbeTimer = null;
};
const setHardwareKeyboardAttached = (value: boolean): void => {
if (hardwareKeyboardAttached === value) return;
hardwareKeyboardAttached = value;
if (typeof document !== 'undefined') {
document.documentElement.classList.toggle('oc-hardware-keyboard', value);
}
for (const listener of subscribers) listener();
};
/**
* Adopt the native shell's answer and stop inferring. Idempotent; safe to call
* before the shell has stamped anything (then it is a no-op and inference
* stays in charge).
*/
export const startHardwareKeyboardBridge = (): (() => void) => {
if (typeof window === 'undefined') return () => {};
const adopt = (value: boolean) => {
hasNativeAnswer = true;
clearFocusProbe();
setHardwareKeyboardAttached(value);
};
if (typeof window.__OPENCHAMBER_HARDWARE_KEYBOARD__ === 'boolean') {
adopt(window.__OPENCHAMBER_HARDWARE_KEYBOARD__);
}
if (bridgeStarted) return () => {};
bridgeStarted = true;
const handleNativeChange = (event: Event) => {
const detail = (event as CustomEvent<{ attached?: boolean }>).detail;
adopt(detail?.attached === true);
};
window.addEventListener('oc:hardware-keyboard', handleNativeChange);
return () => {
window.removeEventListener('oc:hardware-keyboard', handleNativeChange);
bridgeStarted = false;
};
};
/**
* Feed a native `keyboardWillShow` height in. Called by the Capacitor keyboard
* bridge (see `mobileNativeChrome`) on both platforms. An arriving event always
* settles the question, so it cancels any pending focus probe.
*/
export const observeNativeKeyboardHeight = (heightPx: number): void => {
if (hasNativeAnswer || !Number.isFinite(heightPx)) return;
clearFocusProbe();
setHardwareKeyboardAttached(heightPx > 0 && heightPx < SOFTWARE_KEYBOARD_MIN_HEIGHT_PX);
};
/**
* Report that an editor just took focus. If no keyboard event follows, nothing
* was presented — which means a hardware keyboard is attached.
*
* Deliberately one-directional within the window: only the SILENCE concludes
* "hardware". A real `keyboardWillShow` cancels the probe above, so a slow
* keyboard can never be misread.
*/
export const observeEditorFocus = (): void => {
if (hasNativeAnswer || typeof window === 'undefined' || typeof document === 'undefined') return;
// A soft keyboard already up sends no second `keyboardWillShow` — a refocus
// through it (the overlay-close keyboard restore) would look like silence.
if (document.documentElement.classList.contains('oc-keyboard-open')) return;
clearFocusProbe();
focusProbeTimer = window.setTimeout(() => {
focusProbeTimer = null;
setHardwareKeyboardAttached(true);
}, KEYBOARD_EVENT_GRACE_MS);
};
/** Drop the inferred state when the native bridge tears down. */
export const resetHardwareKeyboardDetection = (): void => {
clearFocusProbe();
if (hasNativeAnswer) return;
setHardwareKeyboardAttached(false);
};
const isHardwareKeyboardAttached = (): boolean => hardwareKeyboardAttached;
const subscribeHardwareKeyboard = (listener: () => void): (() => void) => {
subscribers.add(listener);
return () => {
subscribers.delete(listener);
};
};
export function useHardwareKeyboard(): boolean {
return React.useSyncExternalStore(
subscribeHardwareKeyboard,
isHardwareKeyboardAttached,
() => false,
);
}