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