File size: 11,569 Bytes
4e62630
4919030
94ed0cf
89cd532
b104edb
 
 
 
f6e13e9
b104edb
 
 
 
 
 
 
 
 
d433b55
b104edb
 
 
 
 
e442c7f
 
a1a6daf
b104edb
a1a6daf
 
 
 
 
 
 
 
 
 
 
 
f6e13e9
7857e3c
a1a6daf
b104edb
a1a6daf
 
 
 
 
 
 
 
 
 
 
 
f6e13e9
7857e3c
a1a6daf
b104edb
 
 
 
 
 
 
 
 
 
 
 
 
a1a6daf
 
4e62630
f6e13e9
89cd532
94ed0cf
 
a1a6daf
94ed0cf
 
 
 
 
a1a6daf
94ed0cf
 
 
 
 
 
4919030
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b104edb
a1a6daf
 
 
 
b104edb
94ed0cf
 
 
 
 
b104edb
4e62630
94ed0cf
 
 
 
 
 
 
 
f6e13e9
 
 
 
 
4e62630
 
8aab1a5
b104edb
 
 
 
a1a6daf
 
 
 
 
 
 
b104edb
a1a6daf
 
 
b104edb
a1a6daf
d433b55
a1a6daf
 
 
 
 
 
83ddae9
9ed5b48
 
83ddae9
 
 
 
 
f6e13e9
4e62630
 
a1a6daf
94ed0cf
 
 
 
 
 
 
 
a1a6daf
 
 
 
 
d433b55
a1a6daf
 
 
 
94ed0cf
 
a1a6daf
94ed0cf
83ddae9
b104edb
83ddae9
 
 
b104edb
83ddae9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b104edb
83ddae9
b104edb
83ddae9
 
 
 
 
 
 
 
 
f6e13e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83ddae9
b104edb
 
 
 
 
 
 
 
 
 
 
a1a6daf
 
b104edb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca43db4
83ddae9
ca43db4
 
 
 
 
 
 
 
 
 
a1a6daf
ca43db4
38fd55a
 
 
ca43db4
 
 
 
 
 
 
 
 
a1a6daf
ca43db4
 
 
 
 
 
 
 
a1a6daf
e442c7f
 
 
 
 
 
 
 
a1a6daf
 
e442c7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b104edb
83ddae9
b104edb
 
 
 
a1a6daf
 
b104edb
 
 
a1a6daf
 
 
b104edb
 
 
 
 
 
 
 
 
94ed0cf
b104edb
 
 
 
 
 
 
 
 
a1a6daf
4e62630
 
b104edb
a1a6daf
 
