File size: 8,789 Bytes
efe3ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
<script lang="ts">
	import { toast } from 'svelte-sonner';

	import DOMPurify from 'dompurify';
	import { marked } from 'marked';

	import { getContext, tick } from 'svelte';
	const i18n = getContext('i18n');

	import { chatCompletion } from '$lib/apis/openai';

	import ChatBubble from '$lib/components/icons/ChatBubble.svelte';
	import LightBlub from '$lib/components/icons/LightBlub.svelte';
	import Markdown from '../Messages/Markdown.svelte';
	import Skeleton from '../Messages/Skeleton.svelte';

	export let id = '';
	export let model = null;
	export let messages = [];
	export let onAdd = () => {};

	let floatingInput = false;

	let selectedText = '';
	let floatingInputValue = '';

	let prompt = '';
	let responseContent = null;
	let responseDone = false;

	const autoScroll = async () => {
		// Scroll to bottom only if the scroll is at the bottom give 50px buffer
		const responseContainer = document.getElementById('response-container');
		if (
			responseContainer.scrollHeight - responseContainer.clientHeight <=
			responseContainer.scrollTop + 50
		) {
			responseContainer.scrollTop = responseContainer.scrollHeight;
		}
	};

	const askHandler = async () => {
		if (!model) {
			toast.error('Model not selected');
			return;
		}
		prompt = `${floatingInputValue}\n\`\`\`\n${selectedText}\n\`\`\``;
		floatingInputValue = '';

		responseContent = '';
		const [res, controller] = await chatCompletion(localStorage.token, {
			model: model,
			messages: [
				...messages,
				{
					role: 'user',
					content: prompt
				}
			].map((message) => ({
				role: message.role,
				content: message.content
			})),
			stream: true // Enable streaming
		});

		if (res && res.ok) {
			const reader = res.body.getReader();
			const decoder = new TextDecoder();

			const processStream = async () => {
				while (true) {
					// Read data chunks from the response stream
					const { done, value } = await reader.read();
					if (done) {
						break;
					}

					// Decode the received chunk
					const chunk = decoder.decode(value, { stream: true });

					// Process lines within the chunk
					const lines = chunk.split('\n').filter((line) => line.trim() !== '');

					for (const line of lines) {
						if (line.startsWith('data: ')) {
							if (line.startsWith('data: [DONE]')) {
								responseDone = true;

								await tick();
								autoScroll();
								continue;
							} else {
								// Parse the JSON chunk
								try {
									const data = JSON.parse(line.slice(6));

									// Append the `content` field from the "choices" object
									if (data.choices && data.choices[0]?.delta?.content) {
										responseContent += data.choices[0].delta.content;

										autoScroll();
									}
								} catch (e) {
									console.error(e);
								}
							}
						}
					}
				}
			};

			// Process the stream in the background
			await processStream();
		} else {
			toast.error('An error occurred while fetching the explanation');
		}
	};

	const explainHandler = async () => {
		if (!model) {
			toast.error('Model not selected');
			return;
		}
		prompt = `Explain this section to me in more detail\n\n\`\`\`\n${selectedText}\n\`\`\``;

		responseContent = '';
		const [res, controller] = await chatCompletion(localStorage.token, {
			model: model,
			messages: [
				...messages,
				{
					role: 'user',
					content: prompt
				}
			].map((message) => ({
				role: message.role,
				content: message.content
			})),
			stream: true // Enable streaming
		});

		if (res && res.ok) {
			const reader = res.body.getReader();
			const decoder = new TextDecoder();

			const processStream = async () => {
				while (true) {
					// Read data chunks from the response stream
					const { done, value } = await reader.read();
					if (done) {
						break;
					}

					// Decode the received chunk
					const chunk = decoder.decode(value, { stream: true });

					// Process lines within the chunk
					const lines = chunk.split('\n').filter((line) => line.trim() !== '');

					for (const line of lines) {
						if (line.startsWith('data: ')) {
							if (line.startsWith('data: [DONE]')) {
								responseDone = true;

								await tick();
								autoScroll();
								continue;
							} else {
								// Parse the JSON chunk
								try {
									const data = JSON.parse(line.slice(6));

									// Append the `content` field from the "choices" object
									if (data.choices && data.choices[0]?.delta?.content) {
										responseContent += data.choices[0].delta.content;

										autoScroll();
									}
								} catch (e) {
									console.error(e);
								}
							}
						}
					}
				}
			};

			// Process the stream in the background
			await processStream();
		} else {
			toast.error('An error occurred while fetching the explanation');
		}
	};

	const addHandler = async () => {
		const messages = [
			{
				role: 'user',
				content: prompt
			},
			{
				role: 'assistant',
				content: responseContent
			}
		];

		onAdd({
			modelId: model,
			parentId: id,
			messages: messages
		});
	};

	export const closeHandler = () => {
		responseContent = null;
		responseDone = false;
		floatingInput = false;
		floatingInputValue = '';
	};
