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

threadSort.ts

73 lines2.6 KB

1import type { ProjectId } from "@t3tools/contracts";
2import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
3import type { Thread } from "../types";
4​
5export type ThreadSortInput = Pick<Thread, "createdAt" | "updatedAt"> & {
6 latestUserMessageAt?: string | null;
7 messages?: Pick<Thread["messages"][number], "createdAt" | "role">[];
8};
9​
10export function toSortableTimestamp(iso: string | undefined): number | null {
11 if (!iso) return null;
12 const ms = Date.parse(iso);
13 return Number.isFinite(ms) ? ms : null;
15​
16function getLatestUserMessageTimestamp(thread: ThreadSortInput): number {
17 if (thread.latestUserMessageAt) {
18 return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY;
19 }
20​
21 let latestUserMessageTimestamp: number | null = null;
22​
23 for (const message of thread.messages ?? []) {
24 if (message.role !== "user") continue;
25 const messageTimestamp = toSortableTimestamp(message.createdAt);
26 if (messageTimestamp === null) continue;
27 latestUserMessageTimestamp =
28 latestUserMessageTimestamp === null
29 ? messageTimestamp
30 : Math.max(latestUserMessageTimestamp, messageTimestamp);
31 }
32​
33 if (latestUserMessageTimestamp !== null) {
34 return latestUserMessageTimestamp;
35 }
36​
37 return toSortableTimestamp(thread.updatedAt ?? thread.createdAt) ?? Number.NEGATIVE_INFINITY;
39​
40export function getThreadSortTimestamp(
41 thread: ThreadSortInput,
42 sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
43): number {
44 if (sortOrder === "created_at") {
45 return toSortableTimestamp(thread.createdAt) ?? Number.NEGATIVE_INFINITY;
46 }
47 return getLatestUserMessageTimestamp(thread);
49​
50export function sortThreads<T extends Pick<Thread, "id"> & ThreadSortInput>(
51 threads: readonly T[],
52 sortOrder: SidebarThreadSortOrder,
53): T[] {
54 return threads.toSorted((left, right) => {
55 const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
56 const leftTimestamp = getThreadSortTimestamp(left, sortOrder);
57 const byTimestamp =
58 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
59 if (byTimestamp !== 0) return byTimestamp;
60 return right.id.localeCompare(left.id);
61 });
63​
64export function getLatestThreadForProject<
65 T extends Pick<Thread, "id" | "projectId" | "archivedAt"> & ThreadSortInput,
66>(threads: readonly T[], projectId: ProjectId, sortOrder: SidebarThreadSortOrder): T | null {
67 return (
68 sortThreads(
69 threads.filter((thread) => thread.projectId === projectId && thread.archivedAt === null),
70 sortOrder,
71 )[0] ?? null
72 );