Open History to see the last commit
1import { appAtomRegistry } from "../../state/atom-registry";
2import { useAtomValue } from "@effect/atom-react";
3import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
5import { sortInboxThreadsByReturn } from "@t3tools/client-runtime/state/thread-inbox";
6import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
7import { Animated, FlatList, Modal, Pressable, View } from "react-native";
8import { Gesture, GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler";
9import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
10import { threadDragGapOffset } from "./threadDragGap";
11import { useSafeAreaInsets } from "react-native-safe-area-context";
12
13import { AppText as Text } from "../../components/AppText";
14import { SymbolView } from "../../components/AppSymbol";
15import { scopedThreadKey } from "../../lib/scopedEntities";
16import { environmentServerConfigsAtom } from "../../state/server";
17import { environmentThreadShells } from "../../state/threads";
18import {
19 pendingThreadOrderAtom,
20 threadDropBusyAtom,
21 threadArrangementOpenAtom,
22} from "../../state/thread-order";
23import { queuedThreadKeysAtom } from "../../state/use-thread-outbox";
24import { useThreadListActions } from "../home/useThreadListActions";
25import {
26 createThreadMovePlanner,
27 threadDragAction,
28 type ThreadMoveDestination,
29} from "./threadOrder";
30import { getThreadListV2OrderedSection, threadListInboxReturns } from "./threadListV2";
31import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
32
33const ROW_HEIGHT = 56;
34const HEADER_HEIGHT = 48;
35const keyOf = (thread: EnvironmentThreadShell) => scopedThreadKey(thread.environmentId, thread.id);
36type Section = "pinned" | "active" | "snoozed" | "settled";
37type Destination = Exclude<ThreadMoveDestination, string>;
38type Row = {
39 key: string;
40 section: Section;
41 thread?: EnvironmentThreadShell;
42 offset: number;
43 height: number;
44};
45type Drag = {
46 orderVersion: string;
47 sourceSection: Section;
48 thread: EnvironmentThreadShell;
49 startY: number;
50 translation: number;
51 destination: Destination | null;
52};
53
54function ArrangementRow(props: {
55 height: number;
56 offset: number;
57 lifted: boolean;
58 dragging: boolean;
59 children: ReactNode;
60}) {
61 const { dragging, offset, lifted } = props;
62 const style = useAnimatedStyle(() => ({
63 transform: [
64 {
65 translateY: dragging
66 ? withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System })
67 : offset,
68 },
69 ],
70 opacity: lifted ? 0 : 1,
71 }));
72 return (
73 <Reanimated.View
74 style={[{ height: props.height }, style]}
75 className="flex-row items-center border-b border-border-subtle px-5"
76 >
77 {props.children}
78 </Reanimated.View>
79 );
80}
81
82/** Native pan recognition wins over list scrolling only inside the handle. */
83function DragHandle(props: {
84 title: string;
85 disabled: boolean;
86 onStart: () => void;
87 onMove: (translation: number) => void;
88 onEnd: (cancelled: boolean) => void;
89 onStep: (direction: "up" | "down") => void;
90 sectionActions: readonly { name: "pinned" | "active" | "settled"; label: string }[];
91 onSectionMove: (section: "pinned" | "active" | "settled") => void;
92 canMoveUp: boolean;
93 canMoveDown: boolean;
94}) {
95 const latest = useRef(props);
96 latest.current = props;
97 const gesture = useMemo(
98 () =>
99 Gesture.Pan()
100 .enabled(!props.disabled)
101 .minDistance(0)
102 .shouldCancelWhenOutside(false)
103 .runOnJS(true)
104 .onStart(() => latest.current.onStart())
105 .onUpdate((event) => latest.current.onMove(event.translationY))
106 .onEnd((event) => latest.current.onMove(event.translationY))
107 .onFinalize((_, success) => latest.current.onEnd(!success)),
108 [props.disabled],
109 );
110 return (
111 <GestureDetector gesture={gesture}>
112 <View
113 collapsable={false}
114 accessible
115 accessibilityRole="adjustable"
116 accessibilityLabel={`Reorder ${props.title}`}
117 accessibilityHint="Move up and Move down reorder within this section. Other actions move between sections."
118 accessibilityState={{ disabled: props.disabled }}
119 accessibilityActions={[
120 ...props.sectionActions,
121 ...(props.canMoveUp ? [{ name: "decrement", label: "Move up" }] : []),
122 ...(props.canMoveDown ? [{ name: "increment", label: "Move down" }] : []),
123 ]}
124 onAccessibilityAction={({ nativeEvent }) => {
125 if (props.disabled) return;
126 const sectionAction = props.sectionActions.find(
127 (action) => action.name === nativeEvent.actionName,
128 );
129 if (sectionAction) props.onSectionMove(sectionAction.name);
130 if (nativeEvent.actionName === "decrement" && props.canMoveUp) props.onStep("up");
131 if (nativeEvent.actionName === "increment" && props.canMoveDown) props.onStep("down");
132 }}
133 style={{
134 width: 48,
135 height: 48,
136 alignItems: "center",
137 justifyContent: "center",
138 opacity: props.disabled ? 0.3 : 1,
139 }}
140 >
141 <SymbolView
142 name="line.3.horizontal"
143 size={22}
144 tintColorClassName="accent-foreground-muted"
145 />
146 </View>
147 </GestureDetector>
148 );
149}
150
151export function ThreadArrangementSheet(props: { onClose: () => void }) {
152 const insets = useSafeAreaInsets();
153 const threads = useAtomValue(environmentThreadShells.navigationThreadShellsAtom);
154 const configs = useAtomValue(environmentServerConfigsAtom);
155 const queuedThreadKeys = useAtomValue(queuedThreadKeysAtom);
156 const pendingOrder = useAtomValue(pendingThreadOrderAtom);
157 const dropBusy = useAtomValue(threadDropBusyAtom);
158 const { moveThread } = useThreadListActions();
159 const { workingShelfEnabled } = useThreadListV2ShelfPreferences();
160 const [now, setNow] = useState(() => new Date().toISOString());
161 const [expanded, setExpanded] = useState({ snoozed: false, settled: false });
162 useEffect(() => {
163 const wakeAt = Math.min(
164 ...threads.flatMap((thread) => {
165 const at = Date.parse(thread.snoozedUntil ?? "");
166 return at > Date.parse(now) ? [at] : [];
167 }),
168 );
169 if (!Number.isFinite(wakeAt)) return;
170 const timer = setTimeout(
171 () => setNow(new Date().toISOString()),
172 Math.min(Math.max(0, wakeAt - Date.now()) + 1, 2_147_483_647),
173 );
174 return () => clearTimeout(timer);
175 }, [threads, now]);
176 const sections = useMemo(() => {
177 const shared = {
178 threads,
179 now,
180 queuedThreadKeys,
181 pendingOrder,
182 settlementEnvironmentIds: new Set(
183 [...configs].flatMap(([id, config]) =>
184 config.environment.capabilities.threadSettlement ? [id] : [],
185 ),
186 ),
187 snoozeEnvironmentIds: new Set(
188 [...configs].flatMap(([id, config]) =>
189 config.environment.capabilities.threadSnooze ? [id] : [],
190 ),
191 ),
192 };
193 const pinned = getThreadListV2OrderedSection({ ...shared, section: "pinned" });
194 const active = getThreadListV2OrderedSection({ ...shared, section: "active" });
195 const visible = new Set([...pinned, ...active].map(keyOf));
196 const parked = threads.filter(
197 (thread) => thread.archivedAt === null && !visible.has(keyOf(thread)),
198 );
199 return {
200 pinned,
201 // The Working beta orders the inbox by time; show that order here too.
202 active: workingShelfEnabled
203 ? sortInboxThreadsByReturn(active, threadListInboxReturns.returnedAt)
204 : active,
205 snoozed: parked.filter((thread) => effectiveSnoozed(thread, { now })),
206 settled: parked.filter((thread) => !effectiveSnoozed(thread, { now })),
207 };
208 }, [threads, configs, now, queuedThreadKeys, pendingOrder, workingShelfEnabled]);
209 const planners = useMemo(() => {
210 const planner = (section: "pinned" | "active") =>
211 createThreadMovePlanner({
212 ordered: sections[section],
213 allThreads: threads,
214 section,
215 // A time-ordered inbox has no slots, so Active takes no drops while
216 // the Working beta is on. The saved arrangement stays untouched.
217 reorderableEnvironmentIds: new Set(
218 [...configs].flatMap(([id, config]) =>
219 (
220 section === "pinned"
221 ? config.environment.capabilities.threadPinReorder
222 : !workingShelfEnabled && config.environment.capabilities.threadActiveReorder
223 )
224 ? [id]
225 : [],
226 ),
227 ),
228 });
229 return { pinned: planner("pinned"), active: planner("active") };
230 }, [sections, threads, configs, workingShelfEnabled]);
231 const rows = useMemo(() => {
232 const result: Row[] = [];
233 let offset = 0;
234 for (const section of ["pinned", "active", "snoozed", "settled"] as const) {
235 if (section === "snoozed" && sections[section].length === 0) continue;
236 result.push({ key: section, section, offset, height: HEADER_HEIGHT });
237 offset += HEADER_HEIGHT;
238 if ((section === "snoozed" || section === "settled") && !expanded[section]) continue;
239 for (const thread of sections[section]) {
240 result.push({ key: keyOf(thread), section, thread, offset, height: ROW_HEIGHT });
241 offset += ROW_HEIGHT;
242 }
243 }
244 return result;
245 }, [sections, expanded]);
246 const list = useRef<FlatList<Row>>(null);
247 const geometry = useRef({ height: 0, offset: 0 });
248 const drag = useRef<Drag | null>(null);
249 const frame = useRef<number | null>(null);
250 const [preview, setPreview] = useState<Drag | null>(null);
251 const translateY = useRef(new Animated.Value(0)).current;
252 const latest = useRef({ rows, planners, moveThread });
253 latest.current = { rows, planners, moveThread };
254
255 function stop() {
256 if (frame.current !== null) cancelAnimationFrame(frame.current);
257 frame.current = null;
258 drag.current = null;
259 setPreview(null);
260 }
261 const orderVersion = rows
262 .map((row) => `${row.key}:${row.thread?.pinOrderKey}:${row.thread?.activeOrderKey}`)
263 .join("|");
264 useEffect(() => {
265 stop();
266 }, [orderVersion]);
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 (
300 current.sourceSection !== "settled" &&
301 configs.get(current.thread.environmentId)?.environment.capabilities.threadSettlement
302 )
303 destination = { section: "settled", targetId: null, placement: "before" };
304 } else if (latest.current.planners[target.section](keyOf(current.thread), candidate) !== null)
305 destination = candidate;
306 }
307 if (
308 current.destination?.targetId !== destination?.targetId ||
309 current.destination?.section !== destination?.section ||
310 current.destination?.placement !== destination?.placement
311 ) {
312 current.destination = destination;
313 setPreview({ ...current });
314 }
315 }
316 function start(row: Row) {
317 if (!row.thread || preview !== null) return;
318 drag.current = {
319 orderVersion,
320 sourceSection: row.section,
321 thread: row.thread,
322 startY: row.offset + ROW_HEIGHT / 2 - geometry.current.offset,
323 translation: 0,
324 destination: null,
325 };
326 setPreview({ ...drag.current });
327 update(0);
328 let last = performance.now();
329 const tick = () => {
330 const current = drag.current;
331 if (!current) return;
332 const timestamp = performance.now();
333 const dt = Math.min(timestamp - last, 32);
334 last = timestamp;
335 const bounds = geometry.current;
336 const y = current.startY + current.translation;
337 const speed =
338 y < 48
339 ? -Math.min(1, (48 - y) / 48)
340 : y > bounds.height - 48
341 ? Math.min(1, (y - bounds.height + 48) / 48)
342 : 0;
343 const tail = latest.current.rows.at(-1);
344 const maximum = Math.max(0, (tail ? tail.offset + tail.height : 0) - bounds.height);
345 const offset = Math.max(0, Math.min(maximum, bounds.offset + speed * dt * 0.5));
346 if (offset !== bounds.offset) {
347 bounds.offset = offset;
348 list.current?.scrollToOffset({ offset, animated: false });
349 update(current.translation);
350 }
351 frame.current = requestAnimationFrame(tick);
352 };
353 frame.current = requestAnimationFrame(tick);
354 }
355 const visiblePreview = preview?.orderVersion === orderVersion ? preview : null;
356 const sourceRow = visiblePreview
357 ? rows.find((row) => row.key === keyOf(visiblePreview.thread))
358 : undefined;
359 const destination = visiblePreview?.destination;
360 const targetRow = destination
361 ? rows.find(
362 (row) =>
363 row.section === destination.section &&
364 row.key === (destination.targetId ?? destination.section),
365 )
366 : undefined;
367 const insertionOffset = targetRow
368 ? targetRow.offset +
369 (!targetRow.thread || destination?.placement === "after" ? targetRow.height : 0)
370 : sourceRow?.offset;
371 return (
372 <Modal
373 visible
374 animationType="slide"
375 presentationStyle="fullScreen"
376 onRequestClose={props.onClose}
377 >
378 <GestureHandlerRootView style={{ flex: 1 }}>
379 <View
380 className="flex-1 bg-screen"
381 style={{ paddingTop: insets.top, paddingBottom: insets.bottom }}
382 >
383 <View className="flex-row items-center justify-between gap-3 px-5 py-3">
384 <Text className="flex-1 text-xl font-t3-semibold">Arrange threads</Text>
385 <Pressable
386 accessibilityRole="button"
387 onPress={props.onClose}
388 className="min-h-11 justify-center px-3"
389 >
390 <Text className="text-base text-primary-text">Done</Text>
391 </Pressable>
392 </View>
393 <Text className="px-5 pb-3 text-sm text-foreground-muted">
394 Drag to reorder, pin, or settle. Changes save when you drop.
395 </Text>
396 <View
397 onLayout={(event) => {
398 geometry.current.height = event.nativeEvent.layout.height;
399 }}
400 className="flex-1"
401 style={{ overflow: "hidden" }}
402 >
403 <FlatList
404 ref={list}
405 data={rows}
406 keyExtractor={(row) => row.key}
407 scrollEnabled={visiblePreview === null}
408 removeClippedSubviews={false}
409 onScroll={(event) => {
410 geometry.current.offset = event.nativeEvent.contentOffset.y;
411 }}
412 scrollEventThrottle={16}
413 getItemLayout={(_, index) => ({
414 length: rows[index]!.height,
415 offset: rows[index]!.offset,
416 index,
417 })}
418 renderItem={({ item }) => {
419 const thread = item.thread;
420 const planner =
421 item.section === "pinned" || item.section === "active"
422 ? planners[item.section]
423 : null;
424 const capabilities =
425 thread && configs.get(thread.environmentId)?.environment.capabilities;
426 const sectionActions = thread
427 ? (["pinned", "active", "settled"] as const).flatMap<{
428 name: "pinned" | "active" | "settled";
429 label: string;
430 }>((section) => {
431 if (section === item.section) return [];
432 const label = threadDragAction(item.section, section);
433 if (!label) return [];
434 if (section === "settled")
435 return capabilities?.threadSettlement ? [{ name: section, label }] : [];
436 if (
437 ((section === "pinned" || thread.pinnedAt != null) &&
438 !capabilities?.threadPinning) ||
439 (section === "active" &&
440 item.section === "settled" &&
441 !capabilities?.threadSettlement) ||
442 (section === "active" &&
443 item.section === "snoozed" &&
444 !capabilities?.threadSnooze)
445 )
446 return [];
447 return planners[section](item.key, {
448 section,
449 targetId: null,
450 placement: "before",
451 })
452 ? [{ name: section, label }]
453 : [];
454 })
455 : [];
456 return (
457 <ArrangementRow
458 height={item.height}
459 dragging={visiblePreview !== null}
460 lifted={item.key === sourceRow?.key}
461 offset={
462 sourceRow && insertionOffset !== undefined
463 ? threadDragGapOffset(
464 item.offset,
465 sourceRow.offset,
466 sourceRow.height,
467 insertionOffset,
468 )
469 : 0
470 }
471 >
472 {thread ? (
473 <>
474 <Text numberOfLines={2} className="flex-1 text-base">
475 {thread.title}
476 </Text>
477 <DragHandle
478 title={thread.title}
479 disabled={
480 dropBusy ||
481 pendingOrder !== null ||
482 !(
483 configs.get(thread.environmentId)?.environment.capabilities
484 .threadPinReorder ||
485 configs.get(thread.environmentId)?.environment.capabilities
486 .threadActiveReorder
487 )
488 }
489 sectionActions={sectionActions}
490 onSectionMove={(section) => {
491 void moveThread(thread, {
492 section,
493 targetId: null,
494 placement: "before",
495 });
496 }}
497 canMoveUp={planner?.(item.key, "up") != null}
498 canMoveDown={planner?.(item.key, "down") != null}
499 onStep={(direction) => {
500 void moveThread(thread, direction);
501 }}
502 onStart={() => start(item)}
503 onMove={update}
504 onEnd={(cancelled) => {
505 const current = drag.current;
506 if (cancelled || !current?.destination) {
507 stop();
508 return;
509 }
510 if (frame.current !== null) cancelAnimationFrame(frame.current);
511 frame.current = null;
512 drag.current = null;
513 // Retain the gap until the saved order arrives, avoiding a flash back.
514 void moveThread(current.thread, current.destination).finally(stop);
515 }}
516 />
517 </>
518 ) : (
519 <Pressable
520 disabled={item.section === "pinned" || item.section === "active"}
521 className="flex-1 justify-center self-stretch"
522 onPress={() => {
523 const section = item.section;
524 if (section === "snoozed" || section === "settled")
525 setExpanded((value) => ({ ...value, [section]: !value[section] }));
526 }}
527 >
528 <Text className="text-sm font-t3-semibold text-foreground-muted">
529 {item.section[0]!.toUpperCase() + item.section.slice(1)} (
530 {sections[item.section].length})
531 </Text>
532 </Pressable>
533 )}
534 </ArrangementRow>
535 );
536 }}
537 />
538 {visiblePreview ? (
539 <Animated.View
540 pointerEvents="none"
541 className="absolute left-5 right-5 justify-center rounded-xl border border-border bg-screen px-4"
542 style={{ top: 0, height: ROW_HEIGHT, transform: [{ translateY }] }}
543 >
544 <Text
545 numberOfLines={visiblePreview.destination?.section ? 1 : 2}
546 className="text-base font-t3-medium"
547 >
548 {visiblePreview.thread.title}
549 </Text>
550 {visiblePreview.destination?.section ? (
551 <Text className="text-xs text-foreground-muted">
552 {threadDragAction(
553 visiblePreview.sourceSection,
554 visiblePreview.destination.section,
555 )}
556 </Text>
557 ) : null}
558 </Animated.View>
559 ) : null}
560 </View>
561 </View>
562 </GestureHandlerRootView>
563 </Modal>
564 );
565}
566
567export function ThreadArrangementHost() {
568 const open = useAtomValue(threadArrangementOpenAtom);
569 return open ? (
570 <ThreadArrangementSheet onClose={() => appAtomRegistry.set(threadArrangementOpenAtom, false)} />
571 ) : null;
572}