File size: 8,958 Bytes
d3ab1f5
822d5b9
2961a5b
 
 
 
 
 
 
 
 
 
 
8b8322d
d3ab1f5
8b8322d
f60772d
2961a5b
d3ab1f5
 
 
f60772d
59c9d94
f7c8859
211077d
 
f418b8e
e8700b8
42f847d
d3ab1f5
bb21933
d3ab1f5
2961a5b
 
bb42e25
2961a5b
c289a03
d3ab1f5
5dfba10
 
2961a5b
cedb91f
f7c8859
bb42e25
6e3dd98
822d5b9
5ba3d91
2961a5b
 
ad4aac8
f418b8e
 
f7c8859
42f847d
f7c8859
d3ab1f5
e509579
f9489c3
 
 
f7c8859
e509579
 
 
f9489c3
 
 
2961a5b
d3ab1f5
5dfba10
211077d
 
 
 
17c8ce5
2961a5b
 
59c9d94
3f2442b
 
 
 
 
5dfba10
3f2442b
 
 
d3ab1f5
2961a5b
 
 
 
 
 
 
 
 
 
 
6af683b
2961a5b
bb21933
cedb91f
2961a5b
 
 
 
 
 
 
 
 
 
 
 
59c9d94
 
 
 
 
 
 
 
 
 
 
 
 
 
ad4aac8
 
 
59c9d94
2961a5b
 
 
 
 
 
 
bb21933
5ba3d91
 
 
 
bb42e25
5ba3d91
bb42e25
5ba3d91
 
 
 
98c5a87
 
 
 
822d5b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb21933
 
 
 
 
 
d3ab1f5
2961a5b
bb21933
0f2416e
bb21933
1302517
822d5b9
 
 
 
 
 
 
 
2961a5b
 
e509579
5fc0417
e509579
2961a5b
 
 
afa49b3
2961a5b
822d5b9
2961a5b
 
 
 
 
 
 
 
 
5ba3d91
2961a5b
 
 
 
 
 
 
 
 
 
211077d
f7c8859
8ddd681
f7c8859
 
 
 
 
 
 
bb42e25
 
 
 
 
f7c8859
 
 
 
 
 
 
 
2961a5b
f7c8859
2961a5b
f7c8859
93a306e
f7c8859
 
 
 
 
 
 
 
 
 
 
 
2961a5b
 
 
f418b8e
 
6e3dd98
98c5a87
 
 
 
 
 
 
 
