SearchBox.svelte
2.33 KB
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
<script>
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import SearchResults from './SearchResults.svelte';
import {
query,
results,
isLoading,
indexLoaded,
error,
selectedIndex,
showResults,
initIndex,
performSearch,
clearSearch,
navigateResults
} from '$lib/stores/searchStore';
let inputRef;
let debounceTimer;
let isFocused = $state(false);
onMount(() => {
initIndex();
});
function handleInput(e) {
const value = e.target.value;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
performSearch(value);
}, 250);
}
function handleKeydown(e) {
if (!$showResults) return;
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
navigateResults('down', $results.length);
break;
case 'ArrowUp':
e.preventDefault();
navigateResults('up', $results.length);
break;
case 'Enter':
e.preventDefault();
if ($selectedIndex >= 0 && $results[$selectedIndex]) {
const item = $results[$selectedIndex];
if (item.tipo === 'entidad') {
goto(`/entidad/${item.codigo}`);
} else if (item.tipo === 'objeto_gasto') {
goto(`/objeto/${item.codigo}`);
}
clearSearch();
inputRef.value = '';
}
break;
case 'Escape':
clearSearch();
inputRef.value = '';
inputRef.blur();
break;
}
}
function handleClickOutside(e) {
if (!e.target.closest('.search-container')) {
isFocused = false;
}
}
</script>
<svelte:window onclick={handleClickOutside} />
<div class="search-container relative">
<input
bind:this={inputRef}
type="text"
placeholder={$indexLoaded ? "Buscar entidad u objeto de gasto..." : "Cargando..."}
disabled={!$indexLoaded}
class="w-full p-2 border rounded"
oninput={handleInput}
onkeydown={handleKeydown}
onfocus={() => isFocused = true}
/>
{#if $isLoading}
<span class="absolute right-2 top-2 text-sm text-gray-400">...</span>
{/if}
{#if isFocused && $showResults}
<SearchResults
results={$results}
query={$query}
selectedIndex={$selectedIndex}
/>
{/if}
{#if $error}
<p class="text-red-500 text-sm mt-1">{$error}</p>
{/if}
</div>