4e62630
 
 
 
 
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
<script lang="ts">
	import { browser } from "$app/environment";
	import { createEventDispatcher, onMount } from "svelte";

	import HoverTooltip from "$lib/components/HoverTooltip.svelte";
	import IconInternet from "$lib/components/icons/IconInternet.svelte";
	import IconImageGen from "$lib/components/icons/IconImageGen.svelte";
	import IconPaperclip from "$lib/components/icons/IconPaperclip.svelte";
	import IconThinking from "$lib/components/icons/IconThinking.svelte";
	import { useSettingsStore } from "$lib/stores/settings";
	import { webSearchParameters } from "$lib/stores/webSearchParameters";
	import {
		documentParserToolId,
		fetchUrlToolId,
		imageGenToolId,
		webSearchToolId,
	} from "$lib/utils/toolIds";
	import type { Assistant } from "$lib/types/Assistant";
	import { page } from "$app/state";
	import type { ToolFront } from "$lib/types/Tool";
	import ToolLogo from "../ToolLogo.svelte";
	import { goto } from "$app/navigation";
	import { base } from "$app/paths";
	import IconAdd from "~icons/carbon/add";
	import { captureScreen } from "$lib/utils/screenshot";
	import IconScreenshot from "../icons/IconScreenshot.svelte";
	import { loginModalOpen } from "$lib/stores/loginModal";

	interface Props {
		files?: File[];
		mimeTypes?: string[];
		value?: string;
		placeholder?: string;
		loading?: boolean;
		disabled?: boolean;
		assistant?: Assistant | undefined;
		modelHasTools?: boolean;
		modelIsMultimodal?: boolean;
		children?: import("svelte").Snippet;
		onPaste?: (e: ClipboardEvent) => void;
		showThinking?: boolean;
		thinkingIsOn?: boolean;
	}

	let {
		files = $bindable([]),
		mimeTypes = [],
		value = $bindable(""),
		placeholder = "",
		loading = false,
		disabled = false,
		assistant = undefined,
		modelHasTools = false,
		modelIsMultimodal = false,
		children,
		onPaste,
		showThinking = false,
		thinkingIsOn = false,
	}: Props = $props();

	const onFileChange = async (e: Event) => {
		if (!e.target) return;
		const target = e.target as HTMLInputElement;
		files = [...files, ...(target.files ?? [])];

		if (files.some((file) => file.type.startsWith("application/"))) {
			await settings.instantSet({
				tools: [...($settings.tools ?? []), documentParserToolId],
			});
		}
	};

	let textareaElement: HTMLTextAreaElement | undefined = $state();
	let isCompositionOn = $state(false);

	const dispatch = createEventDispatcher<{ submit: { text: string } }>();

	onMount(() => {
		if (!isVirtualKeyboard()) {
			textareaElement?.focus();
		}
		function onFormSubmit() {
			adjustTextareaHeight();
		}

		const formEl = textareaElement?.closest("form");
		formEl?.addEventListener("submit", onFormSubmit);
		return () => {
			formEl?.removeEventListener("submit", onFormSubmit);
		};
	});

	function isVirtualKeyboard(): boolean {
		if (!browser) return false;

		// Check for touch capability
		if (navigator.maxTouchPoints > 0) return true;

		// Check for touch events
		if ("ontouchstart" in window) return true;

		// Fallback to user agent string check
		const userAgent = navigator.userAgent.toLowerCase();

		return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
	}

	function adjustTextareaHeight() {
		if (!textareaElement) {
			return;
		}

		textareaElement.style.height = "auto";
		textareaElement.style.height = `${textareaElement.scrollHeight}px`;

		if (textareaElement.selectionStart === textareaElement.value.length) {
			textareaElement.scrollTop = textareaElement.scrollHeight;
		}
	}

	function handleKeydown(event: KeyboardEvent) {
		if (
			event.key === "Enter" &&
			!event.shiftKey &&
			!isCompositionOn &&
			!isVirtualKeyboard() &&
			value.trim() !== ""
		) {
			event.preventDefault();	
            const textToSend = thinkingIsOn
               ? `${value.trim()} /think`
               : `${value.trim()} /no_think`;
	        dispatch("submit", { text: textToSend });
		}
	}

	const settings = useSettingsStore();

	// tool section

	let webSearchIsOn = $derived(
		modelHasTools
			? ($settings.tools?.includes(webSearchToolId) ?? false) ||
					($settings.tools?.includes(fetchUrlToolId) ?? false)
			: $webSearchParameters.useSearch
	);
	let imageGenIsOn = $derived($settings.tools?.includes(imageGenToolId) ?? false);

	let documentParserIsOn = $derived(
		modelHasTools && files.length > 0 && files.some((file) => file.type.startsWith("application/"))
	);

	let extraTools = $derived(
		page.data.tools
			.filter((t: ToolFront) => $settings.tools?.includes(t._id))
			.filter(
				(t: ToolFront) =>
					![documentParserToolId, imageGenToolId, webSearchToolId, fetchUrlToolId].includes(t._id)
			) satisfies ToolFront[]
	);

	let showWebSearch = $derived(!assistant);
	//let showWebSearch = $derived(false);
	let showImageGen = $derived(modelHasTools && !assistant);
	let showFileUpload = $derived((modelIsMultimodal || modelHasTools) && mimeTypes.length > 0);
	let showExtraTools = $derived(modelHasTools && !assistant);

	let showNoTools = $derived(!showWebSearch && !showImageGen && !showFileUpload && !showExtraTools);

</script>