f418b8e
d3ab1f5
bb21933
 
 
 
 
 
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
<script lang="ts">
	import { PenLine, Send, X } from '@lucide/svelte';
	import {
		Handle,
		useEdges,
		useNodes,
		useNodesData,
		Position,
		type NodeProps,
		type Edge,
		type Node,
		useSvelteFlow
	} from '@xyflow/svelte';
	import { onMount } from 'svelte';

	import ErrorMessage from '$lib/components/error/Error.svelte';
	import type { ChatMessage } from '$lib/helpers/types';
	import { Button } from '$lib/components/ui/button';
	import ComboBoxModels from '$lib/components/model/ComboBoxModels.svelte';
	import Spinner from '$lib/components/loading/Spinner.svelte';
	import Message from './Message.svelte';
	import { MAX_SUGGESTIONS } from '$lib';
	import { triggerAiCall } from '$lib/chat';
	import { SUGGESTIONS_PROMPT } from '$lib/consts';
	import { authState } from '$lib/state/auth.svelte';
	import { signinModalState } from '$lib/state/signin-modal.svelte';
	import Welcome from './Welcome.svelte';
	import ListModels from '$lib/components/model/ListModels.svelte';
	import { breakpointsState } from '$lib/state/breakpoints.svelte';

	let { id }: NodeProps = $props();

	// svelte-ignore state_referenced_locally
	const nodeData = useNodesData(id);
	const { update: updateNodes } = useNodes();
	const { update: updateEdges } = useEdges();
	const { updateNodeData, deleteElements } = useSvelteFlow();

	let selectedModels = $derived<string[]>(
		(nodeData.current?.data.selectedModels as string[]) ?? []
	);
	let messages = $derived((nodeData.current?.data.messages as ChatMessage[]) ?? []);
	let isFirstNode = $derived((nodeData.current?.data.isFirstNode as boolean) ?? false);
	let showWelcome = $derived((nodeData.current?.data.showWelcome as boolean) ?? true);
	let isParentNode = $derived((nodeData.current?.data.isParentNode as boolean) ?? false);
	let isFromEdit = $derived((nodeData.current?.data.isFromEdit as boolean) ?? false);

	let prompt = $state.raw<string>((nodeData.current?.data.prompt as string) ?? '');
	let loading = $state.raw<boolean>(false);
	let errorMessage = $state.raw<Set<string>>(new Set());

	const randomSuggestions = SUGGESTIONS_PROMPT.sort(() => Math.random() - 0.5).slice(
		0,
		breakpointsState.isMobile ? 1 : MAX_SUGGESTIONS
	);

	function toggleModel(modelId: string) {
		updateNodeData(
			id,
			{
				...nodeData.current?.data,
				selectedModels: selectedModels.includes(modelId)
					? selectedModels.filter((m) => m !== modelId)
					: [...selectedModels, modelId]
			},
			{ replace: true }
		);
	}

	function handleTriggerAction(models: string[] = selectedModels) {
		if (!authState.user) {
			signinModalState.open = true;
			return;
		}
		errorMessage = new Set();
		const newNodes: Node[] = [];
		const newEdges: Edge[] = [];
		const newMessages = [...messages, { role: 'user', content: prompt }] as ChatMessage[];
		updateNodeData(
			id,
			{
				...nodeData.current?.data,
				messages: newMessages,
				selectedModels: models
			},
			{ replace: true }
		);

		models.forEach((m) => {
			const newNodeId = `assistant-${crypto.randomUUID()}`;
			const newNode: Node = {
				id: newNodeId,
				type: 'assistant',
				position: {
					x: 0,
					y: 0
				},
				data: {
					role: 'assistant',
					selectedModel: m,
					content: '',
					loading: true,
					messages: newMessages
				}
			};
			const newEdge: Edge = {
				id: `edge-${crypto.randomUUID()}`,
				source: id,
				target: newNodeId
			};
			newNodes.push(newNode);
			newEdges.push(newEdge);
		});
		updateNodes((currentNodes) => [...currentNodes, ...newNodes]);
		updateEdges((currentEdges) => [...currentEdges, ...newEdges]);
		triggerAiCall({
			userId: id,
			newNodes,
			messages: newMessages,
			selectedModels: models,
			prompt,
			nodeData: nodeData.current?.data as Record<string, unknown>,
			authToken: authState.token ?? '',
			billingOption: authState.user?.billingOption ?? 'personal',
			updateNodeData: (nodeId, data, opts) =>
				updateNodeData(nodeId, data, { replace: opts?.replace ?? true }),
			updateNodes,
			updateEdges,
			onLoadingChange: (v) => (loading = v),
			onError: (msg) => {
				errorMessage = new Set([...errorMessage, msg]);
			}
		});
	}

	let lastMessage = $derived(
		messages?.length > 0 && messages[messages.length - 1].role === 'user'
			? messages[messages.length - 1]
			: null
	);

	function handlePromptInput(e: Event & { currentTarget: EventTarget & HTMLTextAreaElement }) {
		const value = (e.target as HTMLTextAreaElement).value;
		if (isFirstNode) {
			if (value.trim() === '') {
				updateNodeData(id, { ...nodeData.current?.data, showWelcome: true }, { replace: true });
			} else {
				updateNodeData(id, { ...nodeData.current?.data, showWelcome: false }, { replace: true });
			}
		}
	}

	function handleDeleteNode() {
		deleteElements({ nodes: [{ id: id }] });
	}

	function handleEditMessage(newContent: string) {
		const newNodeId = `user-${crypto.randomUUID()}`;
		const prevMessages = messages.slice(0, -1);
		const newNode: Node = {
			id: newNodeId,
			type: 'user',
			position: { x: 0, y: 0 },
			data: {
				role: 'user',
				selectedModels,
				messages: prevMessages,
				isFirstNode: false,
				isFromEdit: true,
				showWelcome: false,
				isParentNode: true,
				prompt: newContent
			}
		};
		const newEdge: Edge = {
			id: `edge-${crypto.randomUUID()}`,
			source: id,
			target: newNodeId
		};
		updateNodes((currentNodes) => [...currentNodes, newNode]);
		updateEdges((currentEdges) => [...currentEdges, newEdge]);
	}

	onMount(() => {
		if (prompt.trim() !== '' && prompt) {
			handleTriggerAction();
			prompt = '';
		}
	});
