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

threadSort.ts

280 lines10.9 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​
72export function sortThreads<T extends { readonly id: string } & ThreadSortInput>(
73 threads: readonly T[],
74 sortOrder: SidebarThreadSortOrder,
75): T[] {
76 return Arr.sort(
77 threads,
78 Order.mapInput(
79 Order.Struct({
80 timestamp: Order.flip(Order.Number),
81 id: Order.flip(Order.String),
82 }),
83 (thread: T) => ({
84 timestamp: getThreadSortTimestamp(thread, sortOrder),
85 id: thread.id,
86 }),
87 ),
88 );
90​
91export function getLatestThreadForProject<
92 T extends {
93 readonly id: string;
94 readonly projectId: ProjectId;
95 readonly archivedAt: string | null;
96 } & ThreadSortInput,
97>(threads: readonly T[], projectId: ProjectId, sortOrder: SidebarThreadSortOrder): T | null {
98 return (
99 sortThreads(
100 threads.filter((thread) => thread.projectId === projectId && thread.archivedAt === null),
101 sortOrder,
102 )[0] ?? null
103 );
105​
106// ── Pinned reorder: fractional index keys ──────────────────────────────
107// Pinned threads carry an optional pinOrderKey (a base-26 string). The
108// pinned block sorts keyed threads by plain string comparison, so a drag
109// (web) or Move up/down (mobile) writes ONE key to ONE thread on that
110// thread's own server — neighbors, possibly living on other servers, are
111// never touched, and every client connected to the same servers converges
112// on the same order.
113const PIN_ORDER_DIGITS = "abcdefghijklmnopqrstuvwxyz";
114​
115function isValidPinOrderKey(key: string): boolean {
116 if (key.length === 0) return false;
117 for (const char of key) {
118 if (!PIN_ORDER_DIGITS.includes(char)) return false;
119 }
120 // A trailing minimum digit would leave no room to sort a key immediately
121 // before this one; generators never produce it, so treat it as corrupt.
122 return key.at(-1) !== PIN_ORDER_DIGITS[0];
124​
125/** Midpoint of two digit strings interpreted as fractions in (0, 1).
126 "" stands for the open bound on either side. Requires a < b. */
127function pinOrderMidpoint(a: string, b: string): string {
128 if (b !== "" && a >= b) throw new Error("pinOrderMidpoint: bounds out of order");
129 if (b !== "") {
130 // Recurse past the longest common prefix ("a" pads the shorter side).
131 let n = 0;
132 while ((a.charAt(n) || PIN_ORDER_DIGITS[0]) === b.charAt(n)) n += 1;
133 if (n > 0) return b.slice(0, n) + pinOrderMidpoint(a.slice(n), b.slice(n));
134 }
135 const digitA = a === "" ? 0 : PIN_ORDER_DIGITS.indexOf(a.charAt(0));
136 const digitB = b === "" ? PIN_ORDER_DIGITS.length : PIN_ORDER_DIGITS.indexOf(b.charAt(0));
137 if (digitB - digitA > 1) {
138 return PIN_ORDER_DIGITS.charAt(Math.round((digitA + digitB) / 2));
139 }
140 // Consecutive leading digits: either b has spare digits to shorten into,
141 // or we extend a (never producing a trailing minimum digit — the base
142 // case midpoint("", "") is the middle of the alphabet).
143 if (b.length > 1) return b.charAt(0);
144 return PIN_ORDER_DIGITS.charAt(digitA) + pinOrderMidpoint(a.slice(1), "");
146​
147/** Key that sorts strictly between two neighbors; null bounds mean "top of
148 the pinned block" / "bottom of the keyed run". Returns null instead of
149 throwing when existing keys are corrupt or out of order — callers fall
150 back to rewriting the section. */
151export function pinOrderKeyBetween(before: string | null, after: string | null): string | null {
152 const a = before ?? "";
153 const b = after ?? "";
154 if (a !== "" && !isValidPinOrderKey(a)) return null;
155 if (b !== "" && !isValidPinOrderKey(b)) return null;
156 if (b !== "" && a >= b) return null;
157 return pinOrderMidpoint(a, b);
159​
160/** Evenly spaced keys for rewriting a whole pinned section (used when a
161 drop lands next to keyless threads, so single-key insertion has nothing
162 to anchor on). Two base-26 digits give 675 slots — far beyond any real
163 pinned section — with monotonicity enforced as a belt-and-braces. */
164export function generateSpreadPinOrderKeys(count: number): string[] {
165 const space = PIN_ORDER_DIGITS.length * PIN_ORDER_DIGITS.length;
166 const step = space / (count + 1);
167 const keys: string[] = [];
168 let previous = 0;
169 for (let i = 0; i < count; i += 1) {
170 let value = Math.max(Math.round(step * (i + 1)), previous + 1);
171 // Skip values whose low digit is the minimum (a trailing "a" key).
172 if (value % PIN_ORDER_DIGITS.length === 0) value += 1;
173 value = Math.min(value, space - 1);
174 previous = value;
175 keys.push(
176 PIN_ORDER_DIGITS.charAt(Math.floor(value / PIN_ORDER_DIGITS.length)) +
177 PIN_ORDER_DIGITS.charAt(value % PIN_ORDER_DIGITS.length),
178 );
179 }
180 return keys;
182​
183/**
184 * Assignments needed to realize a new pinned order. When the moved thread
185 * sits between two keyed (or absent) neighbors, this is a single write to
186 * the moved thread. When a neighbor is keyless (threads pinned before
187 * reordering shipped), the whole section gets fresh spread keys — a
188 * one-time materialization; every move after that is single-write.
189 */
190export function planPinnedReorder(input: {
191 /** Thread ids in the desired visual order (after the move). */
192 readonly orderedIds: readonly string[];
193 readonly keysById: ReadonlyMap<string, string | null | undefined>;
194 readonly movedId: string;
195}): ReadonlyArray<{ readonly id: string; readonly orderKey: string }> {
196 const { orderedIds, keysById, movedId } = input;
197 const movedIndex = orderedIds.indexOf(movedId);
198 if (movedIndex === -1) return [];
199 const beforeId = movedIndex > 0 ? orderedIds[movedIndex - 1] : null;
200 const afterId = movedIndex < orderedIds.length - 1 ? orderedIds[movedIndex + 1] : null;
201 const beforeKey = beforeId != null ? (keysById.get(beforeId) ?? null) : null;
202 const afterKey = afterId != null ? (keysById.get(afterId) ?? null) : null;
203 const beforeUsable = beforeId === null || beforeKey != null;
204 const afterUsable = afterId === null || afterKey != null;
205 if (beforeUsable && afterUsable) {
206 const key = pinOrderKeyBetween(beforeKey, afterKey);
207 if (key !== null) return [{ id: movedId, orderKey: key }];
208 }
209 // Keyless neighbor (or corrupt keys): rewrite the section in the new order.
210 const keys = generateSpreadPinOrderKeys(orderedIds.length);
211 return orderedIds.flatMap((id, index) => {
212 const key = keys[index]!;
213 return keysById.get(id) === key ? [] : [{ id, orderKey: key }];
214 });
216​
217/**
218 * Pinned block order: user-arranged keys first (string comparison, id
219 * tiebreak), then keyless threads newest-created first — so threads on
220 * servers that predate reordering keep the static creation order at the
221 * bottom of the block instead of breaking the section.
222 */
223export function sortPinnedThreadsByOrderKey<
224 T extends {
225 readonly id: string;
226 readonly createdAt: string;
227 readonly pinOrderKey?: string | null | undefined;
228 /** Thread ids are only unique within an environment, and the pinned
229 block merges environments — the tiebreak needs both parts or two
230 clients could render equal-key threads in stream-arrival order. */
231 readonly environmentId?: string | undefined;
232 },
233>(threads: readonly T[]): T[] {
234 const keyed: T[] = [];
235 const keyless: T[] = [];
236 for (const thread of threads) {
237 (thread.pinOrderKey != null ? keyed : keyless).push(thread);
238 }
239 const identityTiebreak = (left: T, right: T) =>
240 left.id.localeCompare(right.id) ||
241 (left.environmentId ?? "").localeCompare(right.environmentId ?? "");
242 keyed.sort((left, right) => {
243 const leftKey = left.pinOrderKey!;
244 const rightKey = right.pinOrderKey!;
245 return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : identityTiebreak(left, right);
246 });
247 keyless.sort((left, right) => {
248 const leftMs = Date.parse(left.createdAt);
249 const rightMs = Date.parse(right.createdAt);
250 return (
251 (Number.isNaN(rightMs) ? 0 : rightMs) - (Number.isNaN(leftMs) ? 0 : leftMs) ||
252 identityTiebreak(left, right)
253 );
254 });
255 return [...keyed, ...keyless];
257​
258/**
259 * planPinnedReorder specialized for mobile's Move up / Move down menu
260 * actions: swap the moved thread with its displayed neighbor. Null when the
261 * move falls off either end of the list. Same single-write-per-move
262 * semantics as a web drag.
263 */
264export function planPinnedMove(input: {
265 /** Reorder-capable pinned thread ids in displayed order. */
266 readonly orderedIds: readonly string[];
267 readonly keysById: ReadonlyMap<string, string | null | undefined>;
268 readonly movedId: string;
269 readonly direction: "up" | "down";
270}): ReadonlyArray<{ readonly id: string; readonly orderKey: string }> | null {
271 const { orderedIds, keysById, movedId, direction } = input;
272 const from = orderedIds.indexOf(movedId);
273 if (from === -1) return null;
274 const to = direction === "up" ? from - 1 : from + 1;
275 if (to < 0 || to >= orderedIds.length) return null;
276 const newOrder = [...orderedIds];
277 newOrder.splice(from, 1);
278 newOrder.splice(to, 0, movedId);
279 return planPinnedReorder({ orderedIds: newOrder, keysById, movedId });