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

ThreadArrangementSheet.tsx

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