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

ThreadArrangementSheet.tsx

566 lines21.8 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 { IconButton } from "../../components/ui/IconButton";
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 );
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 );
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 <View className="flex-row items-center justify-between gap-3 px-5 py-3">
381 <Text className="flex-1 text-xl font-t3-semibold">Arrange threads</Text>
382 <IconButton
383 accessibilityLabel="Close arrange threads"
384 icon="xmark"
385 onPress={props.onClose}
386 />
387 </View>
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 capabilities =
420 thread && configs.get(thread.environmentId)?.environment.capabilities;
421 const sectionActions = thread
422 ? (["pinned", "active", "settled"] as const).flatMap<{
423 name: "pinned" | "active" | "settled";
424 label: string;
425 }>((section) => {
426 if (section === item.section) return [];
427 const label = threadDragAction(item.section, section);
428 if (!label) return [];
429 if (section === "settled")
430 return capabilities?.threadSettlement ? [{ name: section, label }] : [];
431 if (
432 ((section === "pinned" || thread.pinnedAt != null) &&
433 !capabilities?.threadPinning) ||
434 (section === "active" &&
435 item.section === "settled" &&
436 !capabilities?.threadSettlement) ||
437 (section === "active" &&
438 item.section === "snoozed" &&
439 !capabilities?.threadSnooze)
440 )
441 return [];
442 return planners[section](item.key, {
443 section,
444 targetId: null,
445 placement: "before",
446 })
447 ? [{ name: section, label }]
448 : [];
449 })
450 : [];
451 return (
452 <ArrangementRow
453 height={item.height}
454 dragging={visiblePreview !== null}
455 lifted={item.key === sourceRow?.key}
456 offset={
457 sourceRow && insertionOffset !== undefined
458 ? threadDragGapOffset(
459 item.offset,
460 sourceRow.offset,
461 sourceRow.height,
462 insertionOffset,
463 )
464 : 0
465 }
466 >
467 {thread ? (
468 <>
469 <Text numberOfLines={2} className="flex-1 text-base">
470 {thread.title}
471 </Text>
472 <DragHandle
473 title={thread.title}
474 disabled={
475 dropBusy ||
476 pendingOrder !== null ||
477 !(
478 configs.get(thread.environmentId)?.environment.capabilities
479 .threadPinReorder ||
480 configs.get(thread.environmentId)?.environment.capabilities
481 .threadActiveReorder
482 )
483 }
484 sectionActions={sectionActions}
485 onSectionMove={(section) => {
486 void moveThread(thread, {
487 section,
488 targetId: null,
489 placement: "before",
490 });
491 }}
492 canMoveUp={planner?.(item.key, "up") != null}
493 canMoveDown={planner?.(item.key, "down") != null}
494 onStep={(direction) => {
495 void moveThread(thread, direction);
496 }}
497 onStart={() => start(item)}
498 onMove={update}
499 onEnd={(cancelled) => {
500 const current = drag.current;
501 if (cancelled || !current?.destination) {
502 stop();
503 return;
504 }
505 if (frame.current !== null) cancelAnimationFrame(frame.current);
506 frame.current = null;
507 drag.current = null;
508 void moveThread(current.thread, current.destination).finally(stop);
509 }}
510 />
511 </>
512 ) : (
513 <Pressable
514 disabled={item.section === "pinned" || item.section === "active"}
515 className="flex-1 justify-center self-stretch"
516 onPress={() => {
517 const section = item.section;
518 if (section === "snoozed" || section === "settled")
519 setExpanded((value) => ({ ...value, [section]: !value[section] }));
520 }}
521 >
522 <Text className="text-sm font-t3-semibold text-foreground-muted">
523 {item.section[0]!.toUpperCase() + item.section.slice(1)} (
524 {sections[item.section].length})
525 </Text>
526 </Pressable>
527 )}
528 </ArrangementRow>
529 );
530 }}
531 />
532 {visiblePreview ? (
533 <Animated.View
534 pointerEvents="none"
535 className="absolute left-5 right-5 justify-center rounded-xl border border-border bg-screen px-4"
536 style={{ top: 0, height: ROW_HEIGHT, transform: [{ translateY }] }}
537 >
538 <Text
539 numberOfLines={visiblePreview.destination?.section ? 1 : 2}
540 className="text-base font-t3-medium"
541 >
542 {visiblePreview.thread.title}
543 </Text>
544 {visiblePreview.destination?.section ? (
545 <Text className="text-xs text-foreground-muted">
546 {threadDragAction(
547 visiblePreview.sourceSection,
548 visiblePreview.destination.section,
549 )}
550 </Text>
551 ) : null}
552 </Animated.View>
553 ) : null}
554 </View>
555 </View>
556 </GestureHandlerRootView>
557 </Modal>
558 );
560​
561export function ThreadArrangementHost() {
562 const open = useAtomValue(threadArrangementOpenAtom);
563 return open ? (
564 <ThreadArrangementSheet onClose={() => appAtomRegistry.set(threadArrangementOpenAtom, false)} />
565 ) : null;