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 readonly queuedCount: number;
69 readonly onOpenQueue: () => void;
70}) {
71 const { width: windowWidth } = useWindowDimensions();
72 const [overlayWidth, setOverlayWidth] = useState(windowWidth);
73 const [queueWidth, setQueueWidth] = useState(0);
74 const hasQueue = props.queuedCount > 0;
75 const labelWidth = Math.max(
76 0,
77 Math.min(overlayWidth, windowWidth) - CONTROL_HEIGHT - 32 - (hasQueue ? queueWidth : 0),
78 );
79 const separationProgress = useSharedValue(props.showScrollToEnd ? 1 : 0);
80
81 useEffect(() => {
82 separationProgress.value = withTiming(props.showScrollToEnd ? 1 : 0, CONTROL_TIMING);
83 }, [props.showScrollToEnd, separationProgress]);
84
85 const arrowTransformStyle = useAnimatedStyle(() => ({
86 transform: [{ translateX: -CONTROL_SEPARATION * (1 - separationProgress.value) }],
87 }));
88 const arrowContentStyle = useAnimatedStyle(() => ({
89 opacity: separationProgress.value,
90 }));
91
92 // Animate an in-flow sizer so native glass receives real layout updates.
93 // Measure labels in a separate, fixed-width host: measuring against the
94 // animated capsule constrains the incoming text to each intermediate width
95 // and repeatedly retargets the animation as it grows.
96 const capsuleWidth = useSharedValue<number | null>(null);
97 const measuredWidthRef = useRef<number | null>(null);
98 const handleLabelLayout = (event: LayoutChangeEvent) => {
99 const width = event.nativeEvent.layout.width;
100 if (width === measuredWidthRef.current) {
101 return;
102 }
103 const first = measuredWidthRef.current === null;
104 measuredWidthRef.current = width;
105 capsuleWidth.value = first ? width : withTiming(width, CONTROL_TIMING);
106 };
107 // Forget the width while no label is shown so the next one appears at its
108 // own size instead of animating from the previous label's.
109 const hasStatus = props.status !== null;
110 const hasCapsule = hasStatus || hasQueue;
111 useEffect(() => {
112 if (!hasStatus) {
113 measuredWidthRef.current = null;
114 capsuleWidth.value = null;
115 }
116 }, [capsuleWidth, hasStatus]);
117 const capsuleStyle = useAnimatedStyle(() => ({
118 transform: [{ translateX: CONTROL_SEPARATION * (1 - separationProgress.value) }],
119 }));
120 // Zero until the first measurement lands, so the capsule never paints around
121 // a label it has not sized to yet.
122 const capsuleSizerStyle = useAnimatedStyle(() => ({ width: capsuleWidth.value ?? 0 }));
123
124 if (!hasCapsule && !props.showScrollToEnd) {
125 return null;
126 }
127
128 // The queue and reconnect labels have separate tap targets.
129 const statusInteractive = props.status?.kind === "connection" || hasQueue;
130 // The host stays centered on the capsule, but its measurement constraint
131 // comes from the overlay, independent of the capsule's current width.
132 const statusContent =
133 props.status !== null ? (
134 <View
135 pointerEvents={props.status.kind === "connection" ? "box-none" : "none"}
136 className="h-11 items-center justify-center"
137 >
138 <Animated.View className="h-11" style={capsuleSizerStyle} />
139 <View
140 pointerEvents="box-none"
141 className="absolute h-11 items-center justify-center"
142 style={{ width: labelWidth }}
143 >
144 <FloatingStatusLabel
145 key={
146 props.status.kind === "working" || props.status.kind === "compacting"
147 ? props.status.kind
148 : `${props.status.kind}:${props.status.label}`
149 }
150 status={props.status}
151 onLayout={handleLabelLayout}
152 />
153 </View>
154 </View>
155 ) : null;
156
157 const capsuleContent = (
158 <View className="flex-row items-center">
159 {statusContent}
160 {hasQueue ? (
161 <Pressable
162 accessibilityRole="button"
163 accessibilityLabel={`Open queue, ${props.queuedCount} messages`}
164 accessibilityHint="Opens queued messages for reordering, steering, or removal"
165 onPress={props.onOpenQueue}
166 onLayout={(event) => setQueueWidth(event.nativeEvent.layout.width)}
167 style={{ maxWidth: Math.min(overlayWidth, windowWidth) * 0.45 }}
168 className="h-11 flex-row items-center gap-2 px-3 active:opacity-70"
169 >
170 {hasStatus ? <View className="mr-1 h-4 w-px bg-border" /> : null}
171 <SymbolView name="list.number" size={13} tintColorClassName="accent-foreground-muted" />
172 <Text className="shrink font-t3-medium text-xs tabular-nums" numberOfLines={1}>
173 {props.queuedCount} queued
174 </Text>
175 </Pressable>
176 ) : null}
177 </View>
178 );
179
180 return (
181 <Animated.View
182 pointerEvents="box-none"
183 className="absolute left-0 right-0 z-20 items-center"
184 style={{ top: -CONTROL_OVERLAY_OFFSET }}
185 onLayout={(event) => setOverlayWidth(event.nativeEvent.layout.width)}
186 entering={NATIVE_LIQUID_GLASS_SUPPORTED ? undefined : CONTROL_ENTERING}
187 exiting={NATIVE_LIQUID_GLASS_SUPPORTED ? undefined : CONTROL_EXITING}
188 >
189 {hasCapsule && NATIVE_LIQUID_GLASS_SUPPORTED ? (
190 <UniwindGlassContainer
191 spacing={GLASS_MERGE_SPACING}
192 pointerEvents="box-none"
193 className="flex-row items-center gap-4"
194 >
195 <AnimatedGlassView
196 colorScheme={props.colorScheme}
197 glassEffectStyle="regular"
198 isInteractive={statusInteractive}
199 pointerEvents={statusInteractive ? "box-none" : "none"}
200 className="h-11 items-center justify-center overflow-hidden rounded-full"
201 style={capsuleStyle}
202 >
203 {capsuleContent}
204 </AnimatedGlassView>
205
206 <AnimatedGlassView
207 colorScheme={props.colorScheme}
208 glassEffectStyle="regular"
209 isInteractive
210 pointerEvents={props.showScrollToEnd ? "auto" : "none"}
211 accessibilityElementsHidden={!props.showScrollToEnd}
212 importantForAccessibility={props.showScrollToEnd ? "auto" : "no-hide-descendants"}
213 className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
214 style={arrowTransformStyle}
215 >
216 <Animated.View style={arrowContentStyle}>
217 <ScrollToEndButton disabled={!props.showScrollToEnd} onPress={props.onScrollToEnd} />
218 </Animated.View>
219 </AnimatedGlassView>
220 </UniwindGlassContainer>
221 ) : hasCapsule ? (
222 <View pointerEvents="box-none" className="flex-row items-center gap-4">
223 <Animated.View
224 pointerEvents={statusInteractive ? "box-none" : "none"}
225 className="h-11 items-center justify-center overflow-hidden rounded-full border border-border bg-card shadow-md shadow-black/10"
226 style={capsuleStyle}
227 >
228 {capsuleContent}
229 </Animated.View>
230
231 <Animated.View
232 pointerEvents={props.showScrollToEnd ? "auto" : "none"}
233 accessibilityElementsHidden={!props.showScrollToEnd}
234 importantForAccessibility={props.showScrollToEnd ? "auto" : "no-hide-descendants"}
235 style={[arrowTransformStyle, arrowContentStyle]}
236 >
237 <ControlPill
238 accessibilityLabel="Scroll to end"
239 activateOnPressIn
240 className="h-11 w-11 border border-border bg-card shadow-md shadow-black/10"
241 disabled={!props.showScrollToEnd}
242 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
243 onPress={props.onScrollToEnd}
244 />
245 </Animated.View>
246 </View>
247 ) : NATIVE_LIQUID_GLASS_SUPPORTED ? (
248 <UniwindGlassView
249 colorScheme={props.colorScheme}
250 glassEffectStyle="regular"
251 isInteractive
252 className="h-11 w-11 items-center justify-center overflow-hidden rounded-full"
253 >
254 <ScrollToEndButton onPress={props.onScrollToEnd} />
255 </UniwindGlassView>
256 ) : (
257 <ControlPill
258 accessibilityLabel="Scroll to end"
259 activateOnPressIn
260 className="h-11 w-11 border border-border bg-card shadow-md shadow-black/10"
261 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
262 onPress={props.onScrollToEnd}
263 />
264 )}
265 </Animated.View>
266 );
267}
268
269function CompactingLabel(props: { readonly onLayout: (event: LayoutChangeEvent) => void }) {
270 return (
271 <StatusLabelRow accessibilityLabel="Compacting" className="gap-1.5" onLayout={props.onLayout}>
272 <SymbolView
273 name="arrow.down.right.and.arrow.up.left"
274 size={13}
275 tintColorClassName="foreground"
276 type="monochrome"
277 />
278 <Text className="font-t3-medium text-xs text-foreground">Compacting…</Text>
279 </StatusLabelRow>
280 );
281}
282
283function FloatingStatusLabel(props: {
284 readonly status: FloatingWorkingStatus;
285 readonly onLayout: (event: LayoutChangeEvent) => void;
286}) {
287 // Keyed by kind so a swap mounts a fresh row and the two cross-fade while
288 // the capsule animates to the new row's measured width.
289 if (props.status.kind === "syncing") {
290 return (
291 <StatusLabelRow
292 key="syncing"
293 accessibilityLabel={props.status.label}
294 className="gap-2"
295 onLayout={props.onLayout}
296 >
297 <ActivityIndicator size="small" colorClassName="accent-icon-muted" />
298 <Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>
299 {props.status.label}
300 </Text>
301 </StatusLabelRow>
302 );
303 }
304 if (props.status.kind === "compacting") {
305 return <CompactingLabel key="compacting" onLayout={props.onLayout} />;
306 }
307 if (props.status.kind === "connection") {
308 return (
309 <StatusLabelRow
310 key="connection"
311 accessibilityLabel={props.status.label}
312 accessibilityRole="button"
313 className="gap-2"
314 onLayout={props.onLayout}
315 onPress={props.status.onPress}
316 >
317 {props.status.tone === "reconnecting" ? (
318 <ActivityIndicator size="small" colorClassName="accent-icon-muted" />
319 ) : (
320 <View className="h-2 w-2 rounded-full bg-red-500" />
321 )}
322 <Text
323 className="max-w-[260px] shrink font-t3-medium text-xs text-foreground"
324 numberOfLines={1}
325 >
326 {props.status.label}
327 </Text>
328 </StatusLabelRow>
329 );
330 }
331 if (props.status.kind === "preparing") {
332 return (
333 <StatusLabelRow
334 key="preparing"
335 accessibilityLabel={props.status.label}
336 className="gap-1.5"
337 onLayout={props.onLayout}
338 >
339 <SymbolView
340 name="arrow.triangle.branch"
341 size={13}
342 tintColorClassName="foreground"
343 type="monochrome"
344 />
345 <ShimmeringWorkContent
346 className="flex-none"
347 textClassName="font-t3-medium"
348 compact
349 icon="arrow.triangle.branch"
350 iconSubtleColor="transparent"
351 label={props.status.label}
352 showIcon={false}
353 />
354 </StatusLabelRow>
355 );
356 }
357 return (
358 <WorkingDuration key="working" startedAt={props.status.startedAt} onLayout={props.onLayout} />
359 );
360}
361
362// Absolute rows cross-fade around the same center without affecting each other.
363function StatusLabelRow(props: {
364 readonly accessibilityLabel?: string;
365 readonly accessibilityRole?: "button";
366 readonly className?: string;
367 readonly children: ReactNode;
368 readonly onLayout: (event: LayoutChangeEvent) => void;
369 readonly onPress?: () => void;
370}) {
371 const rowClassName = `h-11 flex-row items-center px-4 ${props.className ?? ""}`;
372 return (
373 <Animated.View
374 className="absolute max-w-full"
375 entering={LABEL_ENTERING}
376 exiting={LABEL_EXITING}
377 onLayout={props.onLayout}
378 >
379 {props.onPress ? (
380 <Pressable
381 accessibilityLabel={props.accessibilityLabel}
382 accessibilityRole={props.accessibilityRole}
383 className={`${rowClassName} active:opacity-70`}
384 onPress={props.onPress}
385 >
386 {props.children}
387 </Pressable>
388 ) : (
389 <View accessible accessibilityLabel={props.accessibilityLabel} className={rowClassName}>
390 {props.children}
391 </View>
392 )}
393 </Animated.View>
394 );
395}
396
397function WorkingDuration(props: {
398 readonly startedAt: string;
399 readonly onLayout: (event: LayoutChangeEvent) => void;
400}) {
401 return (
402 <StatusLabelRow onLayout={props.onLayout}>
403 <WorkingTimer startedAt={props.startedAt} />
404 </StatusLabelRow>
405 );
406}
407
408export function WorkingTimer(props: { readonly startedAt: string }) {
409 const [nowMs, setNowMs] = useState(() => Date.now());
410 useEffect(() => {
411 const intervalId = setInterval(() => setNowMs(Date.now()), 1_000);
412 return () => clearInterval(intervalId);
413 }, []);
414 return (
415 <SystemText
416 className="shrink text-xs text-foreground"
417 numberOfLines={1}
418 style={{ fontVariant: ["tabular-nums"], fontWeight: "500" }}
419 >
420 Working {formatWorkingDuration(props.startedAt, nowMs)}
421 </SystemText>
422 );
423}
424
425function formatWorkingDuration(startedAt: string, nowMs: number): string {
426 const startedAtMs = Date.parse(startedAt);
427 if (!Number.isFinite(startedAtMs) || nowMs <= startedAtMs) {
428 return "0s";
429 }
430
431 const totalSeconds = Math.floor((nowMs - startedAtMs) / 1_000);
432 if (totalSeconds < 60) {
433 return `${totalSeconds}s`;
434 }
435 if (totalSeconds >= 3_600) {
436 return formatDuration(totalSeconds * 1_000);
437 }
438
439 const minutes = Math.floor(totalSeconds / 60);
440 const seconds = String(totalSeconds % 60).padStart(2, "0");
441 return `${minutes}m ${seconds}s`;
442}
443
444function ScrollToEndButton(props: { readonly disabled?: boolean; readonly onPress: () => void }) {
445 return (
446 <ControlPill
447 accessibilityLabel="Scroll to end"
448 activateOnPressIn
449 className="h-11 w-11 bg-transparent"
450 disabled={props.disabled}
451 icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
452 onPress={props.onPress}
453 />
454 );
455}