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

floating-working-control.tsx

505 lines18.6 KB

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