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

ThreadArrangementSheet.tsx

567 lines21.9 KB

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/ui/AppText";
14import { SymbolView } from "../../components/ui/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 );
81​
82function DragHandle(props: {
83 title: string;
84 disabled: boolean;
85 onStart: () => void;
86 onMove: (translation: number) => void;
87 onEnd: (cancelled: boolean) => void;
88 onStep: (direction: "up" | "down") => void;
89 sectionActions: readonly { name: "pinned" | "active" | "settled"; label: string }[];
90 onSectionMove: (section: "pinned" | "active" | "settled") => void;
91 canMoveUp: boolean;
92 canMoveDown: boolean;
93}) {
94 const latest = useRef(props);
95 latest.current = props;
96 const gesture = useMemo(
97 () =>
98 Gesture.Pan()
99 .enabled(!props.disabled)
100 .minDistance(0)
101 .shouldCancelWhenOutside(false)
102 .runOnJS(true)
103 .onStart(() => latest.current.onStart())
104 .onUpdate((event) => latest.current.onMove(event.translationY))
105 .onEnd((event) => latest.current.onMove(event.translationY))
106 .onFinalize((_, success) => latest.current.onEnd(!success)),
107 [props.disabled],
108 );
109 return (
110 <GestureDetector gesture={gesture}>
111 <View
112 collapsable={false}
113 accessible
114 accessibilityRole="adjustable"
115 accessibilityLabel={`Reorder ${props.title}`}
116 accessibilityHint="Move up and Move down reorder within this section. Other actions move between sections."
117 accessibilityState={{ disabled: props.disabled }}
118 accessibilityActions={[
119 ...props.sectionActions,
120 ...(props.canMoveUp ? [{ name: "decrement", label: "Move up" }] : []),
121 ...(props.canMoveDown ? [{ name: "increment", label: "Move down" }] : []),
122 ]}
123 onAccessibilityAction={({ nativeEvent }) => {
124 if (props.disabled) return;
125 const sectionAction = props.sectionActions.find(
126 (action) => action.name === nativeEvent.actionName,
127 );
128 if (sectionAction) props.onSectionMove(sectionAction.name);
129 if (nativeEvent.actionName === "decrement" && props.canMoveUp) props.onStep("up");
130 if (nativeEvent.actionName === "increment" && props.canMoveDown) props.onStep("down");
131 }}
132 style={{
133 width: 48,
134 height: 48,
135 alignItems: "center",
136 justifyContent: "center",
137 opacity: props.disabled ? 0.3 : 1,
138 }}
139 >
140 <SymbolView
141 name="line.3.horizontal"
142 size={22}
143 tintColorClassName="accent-foreground-muted"
144 />
145 </View>
146 </GestureDetector>
147 );
149​
150export function ThreadArrangementSheet(props: { onClose: () => void }) {
151 const insets = useSafeAreaInsets();
152 const threads = useAtomValue(environmentThreadShells.navigationThreadShellsAtom);
153 const configs = useAtomValue(environmentServerConfigsAtom);
154 const queuedThreadKeys = useAtomValue(queuedThreadKeysAtom);
155 const pendingOrder = useAtomValue(pendingThreadOrderAtom);
156 const dropBusy = useAtomValue(threadDropBusyAtom);
157 const { moveThread } = useThreadListActions();
158 const { workingShelfEnabled } = useThreadListV2ShelfPreferences();
159 const [now, setNow] = useState(() => new Date().toISOString());
160 const [expanded, setExpanded] = useState({ snoozed: false, settled: false });
161 useEffect(() => {
162 const wakeAt = Math.min(
163 ...threads.flatMap((thread) => {
164 const at = Date.parse(thread.snoozedUntil ?? "");
165 return at > Date.parse(now) ? [at] : [];
166 }),
167 );
168 if (!Number.isFinite(wakeAt)) return;
169 const timer = setTimeout(
170 () => setNow(new Date().toISOString()),
171 Math.min(Math.max(0, wakeAt - Date.now()) + 1, 2_147_483_647),
172 );
173 return () => clearTimeout(timer);
174 }, [threads, now]);
175 const sections = useMemo(() => {
176 const shared = {
177 threads,
178 now,
179 queuedThreadKeys,
180 pendingOrder,
181 settlementEnvironmentIds: new Set(
182 [...configs].flatMap(([id, config]) =>
183 config.environment.capabilities.threadSettlement ? [id] : [],
184 ),
185 ),
186 snoozeEnvironmentIds: new Set(
187 [...configs].flatMap(([id, config]) =>
188 config.environment.capabilities.threadSnooze ? [id] : [],
189 ),
190 ),
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: parked.filter((thread) => !effectiveSnoozed(thread, { now })),
205 };
206 }, [threads, configs, now, queuedThreadKeys, pendingOrder, workingShelfEnabled]);
207 const planners = useMemo(() => {
208 const planner = (section: "pinned" | "active") =>
209 createThreadMovePlanner({
210 ordered: sections[section],
211 allThreads: threads,
212 section,
213 reorderableEnvironmentIds: new Set(
214 [...configs].flatMap(([id, config]) =>
215 (
216 section === "pinned"
217 ? config.environment.capabilities.threadPinReorder
218 : !workingShelfEnabled && config.environment.capabilities.threadActiveReorder
219 )
220 ? [id]
221 : [],
222 ),
223 ),
224 });
225 return { pinned: planner("pinned"), active: planner("active") };
226 }, [sections, threads, configs, workingShelfEnabled]);
227 const rows = useMemo(() => {
228 const result: Row[] = [];
229 let offset = 0;
230 for (const section of ["pinned", "active", "snoozed", "settled"] as const) {
231 if (section === "snoozed" && sections[section].length === 0) continue;
232 result.push({ key: section, section, offset, height: HEADER_HEIGHT });
233 offset += HEADER_HEIGHT;
234 if ((section === "snoozed" || section === "settled") && !expanded[section]) continue;
235 for (const thread of sections[section]) {
236 result.push({ key: keyOf(thread), section, thread, offset, height: ROW_HEIGHT });
237 offset += ROW_HEIGHT;
238 }
239 }
240 return result;
241 }, [sections, expanded]);
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 = useRef(new Animated.Value(0)).current;
248 const latest = useRef({ rows, planners, moveThread });
249 latest.current = { rows, planners, moveThread };
250​
251 function stop() {
252 if (frame.current !== null) cancelAnimationFrame(frame.current);
253 frame.current = null;
254 drag.current = null;
255 setPreview(null);
256 }
257 const orderVersion = rows
258 .map((row) => `${row.key}:${row.thread?.pinOrderKey}:${row.thread?.activeOrderKey}`)
259 .join("|");
260 useEffect(() => {
261 stop();
262 }, [orderVersion]);
263 useEffect(
264 () => () => {
265 if (frame.current !== null) cancelAnimationFrame(frame.current);
266 },
267 [],
268 );
269​
270 function update(translation: number) {
271 const current = drag.current;
272 if (current === null) return;
273 current.translation = translation;
274 const { height, offset } = geometry.current;
275 const y = current.startY + translation;
276 translateY.setValue(Math.max(0, Math.min(height - ROW_HEIGHT, y - ROW_HEIGHT / 2)));
277 const contentY = Math.max(0, y + offset);
278 const target =
279 latest.current.rows.find((row) => contentY < row.offset + row.height) ??
280 latest.current.rows.at(-1);
281 let destination: Destination | null = null;
282 if (
283 target &&
284 y >= 0 &&
285 y <= height &&
286 (target.section === "pinned" || target.section === "active" || target.section === "settled")
287 ) {
288 const candidate: Destination = {
289 section: target.section,
290 targetId: target.thread ? target.key : null,
291 placement:
292 !target.thread || contentY < target.offset + target.height / 2 ? "before" : "after",
293 };
294 if (target.section === "settled") {
295 if (
296 current.sourceSection !== "settled" &&
297 configs.get(current.thread.environmentId)?.environment.capabilities.threadSettlement
298 )
299 destination = { section: "settled", targetId: null, placement: "before" };
300 } else if (latest.current.planners[target.section](keyOf(current.thread), candidate) !== null)
301 destination = candidate;
302 }
303 if (
304 current.destination?.targetId !== destination?.targetId ||
305 current.destination?.section !== destination?.section ||
306 current.destination?.placement !== destination?.placement
307 ) {
308 current.destination = destination;
309 setPreview({ ...current });
310 }
311 }
312 function start(row: Row) {
313 if (!row.thread || preview !== null) return;
314 drag.current = {
315 orderVersion,
316 sourceSection: row.section,
317 thread: row.thread,
318 startY: row.offset + ROW_HEIGHT / 2 - geometry.current.offset,
319 translation: 0,
320 destination: null,
321 };
322 setPreview({ ...drag.current });
323 update(0);
324 let last = performance.now();
325 const tick = () => {
326 const current = drag.current;
327 if (!current) return;
328 const timestamp = performance.now();
329 const dt = Math.min(timestamp - last, 32);
330 last = timestamp;
331 const bounds = geometry.current;
332 const y = current.startY + current.translation;
333 const speed =
334 y < 48
335 ? -Math.min(1, (48 - y) / 48)
336 : y > bounds.height - 48
337 ? Math.min(1, (y - bounds.height + 48) / 48)
338 : 0;
339 const tail = latest.current.rows.at(-1);
340 const maximum = Math.max(0, (tail ? tail.offset + tail.height : 0) - bounds.height);
341 const offset = Math.max(0, Math.min(maximum, bounds.offset + speed * dt * 0.5));
342 if (offset !== bounds.offset) {
343 bounds.offset = offset;
344 list.current?.scrollToOffset({ offset, animated: false });
345 update(current.translation);
346 }
347 frame.current = requestAnimationFrame(tick);
348 };
349 frame.current = requestAnimationFrame(tick);
350 }
351 const visiblePreview = preview?.orderVersion === orderVersion ? preview : null;
352 const sourceRow = visiblePreview
353 ? rows.find((row) => row.key === keyOf(visiblePreview.thread))
354 : undefined;
355 const destination = visiblePreview?.destination;
356 const targetRow = destination
357 ? rows.find(
358 (row) =>
359 row.section === destination.section &&
360 row.key === (destination.targetId ?? destination.section),
361 )
362 : undefined;
363 const insertionOffset = targetRow
364 ? targetRow.offset +
365 (!targetRow.thread || destination?.placement === "after" ? targetRow.height : 0)
366 : sourceRow?.offset;
367 return (
368 <Modal
369 visible
370 animationType="slide"
371 presentationStyle="fullScreen"
372 onRequestClose={props.onClose}
373 >
374 <GestureHandlerRootView style={{ flex: 1 }}>
375 <View
376 className="flex-1 bg-screen"
377 style={{ paddingTop: insets.top, paddingBottom: insets.bottom }}
378 >
379 <View className="flex-row items-center justify-between gap-3 px-5 py-3">
380 <Text className="flex-1 text-xl font-t3-semibold">Arrange threads</Text>
381 <Pressable
382 accessibilityRole="button"
383 onPress={props.onClose}
384 className="min-h-11 justify-center px-3"
385 >
386 <Text className="text-base text-primary-text">Done</Text>
387 </Pressable>
388 </View>
389 <Text className="px-5 pb-3 text-sm text-foreground-muted">
390 Drag to reorder, pin, or settle. Changes save when you drop.
391 </Text>
392 <View
393 onLayout={(event) => {
394 geometry.current.height = event.nativeEvent.layout.height;
395 }}
396 className="flex-1"
397 style={{ overflow: "hidden" }}
398 >
399 <FlatList
400 ref={list}
401 data={rows}
402 keyExtractor={(row) => row.key}
403 scrollEnabled={visiblePreview === null}
404 removeClippedSubviews={false}
405 onScroll={(event) => {
406 geometry.current.offset = event.nativeEvent.contentOffset.y;
407 }}
408 scrollEventThrottle={16}
409 getItemLayout={(_, index) => ({
410 length: rows[index]!.height,
411 offset: rows[index]!.offset,
412 index,
413 })}
414 renderItem={({ item }) => {
415 const thread = item.thread;
416 const planner =
417 item.section === "pinned" || item.section === "active"
418 ? planners[item.section]
419 : null;
420 const capabilities =
421 thread && configs.get(thread.environmentId)?.environment.capabilities;
422 const sectionActions = thread
423 ? (["pinned", "active", "settled"] as const).flatMap<{
424 name: "pinned" | "active" | "settled";
425 label: string;
426 }>((section) => {
427 if (section === item.section) return [];
428 const label = threadDragAction(item.section, section);
429 if (!label) return [];
430 if (section === "settled")
431 return capabilities?.threadSettlement ? [{ name: section, label }] : [];
432 if (
433 ((section === "pinned" || thread.pinnedAt != null) &&
434 !capabilities?.threadPinning) ||
435 (section === "active" &&
436 item.section === "settled" &&
437 !capabilities?.threadSettlement) ||
438 (section === "active" &&
439 item.section === "snoozed" &&
440 !capabilities?.threadSnooze)
441 )
442 return [];
443 return planners[section](item.key, {
444 section,
445 targetId: null,
446 placement: "before",
447 })
448 ? [{ name: section, label }]
449 : [];
450 })
451 : [];
452 return (
453 <ArrangementRow
454 height={item.height}
455 dragging={visiblePreview !== null}
456 lifted={item.key === sourceRow?.key}
457 offset={
458 sourceRow && insertionOffset !== undefined
459 ? threadDragGapOffset(
460 item.offset,
461 sourceRow.offset,
462 sourceRow.height,
463 insertionOffset,
464 )
465 : 0
466 }
467 >
468 {thread ? (
469 <>
470 <Text numberOfLines={2} className="flex-1 text-base">
471 {thread.title}
472 </Text>
473 <DragHandle
474 title={thread.title}
475 disabled={
476 dropBusy ||
477 pendingOrder !== null ||
478 !(
479 configs.get(thread.environmentId)?.environment.capabilities
480 .threadPinReorder ||
481 configs.get(thread.environmentId)?.environment.capabilities
482 .threadActiveReorder
483 )
484 }
485 sectionActions={sectionActions}
486 onSectionMove={(section) => {
487 void moveThread(thread, {
488 section,
489 targetId: null,
490 placement: "before",
491 });
492 }}
493 canMoveUp={planner?.(item.key, "up") != null}
494 canMoveDown={planner?.(item.key, "down") != null}
495 onStep={(direction) => {
496 void moveThread(thread, direction);
497 }}
498 onStart={() => start(item)}
499 onMove={update}
500 onEnd={(cancelled) => {
501 const current = drag.current;
502 if (cancelled || !current?.destination) {
503 stop();
504 return;
505 }
506 if (frame.current !== null) cancelAnimationFrame(frame.current);
507 frame.current = null;
508 drag.current = null;
509 void moveThread(current.thread, current.destination).finally(stop);
510 }}
511 />
512 </>
513 ) : (
514 <Pressable
515 disabled={item.section === "pinned" || item.section === "active"}
516 className="flex-1 justify-center self-stretch"
517 onPress={() => {
518 const section = item.section;
519 if (section === "snoozed" || section === "settled")
520 setExpanded((value) => ({ ...value, [section]: !value[section] }));
521 }}
522 >
523 <Text className="text-sm font-t3-semibold text-foreground-muted">
524 {item.section[0]!.toUpperCase() + item.section.slice(1)} (
525 {sections[item.section].length})
526 </Text>
527 </Pressable>
528 )}
529 </ArrangementRow>
530 );
531 }}
532 />
533 {visiblePreview ? (
534 <Animated.View
535 pointerEvents="none"
536 className="absolute left-5 right-5 justify-center rounded-xl border border-border bg-screen px-4"
537 style={{ top: 0, height: ROW_HEIGHT, transform: [{ translateY }] }}
538 >
539 <Text
540 numberOfLines={visiblePreview.destination?.section ? 1 : 2}
541 className="text-base font-t3-medium"
542 >
543 {visiblePreview.thread.title}
544 </Text>
545 {visiblePreview.destination?.section ? (
546 <Text className="text-xs text-foreground-muted">
547 {threadDragAction(
548 visiblePreview.sourceSection,
549 visiblePreview.destination.section,
550 )}
551 </Text>
552 ) : null}
553 </Animated.View>
554 ) : null}
555 </View>
556 </View>
557 </GestureHandlerRootView>
558 </Modal>
559 );
561​
562export function ThreadArrangementHost() {
563 const open = useAtomValue(threadArrangementOpenAtom);
564 return open ? (
565 <ThreadArrangementSheet onClose={() => appAtomRegistry.set(threadArrangementOpenAtom, false)} />
566 ) : null;