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

ThreadArrangementSheet.tsx

566 lines22.6 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 {
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 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 {/* A Modal is its own native hierarchy, so measure its own safe area, including side
376 insets for the camera, instead of the presenting screen's. */}
377 <SafeAreaProvider style={{ flex: 1 }}>
378 <View className="flex-1 bg-screen">
379 <SafeAreaView style={{ flex: 1 }}>
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 </SafeAreaView>
554 </View>
555 </SafeAreaProvider>
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;