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

threadOrder.ts

306 lines11.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​
19export function threadOrderAfterMove(
20 orderedIds: readonly string[],
21 movedId: string,
22 destination: ThreadMoveDestination,
23): string[] | null {
24 if (typeof destination === "object" && destination.section === "settled") return null;
25 const from = orderedIds.indexOf(movedId);
26 if (from < 0 && (typeof destination === "string" || destination.section === undefined))
27 return null;
28 const result = orderedIds.filter((id) => id !== movedId);
29 let to: number;
30 if (typeof destination === "string") {
31 to = from + (destination === "up" ? -1 : 1);
32 if (to < 0 || to >= orderedIds.length) return null;
33 } else {
34 if (destination.targetId === null) {
35 if (destination.section === undefined) return null;
36 to = destination.placement === "before" ? 0 : result.length;
37 } else {
38 const target = result.indexOf(destination.targetId);
39 if (target < 0) return null;
40 to = target + (destination.placement === "after" ? 1 : 0);
41 }
42 }
43 if (to === from) return null;
44 result.splice(to, 0, movedId);
45 return result;
47​
48export type OrderRow = Pick<
49 EnvironmentThreadShell,
50 | "id"
51 | "environmentId"
52 | "pinOrderKey"
53 | "activeOrderKey"
54 | "createdAt"
55 | "unsettledAt"
56 | "pinnedAt"
57>;
58​
59export interface PendingThreadOrder {
60 readonly section: "pinned" | "active";
61 readonly orderedIds: readonly string[];
62 readonly before: ReadonlyMap<string, { readonly key: string | null; readonly anchor: string }>;
63 readonly assignments: ReadonlyMap<string, string>;
64 readonly confirmed: ReadonlySet<string>;
65 readonly commandsComplete: boolean;
67​
68function rowId(row: OrderRow): string {
69 return `${row.environmentId}:${row.id}`;
71​
72function rowOrder(row: OrderRow, section: PendingThreadOrder["section"]) {
73 return {
74 key: (section === "pinned" ? row.pinOrderKey : row.activeOrderKey) ?? null,
75 anchor: section === "pinned" ? (row.pinnedAt ?? "") : (row.unsettledAt ?? row.createdAt),
76 };
78​
79export function createThreadMovePlanner(input: {
80 readonly ordered: readonly OrderRow[];
81 readonly allThreads?: readonly OrderRow[];
82 readonly section: PendingThreadOrder["section"];
83 readonly reorderableEnvironmentIds: ReadonlySet<EnvironmentId>;
84}) {
85 const orderedIds = input.ordered.map(rowId);
86 const keysById = new Map(
87 (input.allThreads ?? input.ordered).map((row) => [
88 rowId(row),
89 rowOrder(row, input.section).key,
90 ]),
91 );
92 const writableIds = new Set(
93 (input.allThreads ?? input.ordered)
94 .filter((row) => input.reorderableEnvironmentIds.has(row.environmentId))
95 .map(rowId),
96 );
97 return (movedId: string, direction: ThreadMoveDestination) => {
98 if (!writableIds.has(movedId)) return null;
99 const nextIds = threadOrderAfterMove(orderedIds, movedId, direction);
100 if (nextIds === null) return null;
101 const assignments = planPinnedReorder({ orderedIds: nextIds, keysById, movedId });
102 return assignments === null ||
103 assignments.length === 0 ||
104 assignments.some((assignment) => !writableIds.has(assignment.id))
105 ? null
106 : assignments;
107 };
109​
110export interface ThreadMoveAvailability {
111 readonly canMoveUp: boolean;
112 readonly canMoveDown: boolean;
114​
115/**
116 * Batch form of "call `createThreadMovePlanner` once per card": one pass over
117 * the section answers up/down availability for every ordered row, so list
118 * construction stays linear instead of one full planner probe (array copies,
119 * hidden-key rescans) per row on the minute-tick rebuild path.
120 */
121export function computeThreadMoveAvailability(input: {
122 readonly ordered: readonly OrderRow[];
123 readonly allThreads?: readonly OrderRow[];
124 readonly section: PendingThreadOrder["section"];
125 readonly reorderableEnvironmentIds: ReadonlySet<EnvironmentId>;
126 readonly pendingOrder?: PendingThreadOrder | null;
127}): Map<string, ThreadMoveAvailability> {
128 const result = new Map<string, ThreadMoveAvailability>();
129 if (input.pendingOrder != null) return result;
130 const rows = input.ordered;
131 if (rows.length < 2) {
132 for (const row of rows) result.set(rowId(row), { canMoveUp: false, canMoveDown: false });
133 return result;
134 }
135 const orderedIds: string[] = [];
136 const indexById = new Map<string, number>();
137 for (const row of rows) {
138 const id = rowId(row);
139 indexById.set(id, orderedIds.length);
140 orderedIds.push(id);
141 }
142 const keysById = new Map<string, string | null>();
143 const writableIds = new Set<string>();
144 for (const row of input.allThreads ?? input.ordered) {
145 const id = rowId(row);
146 keysById.set(id, rowOrder(row, input.section).key);
147 if (input.reorderableEnvironmentIds.has(row.environmentId)) writableIds.add(id);
148 }
149 const reservedKeys = new Set<string>();
150 keysById.forEach((key, id) => {
151 if (key != null && !indexById.has(id)) reservedKeys.add(key);
152 });
153 // A swap permutes two rows without changing the multiset, so the assignment
154 // set differs from the unswapped baseline at at most those two positions, and
155 // mismatch/writability tallies computed once per section answer each row with
156 // a constant-size delta.
157 const midpoints = new Map<string, string | null>();
158 const fastPathKey = (beforeKey: string | null, afterKey: string | null): string | null => {
159 const memoKey = `${beforeKey ?? ""}\u0000${afterKey ?? ""}`;
160 const cached = midpoints.get(memoKey);
161 if (cached !== undefined) return cached;
162 let key = pinOrderKeyBetween(beforeKey, afterKey);
163 while (key !== null && reservedKeys.has(key)) key = pinOrderKeyBetween(key, afterKey);
164 midpoints.set(memoKey, key);
165 return key;
166 };
167 const spreadKeys = generateSpreadPinOrderKeys(orderedIds.length + reservedKeys.size)
168 .filter((key) => !reservedKeys.has(key))
169 .slice(0, orderedIds.length);
170 const currentKeys = orderedIds.map((id) => keysById.get(id) ?? null);
171 const writableRow = orderedIds.map((id) => writableIds.has(id));
172 let baselineWrites = 0;
173 let baselineUnwritableWrites = 0;
174 for (let position = 0; position < orderedIds.length; position += 1) {
175 if (currentKeys[position] === spreadKeys[position]) continue;
176 baselineWrites += 1;
177 if (!writableRow[position]) baselineUnwritableWrites += 1;
178 }
179 const rewriteViable = (index: number): boolean => {
180 let writes = baselineWrites;
181 let unwritableWrites = baselineUnwritableWrites;
182 for (const position of [index, index + 1]) {
183 const other = position === index ? index + 1 : index;
184 if (currentKeys[position] !== spreadKeys[position]) {
185 writes -= 1;
186 if (!writableRow[position]) unwritableWrites -= 1;
187 }
188 if (currentKeys[other] !== spreadKeys[position]) {
189 writes += 1;
190 if (!writableRow[other]) unwritableWrites += 1;
191 }
192 }
193 return writes > 0 && unwritableWrites === 0;
194 };
195 for (const row of rows) {
196 const movedId = rowId(row);
197 const denied = { canMoveUp: false, canMoveDown: false };
198 if (!writableIds.has(movedId)) {
199 result.set(movedId, denied);
200 continue;
201 }
202 const index = indexById.get(movedId);
203 if (index === undefined) {
204 result.set(movedId, denied);
205 continue;
206 }
207 const adjacentAvailable = (towardUp: boolean): boolean => {
208 const shifted = index + (towardUp ? -1 : 1);
209 if (shifted < 0 || shifted >= orderedIds.length) return false;
210 const beforeIndex = towardUp ? index - 2 : index + 1;
211 const afterIndex = towardUp ? index - 1 : index + 2;
212 const beforeId = beforeIndex < 0 ? null : (orderedIds[beforeIndex] ?? null);
213 const afterId = afterIndex >= orderedIds.length ? null : (orderedIds[afterIndex] ?? null);
214 const beforeKey = beforeId === null ? null : (keysById.get(beforeId) ?? null);
215 const afterKey = afterId === null ? null : (keysById.get(afterId) ?? null);
216 if ((beforeId === null || beforeKey != null) && (afterId === null || afterKey != null)) {
217 const key = fastPathKey(beforeKey, afterKey);
218 if (key !== null) return true;
219 }
220 return rewriteViable(Math.min(index, shifted));
221 };
222 result.set(movedId, {
223 canMoveUp: adjacentAvailable(true),
224 canMoveDown: adjacentAvailable(false),
225 });
226 }
227 return result;
229​
230export function createPendingThreadOrder(input: {
231 readonly section: PendingThreadOrder["section"];
232 readonly ordered: readonly OrderRow[];
233 readonly movedId: string;
234 readonly direction: ThreadMoveDestination;
235 readonly assignments: readonly { readonly id: string; readonly orderKey: string }[];
236}): PendingThreadOrder {
237 const orderedIds = threadOrderAfterMove(input.ordered.map(rowId), input.movedId, input.direction);
238 if (orderedIds === null) throw new Error("Cannot begin an invalid thread move");
239 return {
240 section: input.section,
241 orderedIds,
242 before: new Map(input.ordered.map((row) => [rowId(row), rowOrder(row, input.section)])),
243 assignments: new Map(input.assignments.map(({ id, orderKey }) => [id, orderKey])),
244 confirmed: new Set(),
245 commandsComplete: false,
246 };
248​
249/** Receipts and shell updates arrive independently. Only our own key writes
250 * may pass through the hold; membership and other arrangement changes win. */
251export function reconcilePendingThreadOrder(
252 pending: PendingThreadOrder,
253 ordered: readonly OrderRow[],
254): PendingThreadOrder | null {
255 if (ordered.length !== pending.before.size) return null;
256 const confirmed = new Set(pending.confirmed);
257 for (const row of ordered) {
258 const id = rowId(row);
259 const before = pending.before.get(id);
260 const current = rowOrder(row, pending.section);
261 if (before === undefined || current.anchor !== before.anchor) return null;
262 const assigned = pending.assignments.get(id);
263 if (assigned !== undefined && current.key === assigned) confirmed.add(id);
264 else if (current.key !== before.key || confirmed.has(id)) return null;
265 }
266 if (pending.commandsComplete && confirmed.size === pending.assignments.size) return null;
267 return confirmed.size === pending.confirmed.size ? pending : { ...pending, confirmed };
269​
270export function applyPendingThreadOrder<T extends OrderRow>(
271 rows: readonly T[],
272 section: PendingThreadOrder["section"],
273 pending: PendingThreadOrder | null | undefined,
274): T[] {
275 if (pending == null || pending.section !== section) return [...rows];
276 const rank = new Map(pending.orderedIds.map((id, index) => [id, index]));
277 return [...rows].sort(
278 (left, right) => (rank.get(rowId(left)) ?? Infinity) - (rank.get(rowId(right)) ?? Infinity),
279 );
281​
282export function threadDropLifecycle(
283 thread: EnvironmentThreadShell,
284 section: "pinned" | "active",
285 now: string,
286) {
287 if (section === "pinned") return { pin: true, unpin: false, unsettle: false, unsnooze: false };
288 return {
289 pin: false,
290 unpin: thread.pinnedAt != null,
291 unsettle: thread.settledOverride === "settled",
292 unsnooze: effectiveSnoozed(thread, { now }),
293 };
295​
296export type ThreadDragSection = "pinned" | "active" | "snoozed" | "settled";
297​
298export function threadDragAction(source: ThreadDragSection, destination: ThreadDragSection) {
299 if (destination === "snoozed") return null;
300 if (destination === "settled") return source === "settled" ? null : "Settle";
301 if (source === destination) return "Reorder";
302 if (destination === "pinned") return "Pin";
303 if (source === "pinned") return "Unpin";
304 if (source === "settled") return "Unsettle";
305 return "Unsnooze";