</script>

<div
	id={`floating-buttons-${id}`}
	class="absolute rounded-lg mt-1 text-xs z-9999"
	style="display: none"
>
	{#if responseContent === null}
		{#if !floatingInput}
			<div
				class="flex flex-row gap-0.5 shrink-0 p-1 bg-white dark:bg-gray-850 dark:text-gray-100 text-medium rounded-lg shadow-xl"
			>
				<button
					class="px-1 hover:bg-gray-50 dark:hover:bg-gray-800 rounded-sm flex items-center gap-1 min-w-fit"
					on:click={async () => {
						selectedText = window.getSelection().toString();
						floatingInput = true;

						await tick();
						setTimeout(() => {
							const input = document.getElementById('floating-message-input');
							if (input) {
								input.focus();
							}
						}, 0);
					}}
				>
					<ChatBubble className="size-3 shrink-0" />

					<div class="shrink-0">Ask</div>
				</button>
				<button
					class="px-1 hover:bg-gray-50 dark:hover:bg-gray-800 rounded-sm flex items-center gap-1 min-w-fit"
					on:click={() => {
						selectedText = window.getSelection().toString();
						explainHandler();
					}}
				>
					<LightBlub className="size-3 shrink-0" />

					<div class="shrink-0">Explain</div>
				</button>
			</div>
		{:else}
			<div
				class="py-1 flex dark:text-gray-100 bg-gray-50 dark:bg-gray-800 border dark:border-gray-850 w-72 rounded-full shadow-xl"
			>
				<input
					type="text"
					id="floating-message-input"
					class="ml-5 bg-transparent outline-hidden w-full flex-1 text-sm"
					placeholder={$i18n.t('Ask a question')}
					bind:value={floatingInputValue}
					on:keydown={(e) => {
						if (e.key === 'Enter') {
							askHandler();
						}
					}}
				/>

				<div class="ml-1 mr-2">
					<button
						class="{floatingInputValue !== ''
							? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
							: 'text-white bg-gray-200 dark:text-gray-900 dark:bg-gray-700 disabled'} transition rounded-full p-1.5 m-0.5 self-center"
						on:click={() => {
							askHandler();
						}}
					>
						<svg
							xmlns="http://www.w3.org/2000/svg"
							viewBox="0 0 16 16"
							fill="currentColor"
							class="size-4"
						>
							<path
								fill-rule="evenodd"
								d="M8 14a.75.75 0 0 1-.75-.75V4.56L4.03 7.78a.75.75 0 0 1-1.06-1.06l4.5-4.5a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1-1.06 1.06L8.75 4.56v8.69A.75.75 0 0 1 8 14Z"
								clip-rule="evenodd"
							/>
						</svg>
					</button>
				</div>
			</div>
		{/if}
	{:else}
		<div class="bg-white dark:bg-gray-850 dark:text-gray-100 rounded-xl shadow-xl w-80 max-w-full">
			<div
				class="bg-gray-50/50 dark:bg-gray-800 dark:text-gray-100 text-medium rounded-xl px-3.5 py-3 w-full"
			>
				<div class="font-medium">
					<Markdown id={`${id}-float-prompt`} content={prompt} />
				</div>
			</div>

			<div
				class="bg-white dark:bg-gray-850 dark:text-gray-100 text-medium rounded-xl px-3.5 py-3 w-full"
			>
				<div class=" max-h-80 overflow-y-auto w-full markdown-prose-xs" id="response-container">
					{#if responseContent.trim() === ''}
						<Skeleton size="sm" />
					{:else}
						<Markdown id={`${id}-float-response`} content={responseContent} />
					{/if}

					{#if responseDone}
						<div class="flex justify-end pt-3 text-sm font-medium">
							<button
								class="px-3.5 py-1.5 text-sm font-medium bg-black hover:bg-gray-900 text-white dark:bg-white dark:text-black dark:hover:bg-gray-100 transition rounded-full"
								on:click={addHandler}
							>
								{$i18n.t('Add')}
							</button>
						</div>
					{/if}
				</div>
			</div>
		</div>
	{/if}
</div>