Skip to content

Commit

Permalink
fix: Do not overwrite search query when input is focused (#132)
Browse files Browse the repository at this point in the history
  • Loading branch information
evadecker committed Nov 22, 2023
1 parent 64c9c91 commit e67395d
Showing 1 changed file with 35 additions and 16 deletions.
51 changes: 35 additions & 16 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,20 @@
import SearchIcon from '~icons/ri/search-line';
import CloseCircleIcon from '~icons/ri/close-circle-fill';
import { scale } from 'svelte/transition';
import type { FormEventHandler, KeyboardEventHandler } from 'svelte/elements.js';
import type {
FocusEventHandler,
FormEventHandler,
KeyboardEventHandler
} from 'svelte/elements.js';
export let data;
$: currentQuery = $page.url.searchParams.get('q') || '';
let isFocused = false;
let currentQuery = '';
$: if (!isFocused) {
currentQuery = $page.url.searchParams.get('q') || '';
}
$: currentPage = Number($page.url.searchParams.get('page')) || 1;
$: currentTag = $page.url.searchParams.get('tag') as Enums<'tags'> | null;
Expand All @@ -36,31 +45,39 @@
debounceTimer = setTimeout(callback, 250);
};
const handleSearch: FormEventHandler<HTMLInputElement> = (e) => {
currentQuery = e.currentTarget.value;
const newURL = new URL($page.url);
newURL.searchParams.delete('page');
if (currentQuery) {
newURL.searchParams.set('q', currentQuery);
} else {
newURL.searchParams.delete('q');
}
debounce(() => goto(newURL, { keepFocus: true, replaceState: true }));
};
const handleClearSearch = () => {
const newURL = new URL($page.url);
newURL.searchParams.delete('tag');
newURL.searchParams.delete('q');
goto(newURL, { keepFocus: true });
goto(newURL, { keepFocus: true, replaceState: true });
};
const handleSearchKeydown: KeyboardEventHandler<HTMLInputElement> = (e) => {
const handleKeydown: KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === 'Backspace' && currentQuery === '') {
handleClearSearch();
}
};
const handleSearch: FormEventHandler<HTMLInputElement> = (e) => {
currentQuery = e.currentTarget.value;
const newURL = new URL($page.url);
newURL.searchParams.delete('page');
if (currentQuery) {
newURL.searchParams.set('q', currentQuery);
} else {
newURL.searchParams.delete('q');
}
const handleFocus: FocusEventHandler<HTMLInputElement> = () => {
isFocused = true;
};
debounce(() => goto(newURL, { keepFocus: true }));
const handleBlur: FocusEventHandler<HTMLInputElement> = () => {
isFocused = false;
};
const handleTagClick = (tag: Enums<'tags'> | null) => {
Expand Down Expand Up @@ -127,7 +144,9 @@
placeholder="Search covers…"
value={currentQuery}
on:input={handleSearch}
on:keydown={handleSearchKeydown}
on:keydown={handleKeydown}
on:focus={handleFocus}
on:blur={handleBlur}
/>
{#if currentQuery.length > 0}
<button
Expand Down

0 comments on commit e67395d

Please sign in to comment.