feat(mobile): arrange threads with drag handles (#10496)
This commit is contained in:
1 parent
08463e2c40
commit
2a30353530
12 files changed
+1037
-38
No files matched your search
@@ -9,6 +9,7 @@ import { SafeAreaProvider } from "react-native-safe-area-context";
|
||||
import { createStaticNavigation } from "@react-navigation/native";
|
||||
|
||||
import { RegistryContext } from "@effect/atom-react";
|
||||
import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet";
|
||||
import { ConfirmDialogHost } from "./components/ConfirmDialogHost";
|
||||
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
|
||||
import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
|
||||
@@ -94,6 +95,7 @@ function AppContent() {
|
||||
<Navigation linking={appLinking} theme={navigationTheme} />
|
||||
</IncomingShareProvider>
|
||||
<ConfirmDialogHost />
|
||||
<ThreadArrangementHost />
|
||||
</BlurTargetView>
|
||||
{/* Anchored-menu overlays render here — in-window, so the
|
||||
keyboard stays up while a dropdown is open. */}
|
||||
|
||||
@@ -59,6 +59,7 @@ import IconLayoutColumns from "@tabler/icons-react-native/IconLayoutColumns";
|
||||
import IconLayoutSidebar from "@tabler/icons-react-native/IconLayoutSidebar";
|
||||
import IconLayoutSidebarRight from "@tabler/icons-react-native/IconLayoutSidebarRight";
|
||||
import IconLetterSpacing from "@tabler/icons-react-native/IconLetterSpacing";
|
||||
import IconMenu2 from "@tabler/icons-react-native/IconMenu2";
|
||||
import IconLink from "@tabler/icons-react-native/IconLink";
|
||||
import IconMessage from "@tabler/icons-react-native/IconMessage";
|
||||
import IconMinus from "@tabler/icons-react-native/IconMinus";
|
||||
@@ -141,6 +142,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
"info.circle": IconInfoCircle,
|
||||
laptopcomputer: IconDeviceLaptop,
|
||||
link: IconLink,
|
||||
"line.3.horizontal": IconMenu2,
|
||||
"line.3.horizontal.decrease": IconFilter,
|
||||
"line.3.horizontal.decrease.circle": IconFilter,
|
||||
"line.3.horizontal.decrease.circle.fill": IconFilterFilled,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ThreadMoveDestination } from "../threads/threadOrder";
|
||||
import { createThreadMovePlanner } from "../threads/threadOrder";
|
||||
import {
|
||||
LegendList,
|
||||
@@ -122,7 +123,7 @@ interface HomeScreenProps {
|
||||
readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onMoveThread: (
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
direction: ThreadMoveDestination,
|
||||
) => Promise<boolean>;
|
||||
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
@@ -519,7 +520,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
[props.onPinThread],
|
||||
);
|
||||
const handleMoveThread = useCallback(
|
||||
(thread: EnvironmentThreadShell, direction: "up" | "down") => {
|
||||
(thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {
|
||||
void props.onMoveThread(thread, direction);
|
||||
},
|
||||
[props.onMoveThread],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ThreadMoveDestination } from "../threads/threadOrder";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { canSnooze } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useCallback, useRef } from "react";
|
||||
@@ -15,8 +16,16 @@ import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
|
||||
import { queuedThreadKeysAtom } from "../../state/use-thread-outbox";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { beginPendingThreadOrder, getPendingThreadOrder } from "../../state/thread-order";
|
||||
import { createPendingThreadOrder, createThreadMovePlanner } from "../threads/threadOrder";
|
||||
import {
|
||||
beginPendingThreadOrder,
|
||||
getPendingThreadOrder,
|
||||
threadDropBusyAtom,
|
||||
} from "../../state/thread-order";
|
||||
import {
|
||||
createPendingThreadOrder,
|
||||
createThreadMovePlanner,
|
||||
threadDropLifecycle,
|
||||
} from "../threads/threadOrder";
|
||||
import { getThreadListV2OrderedSection } from "../threads/threadListV2";
|
||||
|
||||
/** Version skew: never send settle/unsettle to a server that predates them
|
||||
@@ -229,7 +238,7 @@ export function useThreadListActions(): {
|
||||
readonly unpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly moveThread: (
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
direction: ThreadMoveDestination,
|
||||
) => Promise<boolean>;
|
||||
readonly regenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
} {
|
||||
@@ -474,9 +483,29 @@ export function useThreadListActions(): {
|
||||
reportFailure: false,
|
||||
});
|
||||
const moveThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell, direction: "up" | "down") => {
|
||||
if (getPendingThreadOrder() !== null) return false;
|
||||
const section = thread.pinnedAt != null ? "pinned" : "active";
|
||||
async (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {
|
||||
if (getPendingThreadOrder() !== null || appAtomRegistry.get(threadDropBusyAtom)) return false;
|
||||
const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
|
||||
const current = shells.find(
|
||||
(row) => row.id === thread.id && row.environmentId === thread.environmentId,
|
||||
);
|
||||
if (!current || current.archivedAt !== null) return false;
|
||||
thread = current;
|
||||
const section =
|
||||
typeof direction === "object" && direction.section !== undefined
|
||||
? direction.section
|
||||
: thread.pinnedAt != null
|
||||
? "pinned"
|
||||
: "active";
|
||||
if (section === "settled") {
|
||||
if (!environmentSupportsSettlement(thread.environmentId)) return false;
|
||||
appAtomRegistry.set(threadDropBusyAtom, true);
|
||||
try {
|
||||
return await settleThread(thread);
|
||||
} finally {
|
||||
appAtomRegistry.set(threadDropBusyAtom, false);
|
||||
}
|
||||
}
|
||||
const configs = appAtomRegistry.get(environmentServerConfigsAtom);
|
||||
const supportsReorder = (environmentId: EnvironmentThreadShell["environmentId"]) => {
|
||||
const capabilities = configs.get(environmentId)?.environment.capabilities;
|
||||
@@ -491,7 +520,6 @@ export function useThreadListActions(): {
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
|
||||
const ordered = getThreadListV2OrderedSection({
|
||||
threads: shells,
|
||||
section,
|
||||
@@ -515,24 +543,67 @@ export function useThreadListActions(): {
|
||||
reorderableEnvironmentIds: new Set([...configs.keys()].filter(supportsReorder)),
|
||||
})(scopedThreadKey(thread.environmentId, thread.id), direction);
|
||||
if (assignments === null) return false;
|
||||
const lifecycle = threadDropLifecycle(thread, section, new Date().toISOString());
|
||||
const crossSection = !ordered.some(
|
||||
(row) => row.id === thread.id && row.environmentId === thread.environmentId,
|
||||
);
|
||||
if (
|
||||
crossSection &&
|
||||
(((section === "pinned" || thread.pinnedAt != null) &&
|
||||
!environmentSupportsPinning(thread.environmentId)) ||
|
||||
(thread.settledOverride === "settled" &&
|
||||
!environmentSupportsSettlement(thread.environmentId)) ||
|
||||
(effectiveSnoozed(thread, { now: new Date().toISOString() }) &&
|
||||
!environmentSupportsSnooze(thread.environmentId)))
|
||||
)
|
||||
return false;
|
||||
const shellByKey = new Map(
|
||||
ordered.map((shell) => [scopedThreadKey(shell.environmentId, shell.id), shell]),
|
||||
shells.map((shell) => [scopedThreadKey(shell.environmentId, shell.id), shell]),
|
||||
);
|
||||
selectionHaptic();
|
||||
const pending = beginPendingThreadOrder(
|
||||
createPendingThreadOrder({
|
||||
section,
|
||||
ordered,
|
||||
movedId: scopedThreadKey(thread.environmentId, thread.id),
|
||||
direction,
|
||||
assignments,
|
||||
}),
|
||||
);
|
||||
appAtomRegistry.set(threadDropBusyAtom, true);
|
||||
const pending = crossSection
|
||||
? null
|
||||
: beginPendingThreadOrder(
|
||||
createPendingThreadOrder({
|
||||
section,
|
||||
ordered,
|
||||
movedId: scopedThreadKey(thread.environmentId, thread.id),
|
||||
direction,
|
||||
assignments,
|
||||
}),
|
||||
);
|
||||
let succeeded = false;
|
||||
const reorder = section === "pinned" ? reorderPinnedMutation : reorderActiveMutation;
|
||||
try {
|
||||
if (crossSection) {
|
||||
if (section === "pinned") {
|
||||
const orderKey = assignments.find(
|
||||
({ id }) => id === scopedThreadKey(thread.environmentId, thread.id),
|
||||
)?.orderKey;
|
||||
const result = await pinMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id, ...(orderKey === undefined ? {} : { orderKey }) },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
Alert.alert("Could not pin thread", String(Cause.squash(result.cause)));
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (lifecycle.unpin && !(await unpinThread(thread))) return false;
|
||||
if (lifecycle.unsettle && !(await unsettleThread(thread))) return false;
|
||||
if (lifecycle.unsnooze && !(await unsnoozeThread(thread))) return false;
|
||||
}
|
||||
}
|
||||
for (const assignment of assignments) {
|
||||
if (!pending.isPending()) return false;
|
||||
if (
|
||||
crossSection &&
|
||||
section === "pinned" &&
|
||||
thread.pinnedAt == null &&
|
||||
assignment.id === scopedThreadKey(thread.environmentId, thread.id)
|
||||
)
|
||||
continue;
|
||||
if (pending !== null && !pending.isPending()) return false;
|
||||
const target = shellByKey.get(assignment.id);
|
||||
if (target === undefined) continue;
|
||||
const result = await reorder({
|
||||
@@ -552,13 +623,22 @@ export function useThreadListActions(): {
|
||||
}
|
||||
}
|
||||
succeeded = true;
|
||||
pending.complete();
|
||||
pending?.complete();
|
||||
return true;
|
||||
} finally {
|
||||
if (!succeeded) pending.cancel();
|
||||
if (!succeeded) pending?.cancel();
|
||||
appAtomRegistry.set(threadDropBusyAtom, false);
|
||||
}
|
||||
},
|
||||
[reorderActiveMutation, reorderPinnedMutation],
|
||||
[
|
||||
settleThread,
|
||||
reorderActiveMutation,
|
||||
reorderPinnedMutation,
|
||||
pinMutation,
|
||||
unpinThread,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
],
|
||||
);
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
@@ -0,0 +1,564 @@
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Animated, FlatList, Modal, Pressable, View } from "react-native";
|
||||
import { Gesture, GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler";
|
||||
import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
|
||||
import { threadDragGapOffset } from "./threadDragGap";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { environmentThreadShells } from "../../state/threads";
|
||||
import {
|
||||
pendingThreadOrderAtom,
|
||||
threadDropBusyAtom,
|
||||
threadArrangementOpenAtom,
|
||||
} from "../../state/thread-order";
|
||||
import { queuedThreadKeysAtom } from "../../state/use-thread-outbox";
|
||||
import { useThreadListActions } from "../home/useThreadListActions";
|
||||
import {
|
||||
createThreadMovePlanner,
|
||||
threadDragAction,
|
||||
type ThreadMoveDestination,
|
||||
} from "./threadOrder";
|
||||
import { getThreadListV2OrderedSection } from "./threadListV2";
|
||||
|
||||
const ROW_HEIGHT = 56;
|
||||
const HEADER_HEIGHT = 48;
|
||||
const keyOf = (thread: EnvironmentThreadShell) => scopedThreadKey(thread.environmentId, thread.id);
|
||||
type Section = "pinned" | "active" | "snoozed" | "settled";
|
||||
type Destination = Exclude<ThreadMoveDestination, string>;
|
||||
type Row = {
|
||||
key: string;
|
||||
section: Section;
|
||||
thread?: EnvironmentThreadShell;
|
||||
offset: number;
|
||||
height: number;
|
||||
};
|
||||
type Drag = {
|
||||
orderVersion: string;
|
||||
sourceSection: Section;
|
||||
thread: EnvironmentThreadShell;
|
||||
startY: number;
|
||||
translation: number;
|
||||
destination: Destination | null;
|
||||
};
|
||||
|
||||
function ArrangementRow(props: {
|
||||
height: number;
|
||||
offset: number;
|
||||
lifted: boolean;
|
||||
dragging: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { dragging, offset, lifted } = props;
|
||||
const style = useAnimatedStyle(() => ({
|
||||
transform: [
|
||||
{
|
||||
translateY: dragging
|
||||
? withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System })
|
||||
: offset,
|
||||
},
|
||||
],
|
||||
opacity: lifted ? 0 : 1,
|
||||
}));
|
||||
return (
|
||||
<Reanimated.View
|
||||
style={[{ height: props.height }, style]}
|
||||
className="flex-row items-center border-b border-border-subtle px-5"
|
||||
>
|
||||
{props.children}
|
||||
</Reanimated.View>
|
||||
);
|
||||
}
|
||||
|
||||
/** Native pan recognition wins over list scrolling only inside the handle. */
|
||||
function DragHandle(props: {
|
||||
title: string;
|
||||
disabled: boolean;
|
||||
onStart: () => void;
|
||||
onMove: (translation: number) => void;
|
||||
onEnd: (cancelled: boolean) => void;
|
||||
onStep: (direction: "up" | "down") => void;
|
||||
sectionActions: readonly { name: "pinned" | "active" | "settled"; label: string }[];
|
||||
onSectionMove: (section: "pinned" | "active" | "settled") => void;
|
||||
canMoveUp: boolean;
|
||||
canMoveDown: boolean;
|
||||
}) {
|
||||
const latest = useRef(props);
|
||||
latest.current = props;
|
||||
const gesture = useMemo(
|
||||
() =>
|
||||
Gesture.Pan()
|
||||
.enabled(!props.disabled)
|
||||
.minDistance(0)
|
||||
.shouldCancelWhenOutside(false)
|
||||
.runOnJS(true)
|
||||
.onStart(() => latest.current.onStart())
|
||||
.onUpdate((event) => latest.current.onMove(event.translationY))
|
||||
.onEnd((event) => latest.current.onMove(event.translationY))
|
||||
.onFinalize((_, success) => latest.current.onEnd(!success)),
|
||||
[props.disabled],
|
||||
);
|
||||
return (
|
||||
<GestureDetector gesture={gesture}>
|
||||
<View
|
||||
collapsable={false}
|
||||
accessible
|
||||
accessibilityRole="adjustable"
|
||||
accessibilityLabel={`Reorder ${props.title}`}
|
||||
accessibilityHint="Move up and Move down reorder within this section. Other actions move between sections."
|
||||
accessibilityState={{ disabled: props.disabled }}
|
||||
accessibilityActions={[
|
||||
...props.sectionActions,
|
||||
...(props.canMoveUp ? [{ name: "decrement", label: "Move up" }] : []),
|
||||
...(props.canMoveDown ? [{ name: "increment", label: "Move down" }] : []),
|
||||
]}
|
||||
onAccessibilityAction={({ nativeEvent }) => {
|
||||
if (props.disabled) return;
|
||||
const sectionAction = props.sectionActions.find(
|
||||
(action) => action.name === nativeEvent.actionName,
|
||||
);
|
||||
if (sectionAction) props.onSectionMove(sectionAction.name);
|
||||
if (nativeEvent.actionName === "decrement" && props.canMoveUp) props.onStep("up");
|
||||
if (nativeEvent.actionName === "increment" && props.canMoveDown) props.onStep("down");
|
||||
}}
|
||||
style={{
|
||||
width: 48,
|
||||
height: 48,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
opacity: props.disabled ? 0.3 : 1,
|
||||
}}
|
||||
>
|
||||
<SymbolView
|
||||
name="line.3.horizontal"
|
||||
size={22}
|
||||
tintColorClassName="accent-foreground-muted"
|
||||
/>
|
||||
</View>
|
||||
</GestureDetector>
|
||||
);
|
||||
}
|
||||
|
||||
export function ThreadArrangementSheet(props: { onClose: () => void }) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const threads = useAtomValue(environmentThreadShells.threadShellsAtom);
|
||||
const configs = useAtomValue(environmentServerConfigsAtom);
|
||||
const queuedThreadKeys = useAtomValue(queuedThreadKeysAtom);
|
||||
const pendingOrder = useAtomValue(pendingThreadOrderAtom);
|
||||
const dropBusy = useAtomValue(threadDropBusyAtom);
|
||||
const { moveThread } = useThreadListActions();
|
||||
const [now, setNow] = useState(() => new Date().toISOString());
|
||||
const [expanded, setExpanded] = useState({ snoozed: false, settled: false });
|
||||
useEffect(() => {
|
||||
const wakeAt = Math.min(
|
||||
...threads.flatMap((thread) => {
|
||||
const at = Date.parse(thread.snoozedUntil ?? "");
|
||||
return at > Date.parse(now) ? [at] : [];
|
||||
}),
|
||||
);
|
||||
if (!Number.isFinite(wakeAt)) return;
|
||||
const timer = setTimeout(
|
||||
() => setNow(new Date().toISOString()),
|
||||
Math.min(Math.max(0, wakeAt - Date.now()) + 1, 2_147_483_647),
|
||||
);
|
||||
return () => clearTimeout(timer);
|
||||
}, [threads, now]);
|
||||
const sections = useMemo(() => {
|
||||
const shared = {
|
||||
threads,
|
||||
now,
|
||||
queuedThreadKeys,
|
||||
pendingOrder,
|
||||
settlementEnvironmentIds: new Set(
|
||||
[...configs].flatMap(([id, config]) =>
|
||||
config.environment.capabilities.threadSettlement ? [id] : [],
|
||||
),
|
||||
),
|
||||
snoozeEnvironmentIds: new Set(
|
||||
[...configs].flatMap(([id, config]) =>
|
||||
config.environment.capabilities.threadSnooze ? [id] : [],
|
||||
),
|
||||
),
|
||||
};
|
||||
const pinned = getThreadListV2OrderedSection({ ...shared, section: "pinned" });
|
||||
const active = getThreadListV2OrderedSection({ ...shared, section: "active" });
|
||||
const visible = new Set([...pinned, ...active].map(keyOf));
|
||||
const parked = threads.filter(
|
||||
(thread) => thread.archivedAt === null && !visible.has(keyOf(thread)),
|
||||
);
|
||||
return {
|
||||
pinned,
|
||||
active,
|
||||
snoozed: parked.filter((thread) => effectiveSnoozed(thread, { now })),
|
||||
settled: parked.filter((thread) => !effectiveSnoozed(thread, { now })),
|
||||
};
|
||||
}, [threads, configs, now, queuedThreadKeys, pendingOrder]);
|
||||
const planners = useMemo(() => {
|
||||
const planner = (section: "pinned" | "active") =>
|
||||
createThreadMovePlanner({
|
||||
ordered: sections[section],
|
||||
allThreads: threads,
|
||||
section,
|
||||
reorderableEnvironmentIds: new Set(
|
||||
[...configs].flatMap(([id, config]) =>
|
||||
(
|
||||
section === "pinned"
|
||||
? config.environment.capabilities.threadPinReorder
|
||||
: config.environment.capabilities.threadActiveReorder
|
||||
)
|
||||
? [id]
|
||||
: [],
|
||||
),
|
||||
),
|
||||
});
|
||||
return { pinned: planner("pinned"), active: planner("active") };
|
||||
}, [sections, threads, configs]);
|
||||
const rows = useMemo(() => {
|
||||
const result: Row[] = [];
|
||||
let offset = 0;
|
||||
for (const section of ["pinned", "active", "snoozed", "settled"] as const) {
|
||||
if (section === "snoozed" && sections[section].length === 0) continue;
|
||||
result.push({ key: section, section, offset, height: HEADER_HEIGHT });
|
||||
offset += HEADER_HEIGHT;
|
||||
if ((section === "snoozed" || section === "settled") && !expanded[section]) continue;
|
||||
for (const thread of sections[section]) {
|
||||
result.push({ key: keyOf(thread), section, thread, offset, height: ROW_HEIGHT });
|
||||
offset += ROW_HEIGHT;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}, [sections, expanded]);
|
||||
const list = useRef<FlatList<Row>>(null);
|
||||
const geometry = useRef({ height: 0, offset: 0 });
|
||||
const drag = useRef<Drag | null>(null);
|
||||
const frame = useRef<number | null>(null);
|
||||
const [preview, setPreview] = useState<Drag | null>(null);
|
||||
const translateY = useRef(new Animated.Value(0)).current;
|
||||
const latest = useRef({ rows, planners, moveThread });
|
||||
latest.current = { rows, planners, moveThread };
|
||||
|
||||
function stop() {
|
||||
if (frame.current !== null) cancelAnimationFrame(frame.current);
|
||||
frame.current = null;
|
||||
drag.current = null;
|
||||
setPreview(null);
|
||||
}
|
||||
const orderVersion = rows
|
||||
.map((row) => `${row.key}:${row.thread?.pinOrderKey}:${row.thread?.activeOrderKey}`)
|
||||
.join("|");
|
||||
useEffect(() => {
|
||||
stop();
|
||||
}, [orderVersion]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (frame.current !== null) cancelAnimationFrame(frame.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
function update(translation: number) {
|
||||
const current = drag.current;
|
||||
if (current === null) return;
|
||||
current.translation = translation;
|
||||
const { height, offset } = geometry.current;
|
||||
const y = current.startY + translation;
|
||||
translateY.setValue(Math.max(0, Math.min(height - ROW_HEIGHT, y - ROW_HEIGHT / 2)));
|
||||
const contentY = Math.max(0, y + offset);
|
||||
const target =
|
||||
latest.current.rows.find((row) => contentY < row.offset + row.height) ??
|
||||
latest.current.rows.at(-1);
|
||||
let destination: Destination | null = null;
|
||||
if (
|
||||
target &&
|
||||
y >= 0 &&
|
||||
y <= height &&
|
||||
(target.section === "pinned" || target.section === "active" || target.section === "settled")
|
||||
) {
|
||||
const candidate: Destination = {
|
||||
section: target.section,
|
||||
targetId: target.thread ? target.key : null,
|
||||
placement:
|
||||
!target.thread || contentY < target.offset + target.height / 2 ? "before" : "after",
|
||||
};
|
||||
if (target.section === "settled") {
|
||||
if (
|
||||
current.sourceSection !== "settled" &&
|
||||
configs.get(current.thread.environmentId)?.environment.capabilities.threadSettlement
|
||||
)
|
||||
destination = { section: "settled", targetId: null, placement: "before" };
|
||||
} else if (latest.current.planners[target.section](keyOf(current.thread), candidate) !== null)
|
||||
destination = candidate;
|
||||
}
|
||||
if (
|
||||
current.destination?.targetId !== destination?.targetId ||
|
||||
current.destination?.section !== destination?.section ||
|
||||
current.destination?.placement !== destination?.placement
|
||||
) {
|
||||
current.destination = destination;
|
||||
setPreview({ ...current });
|
||||
}
|
||||
}
|
||||
function start(row: Row) {
|
||||
if (!row.thread || preview !== null) return;
|
||||
drag.current = {
|
||||
orderVersion,
|
||||
sourceSection: row.section,
|
||||
thread: row.thread,
|
||||
startY: row.offset + ROW_HEIGHT / 2 - geometry.current.offset,
|
||||
translation: 0,
|
||||
destination: null,
|
||||
};
|
||||
setPreview({ ...drag.current });
|
||||
update(0);
|
||||
let last = performance.now();
|
||||
const tick = () => {
|
||||
const current = drag.current;
|
||||
if (!current) return;
|
||||
const timestamp = performance.now();
|
||||
const dt = Math.min(timestamp - last, 32);
|
||||
last = timestamp;
|
||||
const bounds = geometry.current;
|
||||
const y = current.startY + current.translation;
|
||||
const speed =
|
||||
y < 48
|
||||
? -Math.min(1, (48 - y) / 48)
|
||||
: y > bounds.height - 48
|
||||
? Math.min(1, (y - bounds.height + 48) / 48)
|
||||
: 0;
|
||||
const tail = latest.current.rows.at(-1);
|
||||
const maximum = Math.max(0, (tail ? tail.offset + tail.height : 0) - bounds.height);
|
||||
const offset = Math.max(0, Math.min(maximum, bounds.offset + speed * dt * 0.5));
|
||||
if (offset !== bounds.offset) {
|
||||
bounds.offset = offset;
|
||||
list.current?.scrollToOffset({ offset, animated: false });
|
||||
update(current.translation);
|
||||
}
|
||||
frame.current = requestAnimationFrame(tick);
|
||||
};
|
||||
frame.current = requestAnimationFrame(tick);
|
||||
}
|
||||
const visiblePreview = preview?.orderVersion === orderVersion ? preview : null;
|
||||
const sourceRow = visiblePreview
|
||||
? rows.find((row) => row.key === keyOf(visiblePreview.thread))
|
||||
: undefined;
|
||||
const destination = visiblePreview?.destination;
|
||||
const targetRow = destination
|
||||
? rows.find(
|
||||
(row) =>
|
||||
row.section === destination.section &&
|
||||
row.key === (destination.targetId ?? destination.section),
|
||||
)
|
||||
: undefined;
|
||||
const insertionOffset = targetRow
|
||||
? targetRow.offset +
|
||||
(!targetRow.thread || destination?.placement === "after" ? targetRow.height : 0)
|
||||
: sourceRow?.offset;
|
||||
return (
|
||||
<Modal
|
||||
visible
|
||||
animationType="slide"
|
||||
presentationStyle="fullScreen"
|
||||
onRequestClose={props.onClose}
|
||||
>
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<View
|
||||
className="flex-1 bg-screen"
|
||||
style={{ paddingTop: insets.top, paddingBottom: insets.bottom }}
|
||||
>
|
||||
<View className="flex-row items-center justify-between gap-3 px-5 py-3">
|
||||
<Text className="flex-1 text-xl font-t3-semibold">Arrange threads</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={props.onClose}
|
||||
className="min-h-11 justify-center px-3"
|
||||
>
|
||||
<Text className="text-base text-primary">Done</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
<Text className="px-5 pb-3 text-sm text-foreground-muted">
|
||||
Drag to reorder, pin, or settle. Changes save when you drop.
|
||||
</Text>
|
||||
<View
|
||||
onLayout={(event) => {
|
||||
geometry.current.height = event.nativeEvent.layout.height;
|
||||
}}
|
||||
className="flex-1"
|
||||
style={{ overflow: "hidden" }}
|
||||
>
|
||||
<FlatList
|
||||
ref={list}
|
||||
data={rows}
|
||||
keyExtractor={(row) => row.key}
|
||||
scrollEnabled={visiblePreview === null}
|
||||
removeClippedSubviews={false}
|
||||
onScroll={(event) => {
|
||||
geometry.current.offset = event.nativeEvent.contentOffset.y;
|
||||
}}
|
||||
scrollEventThrottle={16}
|
||||
getItemLayout={(_, index) => ({
|
||||
length: rows[index]!.height,
|
||||
offset: rows[index]!.offset,
|
||||
index,
|
||||
})}
|
||||
renderItem={({ item }) => {
|
||||
const thread = item.thread;
|
||||
const planner =
|
||||
item.section === "pinned" || item.section === "active"
|
||||
? planners[item.section]
|
||||
: null;
|
||||
const capabilities =
|
||||
thread && configs.get(thread.environmentId)?.environment.capabilities;
|
||||
const sectionActions = thread
|
||||
? (["pinned", "active", "settled"] as const).flatMap<{
|
||||
name: "pinned" | "active" | "settled";
|
||||
label: string;
|
||||
}>((section) => {
|
||||
if (section === item.section) return [];
|
||||
const label = threadDragAction(item.section, section);
|
||||
if (!label) return [];
|
||||
if (section === "settled")
|
||||
return capabilities?.threadSettlement ? [{ name: section, label }] : [];
|
||||
if (
|
||||
((section === "pinned" || thread.pinnedAt != null) &&
|
||||
!capabilities?.threadPinning) ||
|
||||
(section === "active" &&
|
||||
item.section === "settled" &&
|
||||
!capabilities?.threadSettlement) ||
|
||||
(section === "active" &&
|
||||
item.section === "snoozed" &&
|
||||
!capabilities?.threadSnooze)
|
||||
)
|
||||
return [];
|
||||
return planners[section](item.key, {
|
||||
section,
|
||||
targetId: null,
|
||||
placement: "before",
|
||||
})
|
||||
? [{ name: section, label }]
|
||||
: [];
|
||||
})
|
||||
: [];
|
||||
return (
|
||||
<ArrangementRow
|
||||
height={item.height}
|
||||
dragging={visiblePreview !== null}
|
||||
lifted={item.key === sourceRow?.key}
|
||||
offset={
|
||||
sourceRow && insertionOffset !== undefined
|
||||
? threadDragGapOffset(
|
||||
item.offset,
|
||||
sourceRow.offset,
|
||||
sourceRow.height,
|
||||
insertionOffset,
|
||||
)
|
||||
: 0
|
||||
}
|
||||
>
|
||||
{thread ? (
|
||||
<>
|
||||
<Text numberOfLines={2} className="flex-1 text-base">
|
||||
{thread.title}
|
||||
</Text>
|
||||
<DragHandle
|
||||
title={thread.title}
|
||||
disabled={
|
||||
dropBusy ||
|
||||
pendingOrder !== null ||
|
||||
!(
|
||||
configs.get(thread.environmentId)?.environment.capabilities
|
||||
.threadPinReorder ||
|
||||
configs.get(thread.environmentId)?.environment.capabilities
|
||||
.threadActiveReorder
|
||||
)
|
||||
}
|
||||
sectionActions={sectionActions}
|
||||
onSectionMove={(section) => {
|
||||
void moveThread(thread, {
|
||||
section,
|
||||
targetId: null,
|
||||
placement: "before",
|
||||
});
|
||||
}}
|
||||
canMoveUp={planner?.(item.key, "up") != null}
|
||||
canMoveDown={planner?.(item.key, "down") != null}
|
||||
onStep={(direction) => {
|
||||
void moveThread(thread, direction);
|
||||
}}
|
||||
onStart={() => start(item)}
|
||||
onMove={update}
|
||||
onEnd={(cancelled) => {
|
||||
const current = drag.current;
|
||||
if (cancelled || !current?.destination) {
|
||||
stop();
|
||||
return;
|
||||
}
|
||||
if (frame.current !== null) cancelAnimationFrame(frame.current);
|
||||
frame.current = null;
|
||||
drag.current = null;
|
||||
// Retain the gap until the saved order arrives, avoiding a flash back.
|
||||
void moveThread(current.thread, current.destination).finally(stop);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<Pressable
|
||||
disabled={item.section === "pinned" || item.section === "active"}
|
||||
className="flex-1 justify-center self-stretch"
|
||||
onPress={() => {
|
||||
const section = item.section;
|
||||
if (section === "snoozed" || section === "settled")
|
||||
setExpanded((value) => ({ ...value, [section]: !value[section] }));
|
||||
}}
|
||||
>
|
||||
<Text className="text-sm font-t3-semibold text-foreground-muted">
|
||||
{item.section[0]!.toUpperCase() + item.section.slice(1)} (
|
||||
{sections[item.section].length})
|
||||
</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
</ArrangementRow>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
{visiblePreview ? (
|
||||
<Animated.View
|
||||
pointerEvents="none"
|
||||
className="absolute left-5 right-5 justify-center rounded-xl border border-border bg-screen px-4"
|
||||
style={{ top: 0, height: ROW_HEIGHT, transform: [{ translateY }] }}
|
||||
>
|
||||
<Text
|
||||
numberOfLines={visiblePreview.destination?.section ? 1 : 2}
|
||||
className="text-base font-t3-medium"
|
||||
>
|
||||
{visiblePreview.thread.title}
|
||||
</Text>
|
||||
{visiblePreview.destination?.section ? (
|
||||
<Text className="text-xs text-foreground-muted">
|
||||
{threadDragAction(
|
||||
visiblePreview.sourceSection,
|
||||
visiblePreview.destination.section,
|
||||
)}
|
||||
</Text>
|
||||
) : null}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</GestureHandlerRootView>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function ThreadArrangementHost() {
|
||||
const open = useAtomValue(threadArrangementOpenAtom);
|
||||
return open ? (
|
||||
<ThreadArrangementSheet onClose={() => appAtomRegistry.set(threadArrangementOpenAtom, false)} />
|
||||
) : null;
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { threadArrangementOpenAtom } from "../../state/thread-order";
|
||||
import type { ThreadMoveDestination } from "./threadOrder";
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
@@ -395,7 +398,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly titleRegenerationSupported: boolean;
|
||||
/** Server supports reordering this card's section. */
|
||||
readonly reorderSupported?: boolean;
|
||||
readonly onMoveThread?: (thread: EnvironmentThreadShell, direction: "up" | "down") => void;
|
||||
readonly onMoveThread?: (
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: ThreadMoveDestination,
|
||||
) => void;
|
||||
/** Position flags for the card's section so the menu disables the move that
|
||||
would fall off the end of the list. */
|
||||
readonly canMoveUp?: boolean;
|
||||
@@ -515,8 +521,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
// hides the card until wake with the pin intact.)
|
||||
const arrangementMenuItems = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
...(variant === "card" && props.reorderSupported === true
|
||||
...(props.reorderSupported === true
|
||||
? [
|
||||
{ id: "arrange", title: "Arrange threads…", image: "line.3.horizontal" },
|
||||
{
|
||||
id: "move-up",
|
||||
title: "Move up",
|
||||
@@ -583,11 +590,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const slimMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
SLIM_MENU_ACTIONS[0]!,
|
||||
...(thread.pinnedAt != null ? arrangementMenuItems : []),
|
||||
...arrangementMenuItems.filter(
|
||||
(action) => action.id !== "move-up" && action.id !== "move-down",
|
||||
),
|
||||
...titleRegenerationMenuItems,
|
||||
SLIM_MENU_ACTIONS[1]!,
|
||||
],
|
||||
[arrangementMenuItems, thread.pinnedAt, titleRegenerationMenuItems],
|
||||
[arrangementMenuItems, titleRegenerationMenuItems],
|
||||
);
|
||||
const snoozedMenuActions = useMemo<MenuAction[]>(
|
||||
() => [SNOOZED_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SNOOZED_MENU_ACTIONS[1]!],
|
||||
@@ -610,6 +619,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
if (nativeEvent.event === "unsnooze") handleUnsnooze();
|
||||
if (nativeEvent.event === "pin") handlePin();
|
||||
if (nativeEvent.event === "unpin") handleUnpin();
|
||||
if (nativeEvent.event === "arrange") appAtomRegistry.set(threadArrangementOpenAtom, true);
|
||||
if (nativeEvent.event === "move-up") handleMoveUp();
|
||||
if (nativeEvent.event === "move-down") handleMoveDown();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { threadDragAction, threadOrderAfterMove } from "./threadOrder";
|
||||
import { threadDragGapOffset } from "./threadDragGap";
|
||||
|
||||
describe("live thread insertion gap", () => {
|
||||
// Header, pinned row, Active header, two active rows. Geometry stays fixed for hit testing.
|
||||
const offsets = [0, 48, 120, 168, 240];
|
||||
const shifts = (source: number, insertion: number) =>
|
||||
offsets.map((offset) => threadDragGapOffset(offset, source, 72, insertion));
|
||||
|
||||
it("moves the Active header and intervening rows up when unpinning", () => {
|
||||
expect(shifts(48, 312)).toEqual([0, 0, -72, -72, -72]);
|
||||
});
|
||||
it("opens a full gap below the Pinned header when pinning", () => {
|
||||
expect(shifts(240, 48)).toEqual([0, 72, 72, 72, 0]);
|
||||
});
|
||||
it("leaves the source gap in place for cancellation or its current destination", () => {
|
||||
expect(shifts(168, 168)).toEqual([0, 0, 0, 0, 0]);
|
||||
expect(shifts(168, 240)).toEqual([0, 0, 0, 0, 0]);
|
||||
});
|
||||
it("moves only crossed rows for an adjacent reorder", () => {
|
||||
expect(shifts(168, 312)).toEqual([0, 0, 0, 0, -72]);
|
||||
expect(shifts(240, 168)).toEqual([0, 0, 0, 72, 0]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("drag action labels", () => {
|
||||
it("names the action for each destination instead of its section", () => {
|
||||
expect(threadDragAction("active", "pinned")).toBe("Pin");
|
||||
expect(threadDragAction("pinned", "active")).toBe("Unpin");
|
||||
expect(threadDragAction("settled", "active")).toBe("Unsettle");
|
||||
expect(threadDragAction("snoozed", "active")).toBe("Unsnooze");
|
||||
expect(threadDragAction("active", "settled")).toBe("Settle");
|
||||
expect(threadDragAction("pinned", "settled")).toBe("Settle");
|
||||
expect(threadDragAction("active", "active")).toBe("Reorder");
|
||||
});
|
||||
it("does not offer a parked-section reorder or snooze without a wake time", () => {
|
||||
expect(threadDragAction("settled", "settled")).toBeNull();
|
||||
expect(threadDragAction("active", "snoozed")).toBeNull();
|
||||
expect(
|
||||
threadOrderAfterMove(["a", "b"], "a", {
|
||||
section: "settled",
|
||||
targetId: null,
|
||||
placement: "before",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
/** Keep hit testing in the original layout while rows make room for the lifted item. */
|
||||
export function threadDragGapOffset(
|
||||
rowOffset: number,
|
||||
sourceOffset: number,
|
||||
sourceHeight: number,
|
||||
insertionOffset: number,
|
||||
): number {
|
||||
if (rowOffset === sourceOffset) return 0;
|
||||
if (insertionOffset <= sourceOffset) {
|
||||
return rowOffset >= insertionOffset && rowOffset < sourceOffset ? sourceHeight : 0;
|
||||
}
|
||||
return rowOffset > sourceOffset && rowOffset < insertionOffset ? -sourceHeight : 0;
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import { planPinnedMove } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import {
|
||||
createPendingThreadOrder,
|
||||
createThreadMovePlanner,
|
||||
threadOrderAfterMove,
|
||||
threadDropLifecycle,
|
||||
reconcilePendingThreadOrder,
|
||||
type PendingThreadOrder,
|
||||
} from "./threadOrder";
|
||||
@@ -1276,3 +1278,202 @@ describe("mobile move availability", () => {
|
||||
expect(assignments![0]!.orderKey < "dd").toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("thread drag destinations", () => {
|
||||
it("moves across multiple rows while keeping hidden anchors in place", () => {
|
||||
expect(
|
||||
threadOrderAfterMove(["a", "hidden", "b", "c"], "c", {
|
||||
targetId: "a",
|
||||
placement: "before",
|
||||
}),
|
||||
).toEqual(["c", "a", "hidden", "b"]);
|
||||
expect(
|
||||
threadOrderAfterMove(["a", "hidden", "b", "c"], "a", {
|
||||
targetId: "b",
|
||||
placement: "after",
|
||||
}),
|
||||
).toEqual(["hidden", "b", "a", "c"]);
|
||||
});
|
||||
|
||||
it("rejects missing, self, and unchanged destinations", () => {
|
||||
for (const targetId of ["missing", "a", "b"]) {
|
||||
expect(
|
||||
threadOrderAfterMove(["a", "b", "c"], "a", {
|
||||
targetId,
|
||||
placement: "before",
|
||||
}),
|
||||
).toBeNull();
|
||||
}
|
||||
expect(threadOrderAfterMove(["a", "b"], "missing", "down")).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["active", "pinned"] as const)(
|
||||
"persists a dropped %s row and holds its order until confirmed",
|
||||
(section) => {
|
||||
const ordered = ["a", "b", "c", "d"].map((id) =>
|
||||
makeThread({
|
||||
id: ThreadId.make(id),
|
||||
title: id,
|
||||
pinnedAt: section === "pinned" ? NOW : null,
|
||||
}),
|
||||
);
|
||||
const ids = ordered.map((row) => `${row.environmentId}:${row.id}`);
|
||||
const direction = { targetId: ids[0]!, placement: "before" as const };
|
||||
const assignments = createThreadMovePlanner({
|
||||
ordered,
|
||||
section,
|
||||
reorderableEnvironmentIds: new Set([environmentId]),
|
||||
})(ids[3]!, direction)!;
|
||||
const pending = createPendingThreadOrder({
|
||||
section,
|
||||
ordered,
|
||||
movedId: ids[3]!,
|
||||
direction,
|
||||
assignments,
|
||||
});
|
||||
expect(pending.orderedIds).toEqual([ids[3], ids[0], ids[1], ids[2]]);
|
||||
const confirmed = ordered.map((row) => ({
|
||||
...row,
|
||||
[section === "pinned" ? "pinOrderKey" : "activeOrderKey"]: assignments.find(
|
||||
(a) => a.id === `${row.environmentId}:${row.id}`,
|
||||
)!.orderKey,
|
||||
}));
|
||||
expect(
|
||||
getThreadListV2OrderedSection({ threads: confirmed, section, now: NOW }).map(
|
||||
(row) => `${row.environmentId}:${row.id}`,
|
||||
),
|
||||
).toEqual(pending.orderedIds);
|
||||
expect(
|
||||
reconcilePendingThreadOrder({ ...pending, commandsComplete: true }, confirmed),
|
||||
).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it("refuses a drop that would need to rewrite an old server's keyless row", () => {
|
||||
const old = EnvironmentId.make("old-server");
|
||||
const ordered = [environmentId, old, environmentId].map((env, index) =>
|
||||
makeThread({
|
||||
id: ThreadId.make(String(index)),
|
||||
title: String(index),
|
||||
environmentId: env,
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
createThreadMovePlanner({
|
||||
ordered,
|
||||
section: "active",
|
||||
reorderableEnvironmentIds: new Set([environmentId]),
|
||||
})(`${environmentId}:2`, { targetId: `${environmentId}:0`, placement: "before" }),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("allows a long drop past an old server even when both adjacent moves fail", () => {
|
||||
const old = EnvironmentId.make("old-server");
|
||||
const ordered = [
|
||||
makeThread({ id: ThreadId.make("a"), title: "a" }),
|
||||
makeThread({ id: ThreadId.make("b"), title: "b", environmentId: old }),
|
||||
makeThread({ id: ThreadId.make("c"), title: "c", activeOrderKey: "h" }),
|
||||
makeThread({ id: ThreadId.make("d"), title: "d", activeOrderKey: "p" }),
|
||||
];
|
||||
const planner = createThreadMovePlanner({
|
||||
ordered,
|
||||
section: "active",
|
||||
reorderableEnvironmentIds: new Set([environmentId]),
|
||||
});
|
||||
const movedId = `${environmentId}:a`;
|
||||
expect(planner(movedId, "up")).toBeNull();
|
||||
expect(planner(movedId, "down")).toBeNull();
|
||||
const assignments = planner(movedId, { targetId: `${environmentId}:d`, placement: "after" });
|
||||
expect(assignments).toHaveLength(1);
|
||||
expect(assignments![0]!.id).toBe(movedId);
|
||||
expect(assignments![0]!.orderKey > "p").toBe(true);
|
||||
});
|
||||
|
||||
describe("cross-section thread drops", () => {
|
||||
it.each(["pinned", "active"] as const)("inserts into an empty %s section", (section) => {
|
||||
const thread = makeThread({ id: ThreadId.make("source"), title: "source" });
|
||||
const id = `${thread.environmentId}:${thread.id}`;
|
||||
const destination = { section, targetId: null, placement: "before" as const };
|
||||
expect(threadOrderAfterMove([], id, destination)).toEqual([id]);
|
||||
const plan = createThreadMovePlanner({
|
||||
ordered: [],
|
||||
allThreads: [thread],
|
||||
section,
|
||||
reorderableEnvironmentIds: new Set([environmentId]),
|
||||
})(id, destination);
|
||||
expect(plan).toHaveLength(1);
|
||||
expect(plan![0]!.id).toBe(id);
|
||||
});
|
||||
it("places an incoming row between existing anchors without rewriting them", () => {
|
||||
const a = makeThread({ id: ThreadId.make("a"), title: "a", pinOrderKey: "h" });
|
||||
const b = makeThread({ id: ThreadId.make("b"), title: "b", pinOrderKey: "z" });
|
||||
const source = makeThread({ id: ThreadId.make("source"), title: "source" });
|
||||
const id = `${environmentId}:source`;
|
||||
const destination = {
|
||||
section: "pinned" as const,
|
||||
targetId: `${environmentId}:b`,
|
||||
placement: "before" as const,
|
||||
};
|
||||
const plan = createThreadMovePlanner({
|
||||
ordered: [a, b],
|
||||
allThreads: [a, b, source],
|
||||
section: "pinned",
|
||||
reorderableEnvironmentIds: new Set([environmentId]),
|
||||
})(id, destination);
|
||||
expect(plan).toHaveLength(1);
|
||||
expect(plan![0]!.orderKey > "h" && plan![0]!.orderKey < "z").toBe(true);
|
||||
expect(
|
||||
threadOrderAfterMove([`${environmentId}:a`, `${environmentId}:b`], id, destination),
|
||||
).toEqual([`${environmentId}:a`, id, `${environmentId}:b`]);
|
||||
});
|
||||
it("rejects removed targets and unsupported incoming sources", () => {
|
||||
expect(
|
||||
threadOrderAfterMove(["a"], "source", {
|
||||
section: "active",
|
||||
targetId: "gone",
|
||||
placement: "before",
|
||||
}),
|
||||
).toBeNull();
|
||||
const source = makeThread({ id: ThreadId.make("source"), title: "source" });
|
||||
expect(
|
||||
createThreadMovePlanner({
|
||||
ordered: [],
|
||||
allThreads: [source],
|
||||
section: "active",
|
||||
reorderableEnvironmentIds: new Set(),
|
||||
})(`${environmentId}:source`, { section: "active", targetId: null, placement: "before" }),
|
||||
).toBeNull();
|
||||
});
|
||||
it("clears pinning, settlement and snooze when returning a parked thread to Active", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("parked"),
|
||||
title: "parked",
|
||||
pinnedAt: NOW,
|
||||
settledOverride: "settled",
|
||||
snoozedAt: NOW,
|
||||
snoozedUntil: "2099-01-01T00:00:00.000Z",
|
||||
});
|
||||
expect(threadDropLifecycle(thread, "active", NOW)).toEqual({
|
||||
pin: false,
|
||||
unpin: true,
|
||||
unsettle: true,
|
||||
unsnooze: true,
|
||||
});
|
||||
expect(threadDropLifecycle(thread, "pinned", NOW)).toEqual({
|
||||
pin: true,
|
||||
unpin: false,
|
||||
unsettle: false,
|
||||
unsnooze: false,
|
||||
});
|
||||
});
|
||||
it("does not send lifecycle commands for an ordinary Active reorder", () => {
|
||||
expect(
|
||||
threadDropLifecycle(
|
||||
makeThread({ id: ThreadId.make("active"), title: "active" }),
|
||||
"active",
|
||||
NOW,
|
||||
),
|
||||
).toEqual({ pin: false, unpin: false, unsettle: false, unsnooze: false });
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,47 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { planPinnedMove } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import { planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
export type ThreadMoveDestination =
|
||||
| "up"
|
||||
| "down"
|
||||
| {
|
||||
readonly targetId: string | null;
|
||||
readonly section?: "pinned" | "active" | "settled";
|
||||
readonly placement: "before" | "after";
|
||||
};
|
||||
|
||||
/** Resolve against stable row identities, including rows hidden by a filter. */
|
||||
export function threadOrderAfterMove(
|
||||
orderedIds: readonly string[],
|
||||
movedId: string,
|
||||
destination: ThreadMoveDestination,
|
||||
): string[] | null {
|
||||
if (typeof destination === "object" && destination.section === "settled") return null;
|
||||
const from = orderedIds.indexOf(movedId);
|
||||
if (from < 0 && (typeof destination === "string" || destination.section === undefined))
|
||||
return null;
|
||||
const result = orderedIds.filter((id) => id !== movedId);
|
||||
let to: number;
|
||||
if (typeof destination === "string") {
|
||||
to = from + (destination === "up" ? -1 : 1);
|
||||
if (to < 0 || to >= orderedIds.length) return null;
|
||||
} else {
|
||||
if (destination.targetId === null) {
|
||||
if (destination.section === undefined) return null;
|
||||
to = destination.placement === "before" ? 0 : result.length;
|
||||
} else {
|
||||
const target = result.indexOf(destination.targetId);
|
||||
if (target < 0) return null;
|
||||
to = target + (destination.placement === "after" ? 1 : 0);
|
||||
}
|
||||
}
|
||||
if (to === from) return null;
|
||||
result.splice(to, 0, movedId);
|
||||
return result;
|
||||
}
|
||||
|
||||
type OrderRow = Pick<
|
||||
EnvironmentThreadShell,
|
||||
| "id"
|
||||
@@ -49,13 +89,15 @@ export function createThreadMovePlanner(input: {
|
||||
]),
|
||||
);
|
||||
const writableIds = new Set(
|
||||
input.ordered
|
||||
(input.allThreads ?? input.ordered)
|
||||
.filter((row) => input.reorderableEnvironmentIds.has(row.environmentId))
|
||||
.map(rowId),
|
||||
);
|
||||
return (movedId: string, direction: "up" | "down") => {
|
||||
return (movedId: string, direction: ThreadMoveDestination) => {
|
||||
if (!writableIds.has(movedId)) return null;
|
||||
const assignments = planPinnedMove({ orderedIds, keysById, movedId, direction });
|
||||
const nextIds = threadOrderAfterMove(orderedIds, movedId, direction);
|
||||
if (nextIds === null) return null;
|
||||
const assignments = planPinnedReorder({ orderedIds: nextIds, keysById, movedId });
|
||||
return assignments === null ||
|
||||
assignments.length === 0 ||
|
||||
assignments.some((assignment) => !writableIds.has(assignment.id))
|
||||
@@ -68,13 +110,11 @@ export function createPendingThreadOrder(input: {
|
||||
readonly section: PendingThreadOrder["section"];
|
||||
readonly ordered: readonly OrderRow[];
|
||||
readonly movedId: string;
|
||||
readonly direction: "up" | "down";
|
||||
readonly direction: ThreadMoveDestination;
|
||||
readonly assignments: readonly { readonly id: string; readonly orderKey: string }[];
|
||||
}): PendingThreadOrder {
|
||||
const orderedIds = input.ordered.map(rowId);
|
||||
const from = orderedIds.indexOf(input.movedId);
|
||||
orderedIds.splice(from, 1);
|
||||
orderedIds.splice(from + (input.direction === "up" ? -1 : 1), 0, input.movedId);
|
||||
const orderedIds = threadOrderAfterMove(input.ordered.map(rowId), input.movedId, input.direction);
|
||||
if (orderedIds === null) throw new Error("Cannot begin an invalid thread move");
|
||||
return {
|
||||
section: input.section,
|
||||
orderedIds,
|
||||
@@ -118,3 +158,32 @@ export function applyPendingThreadOrder<T extends OrderRow>(
|
||||
(left, right) => (rank.get(rowId(left)) ?? Infinity) - (rank.get(rowId(right)) ?? Infinity),
|
||||
);
|
||||
}
|
||||
|
||||
/** Match desktop re-entry: a pin wakes the thread on the server; Active clears
|
||||
* each underlying parked state before assigning its destination order key. */
|
||||
export function threadDropLifecycle(
|
||||
thread: EnvironmentThreadShell,
|
||||
section: "pinned" | "active",
|
||||
now: string,
|
||||
) {
|
||||
if (section === "pinned") return { pin: true, unpin: false, unsettle: false, unsnooze: false };
|
||||
return {
|
||||
pin: false,
|
||||
unpin: thread.pinnedAt != null,
|
||||
unsettle: thread.settledOverride === "settled",
|
||||
unsnooze: effectiveSnoozed(thread, { now }),
|
||||
};
|
||||
}
|
||||
|
||||
export type ThreadDragSection = "pinned" | "active" | "snoozed" | "settled";
|
||||
|
||||
/** The action shown during hover describes the lifecycle change made on drop. */
|
||||
export function threadDragAction(source: ThreadDragSection, destination: ThreadDragSection) {
|
||||
if (destination === "snoozed") return null;
|
||||
if (destination === "settled") return source === "settled" ? null : "Settle";
|
||||
if (source === destination) return "Reorder";
|
||||
if (destination === "pinned") return "Pin";
|
||||
if (source === "pinned") return "Unpin";
|
||||
if (source === "settled") return "Unsettle";
|
||||
return "Unsnooze";
|
||||
}
|
||||
@@ -12,6 +12,11 @@ import { environmentServerConfigsAtom } from "./server";
|
||||
import { environmentThreadShells } from "./threads";
|
||||
import { queuedThreadKeysAtom } from "./use-thread-outbox";
|
||||
|
||||
// Covers lifecycle commands before a cross-section move can acquire an order hold.
|
||||
export const threadArrangementOpenAtom = Atom.make(false).pipe(Atom.keepAlive);
|
||||
|
||||
export const threadDropBusyAtom = Atom.make(false).pipe(Atom.keepAlive);
|
||||
|
||||
export const pendingThreadOrderAtom = Atom.make<PendingThreadOrder | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
);
|
||||
|
||||
@@ -49,7 +49,11 @@ identify empty sections and a collapsed settled shelf.
|
||||
|
||||
Drag within the pinned or active section to change its order. Other rows slide aside to show the
|
||||
spot where the thread will land. Drops into either section keep the position you choose. On
|
||||
mobile, open a pinned or active thread's menu and choose **Move up** or **Move down**. The server
|
||||
mobile, open a thread's menu and choose **Arrange threads**. Drag a handle within or between
|
||||
**Pinned** and **Active** to reorder, pin, or unpin. Drop onto the **Settled** divider to
|
||||
settle a thread. The dragged card shows the action before you release it. Expand **Snoozed**
|
||||
or **Settled** to drag a parked thread back into either live section. Each drop saves; **Done** returns to the thread list.
|
||||
**Move up** and **Move down** are also available in the thread menu. The server
|
||||
saves the order, so it survives a refresh and appears on your other connected devices.
|
||||
|
||||
On web and desktop, the list also animates section changes made with thread actions such as
|
||||
|
||||
Reference in new issue
Block a user