fix(app): land the fullscreen composer toggle with its layout on every screen

With the keyboard open, entering fullscreen drew one frame of the fullscreen
layout at the inline keyboard lift: Send 310pt too high and the text off
screen. New workspace showed it on about half of the enters and a chat on
about one in eight.

The iOS translate view changed mode through two writers that nothing orders
with the mount. A layout-effect setNativeProps put the resting lift in the
shadow tree after React's commit, so React's own commit still carried the old
mode, and the native driver flipped the mode on its own queue. New workspace
drops its header in fullscreen, which resizes the translated surface, and
Fabric repaints a driven view's committed transform on resize: the stale one.
A chat never resized the surface, so only the driver's timing decided the
frame.

The translate view now commits where it rests as a React prop, from the
keyboard's target shift held in React state, so the commit that carries a
layout carries its lift. The driver follows a frame later, after the mount.
The dock moves the content and the composer slot with two translate views and
puts the mode on the slot, which fullscreen resizes on every screen, so a chat
and New workspace take the same path.

The fullscreen device check now records the screen through eight toggles on a
draft tab and on New workspace and fails on any frame that draws Send away
from its two resting places. Its snapshots are a second apart and passed
against the bug.
This commit is contained in:
Mohamed Boudra
2026-11-29 18:18:14 +01:00
parent 704a7c3055
commit eb462ab659
8 changed files with 309 additions and 123 deletions
+25 -11
View File
@@ -194,9 +194,23 @@ signal because the stock iOS Reanimated value changes at move start, while
writing a replacement Reanimated value every frame interrupts UIKit's hide
animation. Keep this platform choice inside the keyboard module's private platform-specific translate files.
`ComposerDock` always keeps the surface at full height and wraps it in
`KeyboardTranslateView`. The panel root clips it at the header edge, so rows
slide under the header on open and out from under it on close. Do not swap the
On iOS the native driver and Fabric both write the view's transform, and
nothing orders a driver update with a mount. The translate view therefore
commits where it rests as a React prop. Fabric paints a driven view's committed
transform when it creates or resizes the view, in the same mount as the layout,
and the driver follows a frame later. Change `enabled` on the translate view
that the change resizes. Without a resize the old lift stays on screen until the
driver catches up, and a mode sent to the driver from the commit can paint over
the old layout: either way one frame draws the new layout at the old lift.
`ComposerDock` keeps the surface at full height and moves it with two
`KeyboardTranslateView`s on the same translation: one holds the content, one
holds the composer slot. Only the slot changes mode for fullscreen, and
fullscreen resizes it on every screen. Do not put the mode on one view around
both: that view resizes on New workspace, which drops its header, and not in a
chat, so the two screens land the toggle differently. The panel root clips the
surface at the header edge, so rows slide under the header on open and out from
under it on close. Do not swap the
dock to keyboard padding at rest. Changing its height creates either a blank
band or a paused transition when the stream list updates its viewport.
@@ -231,7 +245,7 @@ instead of expanding on close and shrinking again on open.
Fullscreen is a layout mode of the dock, not a second editor. `ComposerDock
fullscreen` fills the stationary viewport with the composer slot over the
still-mounted content, paints its own surface under the safe areas, and turns
the surface translation off. The composer's single tree keeps the editing
the slot's translation off. The content behind it keeps riding the keyboard. The composer's single tree keeps the editing
surface at the same position in both modes, so the mounted editor, its native
buffer, selection, and focus survive the toggle and Send's clear always reaches
the live input. A viewport crossing the compact breakpoint still remounts it:
@@ -278,8 +292,8 @@ for header clearance, but reserves the composer's own capped height before
shrinking the setup scroll view. The form must not take editing space from the
composer.
Move the stream and composer together through `ComposerDock`. Do not translate
them independently.
Move the stream and composer through `ComposerDock`, which gives both the same
translation. Do not translate either from outside the dock.
`KeyboardShiftProvider` owns the normalized shift used for settled insets and
portal geometry, plus the `isMoving` worklet value. It reconciles native
@@ -302,9 +316,9 @@ translation scope is React context and does not cross it (Gotcha 7). It returns:
Do not measure an anchor with `measureInWindow` and correct it by the keyboard
shift. On iOS the translate view uses the native driver, which moves the view
without updating the shadow tree. The translate view commits the resting lift to
the shadow tree once the keyboard settles, so `measureInWindow` includes the lift
at rest and misses it while the keyboard moves. Any correction double-lifts the
without updating the shadow tree. The translate view commits the lift the
keyboard is at or moving to, so `measureInWindow` includes the lift at rest and
runs ahead of the view while the keyboard moves. Any correction double-lifts the
popover or leaves it behind the keyboard. `measureAtRest` measures through
Fabric's transform-free `measureLayout` instead. Re-measure when `isMoving`
settles; the composer's resting position changes as the draft grows.
@@ -316,8 +330,8 @@ the anchor's rect against the layer and commits the placement with `flushSync`,
which runs after layout and before paint. On native a Reanimated frame callback
reads only the anchor's height on the UI thread and holds its bottom edge at
the rest measurement. A height carries no transform. On iOS the absolute
position does not include one while the keyboard moves: the lift runs on the
native driver and reaches the shadow tree only at rest. The
position does not follow the keyboard while it moves: the lift runs on the
native driver, and the shadow tree holds only where the keyboard is going. The
fixed-bottom model is wrong for the centered New workspace composer on tablets,
which grows around its middle, and for width or x changes. The popover is off
there by half the growth, or by the old width, until the next rest measurement.
+8 -3
View File
@@ -131,9 +131,14 @@ file mentions. Set `_SCENARIO=controls` to tap the attach button and the model
selector with a 3pt drag while the keyboard is open, then check that a wide
layout's model popover clears both the trigger and the keyboard. Run it on an
iPhone and on the iPhone Duo unfolded. Set `_SCENARIO=fullscreen` to toggle an
eight-line draft in and out of fullscreen with the keyboard open. Every toggle
must keep the keyboard, fullscreen must cover the screen behind the keyboard
with Send above it, and exit must return the composer to its resting place. These scenarios only need `_SERVER_ID` and `_WORKSPACE_ID`;
eight-line draft in and out of fullscreen with the keyboard open, on a workspace
draft tab and on New workspace. Every toggle must keep the keyboard, fullscreen
must cover the screen behind the keyboard with Send above it, and exit must
return the composer to its resting place. It then records the screen through
eight toggles and fails if any frame draws Send anywhere but its inline or its
fullscreen place; snapshots are a second apart and cannot see one wrong frame.
The recording needs `ffmpeg` on the PATH and reads the booted simulator unless
`_UDID` is set. These scenarios only need `_SERVER_ID` and `_WORKSPACE_ID`;
`_UDID` selects an exact simulator and `_ARTIFACTS_DIR` overrides the output path.
The Android sidebar scroll-retention flow requires a connected host with enough
+165 -22
View File
@@ -1,7 +1,7 @@
// Composer autocomplete placement on iOS with the software keyboard: chat, workspace
// draft tab, and New workspace. Run where agent-device reaches the simulator, with the
// development app connected to the fixture host. See docs/mobile-testing.md.
import { execFileSync } from "node:child_process";
import { execFileSync, spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
@@ -417,9 +417,18 @@ async function assertFullscreenToggleHolds(name, place) {
process.stdout.write(`PASS ${name}: keyboard open and placement held over ${samples} samples\n`);
}
// New workspace submits with Create where a chat has Send.
const sendButton = (snap) =>
snap.data.nodes.find(
(node) =>
node.type === "Button" &&
node.rect &&
(node.label === "Send message" || node.identifier === "workspace-create-submit"),
)?.rect;
const enteredFullscreen = (snap, keyboard) => {
const frame = nodeById(snap, "composer-fullscreen")?.rect;
const send = snap.data.nodes.find((node) => node.label === "Send message" && node.rect)?.rect;
const send = sendButton(snap);
if (!frame || !send) return "fullscreen composer or Send is missing";
// The frame fills the screen below the safe area, behind the keyboard.
if (frame.y < 0 || frame.y + frame.height < keyboard)
@@ -440,33 +449,162 @@ const exitedFullscreen = (resting) => (snap) => {
return null;
};
async function runFullscreenToggles() {
await clearInput("fullscreen");
ad("type", fullscreenDraft);
const typed = nodeById(
await settledWithKeyboard("fullscreen-typed", "message-input-root"),
"message-input-root",
).rect;
const resting = typed.y + typed.height;
// Snapshots sample about once a second, so they cannot see one wrong frame. Record the
// screen through a run of toggles instead: Send has one place inline and one in
// fullscreen, and every recorded frame must draw it at one of the two. A keyboard lift
// that landed a frame after its layout drew Send 310pt higher for that frame. Needs
// ffmpeg on the PATH.
async function assertSendHoldsEveryFrame(name, { screen, keyboard, sends, toggle }) {
const video = path.join(artifactsDir, `${name.replaceAll(" ", "-")}.mp4`);
const recorder = spawn(
"xcrun",
["simctl", "io", udid ?? "booted", "recordVideo", "--codec", "h264", "--force", video],
{ stdio: ["ignore", "ignore", "pipe"] },
);
const finished = new Promise((resolve) => recorder.once("exit", resolve));
await new Promise((resolve, reject) => {
recorder.stderr.on("data", (chunk) => {
if (String(chunk).includes("Recording started")) resolve();
});
finished.then(() => reject(new Error(`${name}: the screen recording did not start`)));
});
// The first frame is the settled inline composer.
await sleep(500);
await toggle();
await sleep(1_000);
recorder.kill("SIGINT");
await finished;
// Decode the column of the screen that holds Send in both modes, one pixel per point.
const left = Math.floor(Math.min(...sends.map((send) => send.x)));
const right = Math.ceil(Math.max(...sends.map((send) => send.x + send.width)));
const width = right - left;
const height = Math.round(screen.height);
const column = `crop=iw*${width / screen.width}:ih:iw*${left / screen.width}:0,scale=${width}:${height}`;
const pixels = execFileSync(
"ffmpeg",
["-loglevel", "fatal", "-i", video, "-fps_mode", "passthrough", "-vf", column].concat([
"-f",
"rawvideo",
"-pix_fmt",
"rgb24",
"-",
]),
{ maxBuffer: 1024 ** 3 },
);
const frameSize = width * height * 3;
const frameCount = Math.floor(pixels.length / frameSize);
if (frameCount < 2) throw new Error(`${name}: the recording holds ${frameCount} frames`);
// Send's colour is the commonest one in the middle of its inline rect.
const [inline] = sends;
const counts = new Map();
for (let y = inline.y + inline.height / 4; y < inline.y + (inline.height * 3) / 4; y += 1) {
for (let x = inline.x + inline.width / 4; x < inline.x + (inline.width * 3) / 4; x += 1) {
const at = (Math.round(y) * width + Math.round(x - left)) * 3;
const colour = (pixels[at] >> 3) * 1024 + (pixels[at + 1] >> 3) * 32 + (pixels[at + 2] >> 3);
counts.set(colour, (counts.get(colour) ?? 0) + 1);
}
}
const [accent] = [...counts].sort((a, b) => b[1] - a[1])[0];
const isAccent = (at) =>
Math.abs((pixels[at] >> 3) - Math.floor(accent / 1024)) <= 2 &&
Math.abs((pixels[at + 1] >> 3) - (Math.floor(accent / 32) % 32)) <= 2 &&
Math.abs((pixels[at + 2] >> 3) - (accent % 32)) <= 2;
// The vertical centre of the rows Send's colour fills, above the keyboard.
const sendCentre = (frame) => {
const rows = [];
for (let y = 0; y < Math.floor(keyboard); y += 1) {
let filled = 0;
for (let x = 0; x < width; x += 1) {
if (isAccent(frame * frameSize + (y * width + x) * 3)) filled += 1;
}
if (filled >= inline.width * 0.4) rows.push(y);
}
return rows.length > 0 ? (rows[0] + rows.at(-1) + 1) / 2 : null;
};
const places = [];
for (let frame = 0; frame < frameCount; frame += 1) {
const centre = sendCentre(frame);
const known = places.some(
(place) =>
place === centre || (place !== null && centre !== null && Math.abs(place - centre) <= 2),
);
if (known) continue;
if (places.length === 2) {
const drawn = centre === null ? "did not draw Send" : `drew Send at ${Math.round(centre)}`;
throw new Error(
`${name}: frame ${frame + 1} of ${frameCount} ${drawn}; it rests at ${places.map((place) => (place === null ? "nowhere" : Math.round(place))).join(" and ")}. See ${video}`,
);
}
places.push(centre);
}
if (places.length !== 2 || places.includes(null))
throw new Error(`${name}: expected Send at two places, saw ${places.join(" and ")}`);
process.stdout.write(
`PASS ${name}: Send drawn only at ${places.map(Math.round).join(" and ")} over ${frameCount} frames\n`,
);
}
async function runFullscreenToggles(host) {
// The enter glyph sits in the input's own padding, so selectors report it covered.
const pressButton = (name, label) => {
const button = snapshot(name).data.nodes.find(
const buttonCentre = (name, snap, label) => {
const button = snap.data.nodes.find(
(node) => node.type === "Button" && node.label === label && node.rect,
)?.rect;
if (!button) throw new Error(`${name}: missing ${label}`);
ad(
"press",
return [
String(Math.round(button.x + button.width / 2)),
String(Math.round(button.y + button.height / 2)),
);
];
};
const pressButton = (name, label) => ad("press", ...buttonCentre(name, snapshot(name), label));
// A run that failed in fullscreen leaves the composer there.
if (nodeById(snapshot(`${host}-fullscreen-start`), "composer-fullscreen"))
pressButton(`${host} fullscreen start`, "Exit fullscreen");
await clearInput(`${host}-fullscreen`);
ad("type", fullscreenDraft);
const typed = nodeById(
await settledWithKeyboard(`${host}-fullscreen-typed`, "message-input-root"),
"message-input-root",
).rect;
const resting = typed.y + typed.height;
for (let round = 1; round <= 4; round += 1) {
pressButton(`fullscreen enter ${round} button`, "Fullscreen");
await assertFullscreenToggleHolds(`fullscreen enter ${round}`, enteredFullscreen);
pressButton(`fullscreen exit ${round} button`, "Exit fullscreen");
await assertFullscreenToggleHolds(`fullscreen exit ${round}`, exitedFullscreen(resting));
pressButton(`${host} fullscreen enter ${round} button`, "Fullscreen");
await assertFullscreenToggleHolds(`${host} fullscreen enter ${round}`, enteredFullscreen);
pressButton(`${host} fullscreen exit ${round} button`, "Exit fullscreen");
await assertFullscreenToggleHolds(
`${host} fullscreen exit ${round}`,
exitedFullscreen(resting),
);
}
await clearInput("fullscreen-done");
const inline = snapshot(`${host}-fullscreen-frames-inline`);
const enter = buttonCentre(`${host} fullscreen frames`, inline, "Fullscreen");
ad("press", ...enter);
const entered = await waitFor(`${host}-fullscreen-frames-entered`, (snap) =>
Boolean(nodeById(snap, "composer-fullscreen") && sendButton(snap)),
);
const exit = buttonCentre(`${host} fullscreen frames`, entered, "Exit fullscreen");
ad("press", ...exit);
await waitFor(
`${host}-fullscreen-frames-exited`,
(snap) => !nodeById(snap, "composer-fullscreen"),
);
await assertSendHoldsEveryFrame(`${host} fullscreen frames`, {
screen: inline.data.nodes.find((node) => node.type === "Application").rect,
keyboard: keyboardTop(inline),
sends: [sendButton(inline), sendButton(entered)],
toggle: async () => {
for (let round = 1; round <= 8; round += 1) {
ad("press", ...enter);
await sleep(600);
ad("press", ...exit);
await sleep(600);
}
},
});
await clearInput(`${host}-fullscreen-done`);
}
if (scenario !== "all") {
@@ -481,8 +619,13 @@ if (scenario !== "all") {
if (scenario === "growth") await runLiveGrowth();
else if (scenario === "previews") await runBoundedPreview();
else if (scenario === "controls") await runControlTaps();
else if (scenario === "fullscreen") await runFullscreenToggles();
else throw new Error(`Unknown scenario: ${scenario}`);
else if (scenario === "fullscreen") {
await runFullscreenToggles("draft");
// New workspace hides its header in fullscreen, which resizes the dock on each toggle.
ad("open", `paseo://new?serverId=${serverId}`, "--platform", "ios", ...deviceArgs);
await waitFor("new-workspace", (snap) => Boolean(nodeById(snap, "message-input-root")), 60_000);
await runFullscreenToggles("new-workspace");
} else throw new Error(`Unknown scenario: ${scenario}`);
process.stdout.write(`Composer ${scenario} regression passed. Artifacts: ${artifactsDir}\n`);
process.exit(0);
}
+39 -33
View File
@@ -232,46 +232,53 @@ export function ComposerDock({
</ComposerViewport>
);
}
// The conversation and the composer ride the keyboard as two views. Only the composer
// changes mode, and its view is the one fullscreen resizes on every screen, which is
// what lands the mode with the layout (see KeyboardTranslateView).
return (
<ComposerViewport
style={dockStyles.viewport}
keyboardGap={placement.keyboardGap}
fullscreen={fullscreen}
>
<KeyboardTranslateView
style={dockStyles.surface}
enabled={!fullscreen}
keyboardGap={placement.keyboardGap}
>
<View
testID="composer-dock-content"
collapsable={false}
style={dockStyles.content}
pointerEvents="box-none"
>
{/* A responder ancestor intercepts native scroll drags on Android Fabric.
Only unclaimed background touches may reach this sibling. */}
<ComposerDockBackground style={StyleSheet.absoluteFill} />
<View style={dockStyles.content} pointerEvents="box-none">
{content}
</View>
</View>
{conversationReservation.spacer}
<ComposerViewportContent
style={fullscreen ? dockStyles.fullscreenSlot : dockStyles.composer}
onLayout={conversationReservation.measureSlot}
>
<View style={dockStyles.surface}>
<KeyboardTranslateView style={dockStyles.surface} keyboardGap={placement.keyboardGap}>
<View
style={
fullscreen
? fullscreenSurface
: [dockStyles.composer, { paddingBottom: placement.restingPadding }]
}
testID="composer-dock-content"
collapsable={false}
style={dockStyles.content}
pointerEvents="box-none"
>
{composer}
{/* A responder ancestor intercepts native scroll drags on Android Fabric.
Only unclaimed background touches may reach this sibling. */}
<ComposerDockBackground style={StyleSheet.absoluteFill} />
<View style={dockStyles.content} pointerEvents="box-none">
{content}
</View>
</View>
</ComposerViewportContent>
</KeyboardTranslateView>
</KeyboardTranslateView>
{conversationReservation.spacer}
<KeyboardTranslateView
style={fullscreen ? StyleSheet.absoluteFill : dockStyles.composer}
enabled={!fullscreen}
keyboardGap={placement.keyboardGap}
>
<ComposerViewportContent
style={fullscreen ? dockStyles.fullscreenSurface : dockStyles.composer}
onLayout={conversationReservation.measureSlot}
>
<View
style={
fullscreen
? fullscreenSurface
: [dockStyles.composer, { paddingBottom: placement.restingPadding }]
}
>
{composer}
</View>
</ComposerViewportContent>
</KeyboardTranslateView>
</View>
{overlay}
</ComposerViewport>
);
@@ -284,9 +291,8 @@ const dockStyles = StyleSheet.create({
surface: { flex: 1 },
content: { flex: 1, justifyContent: "flex-end" },
composer: { width: "100%", flexShrink: 1 },
// Yoga applies minHeight after maxHeight, so these fill the viewport over the
// Yoga applies minHeight after maxHeight, so this fills the viewport over the
// inline cap that ComposerViewportContent keeps animating.
fullscreenSlot: { position: "absolute", top: 0, left: 0, right: 0, bottom: 0, minHeight: "100%" },
fullscreenSurface: { flex: 1, minHeight: "100%" },
centeredViewport: { flex: 1, alignItems: "center", justifyContent: "center" },
centered: { flexShrink: 1, width: "100%" },
@@ -13,6 +13,12 @@ export interface KeyboardShiftContextValue {
export const KeyboardShiftContext = createContext<KeyboardShiftContextValue | null>(null);
/**
* The shift the keyboard is at, or is moving to. React state, where the shared values
* above are not: it changes when a keyboard motion starts and ends, never per frame.
*/
export const KeyboardTargetShiftContext = createContext(0);
/** How the nearest KeyboardTranslateView moves its descendants with the keyboard. */
export interface KeyboardTranslation {
enabled: boolean;
@@ -11,8 +11,8 @@ export function measureInWindow(element: View): Promise<WindowRect> {
/**
* The element's window rect with `frame`'s own transform left out. Whether
* `measureInWindow` includes a transform depends on the driver: Reanimated commits
* it to the shadow tree every frame, the iOS translate view commits it only once the
* keyboard settles. Fabric's `measureLayout` and a view's `measure` origin ignore
* it to the shadow tree every frame, the iOS translate view commits only where the
* keyboard rests. Fabric's `measureLayout` and a view's `measure` origin ignore
* transforms. The frame's parent must not move with the keyboard; the composer dock
* is the only anchor host, and its parent is the stationary dock viewport.
*/
@@ -1,4 +1,4 @@
import { createElement, useEffect, useMemo, type ReactNode } from "react";
import { createElement, useEffect, useMemo, useState, type ReactNode } from "react";
import { Platform } from "react-native";
import type { ViewStyle } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -12,13 +12,14 @@ import {
useSharedValue,
type SharedValue,
} from "react-native-reanimated";
import { scheduleOnRN } from "react-native-worklets";
import {
DEFAULT_IOS_KEYBOARD_INSET_MIN_HEIGHT,
resolveKeyboardShift,
reserveKeyboardLayoutShift,
shouldReconcileHiddenKeyboardEnd,
} from "./policy";
import { KeyboardShiftContext, useKeyboardShift } from "./context";
import { KeyboardShiftContext, KeyboardTargetShiftContext, useKeyboardShift } from "./context";
type KeyboardShiftMode = "translate" | "padding";
@@ -29,6 +30,7 @@ export function KeyboardShiftProvider({ children }: { children: ReactNode }) {
const isIos = Platform.OS === "ios";
const isMoving = useSharedValue(false);
const layoutShift = useSharedValue(0);
const [targetShift, setTargetShift] = useState(0);
useEffect(() => {
bottomInset.value = insets.bottom;
}, [bottomInset, insets.bottom]);
@@ -61,6 +63,7 @@ export function KeyboardShiftProvider({ children }: { children: ReactNode }) {
phase: "start",
});
isMoving.value = true;
scheduleOnRN(setTargetShift, target);
},
onEnd: (event) => {
"worklet";
@@ -81,6 +84,7 @@ export function KeyboardShiftProvider({ children }: { children: ReactNode }) {
keyboardProgress.value = 0;
}
isMoving.value = false;
scheduleOnRN(setTargetShift, target);
},
},
[bottomInset, isIos, isMoving, keyboardHeight, keyboardProgress, layoutShift],
@@ -96,7 +100,11 @@ export function KeyboardShiftProvider({ children }: { children: ReactNode }) {
[bottomInset, isMoving, layoutShift, shift],
);
return createElement(KeyboardShiftContext.Provider, { value }, children);
return createElement(
KeyboardShiftContext.Provider,
{ value },
createElement(KeyboardTargetShiftContext.Provider, { value: targetShift }, children),
);
}
export function useKeyboardShiftStyle(input: { mode: KeyboardShiftMode; enabled?: boolean }): {
@@ -1,10 +1,8 @@
import { useCallback, useLayoutEffect, useMemo, useRef, type ReactNode } from "react";
import { Animated, useAnimatedValue, type View, type ViewProps } from "react-native";
import { useContext, useEffect, useMemo, useRef, type ReactNode, type Ref } from "react";
import { Animated, useAnimatedValue, View, type ViewProps } from "react-native";
import { useKeyboardAnimation } from "react-native-keyboard-controller";
import { useAnimatedReaction } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { scheduleOnRN } from "react-native-worklets";
import { KeyboardTranslationContext, useKeyboardShift } from "./context";
import { KeyboardTargetShiftContext, KeyboardTranslationContext } from "./context";
import { useKeyboardTranslationScope } from "./measure";
import { resolveKeyboardLift } from "./policy";
@@ -20,6 +18,27 @@ interface KeyboardTranslateViewProps extends ViewProps {
keyboardGap?: number;
}
/**
* The view the native driver moves. Animated renders a driven transform from its JS-side
* value, and the keyboard's values never reach JS, so React would commit an unlifted view.
* This commits where the view rests instead, which is what Fabric paints when it creates
* or resizes the view, and what Pressability measures. The driver paints the frames in
* between.
*/
function RestingFrame({
restingTranslateY,
style,
...props
}: ViewProps & { restingTranslateY: number; ref?: Ref<View> }) {
const resting = useMemo(
() => ({ transform: [{ translateY: restingTranslateY }] }),
[restingTranslateY],
);
return <View {...props} style={[style, resting]} />;
}
const DrivenFrame = Animated.createAnimatedComponent(RestingFrame);
export function KeyboardTranslateView({
children,
enabled = true,
@@ -47,29 +66,34 @@ export function KeyboardTranslateView({
});
return Animated.add(lift, gap);
}, [bottomClearance, height, insets.bottom, keyboardGap, progress]);
// Fullscreen resizes this view while disabling translation. iOS Fabric can
// reapply its previous transform during that layout commit. Keep the graph
// attached and apply the mode on the native animation frame; a static zero or
// setValue during the React commit gets overwritten by the resize. Start it in a
// layout effect so it lands on the frame that paints the new layout; a passive
// effect left one frame of the old lift. A rebuilt graph (a new bottomClearance
// after rotation) starts from JS-side keyboard values, so run it on the native
// frame too or it stays stale until the keyboard next moves.
const enabledValue = useAnimatedValue(enabled ? 1 : 0);
useLayoutEffect(() => {
const animation = Animated.timing(enabledValue, {
toValue: enabled ? 1 : 0,
duration: 0,
useNativeDriver: true,
});
animation.start();
return () => animation.stop();
}, [enabled, enabledValue, translateY]);
const keyboardStyle = useMemo(
() => ({ transform: [{ translateY: Animated.multiply(translateY, enabledValue) }] }),
[enabledValue, translateY],
);
// A change of mode or clearance lands with the layout that carries it: the commit holds
// the new resting lift, and Fabric paints a driven view's committed transform when the
// commit resizes the view. A caller that changes `enabled` must do it on the view the
// change resizes; without a resize the old lift stays until the driver catches up below.
const targetShift = useContext(KeyboardTargetShiftContext);
const restingLift = resolveKeyboardLift({
shift: targetShift,
enabled,
bottomClearance,
keyboardGap,
});
// The driver catches up one frame later, when the commit has mounted. Its operations
// are not ordered with a mount: sent from the commit, they could paint the new mode
// over the old layout. After the mount they repaint what Fabric already painted. A
// rebuilt graph (a new bottomClearance after rotation) needs the same push, or it
// keeps the old lift until the keyboard next moves.
useEffect(() => {
const frame = requestAnimationFrame(() => enabledValue.setValue(enabled ? 1 : 0));
return () => cancelAnimationFrame(frame);
}, [enabled, enabledValue, translateY]);
const frameRef = useRef<View>(null);
const translation = useMemo(
() => ({ enabled, bottomClearance, keyboardGap }),
@@ -77,36 +101,16 @@ export function KeyboardTranslateView({
);
const scope = useKeyboardTranslationScope(frameRef, translation);
// The native driver moves the view without telling the shadow tree, and Pressability
// measures its press region there. With a stale region, a touch that drifts a few
// points leaves it and the press is dropped. Commit the lift once the keyboard settles.
// Fabric keeps a setNativeProps transform and carries it into every later commit of
// this view, so a mode change (fullscreen turning translation off or back on) commits
// the new resting lift right after the commit that changes the mode. Waiting for the
// keyboard to settle left the old lift on the resized view until the keyboard moved.
const { layoutShift, isMoving } = useKeyboardShift();
const translationRef = useRef(translation);
const commitRestingLift = useCallback((shift: number) => {
const lift = resolveKeyboardLift({ shift, ...translationRef.current });
frameRef.current?.setNativeProps({ transform: [{ translateY: -lift }] });
}, []);
useLayoutEffect(() => {
translationRef.current = translation;
commitRestingLift(layoutShift.value);
}, [commitRestingLift, layoutShift, translation]);
useAnimatedReaction(
() => (isMoving.value ? null : layoutShift.value),
(restingShift) => {
if (restingShift !== null) scheduleOnRN(commitRestingLift, restingShift);
},
[commitRestingLift],
);
return (
<Animated.View ref={frameRef} style={[style, keyboardStyle]} {...props}>
<DrivenFrame
ref={frameRef}
style={[style, keyboardStyle]}
restingTranslateY={-restingLift}
{...props}
>
<KeyboardTranslationContext.Provider value={scope}>
{children}
</KeyboardTranslationContext.Provider>
</Animated.View>
</DrivenFrame>
);
}