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