Debian Codegraph @

frontend/src/AutocompleteInput.svelte

raw
1 <!--
2 @component
3 An autocomplete input for fuzzy selection of suggestions.
4
5 It receives its `value` and a list of possible `suggestions`. Matching suggestions will be
6 shown in a dropdown below the input field and can be selected by clicking or by keyboard.
7
8 This is an implementation of the Combobox pattern as described by the
9 ARIA Authoring Practices Guide (APG) at
10 https://www.w3.org/WAI/ARIA/apg/patterns/combobox/
11 In particular it should match the Editable Combobox With List Autocomplete example at
12 https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-autocomplete-list/
13 -->
14 <script lang="ts" module>
15 /** Incrementing number to use for element ids in the component. */
16 let id = 0;
17 </script>
18
19 <script lang="ts">
20 import type { KeySpec } from "./keyboard-shortcuts";
21 import { keyboardShortcut } from "./keyboard-shortcuts";
22 import { fuzzyfilter, fuzzywrap, type FuzzyWrappedText } from "./lib/fuzzy";
23
24 interface Props {
25 /** The currently entered value (bindable). */
26 value: string;
27 /** A placeholder for the input field. */
28 placeholder: string;
29 /** The suggestions for the value. */
30 suggestions: readonly string[];
31 /** A function to extract the string that should be used for suggestion filtering. */
32 valueExtractor?: (val: string, input: HTMLInputElement) => string;
33 /** A function to update the value after selecting a suggestion. */
34 valueSelector?: (val: string, input: HTMLInputElement) => string;
35 /** Automatically adjust the size of the input element. */
36 setSize?: boolean;
37 /** An optional class name to assign to the input element. */
38 className?: string;
39 /** A key binding to add for this input. */
40 key?: KeySpec;
41 /** A function that checks the entered value for validity. */
42 checkValidity?: (val: string) => string;
43 /** Whether to mark the input as required. */
44 required?: boolean;
45 /** Whether to show a button to clear the input. */
46 clearButton?: boolean;
47 /** An event handler to run on blur. */
48 onBlur?: (el: HTMLInputElement) => void;
49 /** An event handler to run on enter. */
50 onEnter?: (el: HTMLInputElement) => void;
51 /** An event handler to run on an element being selected. */
52 onSelect?: (el: HTMLInputElement) => void;
53 }
54
55 let {
56 value = $bindable(),
57 placeholder,
58 suggestions,
59 valueExtractor,
60 valueSelector,
61 setSize = false,
62 className,
63 key,
64 checkValidity,
65 clearButton = false,
66 required,
67 onBlur,
68 onEnter,
69 onSelect,
70 }: Props = $props();
71
72 id += 1;
73 const autocomple_id = `combobox-autocomplete-${id.toString()}`;
74
75 let hidden = $state.raw(true);
76 let index = $state.raw(-1);
77 let input: HTMLInputElement | undefined = $state.raw();
78
79 let size = $derived(
80 setSize ? Math.max(value.length, placeholder.length) + 1 : undefined,
81 );
82 let extractedValue = $derived(
83 input && valueExtractor ? valueExtractor(value, input) : value,
84 );
85 let filteredSuggestions: {
86 suggestion: string;
87 fuzzywrapped: FuzzyWrappedText;
88 }[] = $derived.by(() => {
89 const filtered = fuzzyfilter(extractedValue, suggestions)
90 .slice(0, 30)
91 .map((suggestion) => ({
92 suggestion,
93 fuzzywrapped: fuzzywrap(extractedValue, suggestion),
94 }));
95 return filtered.length === 1 && filtered[0]?.suggestion === extractedValue
96 ? []
97 : filtered;
98 });
99
100 $effect(() => {
101 const msg = checkValidity ? checkValidity(value) : "";
102 input?.setCustomValidity(msg);
103 });
104
105 $effect.pre(() => {
106 // ensure the index is pointing to a valid element.
107 index = Math.min(index, filteredSuggestions.length - 1);
108 });
109
110 function select(suggestion: string) {
111 value =
112 input && valueSelector ? valueSelector(suggestion, input) : suggestion;
113 if (input) {
114 onSelect?.(input);
115 }
116 hidden = true;
117 }
118
119 function mousedown(event: MouseEvent, suggestion: string) {
120 if (event.button === 0) {
121 select(suggestion);
122 }
123 }
124
125 let expanded = $derived(!hidden && filteredSuggestions.length > 0);
126
127 function keydown(event: KeyboardEvent) {
128 if (event.key === "Enter") {
129 const suggestion = filteredSuggestions[index]?.suggestion;
130 if (index > -1 && !hidden && suggestion != null) {
131 event.preventDefault();
132 select(suggestion);
133 } else if (input) {
134 onEnter?.(input);
135 }
136 } else if (event.key === " " && event.ctrlKey) {
137 hidden = false;
138 } else if (event.key === "Escape") {
139 event.stopPropagation();
140 if (expanded) {
141 index = -1;
142 hidden = true;
143 } else {
144 value = "";
145 }
146 } else if (event.key === "ArrowUp") {
147 event.preventDefault();
148 index = index === 0 ? filteredSuggestions.length - 1 : index - 1;
149 } else if (event.key === "ArrowDown") {
150 event.preventDefault();
151 index = index === filteredSuggestions.length - 1 ? 0 : index + 1;
152 }
153 }
154 </script>
155
156 <span class={className}>
157 <input
158 type="text"
159 autocomplete="off"
160 role="combobox"
161 aria-expanded={expanded}
162 aria-controls={autocomple_id}
163 bind:value
164 bind:this={input}
165 use:keyboardShortcut={key}
166 onblur={(event) => {
167 hidden = true;
168 onBlur?.(event.currentTarget);
169 }}
170 onfocus={() => {
171 hidden = false;
172 }}
173 oninput={() => {
174 hidden = false;
175 }}
176 onkeydown={keydown}
177 {placeholder}
178 {required}
179 {size}
180 />
181 {#if clearButton && value}
182 <button
183 type="button"
184 tabindex={-1}
185 class="muted round"
186 onclick={() => {
187 value = "";
188 if (input) {
189 onSelect?.(input);
190 }
191 }}
192 >
193 ×
194 </button>
195 {/if}
196 {#if filteredSuggestions.length}
197 <ul {hidden} role="listbox" id={autocomple_id}>
198 {#each filteredSuggestions as { fuzzywrapped, suggestion }, i}
199 <li
200 role="option"
201 aria-selected={i === index}
202 class:selected={i === index}
203 onmousedown={(ev) => {
204 mousedown(ev, suggestion);
205 }}
206 >
207 {#each fuzzywrapped as [type, text]}
208 {#if type === "text"}
209 {text}
210 {:else}
211 <span>{text}</span>
212 {/if}
213 {/each}
214 </li>
215 {/each}
216 </ul>
217 {/if}
218 </span>
219
220 <style>
221 span {
222 position: relative;
223 display: inline-block;
224 }
225
226 input {
227 width: 100%;
228 }
229
230 ul {
231 position: absolute;
232 z-index: var(--z-index-autocomplete);
233 overflow: hidden auto;
234 background-color: var(--background);
235 border: 1px solid var(--border-darker);
236 box-shadow: var(--box-shadow-dropdown);
237 }
238
239 :global(aside) ul {
240 /* the only way to get the list to overflow the
241 aside is to put it in fixed position */
242 position: fixed;
243 }
244
245 li {
246 min-width: 8rem;
247 padding: 0 0.5em;
248 white-space: nowrap;
249 cursor: pointer;
250 }
251
252 li.selected,
253 li:hover {
254 color: var(--background);
255 background-color: var(--link-color);
256 }
257
258 button {
259 position: absolute;
260 top: 8px;
261 right: 4px;
262 background: transparent;
263 }
264
265 li span {
266 height: 1.2em;
267 padding: 0 0.05em;
268 margin: 0 -0.05em;
269 background-color: var(--autocomplete-match);
270 border-radius: 2px;
271 }
272
273 @media print {
274 button {
275 display: none;
276 }
277 }
278 </style>