<div class="flex min-h-full flex-1 flex-col" onpaste={onPaste}>
	<textarea
		rows="1"
		tabindex="0"
		inputmode="text"
		class="scrollbar-custom max-h-[4lh] w-full resize-none overflow-y-auto overflow-x-hidden border-0 bg-transparent px-2.5 py-2.5 outline-none focus:ring-0 focus-visible:ring-0 max-sm:text-[16px] sm:px-3"
		class:text-gray-400={disabled}
		bind:value
		bind:this={textareaElement}
		onkeydown={handleKeydown}
		oncompositionstart={() => (isCompositionOn = true)}
		oncompositionend={() => (isCompositionOn = false)}
		oninput={adjustTextareaHeight}
		onbeforeinput={(ev) => {
			if (page.data.loginRequired) {
				ev.preventDefault();
				$loginModalOpen = true;
			}
		}}
		{placeholder}
		{disabled}
	></textarea>

	{#if !showNoTools}
		<div
			class={[
				"scrollbar-custom -ml-0.5 flex max-w-[calc(100%-40px)] flex-wrap items-center justify-start gap-2.5 px-3 pb-2.5 pt-1.5 text-gray-500 dark:text-gray-400 max-md:flex-nowrap max-md:overflow-x-auto sm:gap-2",
			]}
		>
			{#if showWebSearch}
				<HoverTooltip
					label="Search the web"
					position="top"
					TooltipClassNames="text-xs !text-left !w-auto whitespace-nowrap !py-1 !mb-0 max-sm:hidden {webSearchIsOn
						? 'hidden'
						: ''}"
				>
					<button
						class="base-tool"
						class:active-tool={webSearchIsOn}
						disabled={loading}
						onclick={async (e) => {
							e.preventDefault();
							if (modelHasTools) {
								if (webSearchIsOn) {
									await settings.instantSet({
										tools: ($settings.tools ?? []).filter(
											(t) => t !== webSearchToolId && t !== fetchUrlToolId
										),
									});
								} else {
									await settings.instantSet({
										tools: [...($settings.tools ?? []), webSearchToolId, fetchUrlToolId],
									});
								}
							} else {
								$webSearchParameters.useSearch = !webSearchIsOn;
							}
						}}
					>
						<IconInternet classNames="text-xl" />
						{#if webSearchIsOn}
							Search
						{/if}
					</button>
				</HoverTooltip>
			{/if}
			{#if showThinking}
				<HoverTooltip
					label="Thinking"
					position="top"
					TooltipClassNames="text-xs !text-left !w-auto whitespace-nowrap !py-1 !mb-0 max-sm:hidden {thinkingIsOn
						? 'hidden'
						: ''}"
				>
					<button
						class="base-tool"
						class:active-tool={thinkingIsOn}
						disabled={loading}
						onclick={(e) => {
							e.preventDefault();
							thinkingIsOn = !thinkingIsOn;
						}}
					>
					<IconThinking classNames="text-xl" />
					{#if thinkingIsOn}
							Thinking
						{:else}
							Not Thinking
						{/if}
					
					</button>
				</HoverTooltip>
			{/if}
			{#if showImageGen}
				<HoverTooltip
					label="Generate	images"
					position="top"
					TooltipClassNames="text-xs !text-left !w-auto whitespace-nowrap !py-1 !mb-0 max-sm:hidden {imageGenIsOn
						? 'hidden'
						: ''}"
				>
					<button
						class="base-tool"
						class:active-tool={imageGenIsOn}
						disabled={loading}
						onclick={async (e) => {
							e.preventDefault();
							if (modelHasTools) {
								if (imageGenIsOn) {
									await settings.instantSet({
										tools: ($settings.tools ?? []).filter((t) => t !== imageGenToolId),
									});
								} else {
									await settings.instantSet({
										tools: [...($settings.tools ?? []), imageGenToolId],
									});
								}
							}
						}}
					>
						<IconImageGen classNames="text-xl" />
						{#if imageGenIsOn}
							Image Gen
						{/if}
					</button>
				</HoverTooltip>
			{/if}
			{#if showFileUpload}
				{@const mimeTypesString = mimeTypes
					.map((m) => {
						// if the mime type ends in *, grab the first part so image/* becomes image
						if (m.endsWith("*")) {
							return m.split("/")[0];
						}
						// otherwise, return the second part for example application/pdf becomes pdf
						return m.split("/")[1];
					})
					.join(", ")}
				<div class="flex items-center">
					<HoverTooltip
						label={mimeTypesString.includes("*")
							? "Upload any file"
							: `Upload ${mimeTypesString} files`}
						position="top"
						TooltipClassNames="text-xs !text-left !w-auto whitespace-nowrap !py-1 !mb-0 max-sm:hidden"
					>
						<label class="base-tool relative" class:active-tool={documentParserIsOn}>
							<input
								disabled={loading}
								class="absolute hidden size-0"
								aria-label="Upload file"
								type="file"
								onchange={onFileChange}
								accept={mimeTypes.join(",")}
							/>
							<IconPaperclip classNames="text-xl" />
							{#if documentParserIsOn}
								Document Parser
							{/if}
						</label>
					</HoverTooltip>
				</div>
				{#if mimeTypes.includes("image/*")}
					<HoverTooltip
						label="Capture screenshot"
						position="top"
						TooltipClassNames="text-xs !text-left !w-auto whitespace-nowrap !py-1 !mb-0 max-sm:hidden"
					>
						<button
							class="base-tool"
							onclick={async (e) => {
								e.preventDefault();
								const screenshot = await captureScreen();

								// Convert base64 to blob
								const base64Response = await fetch(screenshot);
								const blob = await base64Response.blob();

								// Create a File object from the blob
								const file = new File([blob], "screenshot.png", { type: "image/png" });

								files = [...files, file];
							}}
						>
							<IconScreenshot classNames="text-xl" />
						</button>
					</HoverTooltip>
				{/if}
			{/if}
			{#if showExtraTools}
				{#each extraTools as tool}
					<button
						class="active-tool base-tool"
						disabled={loading}
						onclick={async (e) => {
							e.preventDefault();
							goto(`${base}/tools/${tool._id}`);
						}}
					>
						{#key tool.icon + tool.color}
							<ToolLogo icon={tool.icon} color={tool.color} size="xs" />
						{/key}
						{tool.displayName}
					</button>
				{/each}
				<HoverTooltip
					label="Browse more tools"
					position="right"
					TooltipClassNames="text-xs !text-left !w-auto whitespace-nowrap !py-1 max-sm:hidden"
				>
					<a
						class="base-tool flex !size-[20px] items-center justify-center rounded-full border !border-gray-200 !bg-white !transition-none dark:!border-gray-500 dark:!bg-transparent"
						href={`${base}/tools`}
						title="Browse more tools"
					>
						<IconAdd class="text-sm" />
					</a>
				</HoverTooltip>
			{/if}
		</div>
	{/if}
	{@render children?.()}
</div>

<style lang="postcss">
	:global(pre),
	:global(textarea) {
		font-family: inherit;
		box-sizing: border-box;
		line-height: 1.5;
	}
</style>