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