Open History to see the last commit
1import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2import {
3 activeThreadSortKey,
4 generateSpreadPinOrderKeys,
5 pinOrderKeyBetween,
6 planPinnedReorder,
7} from "@t3tools/client-runtime/state/thread-sort";
8import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
9import type { EnvironmentId } from "@t3tools/contracts";
10import { msg } from "gt-react-native";
11
12import { m, type MessageResolver } from "../../i18n/messages";
13
14export type ThreadMoveDestination =
15 | "up"
16 | "down"
17 | {
18 readonly targetId: string | null;
19 readonly section?: "pinned" | "active" | "settled";
20 readonly placement: "before" | "after";
21 };
22
23export function threadOrderAfterMove(
24 orderedIds: readonly string[],
25 movedId: string,
26 destination: ThreadMoveDestination,
27): string[] | null {
28 if (typeof destination === "object" && destination.section === "settled") return null;
29 const from = orderedIds.indexOf(movedId);
30 if (from < 0 && (typeof destination === "string" || destination.section === undefined))
31 return null;
32 const result = orderedIds.filter((id) => id !== movedId);
33 let to: number;
34 if (typeof destination === "string") {
35 to = from + (destination === "up" ? -1 : 1);
36 if (to < 0 || to >= orderedIds.length) return null;
37 } else {
38 if (destination.targetId === null) {
39 if (destination.section === undefined) return null;
40 to = destination.placement === "before" ? 0 : result.length;
41 } else {
42 const target = result.indexOf(destination.targetId);
43 if (target < 0) return null;
44 to = target + (destination.placement === "after" ? 1 : 0);
45 }
46 }
47 if (to === from) return null;
48 result.splice(to, 0, movedId);
49 return result;
50}
51
52export type OrderRow = Pick<
53 EnvironmentThreadShell,
54 | "id"
55 | "environmentId"
56 | "pinOrderKey"
57 | "activeOrderKey"
58 | "createdAt"
59 | "unsettledAt"
60 | "pinnedAt"
61>;
62
63export interface PendingThreadOrder {
64 readonly section: "pinned" | "active";
65 readonly orderedIds: readonly string[];
66 readonly before: ReadonlyMap<string, { readonly key: string | null; readonly anchor: string }>;
67 readonly assignments: ReadonlyMap<string, string>;
68 readonly confirmed: ReadonlySet<string>;
69 readonly commandsComplete: boolean;
70}
71
72function rowId(row: OrderRow): string {
73 return `${row.environmentId}:${row.id}`;
74}
75
76function storedKey(row: OrderRow, section: PendingThreadOrder["section"]) {
77 return (section === "pinned" ? row.pinOrderKey : row.activeOrderKey) ?? null;
78}
79
80function rowOrder(row: OrderRow, section: PendingThreadOrder["section"]) {
81 return {
82 key: section === "pinned" ? storedKey(row, section) : activeThreadSortKey(row),
83 anchor: section === "pinned" ? (row.pinnedAt ?? "") : (row.unsettledAt ?? row.createdAt),
84 };
85}
86
87export function createThreadMovePlanner(input: {
88 readonly ordered: readonly OrderRow[];
89 readonly allThreads?: readonly OrderRow[];
90 readonly section: PendingThreadOrder["section"];
91 readonly reorderableEnvironmentIds: ReadonlySet<EnvironmentId>;
92}) {
93 const orderedIds = input.ordered.map(rowId);
94 // Hidden rows keep their stored key: only stored keys can collide with a write.
95 const keysById = new Map([
96 ...(input.allThreads ?? input.ordered).map(
97 (row) => [rowId(row), storedKey(row, input.section)] as const,
98 ),
99 ...input.ordered.map((row) => [rowId(row), rowOrder(row, input.section).key] as const),
100 ]);
101 const writableIds = new Set(
102 (input.allThreads ?? input.ordered)
103 .filter((row) => input.reorderableEnvironmentIds.has(row.environmentId))
104 .map(rowId),
105 );
106 return (movedId: string, direction: ThreadMoveDestination) => {
107 if (!writableIds.has(movedId)) return null;
108 const nextIds = threadOrderAfterMove(orderedIds, movedId, direction);
109 if (nextIds === null) return null;
110 const assignments = planPinnedReorder({ orderedIds: nextIds, keysById, movedId });
111 return assignments === null ||
112 assignments.length === 0 ||
113 assignments.some((assignment) => !writableIds.has(assignment.id))
114 ? null
115 : assignments;
116 };
117}
118
119export interface ThreadMoveAvailability {
120 readonly canMoveUp: boolean;
121 readonly canMoveDown: boolean;
122}
123
124/** Compute per section; per-card planner probes make minute ticks quadratic. */
125export function computeThreadMoveAvailability(input: {
126 readonly ordered: readonly OrderRow[];
127 readonly allThreads?: readonly OrderRow[];
128 readonly section: PendingThreadOrder["section"];
129 readonly reorderableEnvironmentIds: ReadonlySet<EnvironmentId>;
130 readonly pendingOrder?: PendingThreadOrder | null;
131}): Map<string, ThreadMoveAvailability> {
132 const result = new Map<string, ThreadMoveAvailability>();
133 if (input.pendingOrder != null) return result;
134 const rows = input.ordered;
135 if (rows.length < 2) {
136 for (const row of rows) result.set(rowId(row), { canMoveUp: false, canMoveDown: false });
137 return result;
138 }
139 const orderedIds: string[] = [];
140 const indexById = new Map<string, number>();
141 for (const row of rows) {
142 const id = rowId(row);
143 indexById.set(id, orderedIds.length);
144 orderedIds.push(id);
145 }
146 const keysById = new Map<string, string | null>();
147 const writableIds = new Set<string>();
148 for (const row of input.allThreads ?? input.ordered) {
149 const id = rowId(row);
150 keysById.set(id, storedKey(row, input.section));
151 if (input.reorderableEnvironmentIds.has(row.environmentId)) writableIds.add(id);
152 }
153 for (const row of rows) keysById.set(rowId(row), rowOrder(row, input.section).key);
154 const reservedKeys = new Set<string>();
155 keysById.forEach((key, id) => {
156 if (key != null && !indexById.has(id)) reservedKeys.add(key);
157 });
158 // Swaps affect at most two positions; precomputed totals allow constant-size availability checks.
159 const midpoints = new Map<string, string | null>();
160 const fastPathKey = (beforeKey: string | null, afterKey: string | null): string | null => {
161 const memoKey = `${beforeKey ?? ""}\u0000${afterKey ?? ""}`;
162 const cached = midpoints.get(memoKey);
163 if (cached !== undefined) return cached;
164 let key = pinOrderKeyBetween(beforeKey, afterKey);
165 while (key !== null && reservedKeys.has(key)) key = pinOrderKeyBetween(key, afterKey);
166 midpoints.set(memoKey, key);
167 return key;
168 };
169 const spreadKeys = generateSpreadPinOrderKeys(orderedIds.length + reservedKeys.size)
170 .filter((key) => !reservedKeys.has(key))
171 .slice(0, orderedIds.length);
172 const currentKeys = orderedIds.map((id) => keysById.get(id) ?? null);
173 const writableRow = orderedIds.map((id) => writableIds.has(id));
174 let baselineWrites = 0;
175 let baselineUnwritableWrites = 0;
176 for (let position = 0; position < orderedIds.length; position += 1) {
177 if (currentKeys[position] === spreadKeys[position]) continue;
178 baselineWrites += 1;
179 if (!writableRow[position]) baselineUnwritableWrites += 1;
180 }
181 const rewriteViable = (index: number): boolean => {
182 let writes = baselineWrites;
183 let unwritableWrites = baselineUnwritableWrites;
184 for (const position of [index, index + 1]) {
185 const other = position === index ? index + 1 : index;
186 if (currentKeys[position] !== spreadKeys[position]) {
187 writes -= 1;
188 if (!writableRow[position]) unwritableWrites -= 1;
189 }
190 if (currentKeys[other] !== spreadKeys[position]) {
191 writes += 1;
192 if (!writableRow[other]) unwritableWrites += 1;
193 }
194 }
195 return writes > 0 && unwritableWrites === 0;
196 };
197 for (const row of rows) {
198 const movedId = rowId(row);
199 const denied = { canMoveUp: false, canMoveDown: false };
200 if (!writableIds.has(movedId)) {
201 result.set(movedId, denied);
202 continue;
203 }
204 const index = indexById.get(movedId);
205 if (index === undefined) {
206 result.set(movedId, denied);
207 continue;
208 }
209 const adjacentAvailable = (towardUp: boolean): boolean => {
210 const shifted = index + (towardUp ? -1 : 1);
211 if (shifted < 0 || shifted >= orderedIds.length) return false;
212 const beforeIndex = towardUp ? index - 2 : index + 1;
213 const afterIndex = towardUp ? index - 1 : index + 2;
214 const beforeId = beforeIndex < 0 ? null : (orderedIds[beforeIndex] ?? null);
215 const afterId = afterIndex >= orderedIds.length ? null : (orderedIds[afterIndex] ?? null);
216 const beforeKey = beforeId === null ? null : (keysById.get(beforeId) ?? null);
217 const afterKey = afterId === null ? null : (keysById.get(afterId) ?? null);
218 if ((beforeId === null || beforeKey != null) && (afterId === null || afterKey != null)) {
219 const key = fastPathKey(beforeKey, afterKey);
220 if (key !== null) return true;
221 }
222 return rewriteViable(Math.min(index, shifted));
223 };
224 result.set(movedId, {
225 canMoveUp: adjacentAvailable(true),
226 canMoveDown: adjacentAvailable(false),
227 });
228 }
229 return result;
230}
231
232export function createPendingThreadOrder(input: {
233 readonly section: PendingThreadOrder["section"];
234 readonly ordered: readonly OrderRow[];
235 readonly movedId: string;
236 readonly direction: ThreadMoveDestination;
237 readonly assignments: readonly { readonly id: string; readonly orderKey: string }[];
238}): PendingThreadOrder {
239 const orderedIds = threadOrderAfterMove(input.ordered.map(rowId), input.movedId, input.direction);
240 if (orderedIds === null) throw new Error("Cannot begin an invalid thread move");
241 return {
242 section: input.section,
243 orderedIds,
244 before: new Map(input.ordered.map((row) => [rowId(row), rowOrder(row, input.section)])),
245 assignments: new Map(input.assignments.map(({ id, orderKey }) => [id, orderKey])),
246 confirmed: new Set(),
247 commandsComplete: false,
248 };
249}
250
251/** Receipts and shell updates arrive independently. Only our own key writes
252 * may pass through the hold; membership and other arrangement changes win. */
253export function reconcilePendingThreadOrder(
254 pending: PendingThreadOrder,
255 ordered: readonly OrderRow[],
256): PendingThreadOrder | null {
257 if (ordered.length !== pending.before.size) return null;
258 const confirmed = new Set(pending.confirmed);
259 for (const row of ordered) {
260 const id = rowId(row);
261 const before = pending.before.get(id);
262 const current = rowOrder(row, pending.section);
263 if (before === undefined || current.anchor !== before.anchor) return null;
264 const assigned = pending.assignments.get(id);
265 if (assigned !== undefined && current.key === assigned) confirmed.add(id);
266 else if (current.key !== before.key || confirmed.has(id)) return null;
267 }
268 if (pending.commandsComplete && confirmed.size === pending.assignments.size) return null;
269 return confirmed.size === pending.confirmed.size ? pending : { ...pending, confirmed };
270}
271
272export function applyPendingThreadOrder<T extends OrderRow>(
273 rows: readonly T[],
274 section: PendingThreadOrder["section"],
275 pending: PendingThreadOrder | null | undefined,
276): T[] {
277 if (pending == null || pending.section !== section) return [...rows];
278 const rank = new Map(pending.orderedIds.map((id, index) => [id, index]));
279 return [...rows].sort(
280 (left, right) => (rank.get(rowId(left)) ?? Infinity) - (rank.get(rowId(right)) ?? Infinity),
281 );
282}
283
284export function threadDropLifecycle(
285 thread: EnvironmentThreadShell,
286 section: "pinned" | "active",
287 now: string,
288) {
289 if (section === "pinned") return { pin: true, unpin: false, unsettle: false, unsnooze: false };
290 return {
291 pin: false,
292 unpin: thread.pinnedAt != null,
293 unsettle: thread.settledOverride === "settled",
294 unsnooze: effectiveSnoozed(thread, { now }),
295 };
296}
297
298export type ThreadDragSection = "pinned" | "active" | "snoozed" | "settled";
299
300export function threadDragAction(
301 source: ThreadDragSection,
302 destination: ThreadDragSection,
303 resolve: MessageResolver = m,
304) {
305 if (destination === "snoozed") return null;
306 if (destination === "settled")
307 return source === "settled"
308 ? null
309 : resolve(msg("Settle", { $context: "verb, thread action" }));
310 if (source === destination) return resolve(msg("Reorder", { $context: "verb, thread action" }));
311 if (destination === "pinned") return resolve(msg("Pin", { $context: "verb, thread action" }));
312 if (source === "pinned") return resolve(msg("Unpin", { $context: "verb, thread action" }));
313 if (source === "settled") return resolve(msg("Unsettle", { $context: "verb, thread action" }));
314 return resolve(msg("Unsnooze", { $context: "verb, thread action" }));
315}