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

floating-working-control.tsx

446 lines16.2 KB

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