Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ComposerSurface.tsx

285 lines11.2 KB

1import { useState, type ReactNode } from "react";
2import { I18nManager, Platform, type ViewStyle } from "react-native";
3import Animated, {
4 FadeIn,
5 type LayoutAnimationFunction,
6 ReduceMotion,
7 useAnimatedStyle,
8 useDerivedValue,
9 useSharedValue,
10 withTiming,
11} from "react-native-reanimated";
12​
13import { useSafeAreaInsets } from "react-native-safe-area-context";
14​
15import { useAdaptiveWorkspaceLayout } from "../features/layout/AdaptiveWorkspaceLayout";
16import { useSidebarWorkspaceTabs } from "../features/layout/workspace/useSystemWorkspaceTabBar";
17import { useAndroidFloatingTabs } from "../features/settings/appearance/AppearancePreferencesProvider";
18import { compactEditorInsets } from "../features/threads/compactEditorInsets";
19import {
20 useDeviceType,
21 useDuoBottomBarInset,
22 useNativeLayoutMetrics,
23} from "../native/native-layout-metrics";
24import type { ScaledTextRole } from "../features/settings/appearance/useScaledTextRole";
25import { MOBILE_TYPOGRAPHY } from "../lib/typography";
26import { useUniwindTheme } from "../lib/useUniwindTheme";
27import { GlassSurface } from "./ui/GlassSurface";
28​
29const 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.
32const LOWERCASE_MIDLINE_EM = 0.562;
33​
34function lowercaseMidline(text: ScaledTextRole): number {
35 return text.lineHeight - LOWERCASE_MIDLINE_EM * text.fontSize;
37​
38function 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));
42​
43const EXPANDED_EDITOR_INSET = 14;
44// Room under the expanded editor for the toolbar row.
45const EXPANDED_EDITOR_BOTTOM = 52;
46​
47export 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 };
141​
142export const COMPOSER_TRANSITION_DURATION_MS = 220;
143// Side panes animate dock width; nested horizontal transitions would make the surface trail the toolbar.
144const 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};
165const COMPOSER_LAYOUT_TRANSITION = Platform.OS === "android" ? undefined : composerHeightTransition;
166// Share of the one-row composer the draft keeps; a long model name truncates first.
167export const INLINE_EDITOR_MIN_WIDTH = "40%";
168const INLINE_EDITOR_HEIGHT = 36;
169​
170const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface);
171​
172export function ComposerSurface(props: {
173 readonly children: ReactNode;
174 readonly style: ViewStyle;
175 readonly animateLayout?: boolean;
176 readonly tone?: "warning";
177}) {
178 const colors = useUniwindTheme();
179 const targetBorderRadius =
180 typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0;
181 const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android";
182 const animatedBorderRadius = useDerivedValue(() =>
183 shouldAnimate
184 ? withTiming(targetBorderRadius, {
185 duration: COMPOSER_TRANSITION_DURATION_MS,
186 reduceMotion: ReduceMotion.System,
187 })
188 : targetBorderRadius,
189 );
190 const borderCurve = props.style.borderCurve;
191 const animatedShapeStyle = useAnimatedStyle(() => ({
192 borderRadius: animatedBorderRadius.value,
193 ...(borderCurve ? { borderCurve } : {}),
194 }));
195 const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined;
196​
197 // Animate every native frame or glass and content jump to final height inside the clip.
198 return (
199 <Animated.View
200 className={
201 Platform.OS === "android" ? undefined : "shadow-[0_6px_28px] shadow-adaptive-black-a15-a35"
202 }
203 layout={layoutTransition}
204 style={[
205 animatedShapeStyle,
206 {
207 overflow: "hidden",
208 },
209 ]}
210 >
211 <AnimatedGlassSurface
212 chrome="none"
213 fallbackColor={colors["--color-composer-surface"]}
214 fallbackClassName="border border-composer-border"
215 glassEffectStyle="regular"
216 pointerEvents="none"
217 tintColor="transparent"
218 layout={layoutTransition}
219 style={[{ position: "absolute", inset: 0 }, animatedShapeStyle]}
220 >
221 {null}
222 </AnimatedGlassSurface>
223 <Animated.View
224 collapsable={false}
225 className={props.tone === "warning" ? "bg-warning" : undefined}
226 layout={layoutTransition}
227 style={[props.style, animatedShapeStyle]}
228 >
229 {props.children}
230 </Animated.View>
231 </Animated.View>
232 );
234​
235/** Space below the composer pill, inside the bottom inset it is given. */
236export const COMPOSER_BOTTOM_GUTTER = 6;
237​
238/** Control size and pill shape: larger beside a sidebar tab picker and on iPad. */
239export function useComposerChrome() {
240 const { layout } = useAdaptiveWorkspaceLayout();
241 const floatingSidebarComposer = useAndroidFloatingTabs() && layout.usesSplitView;
242 const sidebarWorkspaceTabs = useSidebarWorkspaceTabs();
243 const deviceType = useDeviceType();
244 const usesLargeControls = sidebarWorkspaceTabs === "picker" || deviceType === "pad";
245 return {
246 usesLargeControls,
247 controlSize: usesLargeControls ? ("large" as const) : ("regular" as const),
248 borderRadius: usesLargeControls ? 31 : 27,
249 paddingVertical: usesLargeControls ? 9 : floatingSidebarComposer ? 6 : 2,
250 };
252​
253/**
254 * The inset below a composer pinned to the bottom of a page. Fixed while the keyboard animates:
255 * changing it at keyboardDidHide makes the composer land low, then jump back above the safe area.
256 */
257export function useComposerBottomInset() {
258 const insets = useSafeAreaInsets();
259 const windowMetrics = useNativeLayoutMetrics();
260 const { layout } = useAdaptiveWorkspaceLayout();
261 const bottomBarInset = useDuoBottomBarInset();
262 const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker";
263 // A pushed screen temporarily inherits the outgoing tab bar's safe area.
264 // Use the window edge so hiding that bar cannot move the composer mid-push.
265 const bottomSafeArea =
266 Platform.OS === "ios" ? (windowMetrics?.safeArea.bottom ?? insets.bottom) : insets.bottom;
267 // The pill already adds its own gutter; iPad and Duo align its edge with the native bar.
268 const alignedBottomInset =
269 bottomBarInset ??
270 (Platform.OS === "ios" && Platform.isPad
271 ? Math.max(bottomSafeArea, 12) - (layout.usesSplitView ? 5 : 0)
272 : undefined);
273 // The Duo's floating sidebar pill ends three points below the composer's usual gutter.
274 return Math.max(
275 0,
276 (alignedBottomInset !== undefined
277 ? alignedBottomInset - COMPOSER_BOTTOM_GUTTER
278 : Math.max(bottomSafeArea, 12)) - (hasSidebarTabBar ? 3 : 0),
279 );
281​
282/** The editor's text style: the composer's scaled role in the theme's foreground color. */
283export function useComposerTextStyle(text: ScaledTextRole) {
284 return { ...text, color: useUniwindTheme()["--color-foreground"] };