diff --git a/apps/mobile/src/components/ComposerToolbar.tsx b/apps/mobile/src/components/ComposerToolbar.tsx index cabaabd64a24..eaa23337a88f 100644 --- a/apps/mobile/src/components/ComposerToolbar.tsx +++ b/apps/mobile/src/components/ComposerToolbar.tsx @@ -1,6 +1,8 @@ import type { ComponentProps, ReactNode } from "react"; -import { useState } from "react"; +import { useLayoutEffect, useState } from "react"; import { + PixelRatio, + Platform, Pressable, ScrollView, View, @@ -12,7 +14,16 @@ import { type ViewStyle, } from "react-native"; -import Animated, { FadeIn, useReducedMotion } from "react-native-reanimated"; +import Animated, { + FadeIn, + runOnJS, + useAnimatedStyle, + useReducedMotion, + useSharedValue, + withDelay, + withTiming, + type SharedValue, +} from "react-native-reanimated"; import { cn } from "../lib/cn"; import { AppText as Text } from "./ui/AppText"; @@ -23,6 +34,18 @@ const COMPOSER_TOOLBAR_GAP = 8; const COMPOSER_TOOLBAR_FADE_WIDTH = 18; const COMPOSER_TOOLBAR_SCROLL_EPSILON = 4; const INLINE_CONTROL_LABEL_ENTERING = FadeIn.duration(160); +type LabelPhase = "shown" | "hiding" | "hidden" | "showing"; + +function slideLabel( + reveal: SharedValue, + target: 0 | 1, + setPhase: (phase: LabelPhase) => void, +) { + const slide = withTiming(target, { duration: target === 1 ? 180 : 120 }, (finished) => { + if (finished) runOnJS(setPhase)(target === 1 ? "shown" : "hidden"); + }); + reveal.set(target === 1 ? withDelay(100, slide) : slide); +} export function ComposerInlineControl(props: { readonly size?: "regular" | "large"; readonly accessibilityHint?: string; @@ -46,12 +69,77 @@ export function ComposerInlineControl(props: { const reducedMotion = useReducedMotion(); // Keep the picker anchored to its parent while the editor changes height. const animatesLabel = props.iconOnly !== undefined; + const revealsLabel = animatesLabel && Platform.OS !== "android" && !reducedMotion; const iconSize = props.size === "large" ? 20 : smallIconSize; + const chevronSize = Math.round((props.size === "large" ? 12 : 10) * scale); + const labelShown = !props.iconOnly; + const [phase, setPhase] = useState(labelShown ? "shown" : "hidden"); + const [labelWidth, setLabelWidth] = useState(0); + if (labelShown && (phase === "hidden" || phase === "hiding")) { + setPhase(revealsLabel ? "showing" : "shown"); + } + if (!labelShown && (phase === "shown" || phase === "showing")) { + setPhase(revealsLabel && labelWidth > 0 ? "hiding" : "hidden"); + } + const sliding = phase === "hiding" || phase === "showing"; + const reveal = useSharedValue(labelShown ? 1 : 0); + const revealWidth = useSharedValue(0); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- drives the Reanimated label slide on the UI thread when the label phase changes + useLayoutEffect(() => { + if (phase === "hiding") slideLabel(reveal, 0, setPhase); + else if (phase === "showing" && revealWidth.get() > 0) slideLabel(reveal, 1, setPhase); + else if (phase === "shown") reveal.set(1); + else if (phase === "hidden") reveal.set(0); + }, [phase, reveal, revealWidth]); + const [iconFrame, setIconFrame] = useState({ x: 8, y: 12, width: iconSize, height: iconSize }); + const [labelBox, setLabelBox] = useState({ y: 0, height: 44 }); + const pixelScale = PixelRatio.get(); + const [labelX, setLabelX] = useState(16 + iconSize); + const labelGap = labelX - iconFrame.x - iconFrame.width; + const [chevronInset, setChevronInset] = useState(16 + chevronSize); + const overlayStyle = useAnimatedStyle(() => ({ + width: + Math.round((iconFrame.width + reveal.value * (labelGap + revealWidth.value)) * pixelScale) / + pixelScale, + })); + const overlayLabelStyle = useAnimatedStyle(() => ({ + width: Math.round(reveal.value * revealWidth.value * pixelScale) / pixelScale, + })); + const recordLabelWidth = (width: number) => { + revealWidth.set(width); + if (width !== labelWidth) setLabelWidth(width); + }; + const tint = props.emphasized || props.selected ? "accent-icon" : "accent-icon-muted"; + const iconNode = props.renderIcon ? ( + + {props.renderIcon(iconSize)} + + ) : props.icon ? ( + + ) : null; + const labelContent = ( + <> + + {props.label} + + {props.suffix ? {props.suffix} : null} + + ); return ( - {props.renderIcon ? ( - - {props.renderIcon(iconSize)} - - ) : props.icon ? ( - { + const { x, y, width, height } = event.nativeEvent.layout; + if ( + x !== iconFrame.x || + y !== iconFrame.y || + width !== iconFrame.width || + height !== iconFrame.height + ) { + setIconFrame({ x, y, width, height }); } - type="monochrome" - /> + }} + > + {iconNode} + + {phase === "shown" || phase === "showing" ? ( + { + const { x, y, width, height } = event.nativeEvent.layout; + if (x !== labelX) setLabelX(x); + if (y !== labelBox.y || height !== labelBox.height) setLabelBox({ y, height }); + const firstMeasure = phase === "showing" && revealWidth.get() === 0; + recordLabelWidth(width); + if (firstMeasure) slideLabel(reveal, 1, setPhase); + }} + > + {labelContent} + ) : null} - {props.iconOnly ? null : ( + {sliding ? ( - - {props.label} - + {iconNode} + + + + {labelContent} + + - )} - {!props.iconOnly && props.suffix ? ( - {props.suffix} ) : null} {props.showChevron === false ? null : ( - + { + const { x, width } = event.nativeEvent.layout; + const inset = labelGap + width + iconFrame.x; + if (Math.abs(inset - chevronInset) > 0.5 && x > 0) setChevronInset(inset); + }} + > + + )} diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx index 016b75cfb305..432b7b4afae3 100644 --- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx +++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx @@ -13,9 +13,10 @@ import { AppBar } from "../../components/ui/AppBar"; import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics"; import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { useAtomMount } from "@effect/atom-react"; -import { useMemo, useRef, useState, useSyncExternalStore } from "react"; +import { useMemo, useRef, useState } from "react"; import { Platform, Pressable, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; +import { useKeyboardShowing } from "../../lib/keyboardShowing"; import { AppText as Text } from "../../components/ui/AppText"; import { TerminalContextSheet } from "./TerminalContextSheet"; import { hasNativeTerminalSurface, supportsNativeTerminalOutput } from "./nativeTerminalModule"; @@ -24,7 +25,6 @@ import * as Schema from "effect/Schema"; import { AsyncResult } from "effect/reactivity"; import { KeyboardController, - KeyboardEvents, KeyboardStickyView, useKeyboardState, } from "react-native-keyboard-controller"; @@ -352,26 +352,6 @@ function readLiveTerminalSessions( })); } -// `useKeyboardState` only flips on willShow and didHide; the accessory must -// leave as soon as the keyboard starts hiding, so it follows the will-events. -let keyboardShowing = KeyboardController.isVisible(); -function subscribeKeyboardShowing(onChange: () => void) { - keyboardShowing = KeyboardController.isVisible(); - const willShow = KeyboardEvents.addListener("keyboardWillShow", () => { - keyboardShowing = true; - onChange(); - }); - const willHide = KeyboardEvents.addListener("keyboardWillHide", () => { - keyboardShowing = false; - onChange(); - }); - return () => { - willShow.remove(); - willHide.remove(); - }; -} -const getKeyboardShowing = () => keyboardShowing; - function ThreadTerminal(props: { readonly params: ThreadTerminalRouteScreenProps["route"]["params"]; readonly routeEnvironmentId: EnvironmentId | null; @@ -589,7 +569,7 @@ function ThreadTerminal(props: { height: state.height, isVisible: state.isVisible, })); - const keyboardShowing = useSyncExternalStore(subscribeKeyboardShowing, getKeyboardShowing); + const keyboardShowing = useKeyboardShowing(); // The accessory follows the keyboard, except that the dismiss and show // buttons flip it ahead of the keyboard animation. const [accessory, setAccessory] = useState({ keyboardShowing, dismissed: false }); diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 52ef705e93b2..260880c432b1 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -31,10 +31,18 @@ import { } from "@t3tools/shared/usageLimits"; import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native"; import type { ReactNode } from "react"; -import { useEffect, useEffectEvent, useRef, useState, type RefObject } from "react"; +import { + useEffect, + useEffectEvent, + useLayoutEffect, + useRef, + useState, + type RefObject, +} from "react"; import { I18nManager, Keyboard, Platform, View, type ViewStyle } from "react-native"; import { composerImageGallery } from "../../lib/composerImageGallery"; import { filePreviewGallery } from "../../lib/filePreviewGallery"; +import { useKeyboardShowing } from "../../lib/keyboardShowing"; import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal"; import { composerAttachmentUploadBlockReason, @@ -113,6 +121,13 @@ import { ComposerDictationToolbar, } from "../voice-input/ComposerDictationControl"; import { useVoiceInputController } from "../voice-input/useVoiceInputController"; +import { + EMPTY_COMPACT_COMPOSER_SLOT, + compactSlotAfterLabelLayout, + compactSlotAfterRowLayout, + isWideComposerRow, + resolveCompactComposerLayout, +} from "./compactComposerLayout"; import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation"; import type { ExistingThreadSettingsRouteParams } from "./ThreadSettingsSheet"; import { @@ -122,6 +137,9 @@ import { export const COMPOSER_COLLAPSED_CHROME = 60; +// Only Android gates focus on the keyboard, so iOS never subscribes. +const useAndroidKeyboardShowing = Platform.OS === "android" ? useKeyboardShowing : () => false; + const NO_MACHINES: ReadonlyArray = []; const COLLAPSED_EDITOR_DEFAULT_INSET = 6; // iOS puts line-height slack above glyphs. DM Sans's lowercase midline is @@ -137,9 +155,22 @@ function collapsedEditorInset(text: ScaledTextRole): number { return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift)); } -function useCompactComposerEditor(text: ScaledTextRole, value: string) { +function useCompactComposerEditor( + text: ScaledTextRole, + value: string, + state: { + readonly isFocused: boolean; + readonly keepsSettingsOpen: boolean; + readonly rowAttachmentCount: number; + }, +) { const [contentSize, setContentSize] = useState({ width: 0, height: 0 }); - const [compactWidth, setCompactWidth] = useState(0); + const [slot, setSlot] = useState(EMPTY_COMPACT_COMPOSER_SLOT); + const keyboardShowing = useAndroidKeyboardShowing(); + // Only a keyboard that showed since focus and then hid closes the card, so a refocus that + // is still waiting for its keyboard (after the model sheet) keeps it open. + const [keyboardShownSinceFocus, setKeyboardShownSinceFocus] = useState(false); + if (keyboardShowing && !keyboardShownSinceFocus) setKeyboardShownSinceFocus(true); const contentHeight = contentSize.height; const rowWidth = useSharedValue(0); const editorX = useSharedValue(0); @@ -147,49 +178,131 @@ function useCompactComposerEditor(text: ScaledTextRole, value: string) { const inset = Platform.OS === "android" ? COLLAPSED_EDITOR_DEFAULT_INSET : collapsedEditorInset(text); const minimum = Math.max(INLINE_EDITOR_HEIGHT, Math.ceil(text.lineHeight) + 2 * inset); + const { isExpanded, modelIconOnly, labelShownAtRest } = resolveCompactComposerLayout({ + ...state, + slot, + keyboardDismissed: keyboardShownSinceFocus && !keyboardShowing, + value, + contentSize, + lineHeight: text.lineHeight, + fontSize: text.fontSize, + }); const height = Math.max( minimum, Math.min(text.lineHeight * 4 + 2 * inset, contentHeight + 2 * inset), ); - // A line that fits the expanded editor may still overflow its compact slot. - // Compare its measured width too so widening cannot trigger a collapse loop. - const isExpanded = - value.length > 0 && - (contentHeight > text.lineHeight * 1.5 || - (compactWidth > 0 && contentSize.width > compactWidth)); const compactRowHeight = Math.max(44, minimum); const isRTL = I18nManager.isRTL; - const editorStyle = useAnimatedStyle(() => ({ + const targetSurfaceHeight = isExpanded ? height + 52 : compactRowHeight; + const animatedHeight = useSharedValue(height); + const surfaceHeight = useSharedValue(targetSurfaceHeight); + const expansion = useSharedValue(Number(isExpanded)); + const expansionTarget = useRef({ expanded: isExpanded, pending: false }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- drives the Reanimated card open and close once the editor has laid out at its new width + useLayoutEffect(() => { + const config = { duration: 180, reduceMotion: ReduceMotion.System }; + if (Platform.OS === "android") { + animatedHeight.set(height); + surfaceHeight.set(targetSurfaceHeight); + expansion.set(Number(isExpanded)); + return; + } + const target = expansionTarget.current; + if (target.expanded === isExpanded && !target.pending) { + animatedHeight.set(withTiming(height, config)); + surfaceHeight.set(withTiming(targetSurfaceHeight, config)); + return; + } + target.expanded = isExpanded; + target.pending = true; + // Wrapping settles at the destination width a frame later; animating sooner overshoots. + let nextFrame: number | undefined; + const frame = requestAnimationFrame(() => { + nextFrame = requestAnimationFrame(() => { + target.pending = false; + animatedHeight.set(withTiming(height, config)); + surfaceHeight.set(withTiming(targetSurfaceHeight, config)); + expansion.set(withTiming(Number(isExpanded), config)); + }); + }); + return () => { + cancelAnimationFrame(frame); + if (nextFrame !== undefined) cancelAnimationFrame(nextFrame); + }; + }, [animatedHeight, expansion, height, isExpanded, surfaceHeight, targetSurfaceHeight]); + const containerStyle = useAnimatedStyle(() => ({ + height: surfaceHeight.value, + })); + const editorStyle = useAnimatedStyle(() => { + const compact = compactEditorInsets({ + slotX: editorX.value, + slotWidth: editorWidth.value, + rowWidth: rowWidth.value, + isRTL, + }); + const restBottom = (compactRowHeight - minimum) / 2; + return { + position: "absolute", + overflow: "hidden", + height: animatedHeight.value, + left: compact.left + expansion.value * (14 - compact.left), + right: compact.right + expansion.value * (14 - compact.right), + bottom: restBottom + expansion.value * (52 - restBottom), + }; + }); + const editorContentStyle = useAnimatedStyle(() => ({ position: "absolute", - overflow: "hidden", - height, - ...(isExpanded - ? { left: 14, right: 14 } - : compactEditorInsets({ - slotX: editorX.value, - slotWidth: editorWidth.value, - rowWidth: rowWidth.value, - isRTL, - })), - // The full-width editor must move above the controls in the same frame it widens. - bottom: isExpanded ? 52 : (compactRowHeight - minimum) / 2, + top: 0, + bottom: 0, + start: 0, + width: Math.max(0, isExpanded ? rowWidth.value - 28 : editorWidth.value - 8), + transform: [ + { + translateY: isExpanded + ? (1 - expansion.value) * ((minimum - text.lineHeight) / 2 - inset) + : 0, + }, + ], })); return { isExpanded, - containerStyle: { height: isExpanded ? height + 52 : compactRowHeight }, + modelIconOnly, + rowWidth: slot.rowWidth, + containerStyle, editorStyle, + editorContentStyle, onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => { - rowWidth.set(event.nativeEvent.layout.width); + const width = event.nativeEvent.layout.width; + rowWidth.set(width); + setSlot((current) => compactSlotAfterRowLayout(current, width)); }, onEditorLayout: (event: { nativeEvent: { layout: { x: number; width: number } } }) => { // The expanded toolbar gives this slot to the model control. Keep the // compact geometry for the return transition, rather than recording zero. if (!isExpanded) { - editorX.set(event.nativeEvent.layout.x); - editorWidth.set(event.nativeEvent.layout.width); - setCompactWidth(Math.max(0, event.nativeEvent.layout.width - 8)); + const { x, width } = event.nativeEvent.layout; + editorX.set(x); + editorWidth.set(width); + const compactWidth = Math.max(0, width - 8); + const attachmentCount = state.rowAttachmentCount; + setSlot((current) => + current.compactWidth === compactWidth && current.attachmentCount === attachmentCount + ? current + : { ...current, compactWidth, attachmentCount }, + ); } }, + onEditorFocus: () => setKeyboardShownSinceFocus(false), + onModelControlLayout: (event: { nativeEvent: { layout: { width: number } } }) => { + const { width } = event.nativeEvent.layout; + setSlot((current) => + compactSlotAfterLabelLayout(current, { + width, + isExpanded, + shownAtRest: labelShownAtRest, + }), + ); + }, editorProps: { singleLineCentered: !isExpanded, scrollEnabled: Platform.OS === "android" || contentHeight >= text.lineHeight * 4, @@ -583,9 +696,13 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const usesLargeControls = useSidebarWorkspaceTabs() === "picker" || (Platform.OS === "ios" && Platform.isPad); const surfacePaddingVertical = usesLargeControls ? 9 : floatingSidebarComposer ? 6 : 2; - const [compactRowWidth, setCompactRowWidth] = useState(0); - const compactAttachmentLimit = compactRowWidth >= 500 ? 3 : 1; - const compactEditor = useCompactComposerEditor(bodyText, draftMessage); + const compactEditor = useCompactComposerEditor(bodyText, draftMessage, { + // Dictation hides the editor and keeps focus, so the card would be an empty band. + isFocused: isFocused && !isVoiceInputPresented, + keepsSettingsOpen: settingsSheetPresentation.keepsComposerExpanded, + rowAttachmentCount: isExpanded ? 0 : stripAttachments.length, + }); + const compactAttachmentLimit = isWideComposerRow(compactEditor.rowWidth) ? 3 : 1; const showsCompactDictation = isVoiceInputPresented; const isToolbarVisible = isVoiceInputPresented; const hasEditingAttachments = @@ -649,6 +766,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const onEditorFocusChange = props.onEditorFocusChange; const handleFocus = () => { setIsFocused(true); + compactEditor.onEditorFocus(); settingsSheetPresentation.onEditorFocusChange(true); onEditorFocusChange?.(true); setComposerEditing(true); @@ -789,7 +907,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps ) : null; const modelControl = ( - + @@ -882,12 +1000,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps }} > {isExpanded ? editingAttachments : null} - { - compactEditor.onRowLayout(event); - setCompactRowWidth(event.nativeEvent.layout.width); - }} - > + -