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

ThreadArrangementSheet.tsx

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