Open History to see the last commit
1import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2import { planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
3import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
4import type { EnvironmentId } from "@t3tools/contracts";
5
6export type ThreadMoveDestination =
7 | "up"
8 | "down"
9 | {
10 readonly targetId: string | null;
11 readonly section?: "pinned" | "active" | "settled";
12 readonly placement: "before" | "after";
13 };
14
15/** Resolve against stable row identities, including rows hidden by a filter. */
16export function threadOrderAfterMove(
17 orderedIds: readonly string[],
18 movedId: string,
19 destination: ThreadMoveDestination,
20): string[] | null {
21 if (typeof destination === "object" && destination.section === "settled") return null;
22 const from = orderedIds.indexOf(movedId);
23 if (from < 0 && (typeof destination === "string" || destination.section === undefined))
24 return null;
25 const result = orderedIds.filter((id) => id !== movedId);
26 let to: number;
27 if (typeof destination === "string") {
28 to = from + (destination === "up" ? -1 : 1);
29 if (to < 0 || to >= orderedIds.length) return null;
30 } else {
31 if (destination.targetId === null) {
32 if (destination.section === undefined) return null;
33 to = destination.placement === "before" ? 0 : result.length;
34 } else {
35 const target = result.indexOf(destination.targetId);
36 if (target < 0) return null;
37 to = target + (destination.placement === "after" ? 1 : 0);
38 }
39 }
40 if (to === from) return null;
41 result.splice(to, 0, movedId);
42 return result;
43}
44
45type OrderRow = Pick<
46 EnvironmentThreadShell,
47 | "id"
48 | "environmentId"
49 | "pinOrderKey"
50 | "activeOrderKey"
51 | "createdAt"
52 | "unsettledAt"
53 | "pinnedAt"
54>;
55
56export interface PendingThreadOrder {
57 readonly section: "pinned" | "active";
58 readonly orderedIds: readonly string[];
59 readonly before: ReadonlyMap<string, { readonly key: string | null; readonly anchor: string }>;
60 readonly assignments: ReadonlyMap<string, string>;
61 readonly confirmed: ReadonlySet<string>;
62 readonly commandsComplete: boolean;
63}
64
65function rowId(row: OrderRow): string {
66 return `${row.environmentId}:${row.id}`;
67}
68
69function rowOrder(row: OrderRow, section: PendingThreadOrder["section"]) {
70 return {
71 key: (section === "pinned" ? row.pinOrderKey : row.activeOrderKey) ?? null,
72 anchor: section === "pinned" ? (row.pinnedAt ?? "") : (row.unsettledAt ?? row.createdAt),
73 };
74}
75
76/** Keep every visible row as an anchor, but only offer plans whose key writes
77 * are supported. Menu availability and execution use this same planner. */
78export function createThreadMovePlanner(input: {
79 readonly ordered: readonly OrderRow[];
80 readonly allThreads?: readonly OrderRow[];
81 readonly section: PendingThreadOrder["section"];
82 readonly reorderableEnvironmentIds: ReadonlySet<EnvironmentId>;
83}) {
84 const orderedIds = input.ordered.map(rowId);
85 const keysById = new Map(
86 (input.allThreads ?? input.ordered).map((row) => [
87 rowId(row),
88 rowOrder(row, input.section).key,
89 ]),
90 );
91 const writableIds = new Set(
92 (input.allThreads ?? input.ordered)
93 .filter((row) => input.reorderableEnvironmentIds.has(row.environmentId))
94 .map(rowId),
95 );
96 return (movedId: string, direction: ThreadMoveDestination) => {
97 if (!writableIds.has(movedId)) return null;
98 const nextIds = threadOrderAfterMove(orderedIds, movedId, direction);
99 if (nextIds === null) return null;
100 const assignments = planPinnedReorder({ orderedIds: nextIds, keysById, movedId });
101 return assignments === null ||
102 assignments.length === 0 ||
103 assignments.some((assignment) => !writableIds.has(assignment.id))
104 ? null
105 : assignments;
106 };
107}
108
109export function createPendingThreadOrder(input: {
110 readonly section: PendingThreadOrder["section"];
111 readonly ordered: readonly OrderRow[];
112 readonly movedId: string;
113 readonly direction: ThreadMoveDestination;
114 readonly assignments: readonly { readonly id: string; readonly orderKey: string }[];
115}): PendingThreadOrder {
116 const orderedIds = threadOrderAfterMove(input.ordered.map(rowId), input.movedId, input.direction);
117 if (orderedIds === null) throw new Error("Cannot begin an invalid thread move");
118 return {
119 section: input.section,
120 orderedIds,
121 before: new Map(input.ordered.map((row) => [rowId(row), rowOrder(row, input.section)])),
122 assignments: new Map(input.assignments.map(({ id, orderKey }) => [id, orderKey])),
123 confirmed: new Set(),
124 commandsComplete: false,
125 };
126}
127
128/** Receipts and shell updates arrive independently. Only our own key writes
129 * may pass through the hold; membership and other arrangement changes win. */
130export function reconcilePendingThreadOrder(
131 pending: PendingThreadOrder,
132 ordered: readonly OrderRow[],
133): PendingThreadOrder | null {
134 if (ordered.length !== pending.before.size) return null;
135 const confirmed = new Set(pending.confirmed);
136 for (const row of ordered) {
137 const id = rowId(row);
138 const before = pending.before.get(id);
139 const current = rowOrder(row, pending.section);
140 if (before === undefined || current.anchor !== before.anchor) return null;
141 const assigned = pending.assignments.get(id);
142 if (assigned !== undefined && current.key === assigned) confirmed.add(id);
143 else if (current.key !== before.key || confirmed.has(id)) return null;
144 }
145 if (pending.commandsComplete && confirmed.size === pending.assignments.size) return null;
146 return confirmed.size === pending.confirmed.size ? pending : { ...pending, confirmed };
147}
148
149/** Apply the full section's pending order after search/environment filtering. */
150export function applyPendingThreadOrder<T extends OrderRow>(
151 rows: readonly T[],
152 section: PendingThreadOrder["section"],
153 pending: PendingThreadOrder | null | undefined,
154): T[] {
155 if (pending == null || pending.section !== section) return [...rows];
156 const rank = new Map(pending.orderedIds.map((id, index) => [id, index]));
157 return [...rows].sort(
158 (left, right) => (rank.get(rowId(left)) ?? Infinity) - (rank.get(rowId(right)) ?? Infinity),
159 );
160}
161
162/** Match desktop re-entry: a pin wakes the thread on the server; Active clears
163 * each underlying parked state before assigning its destination order key. */
164export function threadDropLifecycle(
165 thread: EnvironmentThreadShell,
166 section: "pinned" | "active",
167 now: string,
168) {
169 if (section === "pinned") return { pin: true, unpin: false, unsettle: false, unsnooze: false };
170 return {
171 pin: false,
172 unpin: thread.pinnedAt != null,
173 unsettle: thread.settledOverride === "settled",
174 unsnooze: effectiveSnoozed(thread, { now }),
175 };
176}
177
178export type ThreadDragSection = "pinned" | "active" | "snoozed" | "settled";
179
180/** The action shown during hover describes the lifecycle change made on drop. */
181export function threadDragAction(source: ThreadDragSection, destination: ThreadDragSection) {
182 if (destination === "snoozed") return null;
183 if (destination === "settled") return source === "settled" ? null : "Settle";
184 if (source === destination) return "Reorder";
185 if (destination === "pinned") return "Pin";
186 if (source === "pinned") return "Unpin";
187 if (source === "settled") return "Unsettle";
188 return "Unsnooze";
189}