SearchBox.svelte
3.01 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<script>
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import SearchResults from './SearchResults.svelte';
import {
query,
results,
isLoading,
indexLoaded,
error,
selectedIndex,
showResults,
filterType,
initIndex,
performSearch,
clearSearch,
navigateResults,
setFilter
} from '$lib/stores/searchStore';
const filterOptions = [
{ value: 'todos', label: 'Todos' },
{ value: 'entidad', label: 'Entidades' },
{ value: 'objeto_gasto', label: 'Objetos' },
{ value: 'rubro', label: 'Rubros' }
];
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}`);
} else if (item.tipo === 'rubro') {
goto(`/rubro/${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">
<div class="flex gap-2">
<input
bind:this={inputRef}
type="text"
placeholder={$indexLoaded ? "Buscar..." : "Cargando..."}
disabled={!$indexLoaded}
class="flex-1 p-2 border rounded"
oninput={handleInput}
onkeydown={handleKeydown}
onfocus={() => isFocused = true}
/>
<select
class="px-3 py-2 border rounded bg-white text-sm text-slate-600 cursor-pointer"
value={$filterType}
onchange={(e) => setFilter(e.target.value)}
disabled={!$indexLoaded}
>
{#each filterOptions as option}
<option value={option.value}>{option.label}</option>
{/each}
</select>
</div>
{#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>