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

ThreadQueueControl.tsx

624 lines24.2 KB

1import { type StaticScreenProps, useNavigation } from "@react-navigation/native";
2import { useAtomValue } from "@effect/atom-react";
3import type { ChatAttachment, EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
4import { Image } from "expo-image";
5import * as Haptics from "expo-haptics";
6import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
7import { Animated, Platform, Pressable, ScrollView, View } from "react-native";
8import { Gesture, GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler";
9import ReanimatedSwipeable, {
10 type SwipeableMethods,
11} from "react-native-gesture-handler/ReanimatedSwipeable";
12import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
13import { useSafeAreaInsets } from "react-native-safe-area-context";
14import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
15​
16import { MaterialButton } from "../../components/MaterialButton";
17import { AndroidSheetHeader } from "../../components/AndroidScreenHeader";
18import { AppText as Text } from "../../components/AppText";
19import { SymbolView } from "../../components/AppSymbol";
20import { ControlPillMenu } from "../../components/ControlPill";
21import { scopedThreadKey } from "../../lib/scopedEntities";
22import { useUniwindTheme } from "../../lib/useUniwindTheme";
23import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
24import { useAssetUrl } from "../../state/assets";
25import { beginQueuedRunEdit, useQueuedRunEdit } from "../../state/queued-run-edit";
26import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
27import { useAtomCommand } from "../../state/use-atom-command";
28import {
29 buildCancelQueuedRunCommand,
30 resolveQueueDragBeforeRunId,
31 resolveQueueDropBeforeRunId,
32 resolveThreadQueueRowControls,
33} from "./threadQueueControlPresentation";
34import { threadDragGapOffset } from "./threadDragGap";
35​
36const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
37const REMOVE_ACTION_WIDTH = 76;
38const THUMBNAIL_LIMIT = 3;
39​
40type QueueTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId };
41type QueueAction = "steer" | "edit" | "up" | "down" | "remove";
42type QueueRowLayout = { readonly id: RunId; readonly y?: number; readonly height?: number };
43​
44export function useThreadQueueWorkflow(target: QueueTarget) {
45 return useAtomValue(environmentThreadDetails.queueWorkflowAtom(target));
47​
48export function useThreadQueuedCount(target: QueueTarget) {
49 return useAtomValue(environmentThreadDetails.queuedCountAtom(target));
51​
52export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
53 const target = route.params;
54 const navigation = useNavigation();
55 const insets = useSafeAreaInsets();
56 const theme = useUniwindTheme();
57 const workflow = useThreadQueueWorkflow(target);
58 const threadKey = scopedThreadKey(target.environmentId, target.threadId);
59 const editing = useQueuedRunEdit(threadKey);
60 const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun, "reorder queued message");
61 const promote = useAtomCommand(threadEnvironment.promoteQueuedRun, "promote queued message");
62 const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun, "remove queued message");
63 const resume = useAtomCommand(threadEnvironment.resumeThreadQueue, "resume queue");
64 const [resuming, setResuming] = useState(false);
65 const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
66 const busyRef = useRef(false);
67 const [draggedRunId, setDraggedRunId] = useState<RunId | null>(null);
68 const [previewBeforeRunId, setPreviewBeforeRunId] = useState<RunId | null | undefined>();
69 const [dragRows, setDragRows] = useState<ReadonlyArray<QueueRowLayout> | null>(null);
70 const rowLayouts = useRef(new Map<RunId, { y: number; height: number }>());
71 const drag = useRef<{
72 runId: RunId;
73 order: string;
74 beforeRunId: RunId | null | undefined;
75 rows: ReadonlyArray<QueueRowLayout>;
76 } | null>(null);
77 const [translation] = useState(() => new Animated.Value(0));
78 const queuedRuns = workflow?.queuedRuns ?? [];
79 const order = queuedRuns.map(({ run }) => run.id).join(",");
80​
81 useEffect(() => {
82 if (drag.current && drag.current.order !== order) {
83 drag.current = null;
84 setDraggedRunId(null);
85 setPreviewBeforeRunId(undefined);
86 setDragRows(null);
87 translation.setValue(0);
88 }
89 }, [order, translation]);
90​
91 // Nothing left to manage: the sheet closes rather than sitting on an empty
92 // list the user has to dismiss themselves.
93 const hadQueuedRuns = useRef(queuedRuns.length > 0);
94 useEffect(() => {
95 if (queuedRuns.length > 0) {
96 hadQueuedRuns.current = true;
97 return;
98 }
99 if (hadQueuedRuns.current) navigation.goBack();
100 }, [navigation, queuedRuns.length]);
101​
102 const move = async (runId: RunId, beforeRunId: RunId | null) => {
103 if (busyRef.current || !workflow?.canReorder) return;
104 busyRef.current = true;
105 setBusyRunId(runId);
106 void Haptics.selectionAsync();
107 try {
108 await reorder({ ...target, input: { threadId: target.threadId, runId, beforeRunId } });
109 } finally {
110 busyRef.current = false;
111 setBusyRunId(null);
112 }
113 };
114​
115 const act = async (runId: RunId, action: QueueAction) => {
116 if (busyRef.current) return;
117 const index = queuedRuns.findIndex(({ run }) => run.id === runId);
118 if (index < 0) return;
119 if (action === "up" && index > 0) {
120 await move(runId, queuedRuns[index - 1]!.run.id);
121 return;
122 }
123 if (action === "down" && index < queuedRuns.length - 1) {
124 await move(runId, queuedRuns[index + 2]?.run.id ?? null);
125 return;
126 }
127 if (action === "edit") {
128 const entry = queuedRuns[index]!;
129 void Haptics.selectionAsync();
130 beginQueuedRunEdit(threadKey, {
131 runId,
132 messageId: entry.messageId,
133 originalText: entry.text,
134 existingAttachments: entry.attachments,
135 ...(entry.context ? { context: entry.context } : {}),
136 });
137 navigation.goBack();
138 return;
139 }
140 if (action !== "steer" && action !== "remove") return;
141 busyRef.current = true;
142 setBusyRunId(runId);
143 void Haptics.selectionAsync();
144 try {
145 if (action === "remove") {
146 await cancel(buildCancelQueuedRunCommand({ ...target, runId }));
147 } else if (workflow?.activeRun && workflow.canPromoteToSteer) {
148 await promote({
149 ...target,
150 input: {
151 threadId: target.threadId,
152 queuedRunId: runId,
153 targetRunId: workflow.activeRun.id,
154 },
155 });
156 }
157 } finally {
158 busyRef.current = false;
159 setBusyRunId(null);
160 }
161 };
162​
163 const canReorder = workflow?.canReorder === true && queuedRuns.length > 1;
164 const sourceLayout = dragRows?.find((row) => row.id === draggedRunId);
165 const lastLayout = dragRows?.at(-1);
166 const insertionOffset =
167 previewBeforeRunId === undefined
168 ? undefined
169 : previewBeforeRunId === null
170 ? lastLayout?.y === undefined || lastLayout.height === undefined
171 ? undefined
172 : lastLayout.y + lastLayout.height
173 : dragRows?.find((row) => row.id === previewBeforeRunId)?.y;
174 const queueRows = () =>
175 queuedRuns.map(({ run }) => ({ id: run.id, ...rowLayouts.current.get(run.id) }));
176 const content = (
177 <ScrollView
178 className="flex-1"
179 scrollEnabled={draggedRunId === null}
180 // The iOS header is translucent and floats over this view; UIKit has to
181 // inset the content or the first row sits underneath the title.
182 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
183 contentContainerClassName="px-5 pb-6"
184 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}
185 >
186 {workflow?.isHeld && queuedRuns.length > 0 ? (
187 <View className="gap-2 py-3">
188 <Text className="text-sm text-foreground-muted">Queue held after restart</Text>
189 <MaterialButton
190 label="Resume queue"
191 disabled={resuming || busyRunId !== null}
192 onPress={async () => {
193 if (busyRef.current) return;
194 busyRef.current = true;
195 setResuming(true);
196 try {
197 await resume({ ...target, input: { threadId: target.threadId } });
198 } finally {
199 busyRef.current = false;
200 setResuming(false);
201 }
202 }}
203 />
204 </View>
205 ) : null}
206 {queuedRuns.length === 0 ? (
207 <Text className="pt-6 text-center text-sm text-foreground-muted">
208 No messages waiting in this queue.
209 </Text>
210 ) : null}
211 {queuedRuns.map(({ run, text, attachments }, index) => {
212 const layout = dragRows?.find((row) => row.id === run.id);
213 const offset =
214 sourceLayout?.y !== undefined &&
215 sourceLayout.height !== undefined &&
216 layout?.y !== undefined &&
217 insertionOffset !== undefined
218 ? threadDragGapOffset(layout.y, sourceLayout.y, sourceLayout.height, insertionOffset)
219 : 0;
220 const controls = resolveThreadQueueRowControls({
221 busy: busyRunId !== null || draggedRunId !== null,
222 canPromoteToSteer: workflow?.canPromoteToSteer ?? false,
223 canReorder: workflow?.canReorder ?? false,
224 index,
225 isEditing: editing?.runId === run.id,
226 queuedCount: queuedRuns.length,
227 text,
228 });
229 const title =
230 controls.displayText || (attachments.length > 0 ? "Attachments" : "Queued message");
231 return (
232 <QueueShiftedRow
233 key={run.id}
234 offset={offset}
235 dragging={draggedRunId !== null}
236 lifted={draggedRunId === run.id}
237 onLayout={({ nativeEvent }) => rowLayouts.current.set(run.id, nativeEvent.layout)}
238 >
239 <Animated.View
240 className="flex-row items-center border-b border-border bg-sheet"
241 style={
242 draggedRunId === run.id
243 ? { transform: [{ translateY: translation }], zIndex: 1, opacity: 0.85 }
244 : undefined
245 }
246 >
247 {canReorder ? (
248 // Outside the swipeable: two pans on one row would race, and
249 // the handle owns vertical movement while the row owns sideways.
250 <QueueDragHandle
251 disabled={busyRunId !== null}
252 title={title}
253 canMoveUp={controls.canMoveUp}
254 canMoveDown={controls.canMoveDown}
255 onStep={(action) => void act(run.id, action)}
256 onStart={() => {
257 const rows = queueRows();
258 const beforeRunId = resolveQueueDragBeforeRunId(rows, run.id, 0);
259 drag.current = { runId: run.id, order, beforeRunId, rows };
260 translation.setValue(0);
261 setDragRows(rows);
262 setPreviewBeforeRunId(beforeRunId);
263 setDraggedRunId(run.id);
264 void Haptics.selectionAsync();
265 }}
266 onMove={(y) => {
267 const current = drag.current;
268 if (current?.runId !== run.id || current.order !== order) return;
269 translation.setValue(y);
270 const before = resolveQueueDragBeforeRunId(current.rows, run.id, y);
271 if (current.beforeRunId !== before) {
272 current.beforeRunId = before;
273 setPreviewBeforeRunId(before);
274 }
275 }}
276 onEnd={(y, success) => {
277 const started = drag.current;
278 const stop = () => {
279 if (drag.current !== started) return;
280 drag.current = null;
281 setDraggedRunId(null);
282 setPreviewBeforeRunId(undefined);
283 setDragRows(null);
284 translation.setValue(0);
285 };
286 // A remote reorder or a newly started run invalidates this drag.
287 if (!success || started?.order !== order || started.runId !== run.id) {
288 stop();
289 return;
290 }
291 const before = resolveQueueDropBeforeRunId(started.rows, run.id, y);
292 if (before === undefined) {
293 stop();
294 return;
295 }
296 const source = started.rows.find((row) => row.id === run.id);
297 const tail = started.rows.at(-1);
298 const insertion =
299 before === null
300 ? tail?.y !== undefined && tail.height !== undefined
301 ? tail.y + tail.height
302 : undefined
303 : started.rows.find((row) => row.id === before)?.y;
304 if (
305 source?.y !== undefined &&
306 source.height !== undefined &&
307 insertion !== undefined
308 ) {
309 Animated.timing(translation, {
310 toValue: insertion - source.y - (insertion > source.y ? source.height : 0),
311 duration: 160,
312 useNativeDriver: true,
313 }).start();
314 }
315 setPreviewBeforeRunId(before);
316 void move(run.id, before).finally(stop);
317 }}
318 />
319 ) : null}
320 <QueueRowSwipeable
321 enabled={draggedRunId === null && busyRunId === null && controls.canDismiss}
322 background={theme["--color-sheet"]}
323 onRemove={() => void act(run.id, "remove")}
324 >
325 <ControlPillMenu
326 accessibilityLabel={`Actions for queued message ${index + 1}`}
327 shouldOpenOnLongPress
328 actions={[
329 ...(workflow?.canPromoteToSteer
330 ? [
331 {
332 id: "steer",
333 title: "Steer now",
334 attributes: { disabled: !controls.canSteer },
335 image: Platform.OS === "ios" ? "arrow.turn.left.up" : "arrow_upward",
336 },
337 ]
338 : []),
339 {
340 id: "edit",
341 title: "Edit",
342 attributes: { disabled: !controls.canEdit },
343 image: Platform.OS === "ios" ? "pencil" : "edit",
344 },
345 { id: "up", title: "Move up", attributes: { disabled: !controls.canMoveUp } },
346 {
347 id: "down",
348 title: "Move down",
349 attributes: { disabled: !controls.canMoveDown },
350 },
351 {
352 id: "remove",
353 title: "Remove",
354 attributes: { disabled: !controls.canDismiss, destructive: true },
355 },
356 ]}
357 onPressAction={({ nativeEvent }) =>
358 void act(run.id, nativeEvent.event as QueueAction)
359 }
360 >
361 <Pressable
362 accessibilityRole="button"
363 accessibilityLabel={title}
364 accessibilityHint="Opens this message in the composer for editing"
365 disabled={!controls.canEdit}
366 onPress={() => void act(run.id, "edit")}
367 className="min-h-14 flex-row items-center gap-2.5 py-2.5 active:opacity-70"
368 >
369 <QueueAttachmentThumbnails
370 environmentId={target.environmentId}
371 attachments={attachments}
372 />
373 <Text
374 className={
375 controls.isEditing
376 ? "min-w-0 flex-1 text-sm text-foreground-muted"
377 : "min-w-0 flex-1 text-sm text-foreground"
378 }
379 numberOfLines={1}
380 >
381 {title}
382 </Text>
383 {controls.isEditing ? (
384 <Text className="shrink-0 text-2xs uppercase tracking-wide text-primary">
385 Editing
386 </Text>
387 ) : null}
388 {workflow?.canPromoteToSteer ? (
389 <Pressable
390 accessibilityRole="button"
391 accessibilityLabel={`Steer with message ${index + 1} now`}
392 disabled={!controls.canSteer}
393 onPress={() => void act(run.id, "steer")}
394 className="h-8 shrink-0 justify-center rounded-full bg-primary px-3 active:opacity-70 disabled:opacity-40"
395 >
396 <Text className="font-t3-medium text-xs text-primary-foreground">
397 Steer
398 </Text>
399 </Pressable>
400 ) : null}
401 </Pressable>
402 </ControlPillMenu>
403 </QueueRowSwipeable>
404 </Animated.View>
405 </QueueShiftedRow>
406 );
407 })}
408 </ScrollView>
409 );
410​
411 if (Platform.OS === "ios") {
412 // A plain formSheet screen never renders a stack header, so it comes from
413 // a nested native stack inside the sheet (same shape as the git sheet).
414 return (
415 <GestureHandlerRootView style={{ flex: 1 }}>
416 <View collapsable={false} className="flex-1 bg-sheet">
417 <ScreenStack style={{ flex: 1 }}>
418 <Screen
419 activityState={2}
420 enabled
421 isNativeStack
422 screenId="thread-queue-sheet-native"
423 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
424 style={{ backgroundColor: theme["--color-sheet"], flex: 1 }}
425 >
426 {content}
427 <ScreenStackHeaderConfig
428 backgroundColor="rgba(0,0,0,0)"
429 color={theme["--color-foreground"]}
430 hideBackButton
431 hideShadow={false}
432 title="Queued"
433 titleColor={theme["--color-foreground"]}
434 titleFontSize={18}
435 titleFontWeight="800"
436 translucent
437 />
438 </Screen>
439 </ScreenStack>
440 </View>
441 </GestureHandlerRootView>
442 );
443 }
444​
445 return (
446 <GestureHandlerRootView style={{ flex: 1 }}>
447 <View collapsable={false} className="flex-1 bg-sheet">
448 <AndroidSheetHeader title="Queued" onBack={() => navigation.goBack()} />
449 {content}
450 </View>
451 </GestureHandlerRootView>
452 );
454​
455function QueueShiftedRow(props: {
456 readonly offset: number;
457 readonly dragging: boolean;
458 readonly lifted: boolean;
459 readonly onLayout: React.ComponentProps<typeof View>["onLayout"];
460 readonly children: React.ReactNode;
461}) {
462 const { dragging, offset } = props;
463 const style = useAnimatedStyle(() => ({
464 transform: [
465 {
466 translateY: dragging
467 ? withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System })
468 : offset,
469 },
470 ],
471 }));
472 return (
473 <Reanimated.View onLayout={props.onLayout} style={[style, { zIndex: props.lifted ? 1 : 0 }]}>
474 {props.children}
475 </Reanimated.View>
476 );
478​
479/** Swipe left to remove, the one destructive action that needs no menu. */
480function QueueRowSwipeable(props: {
481 readonly enabled: boolean;
482 readonly background: string;
483 readonly onRemove: () => void;
484 readonly children: React.ReactNode;
485}) {
486 const swipeableRef = useRef<SwipeableMethods | null>(null);
487 return (
488 <ReanimatedSwipeable
489 ref={swipeableRef}
490 enabled={props.enabled}
491 friction={2}
492 rightThreshold={40}
493 overshootRight={false}
494 // The sheet's own vertical scroll and the drag handle both move up and
495 // down; a swipe has to be clearly sideways before it takes the gesture.
496 failOffsetY={[-12, 12]}
497 containerStyle={{ backgroundColor: props.background, flex: 1 }}
498 childrenContainerStyle={{ backgroundColor: props.background }}
499 onSwipeableOpen={(direction) => {
500 if (direction !== "right") return;
501 swipeableRef.current?.close();
502 props.onRemove();
503 }}
504 renderRightActions={() => (
505 <View
506 className="items-center justify-center bg-danger"
507 style={{ width: REMOVE_ACTION_WIDTH }}
508 >
509 <SymbolView name="trash" size={16} tintColorClassName="accent-danger-foreground" />
510 <Text className="pt-1 text-2xs font-t3-medium text-danger-foreground">Remove</Text>
511 </View>
512 )}
513 >
514 {props.children}
515 </ReanimatedSwipeable>
516 );
518​
519function QueueAttachmentThumbnails(props: {
520 readonly environmentId: EnvironmentId;
521 readonly attachments: ReadonlyArray<ChatAttachment>;
522}) {
523 const images = props.attachments.filter((attachment) => attachment.mimeType.startsWith("image/"));
524 const shown = images.slice(0, THUMBNAIL_LIMIT);
525 const overflow = props.attachments.length - shown.length;
526 if (props.attachments.length === 0) return null;
527 return (
528 <View className="shrink-0 flex-row items-center gap-1">
529 {shown.map((attachment) => (
530 <QueueAttachmentThumbnail
531 key={attachment.id}
532 environmentId={props.environmentId}
533 attachment={attachment}
534 />
535 ))}
536 {overflow > 0 ? (
537 <View className="h-6 min-w-6 items-center justify-center rounded bg-subtle px-1">
538 <Text className="text-2xs tabular-nums text-foreground-muted">
539 {shown.length === 0 ? `${overflow}` : `+${overflow}`}
540 </Text>
541 </View>
542 ) : null}
543 </View>
544 );
546​
547function QueueAttachmentThumbnail(props: {
548 readonly environmentId: EnvironmentId;
549 readonly attachment: ChatAttachment;
550}) {
551 const url = useAssetUrl(props.environmentId, {
552 _tag: "attachment",
553 attachmentId: props.attachment.id,
554 fileName: props.attachment.name,
555 mimeType: props.attachment.mimeType,
556 disposition: "inline",
557 });
558 if (url === null) {
559 return <View className="h-6 w-6 rounded bg-subtle" />;
560 }
561 return (
562 <Image
563 source={{ uri: url }}
564 contentFit="cover"
565 style={{ width: 24, height: 24, borderRadius: 4 }}
566 accessibilityIgnoresInvertColors
567 />
568 );
570​
571function QueueDragHandle(props: {
572 disabled: boolean;
573 title: string;
574 canMoveUp: boolean;
575 canMoveDown: boolean;
576 onStep: (action: "up" | "down") => void;
577 onStart: () => void;
578 onMove: (y: number) => void;
579 onEnd: (y: number, success: boolean) => void;
580}) {
581 const latest = useRef(props);
582 useLayoutEffect(() => {
583 latest.current = props;
584 });
585 const gesture = useMemo(
586 () =>
587 Gesture.Pan()
588 .enabled(!props.disabled)
589 .minDistance(0)
590 .shouldCancelWhenOutside(false)
591 .runOnJS(true)
592 .onStart(() => latest.current.onStart())
593 .onUpdate((event) => latest.current.onMove(event.translationY))
594 .onFinalize((event, success) => latest.current.onEnd(event.translationY, success)),
595 [props.disabled],
596 );
597 return (
598 <GestureDetector gesture={gesture}>
599 <View
600 collapsable={false}
601 accessible
602 accessibilityRole="adjustable"
603 accessibilityLabel={`Reorder ${props.title}`}
604 accessibilityState={{ disabled: props.disabled }}
605 accessibilityActions={[
606 ...(props.canMoveUp ? [{ name: "decrement", label: "Move up" }] : []),
607 ...(props.canMoveDown ? [{ name: "increment", label: "Move down" }] : []),
608 ]}
609 onAccessibilityAction={({ nativeEvent }) => {
610 if (props.disabled) return;
611 if (nativeEvent.actionName === "decrement" && props.canMoveUp) props.onStep("up");
612 if (nativeEvent.actionName === "increment" && props.canMoveDown) props.onStep("down");
613 }}
614 className="h-12 w-8 items-center justify-center"
615 >
616 <SymbolView
617 name="line.3.horizontal"
618 size={16}
619 tintColorClassName="accent-foreground-muted"
620 />
621 </View>
622 </GestureDetector>
623 );