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

ThreadArrangementSheet.tsx

626 lines27.0 KB

1import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
2import { SheetHeader } from "../../components/ui/SheetHeader";
3import { appAtomRegistry } from "../../state/atom-registry";
4import { useAtomValue } from "@effect/atom-react";
5import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
6import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
7import { sortInboxThreadsByReturn } from "@t3tools/client-runtime/state/thread-inbox";
8import { msg, T, useGT, useMessages, plural, part } from "gt-react-native";
9import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
10import { Animated, Modal, Pressable, useWindowDimensions, View } from "react-native";
11import { Gesture, GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler";
12import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
13import { threadDragGapOffset } from "./threadDragGap";
14import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context";
15​
16import { AppText as Text } from "../../components/ui/AppText";
17import { SymbolView } from "../../components/ui/AppSymbol";
18import { scopedThreadKey } from "../../lib/scopedEntities";
19import { deriveThreadArrangementSizing } from "../../lib/layout";
20import { environmentServerConfigsAtom } from "../../state/server";
21import { threadListEnvironmentsAtom } from "../../state/presentation";
22import { steadyNavigationThreadShellsAtom, steadyShellsHoldingAtom } from "../../state/threads";
23import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort";
24import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../../state/olderSettledShelf";
25import {
26 pendingThreadOrderAtom,
27 threadDropBusyAtom,
28 threadArrangementOpenAtom,
29} from "../../state/thread-order";
30import { queuedThreadKeysAtom } from "../../state/use-thread-outbox";
31import { useThreadListActions } from "../home/useThreadListActions";
32import {
33 createThreadMovePlanner,
34 threadDragAction,
35 type ThreadMoveDestination,
36} from "./threadOrder";
37import {
38 getThreadListV2OrderedSection,
39 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
40 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
41 threadListInboxReturns,
42} from "./threadListV2";
43import { useThreadListNow } from "./use-thread-list-now";
44import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
45import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
46​
47const keyOf = (thread: EnvironmentThreadShell) => scopedThreadKey(thread.environmentId, thread.id);
48type Section = "pinned" | "active" | "snoozed" | "settled";
49type Destination = Exclude<ThreadMoveDestination, string>;
50type Row = {
51 key: string;
52 section: Section;
53 thread?: EnvironmentThreadShell;
54 /** The Settled section's "Show more" row. */
55 more?: true;
56 offset: number;
57 height: number;
58};
59type Drag = {
60 orderVersion: string;
61 sourceSection: Section;
62 thread: EnvironmentThreadShell;
63 startY: number;
64 translation: number;
65 destination: Destination | null;
66};
67​
68const SECTION_LABELS = {
69 pinned: msg({ context: "thread list section" })`Pinned`,
70 active: msg({ context: "thread list section" })`Active`,
71 snoozed: msg({ context: "thread list section" })`Snoozed`,
72 settled: msg({ context: "thread list section" })`Settled`,
73} as const;
74​
75function ArrangementRow(props: {
76 height: number;
77 offset: number;
78 lifted: boolean;
79 dragging: boolean;
80 children: ReactNode;
81}) {
82 const { dragging, offset, lifted } = props;
83 const style = useAnimatedStyle(() => ({
84 transform: [
85 {
86 translateY: dragging
87 ? withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System })
88 : offset,
89 },
90 ],
91 opacity: lifted ? 0 : 1,
92 }));
93 return (
94 <Reanimated.View
95 style={[{ height: props.height }, style]}
96 className="flex-row items-center border-b border-border-subtle px-5"
97 >
98 {props.children}
99 </Reanimated.View>
100 );
102​
103function DragHandle(props: {
104 title: string;
105 disabled: boolean;
106 onStart: () => void;
107 onMove: (translation: number) => void;
108 onEnd: (cancelled: boolean) => void;
109 onStep: (direction: "up" | "down") => void;
110 sectionActions: readonly { name: "pinned" | "active" | "settled"; label: string }[];
111 onSectionMove: (section: "pinned" | "active" | "settled") => void;
112 canMoveUp: boolean;
113 canMoveDown: boolean;
114}) {
115 const gt = useGT();
116 const latest = useRef(props);
117 /* oxlint-disable react/refs -- The pan gesture captures its callbacks once per `disabled` change; they read the latest handlers when native gesture events fire. */
118 latest.current = props;
119 const gesture = useMemo(
120 () =>
121 // oxlint-disable-next-line react/capitalized-calls -- Gesture.Pan is a gesture factory, not a React component.
122 Gesture.Pan()
123 .enabled(!props.disabled)
124 .minDistance(0)
125 .shouldCancelWhenOutside(false)
126 .runOnJS(true)
127 .onStart(() => latest.current.onStart())
128 .onUpdate((event) => latest.current.onMove(event.translationY))
129 .onEnd((event) => latest.current.onMove(event.translationY))
130 .onFinalize((_, success) => latest.current.onEnd(!success)),
131 [props.disabled, latest],
132 );
133 /* oxlint-enable react/refs */
134 return (
135 <GestureDetector gesture={gesture}>
136 <View
137 collapsable={false}
138 accessible
139 accessibilityRole="adjustable"
140 accessibilityLabel={gt`Reorder ${{ title: props.title }}`}
141 accessibilityHint={gt`Move up and Move down reorder within this section. Other actions move between sections.`}
142 accessibilityState={{ disabled: props.disabled }}
143 accessibilityActions={[
144 ...props.sectionActions,
145 ...(props.canMoveUp ? [{ name: "decrement", label: gt`Move up` }] : []),
146 ...(props.canMoveDown ? [{ name: "increment", label: gt`Move down` }] : []),
147 ]}
148 onAccessibilityAction={({ nativeEvent }) => {
149 if (props.disabled) return;
150 const sectionAction = props.sectionActions.find(
151 (action) => action.name === nativeEvent.actionName,
152 );
153 if (sectionAction) props.onSectionMove(sectionAction.name);
154 if (nativeEvent.actionName === "decrement" && props.canMoveUp) props.onStep("up");
155 if (nativeEvent.actionName === "increment" && props.canMoveDown) props.onStep("down");
156 }}
157 style={{
158 width: 48,
159 height: 48,
160 alignItems: "center",
161 justifyContent: "center",
162 opacity: props.disabled ? 0.3 : 1,
163 }}
164 >
165 <SymbolView
166 name="line.3.horizontal"
167 size={22}
168 tintColorClassName="accent-foreground-muted"
169 />
170 </View>
171 </GestureDetector>
172 );
174​
175function ThreadArrangementSheet(props: { onClose: () => void }) {
176 const gt = useGT();
177 const m = useMessages();
178 const { appearance } = useAppearancePreferences();
179 const { fontScale } = useWindowDimensions();
180 const { rowHeight, headerHeight } = deriveThreadArrangementSizing({
181 baseFontSize: appearance.baseFontSize,
182 fontScale,
183 });
184 const threads = useAtomValue(steadyNavigationThreadShellsAtom);
185 const configs = useAtomValue(environmentServerConfigsAtom);
186 const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
187 const queuedThreadKeys = useAtomValue(queuedThreadKeysAtom);
188 const pendingOrder = useAtomValue(pendingThreadOrderAtom);
189 const dropBusy = useAtomValue(threadDropBusyAtom);
190 const holdingRows = useAtomValue(steadyShellsHoldingAtom);
191 const { moveThread } = useThreadListActions();
192 const { workingShelfEnabled } = useThreadListV2ShelfPreferences();
193 const now = useThreadListNow(threads);
194 const [expanded, setExpanded] = useState({ snoozed: false, settled: false });
195 const [settledVisibleCount, setSettledVisibleCount] = useState(
196 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
197 );
198 // Older settled threads load in pages, as in the thread list.
199 const olderSettledShelf = useOlderSettledShelf({
200 scopes: [...configs.keys()].map((environmentId) => ({ environmentId, projectIds: null })),
201 expanded: expanded.settled,
202 visibleCount: settledVisibleCount,
203 });
204 const sections = useMemo(() => {
205 const shared = {
206 threads,
207 now,
208 queuedThreadKeys,
209 pendingOrder,
210 settlementEnvironmentIds: new Set(configs.keys()),
211 snoozeEnvironmentIds: new Set(configs.keys()),
212 };
213 const pinned = getThreadListV2OrderedSection({ ...shared, section: "pinned" });
214 const active = getThreadListV2OrderedSection({ ...shared, section: "active" });
215 const visible = new Set([...pinned, ...active].map(keyOf));
216 const parked = threads.filter(
217 (thread) => thread.archivedAt === null && !visible.has(keyOf(thread)),
218 );
219 return {
220 pinned,
221 active: workingShelfEnabled
222 ? sortInboxThreadsByReturn(active, threadListInboxReturns.returnedAt)
223 : active,
224 snoozed: parked.filter((thread) => effectiveSnoozed(thread, { now })),
225 settled: sortSettledThreads(parked.filter((thread) => !effectiveSnoozed(thread, { now }))),
226 };
227 }, [threads, configs, now, queuedThreadKeys, pendingOrder, workingShelfEnabled]);
228 const listedSettled = sections.settled.filter(olderSettledShelf.isListed);
229 useOlderSettledShelfGrowth(olderSettledShelf, listedSettled);
230 const visibleSettled = listedSettled.slice(0, settledVisibleCount);
231 const settledCount = sections.settled.length + olderSettledShelf.unloadedCount(threads);
232 const planners = useMemo(() => {
233 const planner = (section: "pinned" | "active") =>
234 createThreadMovePlanner({
235 ordered: sections[section],
236 allThreads: threads,
237 section,
238 reorderableEnvironmentIds:
239 section === "pinned"
240 ? listEnvironments.pinReorderEnvironmentIds
241 : workingShelfEnabled
242 ? new Set()
243 : listEnvironments.activeReorderEnvironmentIds,
244 });
245 return { pinned: planner("pinned"), active: planner("active") };
246 }, [sections, threads, listEnvironments, workingShelfEnabled]);
247 const rows = useMemo(() => {
248 const result: Row[] = [];
249 let offset = 0;
250 for (const section of ["pinned", "active", "snoozed", "settled"] as const) {
251 if (section === "snoozed" && sections[section].length === 0) continue;
252 result.push({ key: section, section, offset, height: headerHeight });
253 offset += headerHeight;
254 if ((section === "snoozed" || section === "settled") && !expanded[section]) continue;
255 for (const thread of section === "settled" ? visibleSettled : sections[section]) {
256 result.push({ key: keyOf(thread), section, thread, offset, height: rowHeight });
257 offset += rowHeight;
258 }
259 if (section === "settled" && settledCount > visibleSettled.length) {
260 result.push({ key: "settled-more", section, more: true, offset, height: rowHeight });
261 offset += rowHeight;
262 }
263 }
264 return result;
265 }, [sections, expanded, visibleSettled, settledCount, rowHeight, headerHeight]);
266 const list = useRef<LegendListRef>(null);
267 const geometry = useRef({ height: 0, offset: 0 });
268 const drag = useRef<Drag | null>(null);
269 const frame = useRef<number | null>(null);
270 const [preview, setPreview] = useState<Drag | null>(null);
271 const [translateY] = useState(() => new Animated.Value(0));
272 const latest = useRef({ rows, planners, moveThread });
273 // oxlint-disable-next-line react/refs -- The autoscroll rAF loop started at drag start reads the current rows and planners on every frame.
274 latest.current = { rows, planners, moveThread };
275​
276 function stop() {
277 if (frame.current !== null) cancelAnimationFrame(frame.current);
278 frame.current = null;
279 drag.current = null;
280 setPreview(null);
281 }
282 const orderVersion = rows
283 .map(
284 (row) => `${row.key}:${row.height}:${row.thread?.pinOrderKey}:${row.thread?.activeOrderKey}`,
285 )
286 .join("|");
287 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the in-progress drag gesture when the thread order changes underneath it
288 useEffect(() => {
289 // oxlint-disable-next-line react/exhaustive-effect-dependencies, react/set-state-in-effect -- A changed thread order cancels the in-progress drag and clears its preview; stop only touches refs and state setters.
290 stop();
291 }, [orderVersion]);
292 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the pending drag animation frame on unmount
293 useEffect(
294 () => () => {
295 if (frame.current !== null) cancelAnimationFrame(frame.current);
296 },
297 [],
298 );
299​
300 function update(translation: number) {
301 const current = drag.current;
302 if (current === null) return;
303 current.translation = translation;
304 const { height, offset } = geometry.current;
305 const y = current.startY + translation;
306 translateY.setValue(Math.max(0, Math.min(height - rowHeight, y - rowHeight / 2)));
307 const contentY = Math.max(0, y + offset);
308 const target =
309 latest.current.rows.find((row) => contentY < row.offset + row.height) ??
310 latest.current.rows.at(-1);
311 let destination: Destination | null = null;
312 if (
313 target &&
314 y >= 0 &&
315 y <= height &&
316 (target.section === "pinned" || target.section === "active" || target.section === "settled")
317 ) {
318 const candidate: Destination = {
319 section: target.section,
320 targetId: target.thread ? target.key : null,
321 placement:
322 !target.thread || contentY < target.offset + target.height / 2 ? "before" : "after",
323 };
324 if (target.section === "settled") {
325 if (current.sourceSection !== "settled" && configs.has(current.thread.environmentId))
326 destination = { section: "settled", targetId: null, placement: "before" };
327 } else if (latest.current.planners[target.section](keyOf(current.thread), candidate) !== null)
328 destination = candidate;
329 }
330 if (
331 current.destination?.targetId !== destination?.targetId ||
332 current.destination?.section !== destination?.section ||
333 current.destination?.placement !== destination?.placement
334 ) {
335 current.destination = destination;
336 setPreview({ ...current });
337 }
338 }
339 function start(row: Row) {
340 if (!row.thread || preview !== null) return;
341 drag.current = {
342 orderVersion,
343 sourceSection: row.section,
344 thread: row.thread,
345 startY: row.offset + row.height / 2 - geometry.current.offset,
346 translation: 0,
347 destination: null,
348 };
349 setPreview({ ...drag.current });
350 update(0);
351 // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)
352 let last = performance.now();
353 const tick = () => {
354 const current = drag.current;
355 if (!current) return;
356 const timestamp = performance.now();
357 const dt = Math.min(timestamp - last, 32);
358 last = timestamp;
359 const bounds = geometry.current;
360 const y = current.startY + current.translation;
361 const speed =
362 y < 48
363 ? -Math.min(1, (48 - y) / 48)
364 : y > bounds.height - 48
365 ? Math.min(1, (y - bounds.height + 48) / 48)
366 : 0;
367 const tail = latest.current.rows.at(-1);
368 const maximum = Math.max(0, (tail ? tail.offset + tail.height : 0) - bounds.height);
369 const offset = Math.max(0, Math.min(maximum, bounds.offset + speed * dt * 0.5));
370 if (offset !== bounds.offset) {
371 bounds.offset = offset;
372 list.current?.scrollToOffset({ offset, animated: false });
373 update(current.translation);
374 }
375 frame.current = requestAnimationFrame(tick);
376 };
377 frame.current = requestAnimationFrame(tick);
378 }
379 const visiblePreview = preview?.orderVersion === orderVersion ? preview : null;
380 const sourceRow = visiblePreview
381 ? rows.find((row) => row.key === keyOf(visiblePreview.thread))
382 : undefined;
383 const destination = visiblePreview?.destination;
384 const targetRow = destination
385 ? rows.find(
386 (row) =>
387 row.section === destination.section &&
388 row.key === (destination.targetId ?? destination.section),
389 )
390 : undefined;
391 const insertionOffset = targetRow
392 ? targetRow.offset +
393 (!targetRow.thread || destination?.placement === "after" ? targetRow.height : 0)
394 : sourceRow?.offset;
395 return (
396 <Modal
397 visible
398 animationType="slide"
399 presentationStyle="fullScreen"
400 onRequestClose={props.onClose}
401 >
402 <GestureHandlerRootView style={{ flex: 1 }}>
403 {/* A Modal is its own native hierarchy, so measure its own safe area, including side
404 insets for the camera, instead of the presenting screen's. */}
405 <SafeAreaProvider style={{ flex: 1 }}>
406 <View className="flex-1 bg-screen">
407 <SafeAreaView style={{ flex: 1 }}>
408 <SheetHeader
409 presentation="inline"
410 title={gt`Arrange threads`}
411 onClose={props.onClose}
412 accessibilityLabel={gt`Close arrange threads`}
413 />
414 <Text className="px-5 pb-3 text-sm text-foreground-muted">
415 <T>Drag to reorder, pin, or settle. Changes save when you drop.</T>
416 </Text>
417 <View
418 onLayout={(event) => {
419 geometry.current.height = event.nativeEvent.layout.height;
420 }}
421 className="flex-1"
422 style={{ overflow: "hidden" }}
423 >
424 {/* oxlint-disable-next-line t3code/require-registered-list-scroll -- A full-screen Modal with an inline header; there is no navigation header to register with. */}
425 <LegendList
426 ref={list}
427 data={rows}
428 keyExtractor={(row) => row.key}
429 extraData={{
430 visiblePreview,
431 insertionOffset,
432 dropBusy,
433 pendingOrder,
434 listEnvironments,
435 planners,
436 configs,
437 }}
438 // Rows hold their drag gesture, so each keeps its own view.
439 recycleItems={false}
440 scrollEnabled={visiblePreview === null}
441 onScroll={(event) => {
442 geometry.current.offset = event.nativeEvent.contentOffset.y;
443 }}
444 scrollEventThrottle={16}
445 getFixedItemSize={(row) => row.height}
446 renderItem={({ item }) => {
447 const thread = item.thread;
448 const planner =
449 item.section === "pinned" || item.section === "active"
450 ? planners[item.section]
451 : null;
452 const configLoaded = thread ? configs.has(thread.environmentId) : false;
453 const sectionActions = thread
454 ? (["pinned", "active", "settled"] as const).flatMap<{
455 name: "pinned" | "active" | "settled";
456 label: string;
457 }>((section) => {
458 if (section === item.section) return [];
459 const label = threadDragAction(item.section, section, m);
460 if (!label) return [];
461 if (section === "settled")
462 return configLoaded ? [{ name: section, label }] : [];
463 if (
464 ((section === "pinned" || thread.pinnedAt != null) && !configLoaded) ||
465 (section === "active" && item.section === "settled" && !configLoaded) ||
466 (section === "active" && item.section === "snoozed" && !configLoaded)
467 )
468 return [];
469 return planners[section](item.key, {
470 section,
471 targetId: null,
472 placement: "before",
473 })
474 ? [{ name: section, label }]
475 : [];
476 })
477 : [];
478 return (
479 <ArrangementRow
480 height={item.height}
481 dragging={visiblePreview !== null}
482 lifted={item.key === sourceRow?.key}
483 offset={
484 sourceRow && insertionOffset !== undefined
485 ? threadDragGapOffset(
486 item.offset,
487 sourceRow.offset,
488 sourceRow.height,
489 insertionOffset,
490 )
491 : 0
492 }
493 >
494 {thread ? (
495 <>
496 <Text numberOfLines={2} className="flex-1 text-base">
497 {thread.title}
498 </Text>
499 <DragHandle
500 title={thread.title}
501 disabled={
502 dropBusy ||
503 pendingOrder !== null ||
504 holdingRows ||
505 (!listEnvironments.pinReorderEnvironmentIds.has(
506 thread.environmentId,
507 ) &&
508 !listEnvironments.activeReorderEnvironmentIds.has(
509 thread.environmentId,
510 ))
511 }
512 sectionActions={sectionActions}
513 onSectionMove={(section) => {
514 void moveThread(thread, {
515 section,
516 targetId: null,
517 placement: "before",
518 });
519 }}
520 canMoveUp={planner?.(item.key, "up") != null}
521 canMoveDown={planner?.(item.key, "down") != null}
522 onStep={(direction) => {
523 void moveThread(thread, direction);
524 }}
525 onStart={() => start(item)}
526 onMove={update}
527 onEnd={(cancelled) => {
528 const current = drag.current;
529 if (cancelled || !current?.destination) {
530 stop();
531 return;
532 }
533 if (frame.current !== null) cancelAnimationFrame(frame.current);
534 frame.current = null;
535 drag.current = null;
536 void moveThread(current.thread, current.destination).finally(stop);
537 }}
538 />
539 </>
540 ) : item.more ? (
541 <Pressable
542 disabled={olderSettledShelf.loading}
543 className="flex-1 justify-center self-stretch"
544 onPress={() => {
545 olderSettledShelf.retry();
546 setSettledVisibleCount(
547 (count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT,
548 );
549 }}
550 >
551 <Text className="text-sm text-foreground-muted">
552 {olderSettledShelf.loading
553 ? gt({ context: "older threads are loading" })`Loading`
554 : olderSettledShelf.failed
555 ? gt`Could not load older threads. Retry`
556 : gt`${plural(
557 { count: settledCount - visibleSettled.length },
558 {
559 one: part`Show more (${{ count: settledCount - visibleSettled.length }} settled hidden)`,
560 other: part`Show more (${{ count: settledCount - visibleSettled.length }} settled hidden)`,
561 },
562 )}`}
563 </Text>
564 </Pressable>
565 ) : (
566 <Pressable
567 disabled={item.section === "pinned" || item.section === "active"}
568 className="flex-1 justify-center self-stretch"
569 onPress={() => {
570 const section = item.section;
571 if (section === "snoozed" || section === "settled")
572 setExpanded((value) => ({ ...value, [section]: !value[section] }));
573 }}
574 >
575 <Text className="text-sm font-t3-semibold text-foreground-muted">
576 {gt`${{ section: m(SECTION_LABELS[item.section]) }} (${{
577 count:
578 item.section === "settled"
579 ? settledCount
580 : sections[item.section].length,
581 }})`}
582 </Text>
583 </Pressable>
584 )}
585 </ArrangementRow>
586 );
587 }}
588 />
589 {visiblePreview ? (
590 <Animated.View
591 pointerEvents="none"
592 className="absolute left-5 right-5 justify-center rounded-xl border border-border bg-screen px-4"
593 style={{ top: 0, height: rowHeight, transform: [{ translateY }] }}
594 >
595 <Text
596 numberOfLines={visiblePreview.destination?.section ? 1 : 2}
597 className="text-base font-t3-medium"
598 >
599 {visiblePreview.thread.title}
600 </Text>
601 {visiblePreview.destination?.section ? (
602 <Text className="text-xs text-foreground-muted">
603 {threadDragAction(
604 visiblePreview.sourceSection,
605 visiblePreview.destination.section,
606 m,
607 )}
608 </Text>
609 ) : null}
610 </Animated.View>
611 ) : null}
612 </View>
613 </SafeAreaView>
614 </View>
615 </SafeAreaProvider>
616 </GestureHandlerRootView>
617 </Modal>
618 );
620​
621export function ThreadArrangementHost() {
622 const open = useAtomValue(threadArrangementOpenAtom);
623 return open ? (
624 <ThreadArrangementSheet onClose={() => appAtomRegistry.set(threadArrangementOpenAtom, false)} />
625 ) : null;