</script>

<article
	class="group/user relative z-10 w-[calc(100dvw-2rem)] rounded-3xl border border-border bg-background p-5 shadow-lg/5 lg:w-[600px]"
>
	<div class="nodrag pointer-events-auto cursor-auto">
		{#if isFromEdit}
			<span
				class="mb-2 inline-flex items-center justify-center gap-1 rounded-md bg-accent px-2 py-1 text-[11px] text-muted-foreground"
			>
				<PenLine class="size-2.5" />
				Edited message
			</span>
		{/if}
		<header class="mb-3 flex items-center justify-between">
			<div class="flex flex-wrap items-center gap-1">
				<ListModels {selectedModels} showSelector={!lastMessage} onToggleModel={toggleModel} />
				{#if !lastMessage && !loading}
					<ComboBoxModels onSelect={toggleModel} excludeIds={selectedModels} />
				{/if}
			</div>
		</header>
		<ErrorMessage bind:error={errorMessage} />
		{#if lastMessage}
			<Message nodeId={id} message={lastMessage} onEdit={handleEditMessage} />
		{:else}
			<footer class="flex flex-col items-end transition-all duration-300">
				<textarea
					name="message"
					id="message"
					placeholder="Ask me anything..."
					disabled={loading}
					class="w-full resize-none border-none bg-transparent text-base text-accent-foreground outline-none"
					bind:value={prompt}
					oninput={handlePromptInput}
					onkeydown={(e: KeyboardEvent) => {
						if (e.key === 'Enter' && !e.shiftKey) {
							e.preventDefault();
							prompt = prompt.trim();
							if (prompt) {
								handleTriggerAction();
							}
						}
					}}
				></textarea>
				<div class="flex w-full items-end justify-between gap-1">
					{#if isFirstNode && !loading && !lastMessage}
						<div class="items flex w-full gap-1">
							{#each randomSuggestions as suggestion}
								<Button
									variant="outline"
									size="2xs"
									class="rounded-full! shadow-none!"
									disabled={!selectedModels.length}
									onclick={() => {
										updateNodeData(
											id,
											{ ...nodeData.current?.data, showWelcome: false },
											{ replace: true }
										);
										prompt = suggestion;
										handleTriggerAction();
									}}
								>
									{suggestion}
								</Button>
							{/each}
						</div>
					{:else}
						<div></div>
					{/if}
					<Button
						variant={!selectedModels.length || !prompt ? 'outline' : 'default'}
						size="icon-sm"
						class=""
						disabled={!selectedModels.length || !prompt || loading}
						onclick={() => handleTriggerAction()}
					>
						{#if loading}
							<Spinner className="size-5" />
						{:else}
							<Send />
						{/if}
					</Button>
				</div>
			</footer>
		{/if}
	</div>
	{#if isFirstNode}
		<Welcome bind:showWelcome />
	{:else if isParentNode}
		<Button
			size="icon-lg"
			variant="outline"
			class="absolute -top-2 -right-2 opacity-0 transition-opacity duration-300 group-hover/user:opacity-100"
			onclick={handleDeleteNode}
		>
			<X />
		</Button>
	{/if}
</article>
<Handle type="target" id="t-top" position={Position.Top} class="opacity-0" />
<Handle type="target" id="t-left" position={Position.Left} class="opacity-0" />
<Handle type="target" id="t-right" position={Position.Right} class="opacity-0" />
<Handle type="source" id="s-bottom" position={Position.Bottom} class="opacity-0" />
<Handle type="source" id="s-left" position={Position.Left} class="opacity-0" />
<Handle type="source" id="s-right" position={Position.Right} class="opacity-0" />