feature/search-select-search-in-trigger
This commit is contained in:
@@ -3,7 +3,8 @@
|
||||
import SelectScrollUpButton from "./select-scroll-up-button.svelte";
|
||||
import SelectScrollDownButton from "./select-scroll-down-button.svelte";
|
||||
import { cn, type WithoutChild } from "$lib/utils.js";
|
||||
import { setContext } from 'svelte';
|
||||
import { getContext } from "svelte";
|
||||
import { selectSearchContextKey, type SelectSearchContext } from "./select-search-context";
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
@@ -22,14 +23,38 @@
|
||||
autoFocusSearch?: boolean;
|
||||
} = $props();
|
||||
|
||||
const searchContext = getContext<SelectSearchContext | undefined>(selectSearchContextKey);
|
||||
let searchQuery = $state('');
|
||||
let isOpen = $state(false);
|
||||
let searchInputRef = $state<HTMLInputElement | null>(null);
|
||||
|
||||
// Provide search context to child items
|
||||
setContext('select-search', {
|
||||
get query() { return searchQuery; }
|
||||
$effect(() => {
|
||||
if (!searchContext) return;
|
||||
const unsubscribe = searchContext.query.subscribe((value) => {
|
||||
searchQuery = value;
|
||||
});
|
||||
return unsubscribe;
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!searchContext) return;
|
||||
const unsubscribe = searchContext.open.subscribe((value) => {
|
||||
isOpen = value;
|
||||
});
|
||||
return unsubscribe;
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!searchable || !autoFocusSearch || !isOpen || !searchInputRef) return;
|
||||
searchInputRef.focus();
|
||||
searchInputRef.select();
|
||||
});
|
||||
|
||||
function updateQuery(next: string) {
|
||||
searchQuery = next;
|
||||
searchContext?.query.set(next);
|
||||
}
|
||||
|
||||
function handleContentKeydown(event: KeyboardEvent) {
|
||||
if (!searchable || !searchInputRef) return;
|
||||
if (event.ctrlKey || event.metaKey || event.altKey) return;
|
||||
@@ -58,10 +83,11 @@
|
||||
<input
|
||||
type="text"
|
||||
bind:this={searchInputRef}
|
||||
bind:value={searchQuery}
|
||||
value={searchQuery}
|
||||
placeholder={searchPlaceholder}
|
||||
autofocus={autoFocusSearch}
|
||||
class="placeholder:text-muted-foreground flex h-8 w-full rounded-md border border-input bg-background px-3 py-1 text-sm outline-none focus:border-ring focus:ring-1 focus:ring-ring"
|
||||
oninput={(event) => updateQuery((event.currentTarget as HTMLInputElement).value)}
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
onkeydown={(e) => e.stopPropagation()}
|
||||
/>
|
||||
|
||||
Reference in New Issue
Block a user