Open History to see the last commit
1import { formatDuration } from "@t3tools/shared/orchestrationTiming";
2import { GlassContainer, GlassView } from "expo-glass-effect";
3import { type ReactNode, useEffect, useRef, useState } from "react";
4import {
5 ActivityIndicator,
6 type LayoutChangeEvent,
7 Pressable,
8 Text as SystemText,
9 useWindowDimensions,
10 View,
11} from "react-native";
12import Animated, {
13 Easing,
14 FadeIn,
15 FadeOut,
16 ReduceMotion,
17 useAnimatedStyle,
18 useSharedValue,
19 withTiming,
20} from "react-native-reanimated";
21import { withUniwind } from "uniwind";
22
23import { AppText as Text } from "../../components/AppText";
24import { SymbolView } from "../../components/AppSymbol";
25import { ControlPill } from "../../components/ControlPill";
26import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
27import type { FloatingWorkingStatus } from "./floating-working-status";
28import { ShimmeringWorkContent } from "./thread-work-log";
29
30const CONTROL_HEIGHT = 38.5; // h-11 with the mobile 14px rem
31// The collapsed composer capsule starts 6 below its overlay's top edge, so
32// the pill sits at (gap - 6) above the overlay to leave the same gap to the
33// capsule as the feed's end inset leaves between it and the last row.
34const CONTROL_GAP = 8;
35const COMPOSER_CAPSULE_INSET = 6;
36const GLASS_MERGE_SPACING = 12;
37const CONTROL_ENTERING = FadeIn.duration(180).reduceMotion(ReduceMotion.System);
38const CONTROL_EXITING = FadeOut.duration(120).reduceMotion(ReduceMotion.System);
39const CONTROL_TIMING = {
40 duration: 240,
41 easing: Easing.out(Easing.cubic),
42 reduceMotion: ReduceMotion.System,
43} as const;
44const CONTROL_SEPARATION = (16 + CONTROL_HEIGHT) / 2;
45// Both rows share the same centered anchor, so the outgoing one clears fast and
46// the incoming one waits for it to be mostly gone before it starts to show.
47const LABEL_ENTERING = FadeIn.duration(160).delay(80).reduceMotion(ReduceMotion.System);
48const LABEL_EXITING = FadeOut.duration(100).reduceMotion(ReduceMotion.System);
49
50// Expo reapplies glass after native layout and window reattachment, when UIKit
51// can otherwise leave the label visible but lose the material behind it.
52const UniwindGlassView = withUniwind(GlassView, {
53 style: { fromClassName: "className" },
54});
55const UniwindGlassContainer = withUniwind(GlassContainer, {
56 style: { fromClassName: "className" },
57});
58const AnimatedGlassView = Animated.createAnimatedComponent(UniwindGlassView);
59
60const CONTROL_OVERLAY_OFFSET = CONTROL_HEIGHT + CONTROL_GAP - COMPOSER_CAPSULE_INSET;
61export const FLOATING_WORKING_CONTROL_COVERAGE = CONTROL_OVERLAY_OFFSET + CONTROL_GAP;
62
63export function FloatingWorkingControl(props: {
64 readonly colorScheme: "light" | "dark";
65 readonly status: FloatingWorkingStatus | null;
66 readonly showScrollToEnd: boolean;
67 readonly onScrollToEnd: () => void;
68}) {
69 const { width: windowWidth } = useWindowDimensions();
70 const [overlayWidth, setOverlayWidth] = useState(windowWidth);
71 const labelWidth = Math.max(0, Math.min(overlayWidth, windowWidth) - CONTROL_HEIGHT - 16);
72 const separationProgress = useSharedValue(props.showScrollToEnd ? 1 : 0);
73
74 useEffect(() => {
75 separationProgress.value = withTiming(props.showScrollToEnd ? 1 : 0, CONTROL_TIMING);
76 }, [props.showScrollToEnd, separationProgress]);
77
78 const arrowTransformStyle = useAnimatedStyle(() => ({
79 transform: [{ translateX: -CONTROL_SEPARATION * (1 - separationProgress.value) }],
80 }));
81 const arrowContentStyle = useAnimatedStyle(() => ({
82 opacity: separationProgress.value,
83 }));
84
85 // Animate an in-flow sizer so native glass receives real layout updates.
86 // Measure labels in a separate, fixed-width host: measuring against the
87 // animated capsule constrains the incoming text to each intermediate width
88 // and repeatedly retargets the animation as it grows.
89 const capsuleWidth = useSharedValue<number | null>(null);
90 const measuredWidthRef = useRef<number | null>(null);
91 const handleLabelLayout = (event: LayoutChangeEvent) => {
92 const width = event.nativeEvent.layout.width;
93 if (width === measuredWidthRef.current) {
94 return;
95 }
96 const first = measuredWidthRef.current === null;
97 measuredWidthRef.current = width;
98 capsuleWidth.value = first ? width : withTiming(width, CONTROL_TIMING);
99 };
100 // Forget the width while no label is shown so the next one appears at its
101 // own size instead of animating from the previous label's.
102 const hasStatus = props.status !== null;
103 useEffect(() => {
104 if (!hasStatus) {
105 measuredWidthRef.current = null;
106 capsuleWidth.value = null;
107 }
108 }, [capsuleWidth, hasStatus]);
109 const capsuleStyle = useAnimatedStyle(() => ({
110 transform: [{ translateX: CONTROL_SEPARATION * (1 - separationProgress.value) }],
111 }));
112 // Zero until the first measurement lands, so the capsule never paints around
113 // a label it has not sized to yet.
114 const capsuleSizerStyle = useAnimatedStyle(() => ({ width: capsuleWidth.value ?? 0 }));
115
116 if (props.status === null && !props.showScrollToEnd) {
117 return null;
118 }
119
120 // Only the connection label is a button (tap to reconnect); the others
121 // pass touches through to the feed like before.
122 const statusInteractive = props.status?.kind === "connection";
123 // The host stays centered on the capsule, but its measurement constraint
124 // comes from the overlay, independent of the capsule's current width.
125 const statusContent =
126 props.status !== null ? (
127 <>
128 <Animated.View className="h-11" style={capsuleSizerStyle} />
129 <View
130 pointerEvents="box-none"
131 className="absolute h-11 items-center justify-center"
132 style={{ width: labelWidth }}
133 >
134 <FloatingStatusLabel
135 key={
136 props.status.kind === "working" || props.status.kind === "compacting"
137 ? props.status.kind
138 : `${props.status.kind}:${props.status.label}`
139 }
140 status={props.status}
141 onLayout={handleLabelLayout}
142 />
143 </View>
144 </>
145 ) : null;
146
147 return (
148 <Animated.View
149 pointerEvents="box-none"
150 className="absolute left-0 right-0 z-20 items-center"
151 style={{ top: -CONTROL_OVERLAY_OFFSET }}
152 onLayout={(event) => setOverlayWidth(event.nativeEvent.layout.width)}
153 entering={NATIVE_LIQUID_GLASS_SUPPORTED ? undefined : CONTROL_ENTERING}
154 exiting={NATIVE_LIQUID_GLASS_SUPPORTED ? undefined : CONTROL_EXITING}
155 >
156 {props.status !== null && NATIVE_LIQUID_GLASS_SUPPORTED ? (
157 <UniwindGlassContainer
158 spacing={GLASS_MERGE_SPACING}
159 pointerEvents="box-none"
160 className="flex-row items-center gap-4"
161 >
162 <AnimatedGlassView
163 colorScheme={props.colorScheme}
164 glassEffectStyle="regular"
165 isInteractive={statusInteractive}
166 pointerEvents={statusInteractive ? "box-none" : "none"}
167 className="h-11 items-center justify-center overflow-hidden rounded-full"
168 style={capsuleStyle}
169 >
170 {statusContent}
171 </AnimatedGlassView>
172
173 <AnimatedGlassView
174 colorScheme={props.colorScheme}
175 glassEffectStyle="regular"
176 isInteractive
177 pointerEvents={props.showScrollToEnd ? "auto" : "none"}
178 accessibilityElementsHidden={!props.showScrollToEnd}
179 importantForAccessibility={props.showScrollToEnd ? "auto" : "no-hide-descendants"}
180 className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
181 style={arrowTransformStyle}
182 >
183 <Animated.View style={arrowContentStyle}>
184 <ScrollToEndButton disabled={!props.showScrollToEnd} onPress={props.onScrollToEnd} />
185 </Animated.View>
186 </AnimatedGlassView>
187 </UniwindGlassContainer>
188 ) : props.status !== null ? (
189 <View pointerEvents="box-none" className="flex-row items-center gap-4">
190 <Animated.View
191 pointerEvents={statusInteractive ? "box-none" : "none"}
192 className="h-11 items-center justify-center overflow-hidden rounded-full border border-border bg-card shadow-md shadow-black/10"
193 style={capsuleStyle}
194 >
195 {statusContent}
196 </Animated.View>
197
198 <Animated.View
199 pointerEvents={props.showScrollToEnd ? "auto" : "none"}
200 accessibilityElementsHidden={!props.showScrollToEnd}
201 importantForAccessibility={props.showScrollToEnd ? "auto" : "no-hide-descendants"}
202 style={[arrowTransformStyle, arrowContentStyle]}
203 >
204 <ControlPill
205 accessibilityLabel="Scroll to end"
206 activateOnPressIn
207 className="h-11 w-11 border border-border bg-card shadow-md shadow-black/10"
208 disabled={!props.showScrollToEnd}
209 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
210 onPress={props.onScrollToEnd}
211 />
212 </Animated.View>
213 </View>
214 ) : NATIVE_LIQUID_GLASS_SUPPORTED ? (
215 <UniwindGlassView
216 colorScheme={props.colorScheme}
217 glassEffectStyle="regular"
218 isInteractive
219 className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
220 >
221 <ScrollToEndButton onPress={props.onScrollToEnd} />
222 </UniwindGlassView>
223 ) : (
224 <ControlPill
225 accessibilityLabel="Scroll to end"
226 activateOnPressIn
227 className="h-11 w-11 border border-border bg-card shadow-md shadow-black/10"
228 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
229 onPress={props.onScrollToEnd}
230 />
231 )}
232 </Animated.View>
233 );
234}
235
236function CompactingLabel(props: { readonly onLayout: (event: LayoutChangeEvent) => void }) {
237 return (
238 <StatusLabelRow accessibilityLabel="Compacting" className="gap-1.5" onLayout={props.onLayout}>
239 <SymbolView
240 name="arrow.down.right.and.arrow.up.left"
241 size={13}
242 tintColorClassName="foreground"
243 type="monochrome"
244 />
245 <Text className="font-t3-medium text-xs text-foreground">Compacting…</Text>
246 </StatusLabelRow>
247 );
248}
249
250function FloatingStatusLabel(props: {
251 readonly status: FloatingWorkingStatus;
252 readonly onLayout: (event: LayoutChangeEvent) => void;
253}) {
254 // Keyed by kind so a swap mounts a fresh row and the two cross-fade while
255 // the capsule animates to the new row's measured width.
256 if (props.status.kind === "syncing") {
257 return (
258 <StatusLabelRow
259 key="syncing"
260 accessibilityLabel={props.status.label}
261 className="gap-2"
262 onLayout={props.onLayout}
263 >
264 <ActivityIndicator size="small" colorClassName="accent-icon-muted" />
265 <Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>
266 {props.status.label}
267 </Text>
268 </StatusLabelRow>
269 );
270 }
271 if (props.status.kind === "compacting") {
272 return <CompactingLabel key="compacting" onLayout={props.onLayout} />;
273 }
274 if (props.status.kind === "connection") {
275 return (
276 <StatusLabelRow
277 key="connection"
278 accessibilityLabel={props.status.label}
279 accessibilityRole="button"
280 className="gap-2"
281 onLayout={props.onLayout}
282 onPress={props.status.onPress}
283 >
284 {props.status.tone === "reconnecting" ? (
285 <ActivityIndicator size="small" colorClassName="accent-icon-muted" />
286 ) : (
287 <View className="h-2 w-2 rounded-full bg-red-500" />
288 )}
289 <Text
290 className="max-w-[260px] shrink font-t3-medium text-xs text-foreground"
291 numberOfLines={1}
292 >
293 {props.status.label}
294 </Text>
295 </StatusLabelRow>
296 );
297 }
298 if (props.status.kind === "preparing") {
299 return (
300 <StatusLabelRow
301 key="preparing"
302 accessibilityLabel={props.status.label}
303 className="gap-1.5"
304 onLayout={props.onLayout}
305 >
306 <SymbolView
307 name="arrow.triangle.branch"
308 size={13}
309 tintColorClassName="foreground"
310 type="monochrome"
311 />
312 <ShimmeringWorkContent
313 className="flex-none"
314 textClassName="font-t3-medium"
315 compact
316 icon="arrow.triangle.branch"
317 iconSubtleColor="transparent"
318 label={props.status.label}
319 showIcon={false}
320 />
321 </StatusLabelRow>
322 );
323 }
324 return (
325 <WorkingDuration key="working" startedAt={props.status.startedAt} onLayout={props.onLayout} />
326 );
327}
328
329// Absolute rows cross-fade around the same center without affecting each other.
330function StatusLabelRow(props: {
331 readonly accessibilityLabel: string;
332 readonly accessibilityRole?: "button";
333 readonly className?: string;
334 readonly children: ReactNode;
335 readonly onLayout: (event: LayoutChangeEvent) => void;
336 readonly onPress?: () => void;
337}) {
338 const rowClassName = `h-11 flex-row items-center px-4 ${props.className ?? ""}`;
339 return (
340 <Animated.View
341 className="absolute max-w-full"
342 entering={LABEL_ENTERING}
343 exiting={LABEL_EXITING}
344 onLayout={props.onLayout}
345 >
346 {props.onPress ? (
347 <Pressable
348 accessibilityLabel={props.accessibilityLabel}
349 accessibilityRole={props.accessibilityRole}
350 className={`${rowClassName} active:opacity-70`}
351 onPress={props.onPress}
352 >
353 {props.children}
354 </Pressable>
355 ) : (
356 <View accessible accessibilityLabel={props.accessibilityLabel} className={rowClassName}>
357 {props.children}
358 </View>
359 )}
360 </Animated.View>
361 );
362}
363
364function WorkingDuration(props: {
365 readonly startedAt: string;
366 readonly onLayout: (event: LayoutChangeEvent) => void;
367}) {
368 const [nowMs, setNowMs] = useState(() => Date.now());
369
370 useEffect(() => {
371 setNowMs(Date.now());
372 const intervalId = setInterval(() => setNowMs(Date.now()), 1_000);
373 return () => clearInterval(intervalId);
374 }, [props.startedAt]);
375
376 const duration = formatWorkingDuration(props.startedAt, nowMs);
377 const label = `Working for ${duration}`;
378
379 return (
380 <StatusLabelRow accessibilityLabel={label} onLayout={props.onLayout}>
381 <Text className="font-t3-medium text-xs text-foreground">Working for </Text>
382 <SystemText
383 className="text-xs text-foreground"
384 style={{ fontVariant: ["tabular-nums"], fontWeight: "500" }}
385 >
386 {duration}
387 </SystemText>
388 </StatusLabelRow>
389 );
390}
391
392function formatWorkingDuration(startedAt: string, nowMs: number): string {
393 const startedAtMs = Date.parse(startedAt);
394 if (!Number.isFinite(startedAtMs) || nowMs <= startedAtMs) {
395 return "0s";
396 }
397
398 const totalSeconds = Math.floor((nowMs - startedAtMs) / 1_000);
399 if (totalSeconds < 60) {
400 return `${totalSeconds}s`;
401 }
402 if (totalSeconds >= 3_600) {
403 return formatDuration(totalSeconds * 1_000);
404 }
405
406 const minutes = Math.floor(totalSeconds / 60);
407 const seconds = String(totalSeconds % 60).padStart(2, "0");
408 return `${minutes}m ${seconds}s`;
409}
410
411function ScrollToEndButton(props: { readonly disabled?: boolean; readonly onPress: () => void }) {
412 return (
413 <ControlPill
414 accessibilityLabel="Scroll to end"
415 activateOnPressIn
416 className="h-11 w-11 bg-transparent"
417 disabled={props.disabled}
418 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
419 onPress={props.onPress}
420 />
421 );
422}