cleanup: use context api for select menus and options

This commit is contained in:
James Xylight committed 2025-02-03 19:31:47 -08:00
1 parent ee08787afc
commit dd9abe5345
20 files changed
+271 -336

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
<script lang="ts" generics="T">
import { getContext, onMount, type Snippet } from 'svelte'
import type { HTMLAttributes, HTMLOptionAttributes } from 'svelte/elements'
import type { IconSource } from 'svelte-hero-icons'
interface Props extends Omit<HTMLOptionAttributes, 'prefix'> {
children: Snippet
icon?: IconSource
}
let { children, icon, ...rest }: Props = $props()
let optionElement = $state<HTMLOptionElement>()
let option: any = $derived({
value: optionElement?.value ?? '',
label: optionElement?.innerText?.trim() ?? '',
icon: icon,
disabled: false,
})
interface SelectContext {
options: {
value: string
label: string
icon?: IconSource
disabled: boolean
}[]
}
const context = getContext<SelectContext>('select')
$effect(() => {
if (!context.options.find((v) => v == option)) {
context.options.push(option)
}
})
</script>
<option {...rest} bind:this={optionElement}>
{@render children()}
</option>
+22 -15
View File
@@ -20,25 +20,23 @@
ChevronDown,
ChevronUpDown,
Icon,
type IconSource,
} from 'svelte-hero-icons'
import { browser } from '$app/environment'
import { writable } from 'svelte/store'
let open = $state(false)
let element: HTMLSelectElement | undefined = $state()
let options: { value: any; label: string | null; disabled: boolean }[] =
$state([])
interface SelectContext {
options: {
value: string
label: string
icon?: IconSource
disabled?: boolean
}[]
}
// Capture all options from the select element
$effect(() => {
options = element?.options
? Array.from(element?.options).map((option) => ({
value: option.value,
label: option.innerHTML,
disabled: option.disabled,
}))
: []
const context = setContext<SelectContext>('select', {
options: [],
})
const dispatcher = createEventDispatcher<{
@@ -46,8 +44,9 @@
contextmenu: any
input: any
}>()
interface Props {
value?: T | undefined
value?: T | string | undefined
placeholder?: string | undefined
label?: string | undefined
size?: ButtonSize
@@ -112,7 +111,7 @@
</select>
{/snippet}
{#each options as option}
{#each context.options as option}
{#if customOption}{@render customOption({
option,
selected: option.value == value,
@@ -129,6 +128,14 @@
? '!bg-slate-100 dark:!bg-zinc-800'
: ''}"
>
{#if option.icon}
<Icon
src={option.icon}
size="16"
micro
class="text-slate-600 dark:text-zinc-400"
/>
{/if}
{@html option.label}
{#if option.value == value}
<Icon