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

threadSort.ts

298 lines11.7 KB

1import type { ProjectId } from "@t3tools/contracts";
2import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
3import * as Arr from "effect/Array";
4import * as Order from "effect/Order";
5​
6export interface ThreadSortInput {
7 readonly createdAt: string;
8 readonly updatedAt: string;
9 readonly latestUserMessageAt?: string | null;
10 readonly messages?: ReadonlyArray<{
11 readonly createdAt: string;
12 readonly role: string;
13 }>;
15​
16export function toSortableTimestamp(iso: string | undefined): number | null {
17 if (!iso) return null;
18 const ms = Date.parse(iso);
19 return Number.isFinite(ms) ? ms : null;
21​
22function getFirstSortableTimestamp(...values: Array<string | null | undefined>): number | null {
23 for (const value of values) {
24 const timestamp = toSortableTimestamp(value ?? undefined);
25 if (timestamp !== null) {
26 return timestamp;
27 }
28 }
29​
30 return null;
32​
33function getLatestUserMessageTimestamp(thread: ThreadSortInput): number {
34 if (thread.latestUserMessageAt) {
35 const latestUserMessageTimestamp = toSortableTimestamp(thread.latestUserMessageAt);
36 if (latestUserMessageTimestamp !== null) {
37 return latestUserMessageTimestamp;
38 }
39 }
40​
41 let latestUserMessageTimestamp: number | null = null;
42​
43 for (const message of thread.messages ?? []) {
44 if (message.role !== "user") continue;
45 const messageTimestamp = toSortableTimestamp(message.createdAt);
46 if (messageTimestamp === null) continue;
47 latestUserMessageTimestamp =
48 latestUserMessageTimestamp === null
49 ? messageTimestamp
50 : Math.max(latestUserMessageTimestamp, messageTimestamp);
51 }
52​
53 if (latestUserMessageTimestamp !== null) {
54 return latestUserMessageTimestamp;
55 }
56​
57 return getFirstSortableTimestamp(thread.updatedAt, thread.createdAt) ?? Number.NEGATIVE_INFINITY;
59​
60export function getThreadSortTimestamp(
61 thread: ThreadSortInput,
62 sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
63): number {
64 if (sortOrder === "created_at") {
65 return (
66 getFirstSortableTimestamp(thread.createdAt, thread.updatedAt) ?? Number.NEGATIVE_INFINITY
67 );
68 }
69 return getLatestUserMessageTimestamp(thread);
71​
72/**
73 * Sort anchor for the active thread list: creation time, re-anchored to
74 * unsettledAt when the thread last re-entered the active list (an explicit
75 * un-settle, or a settled thread waking on activity). The list stays static
76 * between lifecycle transitions, but an un-settled thread surfaces at the
77 * top instead of sinking back to its creation-order slot. Shared by web and
78 * mobile so both render the same order. Malformed timestamps sink to 0.
79 */
80export function activeThreadAnchorTimestampMs(thread: {
81 readonly createdAt: string;
82 readonly unsettledAt?: string | null | undefined;
83}): number {
84 return Math.max(
85 toSortableTimestamp(thread.createdAt) ?? 0,
86 toSortableTimestamp(thread.unsettledAt ?? undefined) ?? 0,
87 );
89​
90export function sortThreads<T extends { readonly id: string } & ThreadSortInput>(
91 threads: readonly T[],
92 sortOrder: SidebarThreadSortOrder,
93): T[] {
94 return Arr.sort(
95 threads,
96 Order.mapInput(
97 Order.Struct({
98 timestamp: Order.flip(Order.Number),
99 id: Order.flip(Order.String),
100 }),
101 (thread: T) => ({
102 timestamp: getThreadSortTimestamp(thread, sortOrder),
103 id: thread.id,
104 }),
105 ),
106 );
108​
109export function getLatestThreadForProject<
110 T extends {
111 readonly id: string;
112 readonly projectId: ProjectId;
113 readonly archivedAt: string | null;
114 } & ThreadSortInput,
115>(threads: readonly T[], projectId: ProjectId, sortOrder: SidebarThreadSortOrder): T | null {
116 return (
117 sortThreads(
118 threads.filter((thread) => thread.projectId === projectId && thread.archivedAt === null),
119 sortOrder,
120 )[0] ?? null
121 );
123​
124// ── Pinned reorder: fractional index keys ──────────────────────────────
125// Pinned threads carry an optional pinOrderKey (a base-26 string). The
126// pinned block sorts keyed threads by plain string comparison, so a drag
127// (web) or Move up/down (mobile) writes ONE key to ONE thread on that
128// thread's own server — neighbors, possibly living on other servers, are
129// never touched, and every client connected to the same servers converges
130// on the same order.
131const PIN_ORDER_DIGITS = "abcdefghijklmnopqrstuvwxyz";
132​
133function isValidPinOrderKey(key: string): boolean {
134 if (key.length === 0) return false;
135 for (const char of key) {
136 if (!PIN_ORDER_DIGITS.includes(char)) return false;
137 }
138 // A trailing minimum digit would leave no room to sort a key immediately
139 // before this one; generators never produce it, so treat it as corrupt.
140 return key.at(-1) !== PIN_ORDER_DIGITS[0];
142​
143/** Midpoint of two digit strings interpreted as fractions in (0, 1).
144 "" stands for the open bound on either side. Requires a < b. */
145function pinOrderMidpoint(a: string, b: string): string {
146 if (b !== "" && a >= b) throw new Error("pinOrderMidpoint: bounds out of order");
147 if (b !== "") {
148 // Recurse past the longest common prefix ("a" pads the shorter side).
149 let n = 0;
150 while ((a.charAt(n) || PIN_ORDER_DIGITS[0]) === b.charAt(n)) n += 1;
151 if (n > 0) return b.slice(0, n) + pinOrderMidpoint(a.slice(n), b.slice(n));
152 }
153 const digitA = a === "" ? 0 : PIN_ORDER_DIGITS.indexOf(a.charAt(0));
154 const digitB = b === "" ? PIN_ORDER_DIGITS.length : PIN_ORDER_DIGITS.indexOf(b.charAt(0));
155 if (digitB - digitA > 1) {
156 return PIN_ORDER_DIGITS.charAt(Math.round((digitA + digitB) / 2));
157 }
158 // Consecutive leading digits: either b has spare digits to shorten into,
159 // or we extend a (never producing a trailing minimum digit — the base
160 // case midpoint("", "") is the middle of the alphabet).
161 if (b.length > 1) return b.charAt(0);
162 return PIN_ORDER_DIGITS.charAt(digitA) + pinOrderMidpoint(a.slice(1), "");
164​
165/** Key that sorts strictly between two neighbors; null bounds mean "top of
166 the pinned block" / "bottom of the keyed run". Returns null instead of
167 throwing when existing keys are corrupt or out of order — callers fall
168 back to rewriting the section. */
169export function pinOrderKeyBetween(before: string | null, after: string | null): string | null {
170 const a = before ?? "";
171 const b = after ?? "";
172 if (a !== "" && !isValidPinOrderKey(a)) return null;
173 if (b !== "" && !isValidPinOrderKey(b)) return null;
174 if (b !== "" && a >= b) return null;
175 return pinOrderMidpoint(a, b);
177​
178/** Evenly spaced keys for rewriting a whole pinned section (used when a
179 drop lands next to keyless threads, so single-key insertion has nothing
180 to anchor on). Two base-26 digits give 675 slots — far beyond any real
181 pinned section — with monotonicity enforced as a belt-and-braces. */
182export function generateSpreadPinOrderKeys(count: number): string[] {
183 const space = PIN_ORDER_DIGITS.length * PIN_ORDER_DIGITS.length;
184 const step = space / (count + 1);
185 const keys: string[] = [];
186 let previous = 0;
187 for (let i = 0; i < count; i += 1) {
188 let value = Math.max(Math.round(step * (i + 1)), previous + 1);
189 // Skip values whose low digit is the minimum (a trailing "a" key).
190 if (value % PIN_ORDER_DIGITS.length === 0) value += 1;
191 value = Math.min(value, space - 1);
192 previous = value;
193 keys.push(
194 PIN_ORDER_DIGITS.charAt(Math.floor(value / PIN_ORDER_DIGITS.length)) +
195 PIN_ORDER_DIGITS.charAt(value % PIN_ORDER_DIGITS.length),
196 );
197 }
198 return keys;
200​
201/**
202 * Assignments needed to realize a new pinned order. When the moved thread
203 * sits between two keyed (or absent) neighbors, this is a single write to
204 * the moved thread. When a neighbor is keyless (threads pinned before
205 * reordering shipped), the whole section gets fresh spread keys — a
206 * one-time materialization; every move after that is single-write.
207 */
208export function planPinnedReorder(input: {
209 /** Thread ids in the desired visual order (after the move). */
210 readonly orderedIds: readonly string[];
211 readonly keysById: ReadonlyMap<string, string | null | undefined>;
212 readonly movedId: string;
213}): ReadonlyArray<{ readonly id: string; readonly orderKey: string }> {
214 const { orderedIds, keysById, movedId } = input;
215 const movedIndex = orderedIds.indexOf(movedId);
216 if (movedIndex === -1) return [];
217 const beforeId = movedIndex > 0 ? orderedIds[movedIndex - 1] : null;
218 const afterId = movedIndex < orderedIds.length - 1 ? orderedIds[movedIndex + 1] : null;
219 const beforeKey = beforeId != null ? (keysById.get(beforeId) ?? null) : null;
220 const afterKey = afterId != null ? (keysById.get(afterId) ?? null) : null;
221 const beforeUsable = beforeId === null || beforeKey != null;
222 const afterUsable = afterId === null || afterKey != null;
223 if (beforeUsable && afterUsable) {
224 const key = pinOrderKeyBetween(beforeKey, afterKey);
225 if (key !== null) return [{ id: movedId, orderKey: key }];
226 }
227 // Keyless neighbor (or corrupt keys): rewrite the section in the new order.
228 const keys = generateSpreadPinOrderKeys(orderedIds.length);
229 return orderedIds.flatMap((id, index) => {
230 const key = keys[index]!;
231 return keysById.get(id) === key ? [] : [{ id, orderKey: key }];
232 });
234​
235/**
236 * Pinned block order: user-arranged keys first (string comparison, id
237 * tiebreak), then keyless threads newest-created first — so threads on
238 * servers that predate reordering keep the static creation order at the
239 * bottom of the block instead of breaking the section.
240 */
241export function sortPinnedThreadsByOrderKey<
242 T extends {
243 readonly id: string;
244 readonly createdAt: string;
245 readonly pinOrderKey?: string | null | undefined;
246 /** Thread ids are only unique within an environment, and the pinned
247 block merges environments — the tiebreak needs both parts or two
248 clients could render equal-key threads in stream-arrival order. */
249 readonly environmentId?: string | undefined;
250 },
251>(threads: readonly T[]): T[] {
252 const keyed: T[] = [];
253 const keyless: T[] = [];
254 for (const thread of threads) {
255 (thread.pinOrderKey != null ? keyed : keyless).push(thread);
256 }
257 const identityTiebreak = (left: T, right: T) =>
258 left.id.localeCompare(right.id) ||
259 (left.environmentId ?? "").localeCompare(right.environmentId ?? "");
260 keyed.sort((left, right) => {
261 const leftKey = left.pinOrderKey!;
262 const rightKey = right.pinOrderKey!;
263 return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : identityTiebreak(left, right);
264 });
265 keyless.sort((left, right) => {
266 const leftMs = Date.parse(left.createdAt);
267 const rightMs = Date.parse(right.createdAt);
268 return (
269 (Number.isNaN(rightMs) ? 0 : rightMs) - (Number.isNaN(leftMs) ? 0 : leftMs) ||
270 identityTiebreak(left, right)
271 );
272 });
273 return [...keyed, ...keyless];
275​
276/**
277 * planPinnedReorder specialized for mobile's Move up / Move down menu
278 * actions: swap the moved thread with its displayed neighbor. Null when the
279 * move falls off either end of the list. Same single-write-per-move
280 * semantics as a web drag.
281 */
282export function planPinnedMove(input: {
283 /** Reorder-capable pinned thread ids in displayed order. */
284 readonly orderedIds: readonly string[];
285 readonly keysById: ReadonlyMap<string, string | null | undefined>;
286 readonly movedId: string;
287 readonly direction: "up" | "down";
288}): ReadonlyArray<{ readonly id: string; readonly orderKey: string }> | null {
289 const { orderedIds, keysById, movedId, direction } = input;
290 const from = orderedIds.indexOf(movedId);
291 if (from === -1) return null;
292 const to = direction === "up" ? from - 1 : from + 1;
293 if (to < 0 || to >= orderedIds.length) return null;
294 const newOrder = [...orderedIds];
295 newOrder.splice(from, 1);
296 newOrder.splice(to, 0, movedId);
297 return planPinnedReorder({ orderedIds: newOrder, keysById, movedId });