nex_animation/frontend/src/components/forms/MultiSelect.tsx

186 lines
9.1 KiB
TypeScript

import { useEffect, useId, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { cn } from '../../lib/cn'
import { sameValue, summaryOf, toOptions, type OptionLike } from './options'
import { contentWidth, usePopup } from './use-popup'
import { filterBarCls, itemCls, listCls, noneCls, popCls, triggerCls } from './parts'
import { Caret } from './Caret'
/**
* 全站统一「多选下拉」(替代原生 <select multiple> 的系统列表外观)。
* 与 Select 同一套视觉语言:复选列表 + 全选/清空 + 过滤框。
* 回显超过 30 字退化成「首项 等 N 项」,否则触发器会被撑出整行。
*/
export type MultiSelectProps = {
value: any[] | null | undefined
onChange: (next: any[]) => void
options: OptionLike[] | null | undefined
disabled?: boolean
placeholder?: string
searchThreshold?: number
size?: 'sm' | 'md'
ariaLabel?: string
className?: string
}
export function MultiSelect({
value, onChange, options, disabled, placeholder = '未选择', searchThreshold = 7,
size = 'md', ariaLabel, className
}: MultiSelectProps) {
const picked = useMemo(() => (Array.isArray(value) ? value : []), [value])
const opts = useMemo(() => toOptions(options), [options])
const uid = useId()
const cw = useMemo(() => contentWidth(opts.map((o) => o.label), 62), [opts])
const { open, setOpen, triggerRef, popRef, box } = usePopup({ minW: 190, maxW: 440, listMinH: 210, maxHCap: 320, contentW: cw, disabled })
const listRef = useRef<HTMLDivElement | null>(null)
const searchRef = useRef<HTMLInputElement | null>(null)
const [query, setQuery] = useState('')
const [active, setActive] = useState(-1)
const isSelected = (v: any) => picked.some((p) => sameValue(p, v))
const labels = opts.filter((o) => isSelected(o.value)).map((o) => o.label)
const shown = summaryOf(labels)
const count = labels.length
const view = useMemo(() => {
const q = query.trim().toLowerCase()
return opts.map((_, i) => i).filter((i) => !q || opts[i].label.toLowerCase().includes(q))
}, [opts, query])
const selectableInView = view.filter((i) => !opts[i].disabled).length
const searchable = searchThreshold > 0 && opts.length > searchThreshold
const scrollActive = () => listRef.current?.querySelector<HTMLElement>('[data-act="1"]')?.scrollIntoView({ block: 'nearest' })
useEffect(() => { if (open) queueMicrotask(scrollActive) }, [open, active])
useEffect(() => {
if (query) setActive(view.find((i) => !opts[i].disabled) ?? -1)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [query])
function commit(next: any[]) {
onChange(next)
if (open) queueMicrotask(scrollActive)
}
function toggleIndex(i: number) {
const o = opts[i]
if (!o || o.disabled) return
commit(isSelected(o.value) ? picked.filter((p) => !sameValue(p, o.value)) : [...picked, o.value])
}
function setInView(selected: boolean) {
const inView = view.map((i) => opts[i].value)
if (selected) {
const next = [...picked]
for (const v of inView) if (!picked.some((p) => sameValue(p, v))) next.push(v)
commit(next)
} else {
commit(picked.filter((p) => !inView.some((v) => sameValue(v, p))))
}
}
function toggle(force?: boolean) {
if (disabled) return
const next = force ?? !open
if (!next) { setQuery(''); setOpen(false); triggerRef.current?.focus({ preventScroll: true }); return }
setQuery('')
const first = view.findIndex((i) => isSelected(opts[i].value))
setActive(first >= 0 ? first : view.find((i) => !opts[i].disabled) ?? -1)
setOpen(true)
queueMicrotask(() => { if (searchable) searchRef.current?.focus({ preventScroll: true }); else triggerRef.current?.focus({ preventScroll: true }) })
}
function move(key: 'ArrowDown' | 'ArrowUp' | 'Home' | 'End') {
if (!view.length) return
let pos = view.indexOf(active)
const step = (delta: number) => {
for (let n = 0; n < view.length; n++) {
pos = (pos + delta + view.length) % view.length
if (!opts[view[pos]].disabled) return
}
}
if (key === 'ArrowDown') step(1)
else if (key === 'ArrowUp') step(-1)
else if (key === 'Home') pos = 0
else pos = view.length - 1
setActive(view[pos] ?? -1)
}
function onKeydown(e: React.KeyboardEvent) {
if ((e.target as HTMLElement | null)?.tagName === 'INPUT') return
if (e.key === 'Escape') { if (open) { e.preventDefault(); e.stopPropagation(); toggle(false) } return }
if (e.key === 'Tab') { setOpen(false); return }
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault()
if (!open) { toggle(true); return }
move(e.key)
return
}
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
if (open) { if (active >= 0) toggleIndex(active) } else toggle(true)
}
}
function onSearchKeydown(e: React.KeyboardEvent) {
if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) { e.preventDefault(); e.stopPropagation(); move(e.key as any) }
else if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); if (active >= 0) toggleIndex(active) }
else if (e.key === 'Escape') { e.stopPropagation(); toggle(false) }
}
return (
<span className={cn('relative inline-flex w-full min-w-0 align-middle', open && 'z-[401]', className)}>
<button ref={triggerRef} type="button" disabled={disabled} aria-label={ariaLabel || undefined}
aria-haspopup="listbox" aria-expanded={open}
aria-activedescendant={open && active >= 0 ? `${uid}-o${active}` : undefined}
className={triggerCls({ open, size, disabled })}
onClick={() => toggle()} onKeyDown={onKeydown}>
{!!count && (
<span className="flex-none min-w-[17px] h-[17px] px-[5px] rounded-pill grid place-items-center bg-accent-fill text-on-accent text-tiny font-bold leading-none">{count}</span>
)}
<span className={cn('flex-1 min-w-0 truncate whitespace-nowrap', !shown && 'text-faint')}>{shown || placeholder}</span>
<Caret open={open} />
</button>
{open && box && createPortal(
<div ref={popRef} role="listbox" aria-multiselectable aria-label={ariaLabel || undefined}
className={popCls}
style={{ left: box.left, top: box.top, width: box.width, maxHeight: box.maxH, transform: box.drop ? undefined : 'translateY(-100%)' }}
onMouseDown={(e) => e.stopPropagation()}
onKeyDown={onKeydown}>
<div className={filterBarCls}>
{searchable && (
<input ref={searchRef} type="search" value={query} placeholder="过滤选项…"
aria-label={`${ariaLabel || '选项'}:过滤`}
className="flex-1 min-w-0 h-auto py-[5px] px-2 text-caption rounded-[6px] border border-line-strong bg-field text-ink outline-none focus:border-accent-deep [&::-webkit-search-cancel-button]:appearance-none"
onChange={(e) => setQuery(e.target.value)} onKeyDown={onSearchKeydown} />
)}
<span className="flex-none text-tiny text-faint">{count ? `已选 ${count} 项` : '未选择'}</span>
<button type="button" className="flex-none p-[4px_7px] rounded-[6px] text-tiny border border-line-strong bg-hover text-ink-2 disabled:opacity-40 disabled:cursor-not-allowed hover:not-disabled:border-line-bright hover:not-disabled:text-ink"
disabled={!selectableInView} onClick={() => setInView(true)}>全选</button>
<button type="button" className="flex-none p-[4px_7px] rounded-[6px] text-tiny border border-line-strong bg-hover text-ink-2 disabled:opacity-40 disabled:cursor-not-allowed hover:not-disabled:border-line-bright hover:not-disabled:text-ink"
disabled={!count} onClick={() => setInView(false)}>清空</button>
</div>
<div ref={listRef} className={listCls}>
{view.map((i) => {
const o = opts[i]
const on = isSelected(o.value)
return (
<div key={`${o.value}-${i}`} id={`${uid}-o${i}`} role="option" aria-selected={on}
data-act={i === active ? '1' : '0'}
className={itemCls({ on, act: i === active, off: o.disabled, multi: true })}
onMouseEnter={() => setActive(i)}
onClick={() => toggleIndex(i)}>
<span className={cn('flex-none w-[14px] h-[14px] mt-px rounded-[4px] grid place-items-center border text-on-accent',
on ? 'bg-accent-fill border-accent-fill' : 'border-line-bright')}>
{on && <svg viewBox="0 0 12 12" className="w-[11px] h-[11px]"><path d="M2.6 6.3 4.9 8.6 9.4 3.7" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>}
</span>
<span className="min-w-0 break-anywhere">{o.label}</span>
</div>
)
})}
{!view.length && <div className={noneCls}>{opts.length ? '没有匹配的选项' : '无可选项'}</div>}
</div>
</div>, document.body)}
</span>
)
}