File size: 1,278 Bytes
e6addfc
 
d8e839e
e6addfc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8e839e
e6addfc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import type { Conversation } from "$lib/types/Conversation";
import type { Message } from "$lib/types/Message";
import { v4 } from "uuid";

export function addSibling(
	conv: Pick<Conversation, "messages" | "rootMessageId">,
	message: Omit<Message, "id">,
	siblingId: Message["id"]
): Message["id"] {
	if (conv.messages.length === 0) {
		throw new Error("Cannot add a sibling to an empty conversation");
	}
	if (!conv.rootMessageId) {
		throw new Error("Cannot add a sibling to a legacy conversation");
	}

	const sibling = conv.messages.find((m) => m.id === siblingId);

	if (!sibling) {
		throw new Error("The sibling message doesn't exist");
	}

	if (!sibling.ancestors || sibling.ancestors?.length === 0) {
		throw new Error("The sibling message is the root message, therefore we can't add a sibling");
	}

	const messageId = v4();

	conv.messages.push({
		...message,
		id: messageId,
		ancestors: sibling.ancestors,
		children: [],
	});

	const nearestAncestorId = sibling.ancestors[sibling.ancestors.length - 1];
	const nearestAncestor = conv.messages.find((m) => m.id === nearestAncestorId);

	if (nearestAncestor) {
		if (nearestAncestor.children) {
			nearestAncestor.children.push(messageId);
		} else nearestAncestor.children = [messageId];
	}

	return messageId;
}