The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 628 lines 27 KB
Raw
1 import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
2 import { SheetHeader } from "../../components/ui/SheetHeader";
3 import { appAtomRegistry } from "../../state/atom-registry";
4 import { useAtomValue } from "@effect/atom-react";
5 import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
6 import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
7 import { sortInboxThreadsByReturn } from "@t3tools/client-runtime/state/thread-inbox";
8 import { msg, T, useGT, useMessages } from "gt-react-native";
9 import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
10 import { Animated, Modal, Pressable, useWindowDimensions, View } from "react-native";
11 import { Gesture, GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler";
12 import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
13 import { threadDragGapOffset } from "./threadDragGap";
14 import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context";
15
16 import { AppText as Text } from "../../components/ui/AppText";
17 import { SymbolView } from "../../components/ui/AppSymbol";
18 import { scopedThreadKey } from "../../lib/scopedEntities";
19 import { deriveThreadArrangementSizing } from "../../lib/layout";
20 import { environmentServerConfigsAtom } from "../../state/server";
21 import { threadListEnvironmentsAtom } from "../../state/presentation";
22 import { steadyNavigationThreadShellsAtom, steadyShellsHoldingAtom } from "../../state/threads";
23 import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort";
24 import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../../state/olderSettledShelf";
25 import {
26 pendingThreadOrderAtom,
27 threadDropBusyAtom,
28 threadArrangementOpenAtom,
29 } from "../../state/thread-order";
30 import { queuedThreadKeysAtom } from "../../state/use-thread-outbox";
31 import { useThreadListActions } from "../home/useThreadListActions";
32 import {
33 createThreadMovePlanner,
34 threadDragAction,
35 type ThreadMoveDestination,
36 } from "./threadOrder";
37 import {
38 getThreadListV2OrderedSection,
39 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
40 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
41 threadListInboxReturns,
42 } from "./threadListV2";
43 import { useThreadListNow } from "./use-thread-list-now";
44 import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
45 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
46
47 const keyOf = (thread: EnvironmentThreadShell) => scopedThreadKey(thread.environmentId, thread.id);
48 type Section = "pinned" | "active" | "snoozed" | "settled";
49 type Destination = Exclude<ThreadMoveDestination, string>;
50 type Row = {
51 key: string;
52 section: Section;
53 thread?: EnvironmentThreadShell;
54 /** The Settled section's "Show more" row. */
55 more?: true;
56 offset: number;
57 height: number;
58 };
59 type Drag = {
60 orderVersion: string;
61 sourceSection: Section;
62 thread: EnvironmentThreadShell;
63 startY: number;
64 translation: number;
65 destination: Destination | null;
66 };
67
68 const SECTION_LABELS = {
69 pinned: msg("Pinned", { $context: "thread list section" }),
70 active: msg("Active", { $context: "thread list section" }),
71 snoozed: msg("Snoozed", { $context: "thread list section" }),
72 settled: msg("Settled", { $context: "thread list section" }),
73 } as const;
74
75 function ArrangementRow(props: {
76 height: number;
77 offset: number;
78 lifted: boolean;
79 dragging: boolean;
80 children: ReactNode;
81 }) {
82 const { dragging, offset, lifted } = props;
83 const style = useAnimatedStyle(() => ({
84 transform: [
85 {
86 translateY: dragging
87 ? withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System })
88 : offset,
89 },
90 ],
91 opacity: lifted ? 0 : 1,
92 }));
93 return (
94 <Reanimated.View
95 style={[{ height: props.height }, style]}
96 className="flex-row items-center border-b border-border-subtle px-5"
97 >
98 {props.children}
99 </Reanimated.View>
100 );
101 }
102
103 function DragHandle(props: {
104 title: string;
105 disabled: boolean;
106 onStart: () => void;
107 onMove: (translation: number) => void;
108 onEnd: (cancelled: boolean) => void;
109 onStep: (direction: "up" | "down") => void;
110 sectionActions: readonly { name: "pinned" | "active" | "settled"; label: string }[];
111 onSectionMove: (section: "pinned" | "active" | "settled") => void;
112 canMoveUp: boolean;
113 canMoveDown: boolean;
114 }) {
115 const gt = useGT();
116 const latest = useRef(props);
117 /* oxlint-disable react/refs -- The pan gesture captures its callbacks once per `disabled` change; they read the latest handlers when native gesture events fire. */
118 latest.current = props;
119 const gesture = useMemo(
120 () =>
121 // oxlint-disable-next-line react/capitalized-calls -- Gesture.Pan is a gesture factory, not a React component.
122 Gesture.Pan()
123 .enabled(!props.disabled)
124 .minDistance(0)
125 .shouldCancelWhenOutside(false)
126 .runOnJS(true)
127 .onStart(() => latest.current.onStart())
128 .onUpdate((event) => latest.current.onMove(event.translationY))
129 .onEnd((event) => latest.current.onMove(event.translationY))
130 .onFinalize((_, success) => latest.current.onEnd(!success)),
131 [props.disabled, latest],
132 );
133 /* oxlint-enable react/refs */
134 return (
135 <GestureDetector gesture={gesture}>
136 <View
137 collapsable={false}
138 accessible
139 accessibilityRole="adjustable"
140 accessibilityLabel={gt("Reorder {title}", { title: props.title })}
141 accessibilityHint={gt(
142 "Move up and Move down reorder within this section. Other actions move between sections.",
143 )}
144 accessibilityState={{ disabled: props.disabled }}
145 accessibilityActions={[
146 ...props.sectionActions,
147 ...(props.canMoveUp ? [{ name: "decrement", label: gt("Move up") }] : []),
148 ...(props.canMoveDown ? [{ name: "increment", label: gt("Move down") }] : []),
149 ]}
150 onAccessibilityAction={({ nativeEvent }) => {
151 if (props.disabled) return;
152 const sectionAction = props.sectionActions.find(
153 (action) => action.name === nativeEvent.actionName,
154 );
155 if (sectionAction) props.onSectionMove(sectionAction.name);
156 if (nativeEvent.actionName === "decrement" && props.canMoveUp) props.onStep("up");
157 if (nativeEvent.actionName === "increment" && props.canMoveDown) props.onStep("down");
158 }}
159 style={{
160 width: 48,
161 height: 48,
162 alignItems: "center",
163 justifyContent: "center",
164 opacity: props.disabled ? 0.3 : 1,
165 }}
166 >
167 <SymbolView
168 name="line.3.horizontal"
169 size={22}
170 tintColorClassName="accent-foreground-muted"
171 />
172 </View>
173 </GestureDetector>
174 );
175 }
176
177 function ThreadArrangementSheet(props: { onClose: () => void }) {
178 const gt = useGT();
179 const m = useMessages();
180 const { appearance } = useAppearancePreferences();
181 const { fontScale } = useWindowDimensions();
182 const { rowHeight, headerHeight } = deriveThreadArrangementSizing({
183 baseFontSize: appearance.baseFontSize,
184 fontScale,
185 });
186 const threads = useAtomValue(steadyNavigationThreadShellsAtom);
187 const configs = useAtomValue(environmentServerConfigsAtom);
188 const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
189 const queuedThreadKeys = useAtomValue(queuedThreadKeysAtom);
190 const pendingOrder = useAtomValue(pendingThreadOrderAtom);
191 const dropBusy = useAtomValue(threadDropBusyAtom);
192 const holdingRows = useAtomValue(steadyShellsHoldingAtom);
193 const { moveThread } = useThreadListActions();
194 const { workingShelfEnabled } = useThreadListV2ShelfPreferences();
195 const now = useThreadListNow(threads);
196 const [expanded, setExpanded] = useState({ snoozed: false, settled: false });
197 const [settledVisibleCount, setSettledVisibleCount] = useState(
198 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
199 );
200 // Older settled threads load in pages, as in the thread list.
201 const olderSettledShelf = useOlderSettledShelf({
202 scopes: [...configs.keys()].map((environmentId) => ({ environmentId, projectIds: null })),
203 expanded: expanded.settled,
204 visibleCount: settledVisibleCount,
205 });
206 const sections = useMemo(() => {
207 const shared = {
208 threads,
209 now,
210 queuedThreadKeys,
211 pendingOrder,
212 settlementEnvironmentIds: new Set(configs.keys()),
213 snoozeEnvironmentIds: new Set(configs.keys()),
214 };
215 const pinned = getThreadListV2OrderedSection({ ...shared, section: "pinned" });
216 const active = getThreadListV2OrderedSection({ ...shared, section: "active" });
217 const visible = new Set([...pinned, ...active].map(keyOf));
218 const parked = threads.filter(
219 (thread) => thread.archivedAt === null && !visible.has(keyOf(thread)),
220 );
221 return {
222 pinned,
223 active: workingShelfEnabled
224 ? sortInboxThreadsByReturn(active, threadListInboxReturns.returnedAt)
225 : active,
226 snoozed: parked.filter((thread) => effectiveSnoozed(thread, { now })),
227 settled: sortSettledThreads(parked.filter((thread) => !effectiveSnoozed(thread, { now }))),
228 };
229 }, [threads, configs, now, queuedThreadKeys, pendingOrder, workingShelfEnabled]);
230 const listedSettled = sections.settled.filter(olderSettledShelf.isListed);
231 useOlderSettledShelfGrowth(olderSettledShelf, listedSettled);
232 const visibleSettled = listedSettled.slice(0, settledVisibleCount);
233 const settledCount = sections.settled.length + olderSettledShelf.unloadedCount(threads);
234 const planners = useMemo(() => {
235 const planner = (section: "pinned" | "active") =>
236 createThreadMovePlanner({
237 ordered: sections[section],
238 allThreads: threads,
239 section,
240 reorderableEnvironmentIds:
241 section === "pinned"
242 ? listEnvironments.pinReorderEnvironmentIds
243 : workingShelfEnabled
244 ? new Set()
245 : listEnvironments.activeReorderEnvironmentIds,
246 });
247 return { pinned: planner("pinned"), active: planner("active") };
248 }, [sections, threads, listEnvironments, workingShelfEnabled]);
249 const rows = useMemo(() => {
250 const result: Row[] = [];
251 let offset = 0;
252 for (const section of ["pinned", "active", "snoozed", "settled"] as const) {
253 if (section === "snoozed" && sections[section].length === 0) continue;
254 result.push({ key: section, section, offset, height: headerHeight });
255 offset += headerHeight;
256 if ((section === "snoozed" || section === "settled") && !expanded[section]) continue;
257 for (const thread of section === "settled" ? visibleSettled : sections[section]) {
258 result.push({ key: keyOf(thread), section, thread, offset, height: rowHeight });
259 offset += rowHeight;
260 }
261 if (section === "settled" && settledCount > visibleSettled.length) {
262 result.push({ key: "settled-more", section, more: true, offset, height: rowHeight });
263 offset += rowHeight;
264 }
265 }
266 return result;
267 }, [sections, expanded, visibleSettled, settledCount, rowHeight, headerHeight]);
268 const list = useRef<LegendListRef>(null);
269 const geometry = useRef({ height: 0, offset: 0 });
270 const drag = useRef<Drag | null>(null);
271 const frame = useRef<number | null>(null);
272 const [preview, setPreview] = useState<Drag | null>(null);
273 const [translateY] = useState(() => new Animated.Value(0));
274 const latest = useRef({ rows, planners, moveThread });
275 // oxlint-disable-next-line react/refs -- The autoscroll rAF loop started at drag start reads the current rows and planners on every frame.
276 latest.current = { rows, planners, moveThread };
277
278 function stop() {
279 if (frame.current !== null) cancelAnimationFrame(frame.current);
280 frame.current = null;
281 drag.current = null;
282 setPreview(null);
283 }
284 const orderVersion = rows
285 .map(
286 (row) => `${row.key}:${row.height}:${row.thread?.pinOrderKey}:${row.thread?.activeOrderKey}`,
287 )
288 .join("|");
289 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the in-progress drag gesture when the thread order changes underneath it
290 useEffect(() => {
291 // oxlint-disable-next-line react/exhaustive-effect-dependencies, react/set-state-in-effect -- A changed thread order cancels the in-progress drag and clears its preview; stop only touches refs and state setters.
292 stop();
293 }, [orderVersion]);
294 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the pending drag animation frame on unmount
295 useEffect(
296 () => () => {
297 if (frame.current !== null) cancelAnimationFrame(frame.current);
298 },
299 [],
300 );
301
302 function update(translation: number) {
303 const current = drag.current;
304 if (current === null) return;
305 current.translation = translation;
306 const { height, offset } = geometry.current;
307 const y = current.startY + translation;
308 translateY.setValue(Math.max(0, Math.min(height - rowHeight, y - rowHeight / 2)));
309 const contentY = Math.max(0, y + offset);
310 const target =
311 latest.current.rows.find((row) => contentY < row.offset + row.height) ??
312 latest.current.rows.at(-1);
313 let destination: Destination | null = null;
314 if (
315 target &&
316 y >= 0 &&
317 y <= height &&
318 (target.section === "pinned" || target.section === "active" || target.section === "settled")
319 ) {
320 const candidate: Destination = {
321 section: target.section,
322 targetId: target.thread ? target.key : null,
323 placement:
324 !target.thread || contentY < target.offset + target.height / 2 ? "before" : "after",
325 };
326 if (target.section === "settled") {
327 if (current.sourceSection !== "settled" && configs.has(current.thread.environmentId))
328 destination = { section: "settled", targetId: null, placement: "before" };
329 } else if (latest.current.planners[target.section](keyOf(current.thread), candidate) !== null)
330 destination = candidate;
331 }
332 if (
333 current.destination?.targetId !== destination?.targetId ||
334 current.destination?.section !== destination?.section ||
335 current.destination?.placement !== destination?.placement
336 ) {
337 current.destination = destination;
338 setPreview({ ...current });
339 }
340 }
341 function start(row: Row) {
342 if (!row.thread || preview !== null) return;
343 drag.current = {
344 orderVersion,
345 sourceSection: row.section,
346 thread: row.thread,
347 startY: row.offset + row.height / 2 - geometry.current.offset,
348 translation: 0,
349 destination: null,
350 };
351 setPreview({ ...drag.current });
352 update(0);
353 // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)
354 let last = performance.now();
355 const tick = () => {
356 const current = drag.current;
357 if (!current) return;
358 const timestamp = performance.now();
359 const dt = Math.min(timestamp - last, 32);
360 last = timestamp;
361 const bounds = geometry.current;
362 const y = current.startY + current.translation;
363 const speed =
364 y < 48
365 ? -Math.min(1, (48 - y) / 48)
366 : y > bounds.height - 48
367 ? Math.min(1, (y - bounds.height + 48) / 48)
368 : 0;
369 const tail = latest.current.rows.at(-1);
370 const maximum = Math.max(0, (tail ? tail.offset + tail.height : 0) - bounds.height);
371 const offset = Math.max(0, Math.min(maximum, bounds.offset + speed * dt * 0.5));
372 if (offset !== bounds.offset) {
373 bounds.offset = offset;
374 list.current?.scrollToOffset({ offset, animated: false });
375 update(current.translation);
376 }
377 frame.current = requestAnimationFrame(tick);
378 };
379 frame.current = requestAnimationFrame(tick);
380 }
381 const visiblePreview = preview?.orderVersion === orderVersion ? preview : null;
382 const sourceRow = visiblePreview
383 ? rows.find((row) => row.key === keyOf(visiblePreview.thread))
384 : undefined;
385 const destination = visiblePreview?.destination;
386 const targetRow = destination
387 ? rows.find(
388 (row) =>
389 row.section === destination.section &&
390 row.key === (destination.targetId ?? destination.section),
391 )
392 : undefined;
393 const insertionOffset = targetRow
394 ? targetRow.offset +
395 (!targetRow.thread || destination?.placement === "after" ? targetRow.height : 0)
396 : sourceRow?.offset;
397 return (
398 <Modal
399 visible
400 animationType="slide"
401 presentationStyle="fullScreen"
402 onRequestClose={props.onClose}
403 >
404 <GestureHandlerRootView style={{ flex: 1 }}>
405 {/* A Modal is its own native hierarchy, so measure its own safe area, including side
406 insets for the camera, instead of the presenting screen's. */}
407 <SafeAreaProvider style={{ flex: 1 }}>
408 <View className="flex-1 bg-screen">
409 <SafeAreaView style={{ flex: 1 }}>
410 <SheetHeader
411 presentation="inline"
412 title={gt("Arrange threads")}
413 onClose={props.onClose}
414 accessibilityLabel={gt("Close arrange threads")}
415 />
416 <Text className="px-5 pb-3 text-sm text-foreground-muted">
417 <T>Drag to reorder, pin, or settle. Changes save when you drop.</T>
418 </Text>
419 <View
420 onLayout={(event) => {
421 geometry.current.height = event.nativeEvent.layout.height;
422 }}
423 className="flex-1"
424 style={{ overflow: "hidden" }}
425 >
426 {/* oxlint-disable-next-line t3code/require-registered-list-scroll -- A full-screen Modal with an inline header; there is no navigation header to register with. */}
427 <LegendList
428 ref={list}
429 data={rows}
430 keyExtractor={(row) => row.key}
431 extraData={{
432 visiblePreview,
433 insertionOffset,
434 dropBusy,
435 pendingOrder,
436 listEnvironments,
437 planners,
438 configs,
439 }}
440 // Rows hold their drag gesture, so each keeps its own view.
441 recycleItems={false}
442 scrollEnabled={visiblePreview === null}
443 onScroll={(event) => {
444 geometry.current.offset = event.nativeEvent.contentOffset.y;
445 }}
446 scrollEventThrottle={16}
447 getFixedItemSize={(row) => row.height}
448 renderItem={({ item }) => {
449 const thread = item.thread;
450 const planner =
451 item.section === "pinned" || item.section === "active"
452 ? planners[item.section]
453 : null;
454 const configLoaded = thread ? configs.has(thread.environmentId) : false;
455 const sectionActions = thread
456 ? (["pinned", "active", "settled"] as const).flatMap<{
457 name: "pinned" | "active" | "settled";
458 label: string;
459 }>((section) => {
460 if (section === item.section) return [];
461 const label = threadDragAction(item.section, section, m);
462 if (!label) return [];
463 if (section === "settled")
464 return configLoaded ? [{ name: section, label }] : [];
465 if (
466 ((section === "pinned" || thread.pinnedAt != null) && !configLoaded) ||
467 (section === "active" && item.section === "settled" && !configLoaded) ||
468 (section === "active" && item.section === "snoozed" && !configLoaded)
469 )
470 return [];
471 return planners[section](item.key, {
472 section,
473 targetId: null,
474 placement: "before",
475 })
476 ? [{ name: section, label }]
477 : [];
478 })
479 : [];
480 return (
481 <ArrangementRow
482 height={item.height}
483 dragging={visiblePreview !== null}
484 lifted={item.key === sourceRow?.key}
485 offset={
486 sourceRow && insertionOffset !== undefined
487 ? threadDragGapOffset(
488 item.offset,
489 sourceRow.offset,
490 sourceRow.height,
491 insertionOffset,
492 )
493 : 0
494 }
495 >
496 {thread ? (
497 <>
498 <Text numberOfLines={2} className="flex-1 text-base">
499 {thread.title}
500 </Text>
501 <DragHandle
502 title={thread.title}
503 disabled={
504 dropBusy ||
505 pendingOrder !== null ||
506 holdingRows ||
507 (!listEnvironments.pinReorderEnvironmentIds.has(
508 thread.environmentId,
509 ) &&
510 !listEnvironments.activeReorderEnvironmentIds.has(
511 thread.environmentId,
512 ))
513 }
514 sectionActions={sectionActions}
515 onSectionMove={(section) => {
516 void moveThread(thread, {
517 section,
518 targetId: null,
519 placement: "before",
520 });
521 }}
522 canMoveUp={planner?.(item.key, "up") != null}
523 canMoveDown={planner?.(item.key, "down") != null}
524 onStep={(direction) => {
525 void moveThread(thread, direction);
526 }}
527 onStart={() => start(item)}
528 onMove={update}
529 onEnd={(cancelled) => {
530 const current = drag.current;
531 if (cancelled || !current?.destination) {
532 stop();
533 return;
534 }
535 if (frame.current !== null) cancelAnimationFrame(frame.current);
536 frame.current = null;
537 drag.current = null;
538 void moveThread(current.thread, current.destination).finally(stop);
539 }}
540 />
541 </>
542 ) : item.more ? (
543 <Pressable
544 disabled={olderSettledShelf.loading}
545 className="flex-1 justify-center self-stretch"
546 onPress={() => {
547 olderSettledShelf.retry();
548 setSettledVisibleCount(
549 (count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT,
550 );
551 }}
552 >
553 <Text className="text-sm text-foreground-muted">
554 {olderSettledShelf.loading
555 ? gt("Loading", { $context: "older threads are loading" })
556 : olderSettledShelf.failed
557 ? gt("Could not load older threads. Retry")
558 : gt(
559 "{count, plural, one {Show more ({count} settled hidden)} other {Show more ({count} settled hidden)}}",
560 {
561 count: settledCount - visibleSettled.length,
562 },
563 )}
564 </Text>
565 </Pressable>
566 ) : (
567 <Pressable
568 disabled={item.section === "pinned" || item.section === "active"}
569 className="flex-1 justify-center self-stretch"
570 onPress={() => {
571 const section = item.section;
572 if (section === "snoozed" || section === "settled")
573 setExpanded((value) => ({ ...value, [section]: !value[section] }));
574 }}
575 >
576 <Text className="text-sm font-t3-semibold text-foreground-muted">
577 {gt("{section} ({count})", {
578 section: m(SECTION_LABELS[item.section]),
579 count:
580 item.section === "settled"
581 ? settledCount
582 : sections[item.section].length,
583 })}
584 </Text>
585 </Pressable>
586 )}
587 </ArrangementRow>
588 );
589 }}
590 />
591 {visiblePreview ? (
592 <Animated.View
593 pointerEvents="none"
594 className="absolute left-5 right-5 justify-center rounded-xl border border-border bg-screen px-4"
595 style={{ top: 0, height: rowHeight, transform: [{ translateY }] }}
596 >
597 <Text
598 numberOfLines={visiblePreview.destination?.section ? 1 : 2}
599 className="text-base font-t3-medium"
600 >
601 {visiblePreview.thread.title}
602 </Text>
603 {visiblePreview.destination?.section ? (
604 <Text className="text-xs text-foreground-muted">
605 {threadDragAction(
606 visiblePreview.sourceSection,
607 visiblePreview.destination.section,
608 m,
609 )}
610 </Text>
611 ) : null}
612 </Animated.View>
613 ) : null}
614 </View>
615 </SafeAreaView>
616 </View>
617 </SafeAreaProvider>
618 </GestureHandlerRootView>
619 </Modal>
620 );
621 }
622
623 export function ThreadArrangementHost() {
624 const open = useAtomValue(threadArrangementOpenAtom);
625 return open ? (
626 <ThreadArrangementSheet onClose={() => appAtomRegistry.set(threadArrangementOpenAtom, false)} />
627 ) : null;
628 }