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