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

ThreadQueueControl.tsx

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