Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadArrangementSheet.tsx

579 lines24.5 KB

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 );
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 );
163​
164function 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(configs.keys()),
190 snoozeEnvironmentIds: new Set(configs.keys()),
191 };
192 const pinned = getThreadListV2OrderedSection({ ...shared, section: "pinned" });
193 const active = getThreadListV2OrderedSection({ ...shared, section: "active" });
194 const visible = new Set([...pinned, ...active].map(keyOf));
195 const parked = threads.filter(
196 (thread) => thread.archivedAt === null && !visible.has(keyOf(thread)),
197 );
198 return {
199 pinned,
200 active: workingShelfEnabled
201 ? sortInboxThreadsByReturn(active, threadListInboxReturns.returnedAt)
202 : active,
203 snoozed: parked.filter((thread) => effectiveSnoozed(thread, { now })),
204 settled: sortSettledThreads(parked.filter((thread) => !effectiveSnoozed(thread, { now }))),
205 };
206 }, [threads, configs, now, queuedThreadKeys, pendingOrder, workingShelfEnabled]);
207 const listedSettled = sections.settled.filter(olderSettledShelf.isListed);
208 useOlderSettledShelfGrowth(olderSettledShelf, listedSettled);
209 const visibleSettled = listedSettled.slice(0, settledVisibleCount);
210 const settledCount = sections.settled.length + olderSettledShelf.unloadedCount(threads);
211 const planners = useMemo(() => {
212 const planner = (section: "pinned" | "active") =>
213 createThreadMovePlanner({
214 ordered: sections[section],
215 allThreads: threads,
216 section,
217 reorderableEnvironmentIds: new Set(
218 section === "pinned" || !workingShelfEnabled ? configs.keys() : [],
219 ),
220 });
221 return { pinned: planner("pinned"), active: planner("active") };
222 }, [sections, threads, configs, workingShelfEnabled]);
223 const rows = useMemo(() => {
224 const result: Row[] = [];
225 let offset = 0;
226 for (const section of ["pinned", "active", "snoozed", "settled"] as const) {
227 if (section === "snoozed" && sections[section].length === 0) continue;
228 result.push({ key: section, section, offset, height: HEADER_HEIGHT });
229 offset += HEADER_HEIGHT;
230 if ((section === "snoozed" || section === "settled") && !expanded[section]) continue;
231 for (const thread of section === "settled" ? visibleSettled : sections[section]) {
232 result.push({ key: keyOf(thread), section, thread, offset, height: ROW_HEIGHT });
233 offset += ROW_HEIGHT;
234 }
235 if (section === "settled" && settledCount > visibleSettled.length) {
236 result.push({ key: "settled-more", section, more: true, offset, height: ROW_HEIGHT });
237 offset += ROW_HEIGHT;
238 }
239 }
240 return result;
241 }, [sections, expanded, visibleSettled, settledCount]);
242 const list = useRef<FlatList<Row>>(null);
243 const geometry = useRef({ height: 0, offset: 0 });
244 const drag = useRef<Drag | null>(null);
245 const frame = useRef<number | null>(null);
246 const [preview, setPreview] = useState<Drag | null>(null);
247 const [translateY] = useState(() => new Animated.Value(0));
248 const latest = useRef({ rows, planners, moveThread });
249 // oxlint-disable-next-line react/refs -- The autoscroll rAF loop started at drag start reads the current rows and planners on every frame.
250 latest.current = { rows, planners, moveThread };
251​
252 function stop() {
253 if (frame.current !== null) cancelAnimationFrame(frame.current);
254 frame.current = null;
255 drag.current = null;
256 setPreview(null);
257 }
258 const orderVersion = rows
259 .map((row) => `${row.key}:${row.thread?.pinOrderKey}:${row.thread?.activeOrderKey}`)
260 .join("|");
261 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the in-progress drag gesture when the thread order changes underneath it
262 useEffect(() => {
263 // 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.
264 stop();
265 }, [orderVersion]);
266 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the pending drag animation frame on unmount
267 useEffect(
268 () => () => {
269 if (frame.current !== null) cancelAnimationFrame(frame.current);
270 },
271 [],
272 );
273​
274 function update(translation: number) {
275 const current = drag.current;
276 if (current === null) return;
277 current.translation = translation;
278 const { height, offset } = geometry.current;
279 const y = current.startY + translation;
280 translateY.setValue(Math.max(0, Math.min(height - ROW_HEIGHT, y - ROW_HEIGHT / 2)));
281 const contentY = Math.max(0, y + offset);
282 const target =
283 latest.current.rows.find((row) => contentY < row.offset + row.height) ??
284 latest.current.rows.at(-1);
285 let destination: Destination | null = null;
286 if (
287 target &&
288 y >= 0 &&
289 y <= height &&
290 (target.section === "pinned" || target.section === "active" || target.section === "settled")
291 ) {
292 const candidate: Destination = {
293 section: target.section,
294 targetId: target.thread ? target.key : null,
295 placement:
296 !target.thread || contentY < target.offset + target.height / 2 ? "before" : "after",
297 };
298 if (target.section === "settled") {
299 if (current.sourceSection !== "settled" && configs.has(current.thread.environmentId))
300 destination = { section: "settled", targetId: null, placement: "before" };
301 } else if (latest.current.planners[target.section](keyOf(current.thread), candidate) !== null)
302 destination = candidate;
303 }
304 if (
305 current.destination?.targetId !== destination?.targetId ||
306 current.destination?.section !== destination?.section ||
307 current.destination?.placement !== destination?.placement
308 ) {
309 current.destination = destination;
310 setPreview({ ...current });
311 }
312 }
313 function start(row: Row) {
314 if (!row.thread || preview !== null) return;
315 drag.current = {
316 orderVersion,
317 sourceSection: row.section,
318 thread: row.thread,
319 startY: row.offset + ROW_HEIGHT / 2 - geometry.current.offset,
320 translation: 0,
321 destination: null,
322 };
323 setPreview({ ...drag.current });
324 update(0);
325 // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)
326 let last = performance.now();
327 const tick = () => {
328 const current = drag.current;
329 if (!current) return;
330 const timestamp = performance.now();
331 const dt = Math.min(timestamp - last, 32);
332 last = timestamp;
333 const bounds = geometry.current;
334 const y = current.startY + current.translation;
335 const speed =
336 y < 48
337 ? -Math.min(1, (48 - y) / 48)
338 : y > bounds.height - 48
339 ? Math.min(1, (y - bounds.height + 48) / 48)
340 : 0;
341 const tail = latest.current.rows.at(-1);
342 const maximum = Math.max(0, (tail ? tail.offset + tail.height : 0) - bounds.height);
343 const offset = Math.max(0, Math.min(maximum, bounds.offset + speed * dt * 0.5));
344 if (offset !== bounds.offset) {
345 bounds.offset = offset;
346 list.current?.scrollToOffset({ offset, animated: false });
347 update(current.translation);
348 }
349 frame.current = requestAnimationFrame(tick);
350 };
351 frame.current = requestAnimationFrame(tick);
352 }
353 const visiblePreview = preview?.orderVersion === orderVersion ? preview : null;
354 const sourceRow = visiblePreview
355 ? rows.find((row) => row.key === keyOf(visiblePreview.thread))
356 : undefined;
357 const destination = visiblePreview?.destination;
358 const targetRow = destination
359 ? rows.find(
360 (row) =>
361 row.section === destination.section &&
362 row.key === (destination.targetId ?? destination.section),
363 )
364 : undefined;
365 const insertionOffset = targetRow
366 ? targetRow.offset +
367 (!targetRow.thread || destination?.placement === "after" ? targetRow.height : 0)
368 : sourceRow?.offset;
369 return (
370 <Modal
371 visible
372 animationType="slide"
373 presentationStyle="fullScreen"
374 onRequestClose={props.onClose}
375 >
376 <GestureHandlerRootView style={{ flex: 1 }}>
377 {/* A Modal is its own native hierarchy, so measure its own safe area, including side
378 insets for the camera, instead of the presenting screen's. */}
379 <SafeAreaProvider style={{ flex: 1 }}>
380 <View className="flex-1 bg-screen">
381 <SafeAreaView style={{ flex: 1 }}>
382 <SheetHeader
383 presentation="inline"
384 title="Arrange threads"
385 onClose={props.onClose}
386 accessibilityLabel="Close arrange threads"
387 />
388 <Text className="px-5 pb-3 text-sm text-foreground-muted">
389 Drag to reorder, pin, or settle. Changes save when you drop.
390 </Text>
391 <View
392 onLayout={(event) => {
393 geometry.current.height = event.nativeEvent.layout.height;
394 }}
395 className="flex-1"
396 style={{ overflow: "hidden" }}
397 >
398 <FlatList
399 ref={list}
400 data={rows}
401 keyExtractor={(row) => row.key}
402 scrollEnabled={visiblePreview === null}
403 removeClippedSubviews={false}
404 onScroll={(event) => {
405 geometry.current.offset = event.nativeEvent.contentOffset.y;
406 }}
407 scrollEventThrottle={16}
408 getItemLayout={(_, index) => ({
409 length: rows[index]!.height,
410 offset: rows[index]!.offset,
411 index,
412 })}
413 renderItem={({ item }) => {
414 const thread = item.thread;
415 const planner =
416 item.section === "pinned" || item.section === "active"
417 ? planners[item.section]
418 : null;
419 const configLoaded = thread ? configs.has(thread.environmentId) : false;
420 const sectionActions = thread
421 ? (["pinned", "active", "settled"] as const).flatMap<{
422 name: "pinned" | "active" | "settled";
423 label: string;
424 }>((section) => {
425 if (section === item.section) return [];
426 const label = threadDragAction(item.section, section);
427 if (!label) return [];
428 if (section === "settled")
429 return configLoaded ? [{ name: section, label }] : [];
430 if (
431 ((section === "pinned" || thread.pinnedAt != null) && !configLoaded) ||
432 (section === "active" && item.section === "settled" && !configLoaded) ||
433 (section === "active" && item.section === "snoozed" && !configLoaded)
434 )
435 return [];
436 return planners[section](item.key, {
437 section,
438 targetId: null,
439 placement: "before",
440 })
441 ? [{ name: section, label }]
442 : [];
443 })
444 : [];
445 return (
446 <ArrangementRow
447 height={item.height}
448 dragging={visiblePreview !== null}
449 lifted={item.key === sourceRow?.key}
450 offset={
451 sourceRow && insertionOffset !== undefined
452 ? threadDragGapOffset(
453 item.offset,
454 sourceRow.offset,
455 sourceRow.height,
456 insertionOffset,
457 )
458 : 0
459 }
460 >
461 {thread ? (
462 <>
463 <Text numberOfLines={2} className="flex-1 text-base">
464 {thread.title}
465 </Text>
466 <DragHandle
467 title={thread.title}
468 disabled={
469 dropBusy ||
470 pendingOrder !== null ||
471 !configs.has(thread.environmentId)
472 }
473 sectionActions={sectionActions}
474 onSectionMove={(section) => {
475 void moveThread(thread, {
476 section,
477 targetId: null,
478 placement: "before",
479 });
480 }}
481 canMoveUp={planner?.(item.key, "up") != null}
482 canMoveDown={planner?.(item.key, "down") != null}
483 onStep={(direction) => {
484 void moveThread(thread, direction);
485 }}
486 onStart={() => start(item)}
487 onMove={update}
488 onEnd={(cancelled) => {
489 const current = drag.current;
490 if (cancelled || !current?.destination) {
491 stop();
492 return;
493 }
494 if (frame.current !== null) cancelAnimationFrame(frame.current);
495 frame.current = null;
496 drag.current = null;
497 void moveThread(current.thread, current.destination).finally(stop);
498 }}
499 />
500 </>
501 ) : item.more ? (
502 <Pressable
503 disabled={olderSettledShelf.loading}
504 className="flex-1 justify-center self-stretch"
505 onPress={() => {
506 olderSettledShelf.retry();
507 setSettledVisibleCount(
508 (count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT,
509 );
510 }}
511 >
512 <Text className="text-sm text-foreground-muted">
513 {olderSettledShelf.loading
514 ? "Loading"
515 : olderSettledShelf.failed
516 ? "Could not load older threads. Retry"
517 : `Show more (${settledCount - visibleSettled.length} settled hidden)`}
518 </Text>
519 </Pressable>
520 ) : (
521 <Pressable
522 disabled={item.section === "pinned" || item.section === "active"}
523 className="flex-1 justify-center self-stretch"
524 onPress={() => {
525 const section = item.section;
526 if (section === "snoozed" || section === "settled")
527 setExpanded((value) => ({ ...value, [section]: !value[section] }));
528 }}
529 >
530 <Text className="text-sm font-t3-semibold text-foreground-muted">
531 {item.section[0]!.toUpperCase() + item.section.slice(1)} (
532 {item.section === "settled"
533 ? settledCount
534 : sections[item.section].length}
535 )
536 </Text>
537 </Pressable>
538 )}
539 </ArrangementRow>
540 );
541 }}
542 />
543 {visiblePreview ? (
544 <Animated.View
545 pointerEvents="none"
546 className="absolute left-5 right-5 justify-center rounded-xl border border-border bg-screen px-4"
547 style={{ top: 0, height: ROW_HEIGHT, transform: [{ translateY }] }}
548 >
549 <Text
550 numberOfLines={visiblePreview.destination?.section ? 1 : 2}
551 className="text-base font-t3-medium"
552 >
553 {visiblePreview.thread.title}
554 </Text>
555 {visiblePreview.destination?.section ? (
556 <Text className="text-xs text-foreground-muted">
557 {threadDragAction(
558 visiblePreview.sourceSection,
559 visiblePreview.destination.section,
560 )}
561 </Text>
562 ) : null}
563 </Animated.View>
564 ) : null}
565 </View>
566 </SafeAreaView>
567 </View>
568 </SafeAreaProvider>
569 </GestureHandlerRootView>
570 </Modal>
571 );
573​
574export function ThreadArrangementHost() {
575 const open = useAtomValue(threadArrangementOpenAtom);
576 return open ? (
577 <ThreadArrangementSheet onClose={() => appAtomRegistry.set(threadArrangementOpenAtom, false)} />
578 ) : null;