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, 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 { useSafeAreaInsets } 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 {
20 pendingThreadOrderAtom,
21 threadDropBusyAtom,
22 threadArrangementOpenAtom,
23} from "../../state/thread-order";
24import { queuedThreadKeysAtom } from "../../state/use-thread-outbox";
25import { useThreadListActions } from "../home/useThreadListActions";
26import {
27 createThreadMovePlanner,
28 threadDragAction,
29 type ThreadMoveDestination,
30} from "./threadOrder";
31import { getThreadListV2OrderedSection, threadListInboxReturns } from "./threadListV2";
32import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
33
34const ROW_HEIGHT = 56;
35const HEADER_HEIGHT = 48;
36const keyOf = (thread: EnvironmentThreadShell) => scopedThreadKey(thread.environmentId, thread.id);
37type Section = "pinned" | "active" | "snoozed" | "settled";
38type Destination = Exclude<ThreadMoveDestination, string>;
39type Row = {
40 key: string;
41 section: Section;
42 thread?: EnvironmentThreadShell;
43 offset: number;
44 height: number;
45};
46type Drag = {
47 orderVersion: string;
48 sourceSection: Section;
49 thread: EnvironmentThreadShell;
50 startY: number;
51 translation: number;
52 destination: Destination | null;
53};
54
55function ArrangementRow(props: {
56 height: number;
57 offset: number;
58 lifted: boolean;
59 dragging: boolean;
60 children: ReactNode;
61}) {
62 const { dragging, offset, lifted } = props;
63 const style = useAnimatedStyle(() => ({
64 transform: [
65 {
66 translateY: dragging
67 ? withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System })
68 : offset,
69 },
70 ],
71 opacity: lifted ? 0 : 1,
72 }));
73 return (
74 <Reanimated.View
75 style={[{ height: props.height }, style]}
76 className="flex-row items-center border-b border-border-subtle px-5"
77 >
78 {props.children}
79 </Reanimated.View>
80 );
81}
82
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 active: workingShelfEnabled
202 ? sortInboxThreadsByReturn(active, threadListInboxReturns.returnedAt)
203 : active,
204 snoozed: parked.filter((thread) => effectiveSnoozed(thread, { now })),
205 settled: parked.filter((thread) => !effectiveSnoozed(thread, { now })),
206 };
207 }, [threads, configs, now, queuedThreadKeys, pendingOrder, workingShelfEnabled]);
208 const planners = useMemo(() => {
209 const planner = (section: "pinned" | "active") =>
210 createThreadMovePlanner({
211 ordered: sections[section],
212 allThreads: threads,
213 section,
214 reorderableEnvironmentIds: new Set(
215 [...configs].flatMap(([id, config]) =>
216 (
217 section === "pinned"
218 ? config.environment.capabilities.threadPinReorder
219 : !workingShelfEnabled && config.environment.capabilities.threadActiveReorder
220 )
221 ? [id]
222 : [],
223 ),
224 ),
225 });
226 return { pinned: planner("pinned"), active: planner("active") };
227 }, [sections, threads, configs, workingShelfEnabled]);
228 const rows = useMemo(() => {
229 const result: Row[] = [];
230 let offset = 0;
231 for (const section of ["pinned", "active", "snoozed", "settled"] as const) {
232 if (section === "snoozed" && sections[section].length === 0) continue;
233 result.push({ key: section, section, offset, height: HEADER_HEIGHT });
234 offset += HEADER_HEIGHT;
235 if ((section === "snoozed" || section === "settled") && !expanded[section]) continue;
236 for (const thread of sections[section]) {
237 result.push({ key: keyOf(thread), section, thread, offset, height: ROW_HEIGHT });
238 offset += ROW_HEIGHT;
239 }
240 }
241 return result;
242 }, [sections, expanded]);
243 const list = useRef<FlatList<Row>>(null);
244 const geometry = useRef({ height: 0, offset: 0 });
245 const drag = useRef<Drag | null>(null);
246 const frame = useRef<number | null>(null);
247 const [preview, setPreview] = useState<Drag | null>(null);
248 const translateY = useRef(new Animated.Value(0)).current;
249 const latest = useRef({ rows, planners, moveThread });
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 useEffect(() => {
262 stop();
263 }, [orderVersion]);
264 useEffect(
265 () => () => {
266 if (frame.current !== null) cancelAnimationFrame(frame.current);
267 },
268 [],
269 );
270
271 function update(translation: number) {
272 const current = drag.current;
273 if (current === null) return;
274 current.translation = translation;
275 const { height, offset } = geometry.current;
276 const y = current.startY + translation;
277 translateY.setValue(Math.max(0, Math.min(height - ROW_HEIGHT, y - ROW_HEIGHT / 2)));
278 const contentY = Math.max(0, y + offset);
279 const target =
280 latest.current.rows.find((row) => contentY < row.offset + row.height) ??
281 latest.current.rows.at(-1);
282 let destination: Destination | null = null;
283 if (
284 target &&
285 y >= 0 &&
286 y <= height &&
287 (target.section === "pinned" || target.section === "active" || target.section === "settled")
288 ) {
289 const candidate: Destination = {
290 section: target.section,
291 targetId: target.thread ? target.key : null,
292 placement:
293 !target.thread || contentY < target.offset + target.height / 2 ? "before" : "after",
294 };
295 if (target.section === "settled") {
296 if (
297 current.sourceSection !== "settled" &&
298 configs.get(current.thread.environmentId)?.environment.capabilities.threadSettlement
299 )
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 let last = performance.now();
326 const tick = () => {
327 const current = drag.current;
328 if (!current) return;
329 const timestamp = performance.now();
330 const dt = Math.min(timestamp - last, 32);
331 last = timestamp;
332 const bounds = geometry.current;
333 const y = current.startY + current.translation;
334 const speed =
335 y < 48
336 ? -Math.min(1, (48 - y) / 48)
337 : y > bounds.height - 48
338 ? Math.min(1, (y - bounds.height + 48) / 48)
339 : 0;
340 const tail = latest.current.rows.at(-1);
341 const maximum = Math.max(0, (tail ? tail.offset + tail.height : 0) - bounds.height);
342 const offset = Math.max(0, Math.min(maximum, bounds.offset + speed * dt * 0.5));
343 if (offset !== bounds.offset) {
344 bounds.offset = offset;
345 list.current?.scrollToOffset({ offset, animated: false });
346 update(current.translation);
347 }
348 frame.current = requestAnimationFrame(tick);
349 };
350 frame.current = requestAnimationFrame(tick);
351 }
352 const visiblePreview = preview?.orderVersion === orderVersion ? preview : null;
353 const sourceRow = visiblePreview
354 ? rows.find((row) => row.key === keyOf(visiblePreview.thread))
355 : undefined;
356 const destination = visiblePreview?.destination;
357 const targetRow = destination
358 ? rows.find(
359 (row) =>
360 row.section === destination.section &&
361 row.key === (destination.targetId ?? destination.section),
362 )
363 : undefined;
364 const insertionOffset = targetRow
365 ? targetRow.offset +
366 (!targetRow.thread || destination?.placement === "after" ? targetRow.height : 0)
367 : sourceRow?.offset;
368 return (
369 <Modal
370 visible
371 animationType="slide"
372 presentationStyle="fullScreen"
373 onRequestClose={props.onClose}
374 >
375 <GestureHandlerRootView style={{ flex: 1 }}>
376 <View
377 className="flex-1 bg-screen"
378 style={{ paddingTop: insets.top, paddingBottom: insets.bottom }}
379 >
380 <SheetHeader
381 presentation="inline"
382 title="Arrange threads"
383 onClose={props.onClose}
384 accessibilityLabel="Close arrange threads"
385 />
386 <Text className="px-5 pb-3 text-sm text-foreground-muted">
387 Drag to reorder, pin, or settle. Changes save when you drop.
388 </Text>
389 <View
390 onLayout={(event) => {
391 geometry.current.height = event.nativeEvent.layout.height;
392 }}
393 className="flex-1"
394 style={{ overflow: "hidden" }}
395 >
396 <FlatList
397 ref={list}
398 data={rows}
399 keyExtractor={(row) => row.key}
400 scrollEnabled={visiblePreview === null}
401 removeClippedSubviews={false}
402 onScroll={(event) => {
403 geometry.current.offset = event.nativeEvent.contentOffset.y;
404 }}
405 scrollEventThrottle={16}
406 getItemLayout={(_, index) => ({
407 length: rows[index]!.height,
408 offset: rows[index]!.offset,
409 index,
410 })}
411 renderItem={({ item }) => {
412 const thread = item.thread;
413 const planner =
414 item.section === "pinned" || item.section === "active"
415 ? planners[item.section]
416 : null;
417 const capabilities =
418 thread && configs.get(thread.environmentId)?.environment.capabilities;
419 const sectionActions = thread
420 ? (["pinned", "active", "settled"] as const).flatMap<{
421 name: "pinned" | "active" | "settled";
422 label: string;
423 }>((section) => {
424 if (section === item.section) return [];
425 const label = threadDragAction(item.section, section);
426 if (!label) return [];
427 if (section === "settled")
428 return capabilities?.threadSettlement ? [{ name: section, label }] : [];
429 if (
430 ((section === "pinned" || thread.pinnedAt != null) &&
431 !capabilities?.threadPinning) ||
432 (section === "active" &&
433 item.section === "settled" &&
434 !capabilities?.threadSettlement) ||
435 (section === "active" &&
436 item.section === "snoozed" &&
437 !capabilities?.threadSnooze)
438 )
439 return [];
440 return planners[section](item.key, {
441 section,
442 targetId: null,
443 placement: "before",
444 })
445 ? [{ name: section, label }]
446 : [];
447 })
448 : [];
449 return (
450 <ArrangementRow
451 height={item.height}
452 dragging={visiblePreview !== null}
453 lifted={item.key === sourceRow?.key}
454 offset={
455 sourceRow && insertionOffset !== undefined
456 ? threadDragGapOffset(
457 item.offset,
458 sourceRow.offset,
459 sourceRow.height,
460 insertionOffset,
461 )
462 : 0
463 }
464 >
465 {thread ? (
466 <>
467 <Text numberOfLines={2} className="flex-1 text-base">
468 {thread.title}
469 </Text>
470 <DragHandle
471 title={thread.title}
472 disabled={
473 dropBusy ||
474 pendingOrder !== null ||
475 !(
476 configs.get(thread.environmentId)?.environment.capabilities
477 .threadPinReorder ||
478 configs.get(thread.environmentId)?.environment.capabilities
479 .threadActiveReorder
480 )
481 }
482 sectionActions={sectionActions}
483 onSectionMove={(section) => {
484 void moveThread(thread, {
485 section,
486 targetId: null,
487 placement: "before",
488 });
489 }}
490 canMoveUp={planner?.(item.key, "up") != null}
491 canMoveDown={planner?.(item.key, "down") != null}
492 onStep={(direction) => {
493 void moveThread(thread, direction);
494 }}
495 onStart={() => start(item)}
496 onMove={update}
497 onEnd={(cancelled) => {
498 const current = drag.current;
499 if (cancelled || !current?.destination) {
500 stop();
501 return;
502 }
503 if (frame.current !== null) cancelAnimationFrame(frame.current);
504 frame.current = null;
505 drag.current = null;
506 void moveThread(current.thread, current.destination).finally(stop);
507 }}
508 />
509 </>
510 ) : (
511 <Pressable
512 disabled={item.section === "pinned" || item.section === "active"}
513 className="flex-1 justify-center self-stretch"
514 onPress={() => {
515 const section = item.section;
516 if (section === "snoozed" || section === "settled")
517 setExpanded((value) => ({ ...value, [section]: !value[section] }));
518 }}
519 >
520 <Text className="text-sm font-t3-semibold text-foreground-muted">
521 {item.section[0]!.toUpperCase() + item.section.slice(1)} (
522 {sections[item.section].length})
523 </Text>
524 </Pressable>
525 )}
526 </ArrangementRow>
527 );
528 }}
529 />
530 {visiblePreview ? (
531 <Animated.View
532 pointerEvents="none"
533 className="absolute left-5 right-5 justify-center rounded-xl border border-border bg-screen px-4"
534 style={{ top: 0, height: ROW_HEIGHT, transform: [{ translateY }] }}
535 >
536 <Text
537 numberOfLines={visiblePreview.destination?.section ? 1 : 2}
538 className="text-base font-t3-medium"
539 >
540 {visiblePreview.thread.title}
541 </Text>
542 {visiblePreview.destination?.section ? (
543 <Text className="text-xs text-foreground-muted">
544 {threadDragAction(
545 visiblePreview.sourceSection,
546 visiblePreview.destination.section,
547 )}
548 </Text>
549 ) : null}
550 </Animated.View>
551 ) : null}
552 </View>
553 </View>
554 </GestureHandlerRootView>
555 </Modal>
556 );
557}
558
559export function ThreadArrangementHost() {
560 const open = useAtomValue(threadArrangementOpenAtom);
561 return open ? (
562 <ThreadArrangementSheet onClose={() => appAtomRegistry.set(threadArrangementOpenAtom, false)} />
563 ) : null;
564}