File size: 9,440 Bytes
55bd140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<script lang="ts">
	import { getAllTags } from '$lib/apis/chats';
	import { folders, tags } from '$lib/stores';
	import { getContext, createEventDispatcher, onMount, onDestroy, tick } from 'svelte';
	import { fade } from 'svelte/transition';
	import Search from '$lib/components/icons/Search.svelte';
	import XMark from '$lib/components/icons/XMark.svelte';

	const dispatch = createEventDispatcher();
	const i18n = getContext('i18n');

	export let placeholder = '';
	export let value = '';
	export let showClearButton = false;

	export let onFocus = () => {};
	export let onKeydown = (e) => {};

	let selectedIdx = 0;
	let selectedOption = null;

	let lastWord = '';
	$: lastWord = value ? value.split(' ').at(-1) : value;

	let options = [
		{
			name: 'tag:',
			description: $i18n.t('search for tags')
		},
		{
			name: 'folder:',
			description: $i18n.t('search for folders')
		},
		{
			name: 'pinned:',
			description: $i18n.t('search for pinned chats')
		},
		{
			name: 'shared:',
			description: $i18n.t('search for shared chats')
		},
		{
			name: 'archived:',
			description: $i18n.t('search for archived chats')
		}
	];
	let focused = false;
	let loading = false;

	let hovering = false;

	let filteredOptions = options;
	$: filteredOptions = options.filter((option) => {
		return option.name.startsWith(lastWord);
	});

	let filteredItems = [];

	$: if (lastWord && lastWord !== null) {
		initItems();
	}

	const initItems = async () => {
		console.log('initItems', lastWord);
		loading = true;
		await tick();

		if (lastWord.startsWith('tag:')) {
			filteredItems = [
				...$tags,
				{
					id: 'none',
					name: $i18n.t('Untagged')
				}
			]
				.filter((tag) => {
					const tagName = lastWord.slice(4);
					if (tagName) {
						const tagId = tagName.replaceAll(' ', '_').toLowerCase();

						if (tag.id !== tagId) {
							return tag.id.startsWith(tagId);
						} else {
							return false;
						}
					} else {
						return true;
					}
				})
				.map((tag) => {
					return {
						id: tag.id,
						name: tag.name,
						type: 'tag'
					};
				});
		} else if (lastWord.startsWith('folder:')) {
			filteredItems = [...$folders]
				.filter((folder) => {
					const folderName = lastWord.slice(7);
					if (folderName) {
						const id = folder.name.replaceAll(' ', '_').toLowerCase();
						const folderId = folderName.replaceAll(' ', '_').toLowerCase();

						if (id !== folderId) {
							return id.startsWith(folderId);
						} else {
							return false;
						}
					} else {
						return true;
					}
				})
				.map((folder) => {
					return {
						id: folder.name.replaceAll(' ', '_').toLowerCase(),
						name: folder.name,
						type: 'folder'
					};
				});
		} else if (lastWord.startsWith('pinned:')) {
			filteredItems = [
				{
					id: 'true',
					name: 'true',
					type: 'pinned'
				},
				{
					id: 'false',
					name: 'false',
					type: 'pinned'
				}
			].filter((item) => {
				const pinnedValue = lastWord.slice(7);
				if (pinnedValue) {
					return item.id.startsWith(pinnedValue) && item.id !== pinnedValue;
				} else {
					return true;
				}
			});
		} else if (lastWord.startsWith('shared:')) {
			filteredItems = [
				{
					id: 'true',
					name: 'true',
					type: 'shared'
				},
				{
					id: 'false',
					name: 'false',
					type: 'shared'
				}
			].filter((item) => {
				const sharedValue = lastWord.slice(7);
				if (sharedValue) {
					return item.id.startsWith(sharedValue) && item.id !== sharedValue;
				} else {
					return true;
				}
			});
		} else if (lastWord.startsWith('archived:')) {
			filteredItems = [
				{
					id: 'true',
					name: 'true',
					type: 'archived'
				},
				{
					id: 'false',
					name: 'false',
					type: 'archived'
				}
			].filter((item) => {
				const archivedValue = lastWord.slice(9);
				if (archivedValue) {
					return item.id.startsWith(archivedValue) && item.id !== archivedValue;
				} else {
					return true;
				}
			});
		} else {
			filteredItems = [];
		}

		loading = false;
	};

	const initTags = async () => {
		loading = true;

		await tags.set(await getAllTags(localStorage.token));
		loading = false;
	};

	const clearSearchInput = () => {
		value = '';
		dispatch('input');
	};
</script>

