149 lines
6.4 KiB
Svelte
149 lines
6.4 KiB
Svelte
<script lang="ts" generics="T extends string | number">
|
|
import { IconCheck, IconChevronDown } from "./icons"
|
|
import { gsap } from "gsap"
|
|
import { onDestroy, tick } from "svelte"
|
|
import { animate, bound, duration, type Option } from "./motion"
|
|
import { scrollbar } from "./scrollbar"
|
|
|
|
let { label, value = $bindable(), options, disabled = false, onchange }: {
|
|
label: string; value: T; options: readonly Option<T>[]; disabled?: boolean; onchange?: (next: T) => void
|
|
} = $props()
|
|
const id = $props.id()
|
|
let button: HTMLButtonElement, menu: HTMLDivElement, list: HTMLDivElement
|
|
let open = $state(false)
|
|
let active = $state(-1)
|
|
let enabled = $derived(options.map((_, index) => index).filter(index => !options[index].disabled))
|
|
let selected = $derived(options.find(option => option.value === value))
|
|
let query = "", typeAt = 0
|
|
|
|
function positionMenu() {
|
|
if (!open) return
|
|
const b = button.getBoundingClientRect()
|
|
const viewport = button.closest("[data-workspace-scroll]")?.getBoundingClientRect()
|
|
const top = viewport?.top ?? 0, bottom = viewport?.bottom ?? innerHeight
|
|
if (!b.width || b.bottom <= top || b.top >= bottom) return close()
|
|
const border = menu.offsetHeight - menu.clientHeight
|
|
const above = b.top - top - 10, below = bottom - b.bottom - 10
|
|
const upward = below < Math.min(list.scrollHeight + border, 220) && above > below
|
|
const width = Math.min(Math.max(b.width, 164), innerWidth - 16)
|
|
const height = Math.min(320, Math.max(48, upward ? above : below))
|
|
list.style.maxHeight = height - border + "px"
|
|
menu.style.width = width + "px"
|
|
menu.style.left = bound(b.left, 8, innerWidth - width - 8) + "px"
|
|
menu.style.top = (upward ? b.top - menu.offsetHeight - 6 : b.bottom + 6) + "px"
|
|
}
|
|
|
|
function highlight(index: number, reveal = true) {
|
|
if (!enabled.includes(index)) return
|
|
if (active !== index) {
|
|
const previous = list.children[active]
|
|
if (previous) animate(previous, { "--hover-ink": 0 })
|
|
active = index
|
|
animate(list.children[index], { "--hover-ink": .14 })
|
|
}
|
|
if (!reveal) return
|
|
const row = list.children[index] as HTMLElement
|
|
if (row.offsetTop < list.scrollTop) list.scrollTop = row.offsetTop
|
|
else if (row.offsetTop + row.offsetHeight > list.scrollTop + list.clientHeight) {
|
|
list.scrollTop = row.offsetTop + row.offsetHeight - list.clientHeight
|
|
}
|
|
}
|
|
|
|
async function show() {
|
|
if (open || disabled) return
|
|
open = true
|
|
query = ""
|
|
await tick()
|
|
if (!open || !menu?.isConnected) return
|
|
gsap.killTweensOf(menu)
|
|
if (!menu.matches(":popover-open")) menu.showPopover()
|
|
positionMenu()
|
|
const current = options.findIndex(option => option.value === value && !option.disabled)
|
|
highlight(current < 0 ? enabled[0] : current)
|
|
animate(button.querySelector(".combo-arrow"), { rotation: 180 })
|
|
gsap.fromTo(menu, { opacity: .7, y: 5 }, { opacity: 1, y: 0, duration: duration(), ease: "power2.out" })
|
|
}
|
|
|
|
function close() {
|
|
if (!open) return
|
|
open = false
|
|
animate(button.querySelector(".combo-arrow"), { rotation: 0 })
|
|
if (menu?.matches(":popover-open")) {
|
|
animate(menu, { opacity: 0, y: -4, onComplete: () => { if (!open) menu.hidePopover() } })
|
|
}
|
|
}
|
|
|
|
function choose(index: number) {
|
|
if (!enabled.includes(index)) return
|
|
const option = options[index]
|
|
close()
|
|
button.focus({ preventScroll: true })
|
|
if (option.value === value) return
|
|
if (onchange) onchange(option.value)
|
|
else value = option.value
|
|
}
|
|
|
|
async function key(event: KeyboardEvent) {
|
|
const k = event.key
|
|
if (k === "Tab") return close()
|
|
if (k === "Escape" && open) { event.preventDefault(); event.stopPropagation(); return close() }
|
|
const movement = ["ArrowDown", "ArrowUp", "Home", "End"].includes(k)
|
|
const enter = k === "Enter" || k === " "
|
|
const search = k.length === 1 && !enter && !event.ctrlKey && !event.altKey && !event.metaKey
|
|
if (!movement && !enter && !search) return
|
|
event.preventDefault()
|
|
if (!open) {
|
|
await show()
|
|
if (!search && k !== "Home" && k !== "End") return
|
|
}
|
|
if (!enabled.length) return
|
|
if (enter) return choose(active)
|
|
if (movement) {
|
|
const place = enabled.indexOf(active) + (k === "ArrowDown" ? 1 : -1)
|
|
const next = k === "Home" ? 0 : k === "End" ? enabled.length - 1 : bound(place, 0, enabled.length - 1)
|
|
return highlight(enabled[next])
|
|
}
|
|
const now = performance.now()
|
|
query = (now - typeAt < 650 ? query : "") + k.toLowerCase()
|
|
typeAt = now
|
|
const result = enabled.find(index => options[index].label.toLowerCase().startsWith(query))
|
|
if (result !== undefined) highlight(result)
|
|
}
|
|
|
|
function outside(event: PointerEvent) {
|
|
if (open && event.target instanceof Node && !button.contains(event.target) && !menu.contains(event.target)) close()
|
|
}
|
|
function onScroll(event: Event) {
|
|
if (!(event.target instanceof Node) || !menu?.contains(event.target)) positionMenu()
|
|
}
|
|
onDestroy(() => { if (menu) gsap.killTweensOf(menu) })
|
|
</script>
|
|
|
|
<svelte:window onresize={positionMenu} />
|
|
<svelte:document onpointerdown={outside} onscrollcapture={onScroll} />
|
|
|
|
<div class="combo">
|
|
<button class="combo-trigger" type="button" role="combobox" bind:this={button} aria-label={label}
|
|
aria-describedby={id + "-value"} aria-haspopup="listbox" aria-expanded={open}
|
|
aria-controls={open ? id + "-choices" : undefined}
|
|
aria-activedescendant={open && active >= 0 ? id + "-" + active : undefined}
|
|
{disabled} onclick={() => open ? close() : show()} onkeydown={key}>
|
|
<span id={id + "-value"}>{selected?.label ?? "Choose"}</span>
|
|
<IconChevronDown class="combo-arrow" size={16} aria-hidden="true" />
|
|
</button>
|
|
<div bind:this={menu} id={id + "-choices"} class="combo-menu" popover="manual" role="listbox"
|
|
aria-label={label} aria-hidden={!open} inert={!open}>
|
|
<div class="combo-list" bind:this={list} use:scrollbar={"y"}>
|
|
{#each options as option, index (option.value)}
|
|
<div class="combo-option" id={id + "-" + index} role="option" aria-selected={option.value === value}
|
|
aria-disabled={option.disabled ?? false} tabindex="-1"
|
|
onpointermove={() => highlight(index, false)} onmousedown={(event) => event.preventDefault()}
|
|
onclick={() => choose(index)} onkeydown={(event) => { if (event.key === "Enter") choose(index) }}>
|
|
<span>{option.label}</span>
|
|
{#if option.value === value}<IconCheck size={16} aria-hidden="true" />{/if}
|
|
</div>
|
|
{/each}
|
|
</div>
|
|
</div>
|
|
</div>
|