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

threadOrder.ts

330 lines13.6 KB

1import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2import {
3 generateSpreadPinOrderKeys,
4 pinOrderKeyBetween,
5 planPinnedReorder,
6} from "@t3tools/client-runtime/state/thread-sort";
7import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
8import type { EnvironmentId } from "@t3tools/contracts";
9​
10export type ThreadMoveDestination =
11 | "up"
12 | "down"
13 | {
14 readonly targetId: string | null;
15 readonly section?: "pinned" | "active" | "settled";
16 readonly placement: "before" | "after";
17 };
18​
19/** Resolve against stable row identities, including rows hidden by a filter. */
20export function threadOrderAfterMove(
21 orderedIds: readonly string[],
22 movedId: string,
23 destination: ThreadMoveDestination,
24): string[] | null {
25 if (typeof destination === "object" && destination.section === "settled") return null;
26 const from = orderedIds.indexOf(movedId);
27 if (from < 0 && (typeof destination === "string" || destination.section === undefined))
28 return null;
29 const result = orderedIds.filter((id) => id !== movedId);
30 let to: number;
31 if (typeof destination === "string") {
32 to = from + (destination === "up" ? -1 : 1);
33 if (to < 0 || to >= orderedIds.length) return null;
34 } else {
35 if (destination.targetId === null) {
36 if (destination.section === undefined) return null;
37 to = destination.placement === "before" ? 0 : result.length;
38 } else {
39 const target = result.indexOf(destination.targetId);
40 if (target < 0) return null;
41 to = target + (destination.placement === "after" ? 1 : 0);
42 }
43 }
44 if (to === from) return null;
45 result.splice(to, 0, movedId);
46 return result;
48​
49export type OrderRow = Pick<
50 EnvironmentThreadShell,
51 | "id"
52 | "environmentId"
53 | "pinOrderKey"
54 | "activeOrderKey"
55 | "createdAt"
56 | "unsettledAt"
57 | "pinnedAt"
58>;
59​
60export interface PendingThreadOrder {
61 readonly section: "pinned" | "active";
62 readonly orderedIds: readonly string[];
63 readonly before: ReadonlyMap<string, { readonly key: string | null; readonly anchor: string }>;
64 readonly assignments: ReadonlyMap<string, string>;
65 readonly confirmed: ReadonlySet<string>;
66 readonly commandsComplete: boolean;
68​
69function rowId(row: OrderRow): string {
70 return `${row.environmentId}:${row.id}`;
72​
73function rowOrder(row: OrderRow, section: PendingThreadOrder["section"]) {
74 return {
75 key: (section === "pinned" ? row.pinOrderKey : row.activeOrderKey) ?? null,
76 anchor: section === "pinned" ? (row.pinnedAt ?? "") : (row.unsettledAt ?? row.createdAt),
77 };
79​
80/** Keep every visible row as an anchor, but only offer plans whose key writes
81 * are supported. Menu availability and execution use this same planner. */
82export function createThreadMovePlanner(input: {
83 readonly ordered: readonly OrderRow[];
84 readonly allThreads?: readonly OrderRow[];
85 readonly section: PendingThreadOrder["section"];
86 readonly reorderableEnvironmentIds: ReadonlySet<EnvironmentId>;
87}) {
88 const orderedIds = input.ordered.map(rowId);
89 const keysById = new Map(
90 (input.allThreads ?? input.ordered).map((row) => [
91 rowId(row),
92 rowOrder(row, input.section).key,
93 ]),
94 );
95 const writableIds = new Set(
96 (input.allThreads ?? input.ordered)
97 .filter((row) => input.reorderableEnvironmentIds.has(row.environmentId))
98 .map(rowId),
99 );
100 return (movedId: string, direction: ThreadMoveDestination) => {
101 if (!writableIds.has(movedId)) return null;
102 const nextIds = threadOrderAfterMove(orderedIds, movedId, direction);
103 if (nextIds === null) return null;
104 const assignments = planPinnedReorder({ orderedIds: nextIds, keysById, movedId });
105 return assignments === null ||
106 assignments.length === 0 ||
107 assignments.some((assignment) => !writableIds.has(assignment.id))
108 ? null
109 : assignments;
110 };
112​
113export interface ThreadMoveAvailability {
114 readonly canMoveUp: boolean;
115 readonly canMoveDown: boolean;
117​
118/**
119 * Batch form of "call `createThreadMovePlanner` once per card": one pass over
120 * the section answers up/down availability for every ordered row, so list
121 * construction stays linear instead of one full planner probe (array copies,
122 * hidden-key rescans) per row on the minute-tick rebuild path. The mirror of
123 * the planner's plan rules lives in the body below; the reference-parity test
124 * pins them row-by-row, including adversarial keys and hidden reservations.
125 */
126export function computeThreadMoveAvailability(input: {
127 readonly ordered: readonly OrderRow[];
128 readonly allThreads?: readonly OrderRow[];
129 readonly section: PendingThreadOrder["section"];
130 readonly reorderableEnvironmentIds: ReadonlySet<EnvironmentId>;
131 readonly pendingOrder?: PendingThreadOrder | null;
132}): Map<string, ThreadMoveAvailability> {
133 const result = new Map<string, ThreadMoveAvailability>();
134 // A reorder in flight locks the whole list until its receipt lands.
135 if (input.pendingOrder != null) return result;
136 const rows = input.ordered;
137 const orderedIds = rows.map(rowId);
138 const indexById = new Map(orderedIds.map((id, index) => [id, index] as const));
139 const keysById = new Map(
140 (input.allThreads ?? input.ordered).map(
141 (row) => [rowId(row), rowOrder(row, input.section).key] as const,
142 ),
143 );
144 const writableIds = new Set(
145 (input.allThreads ?? input.ordered)
146 .filter((row) => input.reorderableEnvironmentIds.has(row.environmentId))
147 .map(rowId),
148 );
149 const visibleIds = new Set(orderedIds);
150 const reservedKeys = new Set(
151 [...keysById].flatMap(([id, key]) => (!visibleIds.has(id) && key != null ? [key] : [])),
152 );
153 // Mirror of `planPinnedReorder` for adjacent swaps, hoisted so every row is
154 // answered in O(1) amortized instead of one planner probe per row:
155 //
156 // Fast path (both neighbors keyed): the fresh key between the landing
157 // neighbors, walking forward while hidden reserved keys block it. The walk
158 // depends only on the neighbor key pair - each adjacency is probed by at
159 // most two rows (down of the left member, up of the right member) - so the
160 // memo keeps even a fully adversarial reserved-key layout linear per build.
161 //
162 // Rewrite path (keyless/unusable neighbor, or key space exhausted): fresh
163 // spread keys for every row; only positions whose current key differs get
164 // written. A swap permutes two rows without changing the multiset, so the
165 // assignment set differs from the unswapped baseline at at most those two
166 // positions, and mismatch/writability tallies computed once per section
167 // answer each row with a constant-size delta.
168 const midpoints = new Map<string, string | null>();
169 const fastPathKey = (beforeKey: string | null, afterKey: string | null): string | null => {
170 const memoKey = `${beforeKey ?? ""}\u0000${afterKey ?? ""}`;
171 const cached = midpoints.get(memoKey);
172 if (cached !== undefined) return cached;
173 let key = pinOrderKeyBetween(beforeKey, afterKey);
174 while (key !== null && reservedKeys.has(key)) key = pinOrderKeyBetween(key, afterKey);
175 midpoints.set(memoKey, key);
176 return key;
177 };
178 const spreadKeys = generateSpreadPinOrderKeys(orderedIds.length + reservedKeys.size)
179 .filter((key) => !reservedKeys.has(key))
180 .slice(0, orderedIds.length);
181 const currentKeys = orderedIds.map((id) => keysById.get(id) ?? null);
182 const writableRow = orderedIds.map((id) => writableIds.has(id));
183 let baselineWrites = 0;
184 let baselineUnwritableWrites = 0;
185 for (let position = 0; position < orderedIds.length; position += 1) {
186 if (currentKeys[position] === spreadKeys[position]) continue;
187 baselineWrites += 1;
188 if (!writableRow[position]) baselineUnwritableWrites += 1;
189 }
190 // `movedId` swaps with its neighbor; ids at the two swapped positions change,
191 // so only their tally contributions are recomputed.
192 const rewriteViable = (index: number): boolean => {
193 let writes = baselineWrites;
194 let unwritableWrites = baselineUnwritableWrites;
195 for (const position of [index, index + 1]) {
196 const other = position === index ? index + 1 : index;
197 if (currentKeys[position] !== spreadKeys[position]) {
198 writes -= 1;
199 if (!writableRow[position]) unwritableWrites -= 1;
200 }
201 // After the swap this position holds the row that was at `other`.
202 if (currentKeys[other] !== spreadKeys[position]) {
203 writes += 1;
204 if (!writableRow[other]) unwritableWrites += 1;
205 }
206 }
207 return writes > 0 && unwritableWrites === 0;
208 };
209 for (const row of rows) {
210 const movedId = rowId(row);
211 const denied = { canMoveUp: false, canMoveDown: false };
212 if (!writableIds.has(movedId)) {
213 result.set(movedId, denied);
214 continue;
215 }
216 const index = indexById.get(movedId);
217 if (index === undefined) {
218 result.set(movedId, denied);
219 continue;
220 }
221 const adjacentAvailable = (towardUp: boolean): boolean => {
222 const shifted = index + (towardUp ? -1 : 1);
223 if (shifted < 0 || shifted >= orderedIds.length) return false;
224 // The swap exchanges the row with its neighbor; afterwards the moved row
225 // sits at `shifted` between `beforeIndex` and `afterIndex` of the OLD
226 // order: moving up it lands between old(index-2) and old(index-1),
227 // moving down between old(index+1) and old(index+2).
228 const beforeIndex = towardUp ? index - 2 : index + 1;
229 const afterIndex = towardUp ? index - 1 : index + 2;
230 const beforeId = beforeIndex < 0 ? null : (orderedIds[beforeIndex] ?? null);
231 const afterId = afterIndex >= orderedIds.length ? null : (orderedIds[afterIndex] ?? null);
232 const beforeKey = beforeId === null ? null : (keysById.get(beforeId) ?? null);
233 const afterKey = afterId === null ? null : (keysById.get(afterId) ?? null);
234 if ((beforeId === null || beforeKey != null) && (afterId === null || afterKey != null)) {
235 const key = fastPathKey(beforeKey, afterKey);
236 // A fresh key is a single-write plan for the (writable) moved row.
237 if (key !== null) return true;
238 }
239 // Keyless neighbor or exhausted key space: the section rewrite runs.
240 return rewriteViable(Math.min(index, shifted));
241 };
242 result.set(movedId, {
243 canMoveUp: adjacentAvailable(true),
244 canMoveDown: adjacentAvailable(false),
245 });
246 }
247 return result;
249​
250export function createPendingThreadOrder(input: {
251 readonly section: PendingThreadOrder["section"];
252 readonly ordered: readonly OrderRow[];
253 readonly movedId: string;
254 readonly direction: ThreadMoveDestination;
255 readonly assignments: readonly { readonly id: string; readonly orderKey: string }[];
256}): PendingThreadOrder {
257 const orderedIds = threadOrderAfterMove(input.ordered.map(rowId), input.movedId, input.direction);
258 if (orderedIds === null) throw new Error("Cannot begin an invalid thread move");
259 return {
260 section: input.section,
261 orderedIds,
262 before: new Map(input.ordered.map((row) => [rowId(row), rowOrder(row, input.section)])),
263 assignments: new Map(input.assignments.map(({ id, orderKey }) => [id, orderKey])),
264 confirmed: new Set(),
265 commandsComplete: false,
266 };
268​
269/** Receipts and shell updates arrive independently. Only our own key writes
270 * may pass through the hold; membership and other arrangement changes win. */
271export function reconcilePendingThreadOrder(
272 pending: PendingThreadOrder,
273 ordered: readonly OrderRow[],
274): PendingThreadOrder | null {
275 if (ordered.length !== pending.before.size) return null;
276 const confirmed = new Set(pending.confirmed);
277 for (const row of ordered) {
278 const id = rowId(row);
279 const before = pending.before.get(id);
280 const current = rowOrder(row, pending.section);
281 if (before === undefined || current.anchor !== before.anchor) return null;
282 const assigned = pending.assignments.get(id);
283 if (assigned !== undefined && current.key === assigned) confirmed.add(id);
284 else if (current.key !== before.key || confirmed.has(id)) return null;
285 }
286 if (pending.commandsComplete && confirmed.size === pending.assignments.size) return null;
287 return confirmed.size === pending.confirmed.size ? pending : { ...pending, confirmed };
289​
290/** Apply the full section's pending order after search/environment filtering. */
291export function applyPendingThreadOrder<T extends OrderRow>(
292 rows: readonly T[],
293 section: PendingThreadOrder["section"],
294 pending: PendingThreadOrder | null | undefined,
295): T[] {
296 if (pending == null || pending.section !== section) return [...rows];
297 const rank = new Map(pending.orderedIds.map((id, index) => [id, index]));
298 return [...rows].sort(
299 (left, right) => (rank.get(rowId(left)) ?? Infinity) - (rank.get(rowId(right)) ?? Infinity),
300 );
302​
303/** Match desktop re-entry: a pin wakes the thread on the server; Active clears
304 * each underlying parked state before assigning its destination order key. */
305export function threadDropLifecycle(
306 thread: EnvironmentThreadShell,
307 section: "pinned" | "active",
308 now: string,
309) {
310 if (section === "pinned") return { pin: true, unpin: false, unsettle: false, unsnooze: false };
311 return {
312 pin: false,
313 unpin: thread.pinnedAt != null,
314 unsettle: thread.settledOverride === "settled",
315 unsnooze: effectiveSnoozed(thread, { now }),
316 };
318​
319export type ThreadDragSection = "pinned" | "active" | "snoozed" | "settled";
320​
321/** The action shown during hover describes the lifecycle change made on drop. */
322export function threadDragAction(source: ThreadDragSection, destination: ThreadDragSection) {
323 if (destination === "snoozed") return null;
324 if (destination === "settled") return source === "settled" ? null : "Settle";
325 if (source === destination) return "Reorder";
326 if (destination === "pinned") return "Pin";
327 if (source === "pinned") return "Unpin";
328 if (source === "settled") return "Unsettle";
329 return "Unsnooze";