The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 283 lines 11.1 KB
Raw
1 import { useState, type ReactNode } from "react";
2 import { I18nManager, Platform, type ViewStyle } from "react-native";
3 import Animated, {
4 FadeIn,
5 type LayoutAnimationFunction,
6 ReduceMotion,
7 useAnimatedStyle,
8 useDerivedValue,
9 useSharedValue,
10 withTiming,
11 } from "react-native-reanimated";
12
13 import { useSafeAreaInsets } from "react-native-safe-area-context";
14
15 import { useAdaptiveWorkspaceLayout } from "../features/layout/AdaptiveWorkspaceLayout";
16 import { useSidebarWorkspaceTabs } from "../features/layout/workspace/useSystemWorkspaceTabBar";
17 import { useAndroidFloatingTabs } from "../features/settings/appearance/AppearancePreferencesProvider";
18 import { compactEditorInsets } from "../features/threads/compactEditorInsets";
19 import {
20 useDeviceType,
21 useDuoBottomBarInset,
22 useNativeLayoutMetrics,
23 } from "../native/native-layout-metrics";
24 import type { ScaledTextRole } from "../features/settings/appearance/useScaledTextRole";
25 import { MOBILE_TYPOGRAPHY } from "../lib/typography";
26 import { useUniwindTheme } from "../lib/useUniwindTheme";
27 import { GlassSurface } from "./ui/GlassSurface";
28
29 const COLLAPSED_EDITOR_DEFAULT_INSET = 6;
30 // iOS puts line-height slack above glyphs. DM Sans's lowercase midline is
31 // descender (0.31em) + half x-height (0.504em) above the line bottom.
32 const LOWERCASE_MIDLINE_EM = 0.562;
33
34 function lowercaseMidline(text: ScaledTextRole): number {
35 return text.lineHeight - LOWERCASE_MIDLINE_EM * text.fontSize;
36 }
37
38 function collapsedEditorInset(text: ScaledTextRole): number {
39 const shift = lowercaseMidline(text) - lowercaseMidline(MOBILE_TYPOGRAPHY.body);
40 return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift));
41 }
42
43 const EXPANDED_EDITOR_INSET = 14;
44 // Room under the expanded editor for the toolbar row.
45 const EXPANDED_EDITOR_BOTTOM = 52;
46
47 export function useCompactComposerEditor(text: ScaledTextRole, value: string, animate: boolean) {
48 const [contentSize, setContentSize] = useState({ width: 0, height: 0 });
49 const [compactWidth, setCompactWidth] = useState(0);
50 const contentHeight = contentSize.height;
51 const rowWidth = useSharedValue(0);
52 const editorX = useSharedValue(0);
53 const editorWidth = useSharedValue(0);
54 const inset =
55 Platform.OS === "android" ? COLLAPSED_EDITOR_DEFAULT_INSET : collapsedEditorInset(text);
56 const minimum = Math.max(INLINE_EDITOR_HEIGHT, Math.ceil(text.lineHeight) + 2 * inset);
57 const height = Math.max(
58 minimum,
59 Math.min(text.lineHeight * 4 + 2 * inset, contentHeight + 2 * inset),
60 );
61 // A line that fits the expanded editor may still overflow its compact slot.
62 // Compare its measured width too so widening cannot trigger a collapse loop.
63 const isExpanded =
64 value.length > 0 &&
65 (contentHeight > text.lineHeight * 1.5 ||
66 (compactWidth > 0 && contentSize.width > compactWidth));
67 const compactRowHeight = Math.max(44, minimum);
68 const compactBottom = (compactRowHeight - minimum) / 2;
69 const isRTL = I18nManager.isRTL;
70 const expandedRowHeight = height + EXPANDED_EDITOR_BOTTOM;
71 const expansion = useDerivedValue(() => {
72 const target = isExpanded ? 1 : 0;
73 return animate
74 ? withTiming(target, {
75 duration: COMPOSER_TRANSITION_DURATION_MS,
76 reduceMotion: ReduceMotion.System,
77 })
78 : target;
79 });
80 const editorStyle = useAnimatedStyle(() => {
81 const compactInsets = compactEditorInsets({
82 slotX: editorX.value,
83 slotWidth: editorWidth.value,
84 rowWidth: rowWidth.value,
85 isRTL,
86 });
87 const progress = expansion.value;
88 // Hanging from the row top lets the text ride the growing edge and ignore the stale
89 // height measured while it still wrapped in the compact slot. Layout props only:
90 // Reanimated applies transforms frames ahead of layout, which tore the text from its frame.
91 return {
92 position: "absolute",
93 overflow: "hidden",
94 // The compact slot is unknown until its first layout, so the editor would draw over the + button.
95 opacity: isExpanded || editorWidth.value > 0 ? 1 : 0,
96 height,
97 top: compactBottom * (1 - progress),
98 left: compactInsets.left + (EXPANDED_EDITOR_INSET - compactInsets.left) * progress,
99 // Snapping the far edge keeps the line from rewrapping while the near edge moves.
100 right: isExpanded ? EXPANDED_EDITOR_INSET : compactInsets.right,
101 };
102 });
103 const containerStyle = useAnimatedStyle(() => ({
104 height: compactRowHeight + (expandedRowHeight - compactRowHeight) * expansion.value,
105 }));
106 return {
107 isExpanded,
108 containerStyle,
109 // The expanded toolbar takes the row the text is leaving; reveal it once the text has lifted.
110 // An entering animation hides it from its first frame, which a shared-value opacity cannot.
111 toolbarControlsEntering:
112 animate && isExpanded
113 ? FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS / 2)
114 .duration(COMPOSER_TRANSITION_DURATION_MS / 2)
115 .reduceMotion(ReduceMotion.System)
116 : undefined,
117 editorStyle,
118 onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => {
119 rowWidth.set(event.nativeEvent.layout.width);
120 },
121 onEditorLayout: (event: { nativeEvent: { layout: { x: number; width: number } } }) => {
122 // The expanded toolbar gives this slot to the model control. Keep the
123 // compact geometry for the return transition, rather than recording zero.
124 if (!isExpanded) {
125 editorX.set(event.nativeEvent.layout.x);
126 editorWidth.set(event.nativeEvent.layout.width);
127 setCompactWidth(Math.max(0, event.nativeEvent.layout.width - 8));
128 }
129 },
130 editorProps: {
131 singleLineCentered: !isExpanded,
132 scrollEnabled: Platform.OS === "android" || contentHeight >= text.lineHeight * 4,
133 contentInsetVertical: inset,
134 onContentSizeChange: (size: { width: number; height: number }) => {
135 setContentSize(size);
136 },
137 style: { flex: 1 },
138 },
139 };
140 }
141
142 export const COMPOSER_TRANSITION_DURATION_MS = 220;
143 // Side panes animate dock width; nested horizontal transitions would make the surface trail the toolbar.
144 const composerHeightTransition: LayoutAnimationFunction = (values) => {
145 "worklet";
146 const timing = {
147 duration: COMPOSER_TRANSITION_DURATION_MS,
148 reduceMotion: ReduceMotion.System,
149 };
150 return {
151 initialValues: {
152 originX: values.targetOriginX,
153 originY: values.currentOriginY,
154 width: values.targetWidth,
155 height: values.currentHeight,
156 },
157 animations: {
158 originX: values.targetOriginX,
159 originY: withTiming(values.targetOriginY, timing),
160 width: values.targetWidth,
161 height: withTiming(values.targetHeight, timing),
162 },
163 };
164 };
165 const COMPOSER_LAYOUT_TRANSITION = Platform.OS === "android" ? undefined : composerHeightTransition;
166 // Share of the one-row composer the draft keeps; a long model name truncates first.
167 export const INLINE_EDITOR_MIN_WIDTH = "40%";
168 const INLINE_EDITOR_HEIGHT = 36;
169
170 const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface);
171
172 export function ComposerSurface(props: {
173 readonly children: ReactNode;
174 readonly style: ViewStyle;
175 readonly animateLayout?: boolean;
176 }) {
177 const colors = useUniwindTheme();
178 const targetBorderRadius =
179 typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0;
180 const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android";
181 const animatedBorderRadius = useDerivedValue(() =>
182 shouldAnimate
183 ? withTiming(targetBorderRadius, {
184 duration: COMPOSER_TRANSITION_DURATION_MS,
185 reduceMotion: ReduceMotion.System,
186 })
187 : targetBorderRadius,
188 );
189 const borderCurve = props.style.borderCurve;
190 const animatedShapeStyle = useAnimatedStyle(() => ({
191 borderRadius: animatedBorderRadius.value,
192 ...(borderCurve ? { borderCurve } : {}),
193 }));
194 const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined;
195
196 // Animate every native frame or glass and content jump to final height inside the clip.
197 return (
198 <Animated.View
199 className={
200 Platform.OS === "android" ? undefined : "shadow-[0_6px_28px] shadow-adaptive-black-a15-a35"
201 }
202 layout={layoutTransition}
203 style={[
204 animatedShapeStyle,
205 {
206 overflow: "hidden",
207 },
208 ]}
209 >
210 <AnimatedGlassSurface
211 chrome="none"
212 fallbackColor={colors["--color-composer-surface"]}
213 fallbackClassName="border border-composer-border"
214 glassEffectStyle="regular"
215 pointerEvents="none"
216 tintColor="transparent"
217 layout={layoutTransition}
218 style={[{ position: "absolute", inset: 0 }, animatedShapeStyle]}
219 >
220 {null}
221 </AnimatedGlassSurface>
222 <Animated.View
223 collapsable={false}
224 layout={layoutTransition}
225 style={[props.style, animatedShapeStyle]}
226 >
227 {props.children}
228 </Animated.View>
229 </Animated.View>
230 );
231 }
232
233 /** Space below the composer pill, inside the bottom inset it is given. */
234 export const COMPOSER_BOTTOM_GUTTER = 6;
235
236 /** Control size and pill shape: larger beside a sidebar tab picker and on iPad. */
237 export function useComposerChrome() {
238 const { layout } = useAdaptiveWorkspaceLayout();
239 const floatingSidebarComposer = useAndroidFloatingTabs() && layout.usesSplitView;
240 const sidebarWorkspaceTabs = useSidebarWorkspaceTabs();
241 const deviceType = useDeviceType();
242 const usesLargeControls = sidebarWorkspaceTabs === "picker" || deviceType === "pad";
243 return {
244 usesLargeControls,
245 controlSize: usesLargeControls ? ("large" as const) : ("regular" as const),
246 borderRadius: usesLargeControls ? 31 : 27,
247 paddingVertical: usesLargeControls ? 9 : floatingSidebarComposer ? 6 : 2,
248 };
249 }
250
251 /**
252 * The inset below a composer pinned to the bottom of a page. Fixed while the keyboard animates:
253 * changing it at keyboardDidHide makes the composer land low, then jump back above the safe area.
254 */
255 export function useComposerBottomInset() {
256 const insets = useSafeAreaInsets();
257 const windowMetrics = useNativeLayoutMetrics();
258 const { layout } = useAdaptiveWorkspaceLayout();
259 const bottomBarInset = useDuoBottomBarInset();
260 const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker";
261 // A pushed screen temporarily inherits the outgoing tab bar's safe area.
262 // Use the window edge so hiding that bar cannot move the composer mid-push.
263 const bottomSafeArea =
264 Platform.OS === "ios" ? (windowMetrics?.safeArea.bottom ?? insets.bottom) : insets.bottom;
265 // The pill already adds its own gutter; iPad and Duo align its edge with the native bar.
266 const alignedBottomInset =
267 bottomBarInset ??
268 (Platform.OS === "ios" && Platform.isPad
269 ? Math.max(bottomSafeArea, 12) - (layout.usesSplitView ? 5 : 0)
270 : undefined);
271 // The Duo's floating sidebar pill ends three points below the composer's usual gutter.
272 return Math.max(
273 0,
274 (alignedBottomInset !== undefined
275 ? alignedBottomInset - COMPOSER_BOTTOM_GUTTER
276 : Math.max(bottomSafeArea, 12)) - (hasSidebarTabBar ? 3 : 0),
277 );
278 }
279
280 /** The editor's text style: the composer's scaled role in the theme's foreground color. */
281 export function useComposerTextStyle(text: ScaledTextRole) {
282 return { ...text, color: useUniwindTheme()["--color-foreground"] };
283 }