feat: refactor thought threads handling to improve structure and efficiency

This commit is contained in:
2025-09-07 15:09:45 +02:00
parent 40695b7ad3
commit 5ce6d9f2da
7 changed files with 89 additions and 90 deletions

View File

@@ -1,35 +1,39 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
import { Thought } from "./api";
import { Thought, ThoughtThread as ThoughtThreadType } from "./api";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function buildThoughtThreads(allThoughts: Thought[]) {
const repliesByParentId = new Map<string, Thought[]>();
const topLevelThoughts: Thought[] = [];
export function buildThoughtThreads(thoughts: Thought[]): ThoughtThreadType[] {
const thoughtMap = new Map<string, Thought>();
thoughts.forEach((t) => thoughtMap.set(t.id, t));
// 1. Group all thoughts into top-level posts or replies
for (const thought of allThoughts) {
const threads: ThoughtThreadType[] = [];
const repliesMap: Record<string, Thought[]> = {};
thoughts.forEach((thought) => {
if (thought.replyToId) {
// It's a reply, group it with its parent
const replies = repliesByParentId.get(thought.replyToId) || [];
replies.push(thought);
repliesByParentId.set(thought.replyToId, replies);
} else {
// It's a top-level thought
topLevelThoughts.push(thought);
if (!repliesMap[thought.replyToId]) {
repliesMap[thought.replyToId] = [];
}
repliesMap[thought.replyToId].push(thought);
}
});
function buildThread(thought: Thought): ThoughtThreadType {
return {
...thought,
replies: (repliesMap[thought.id] || []).map(buildThread),
};
}
// 2. Sort top-level thoughts by date, newest first
topLevelThoughts.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
thoughts.forEach((thought) => {
if (!thought.replyToId) {
threads.push(buildThread(thought));
}
});
// 3. Sort replies within each thread by date, oldest first for conversational flow
for (const replies of repliesByParentId.values()) {
replies.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
}
return { topLevelThoughts, repliesByParentId };
return threads;
}