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

floating-working-control.tsx

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