<div class="px-1 mb-1 flex justify-center space-x-2 relative z-10" id="search-container">
	<div class="flex w-full rounded-xl" id="chat-search">
		<div class="self-center py-2 rounded-l-xl bg-transparent dark:text-gray-300">
			<Search />
		</div>

		<input
			id="search-input"
			class="w-full rounded-r-xl py-1.5 pl-2.5 text-sm bg-transparent dark:text-gray-300 outline-hidden"
			placeholder={placeholder ? placeholder : $i18n.t('Search')}
			autocomplete="off"
			bind:value
			on:input={() => {
				dispatch('input');
			}}
			on:click={() => {
				if (!focused) {
					onFocus();
					hovering = false;

					focused = true;
					initTags();
				}
			}}
			on:blur={() => {
				if (!hovering) {
					focused = false;
				}
			}}
			on:keydown={(e) => {
				if (e.key === 'Enter') {
					if (filteredItems.length > 0) {
						const itemElement = document.getElementById(`search-item-${selectedIdx}`);
						itemElement.click();
						return;
					}

					if (filteredOptions.length > 0) {
						const optionElement = document.getElementById(`search-option-${selectedIdx}`);
						optionElement.click();
						return;
					}

				}

				if (e.key === 'ArrowUp') {
					e.preventDefault();
					selectedIdx = Math.max(0, selectedIdx - 1);
				} else if (e.key === 'ArrowDown') {
					e.preventDefault();

					if (filteredItems.length > 0) {
						if (selectedIdx === filteredItems.length - 1) {
							focused = false;
						} else {
							selectedIdx = Math.min(selectedIdx + 1, filteredItems.length - 1);
						}
					} else {
						if (selectedIdx === filteredOptions.length - 1) {
							focused = false;
						} else {
							selectedIdx = Math.min(selectedIdx + 1, filteredOptions.length - 1);
						}
					}
				} else {
					// if the user types something, reset to the top selection.
					if (!focused) {
						onFocus();
						hovering = false;

						focused = true;
						initTags();
					}

					selectedIdx = 0;
				}

				const item = document.querySelector(`[data-selected="true"]`);
				item?.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });

				if (!document.getElementById('search-options-container')) {
					onKeydown(e);
				}
			}}
		/>

		{#if showClearButton && value}
			<div class="self-center pl-1.5 translate-y-[0.5px] rounded-l-xl bg-transparent">
				<button
					class="p-0.5 rounded-full hover:bg-gray-100 dark:hover:bg-gray-900 transition"
					on:click={clearSearchInput}
				>
					<XMark className="size-3" strokeWidth="2" />
				</button>
			</div>
		{/if}
	</div>

	{#if focused && (filteredOptions.length > 0 || filteredItems.length > 0)}
		<!-- svelte-ignore a11y-no-static-element-interactions -->
		<div
			class="absolute top-0 mt-8 left-0 right-1 border border-gray-100 dark:border-gray-900 bg-gray-50 dark:bg-gray-950 rounded-2xl z-10 shadow-lg"
			id="search-options-container"
			in:fade={{ duration: 50 }}
			on:mouseenter={() => {
				hovering = true;
				selectedIdx = null;
			}}
			on:mouseleave={() => {
				hovering = false;
				selectedIdx = 0;
			}}
		>
			<div class="px-3 py-2.5 text-xs group">
				{#if filteredItems.length > 0}
					<div class="px-1 font-medium dark:text-gray-300 text-gray-700 mb-1 capitalize">
						{selectedOption}
					</div>

					<div class="max-h-60 overflow-auto">
						{#each filteredItems as item, itemIdx}
							<button
								class=" px-1.5 py-0.5 flex gap-1 hover:bg-gray-100 dark:hover:bg-gray-900 w-full rounded {selectedIdx ===
								itemIdx
									? 'bg-gray-100 dark:bg-gray-900'
									: ''}"
								data-selected={selectedIdx === itemIdx}
								id="search-item-{itemIdx}"
								on:click|stopPropagation={async () => {
									const words = value.split(' ');

									words.pop();
									words.push(`${item.type}:${item.id} `);

									value = words.join(' ');

									filteredItems = [];
									dispatch('input');
								}}
							>
								<div class="dark:text-gray-300 text-gray-700 font-medium line-clamp-1 shrink-0">
									{item.name}
								</div>

								<div class=" text-gray-500 line-clamp-1">
									{item.id}
								</div>
							</button>
						{/each}
					</div>
				{:else if filteredOptions.length > 0}
					<div class="px-1 font-medium dark:text-gray-300 text-gray-700 mb-1">
						{$i18n.t('Search options')}
					</div>

					<div class=" max-h-60 overflow-auto">
						{#each filteredOptions as option, optionIdx}
							<button
								class=" px-1.5 py-0.5 flex gap-1 hover:bg-gray-100 dark:hover:bg-gray-900 w-full rounded {selectedIdx ===
								optionIdx
									? 'bg-gray-100 dark:bg-gray-900'
									: ''}"
								id="search-option-{optionIdx}"
								on:click|stopPropagation={async () => {
									const words = value.split(' ');

									words.pop();
									words.push(`${option.name}`);

									selectedOption = option.name.replace(':', '');

									value = words.join(' ');

									dispatch('input');
								}}
							>
								<div class="dark:text-gray-300 text-gray-700 font-medium">{option.name}</div>

								<div class=" text-gray-500 line-clamp-1">
									{option.description}
								</div>
							</button>
						{/each}
					</div>
				{/if}
			</div>
		</div>
	{/if}
</div>