194 lines
8.5 KiB
TypeScript
194 lines
8.5 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, type SelectOption } from './options'
|
||
import { contentWidth, usePopup } from './use-popup'
|
||
import { filterBarCls, filterInputCls, itemCls, listCls, noneCls, popCls, tickCls, triggerCls } from './parts'
|
||
import { Caret } from './Caret'
|
||
|
||
/**
|
||
* 全站统一下拉控件(替代原生 <select> 的系统外观)。
|
||
*
|
||
* 可见部分是自绘触发器 + 挂到 body 的弹层:抽屉、表格、滚动容器都不会裁切它,
|
||
* 深浅主题一致。键盘(↑↓ Home End Enter Esc 首字母定位)与 ARIA 齐备;
|
||
* 选项超过阈值自动出现过滤框,否则长列表只能靠滚动条盲摸。
|
||
* 弹层宽度按最长选项量出来,既不裁字也不会比触发器还窄。
|
||
*/
|
||
export type SelectProps = {
|
||
value: any
|
||
onChange: (next: any) => void
|
||
options: OptionLike[] | null | undefined
|
||
disabled?: boolean
|
||
placeholder?: string
|
||
/** 选项超过该数量时自动显示过滤框(与 MultiSelect 一致) */
|
||
searchThreshold?: number
|
||
/** sm 用于表格行内/工具条,md 用于表单 */
|
||
size?: 'sm' | 'md'
|
||
ariaLabel?: string
|
||
className?: string
|
||
id?: string
|
||
name?: string
|
||
/** 禁用时要解释原因(「不能修改自己的角色」),否则灰掉的下拉只会让人反复点 */
|
||
title?: string
|
||
}
|
||
|
||
export function Select({
|
||
value, onChange, options, disabled, placeholder = '请选择', searchThreshold = 8,
|
||
size = 'md', ariaLabel, className, id, name, title
|
||
}: SelectProps) {
|
||
const opts = useMemo(() => toOptions(options), [options])
|
||
const uid = useId()
|
||
const { open, setOpen, triggerRef, popRef, box } = usePopup({
|
||
minW: 168, maxW: 420, listMinH: 190, maxHCap: 300,
|
||
contentW: useMemo(() => contentWidth(opts.map((o) => o.label), 44), [opts]),
|
||
disabled
|
||
})
|
||
const listRef = useRef<HTMLDivElement | null>(null)
|
||
const searchRef = useRef<HTMLInputElement | null>(null)
|
||
const [query, setQuery] = useState('')
|
||
const [active, setActive] = useState(-1)
|
||
|
||
const selIndex = useMemo(() => opts.findIndex((o) => sameValue(o.value, value)), [opts, value])
|
||
const shown = selIndex >= 0 ? opts[selIndex].label : ''
|
||
const view = useMemo(() => {
|
||
const q = query.trim().toLowerCase()
|
||
const all = opts.map((_, i) => i)
|
||
return q ? all.filter((i) => opts[i].label.toLowerCase().includes(q)) : all
|
||
}, [opts, query])
|
||
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 toggle(force?: boolean) {
|
||
if (disabled) return
|
||
const next = force ?? !open
|
||
if (!next) { setQuery(''); setOpen(false); triggerRef.current?.focus({ preventScroll: true }); return }
|
||
setQuery('')
|
||
setActive(selIndex >= 0 ? selIndex : opts.findIndex((o) => !o.disabled))
|
||
setOpen(true)
|
||
queueMicrotask(() => { if (searchable) searchRef.current?.focus({ preventScroll: true }); else triggerRef.current?.focus({ preventScroll: true }) })
|
||
}
|
||
|
||
function choose(i: number) {
|
||
const o = opts[i]
|
||
if (!o || o.disabled) return
|
||
onChange(o.value)
|
||
setOpen(false)
|
||
setQuery('')
|
||
triggerRef.current?.focus({ preventScroll: true })
|
||
}
|
||
|
||
function move(delta: number) {
|
||
if (!opts.length) return
|
||
if (!open) { toggle(true); return }
|
||
if (!view.length) return
|
||
let pos = Math.max(0, view.indexOf(active))
|
||
for (let n = 0; n < view.length; n++) {
|
||
pos = (pos + delta + view.length) % view.length
|
||
if (!opts[view[pos]].disabled) break
|
||
}
|
||
setActive(view[pos])
|
||
}
|
||
|
||
let typeBuf = ''
|
||
let typeTimer = 0
|
||
function typeAhead(ch: string) {
|
||
typeBuf += ch.toLowerCase()
|
||
window.clearTimeout(typeTimer)
|
||
typeTimer = window.setTimeout(() => { typeBuf = '' }, 420)
|
||
const hit = view.find((i) => opts[i].label.toLowerCase().startsWith(typeBuf))
|
||
if (hit !== undefined) setActive(hit)
|
||
}
|
||
|
||
function onKeydown(e: React.KeyboardEvent) {
|
||
if ((e.target as HTMLElement | null)?.tagName === 'INPUT') return
|
||
if (e.key === 'Escape') { if (open) { e.preventDefault(); e.stopPropagation(); setOpen(false) } return }
|
||
if (e.key === 'Tab') { setOpen(false); return }
|
||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); move(e.key === 'ArrowDown' ? 1 : -1); return }
|
||
if (e.key === 'Home' || e.key === 'End') {
|
||
if (!open) return
|
||
e.preventDefault()
|
||
const order = e.key === 'Home' ? view : [...view].reverse()
|
||
setActive(order.find((i) => !opts[i].disabled) ?? view[0] ?? -1)
|
||
return
|
||
}
|
||
if (e.key === 'Enter' || e.key === ' ') {
|
||
e.preventDefault()
|
||
if (open) choose(active)
|
||
else toggle(true)
|
||
return
|
||
}
|
||
if (e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey) {
|
||
if (!open) { toggle(true); return }
|
||
typeAhead(e.key)
|
||
}
|
||
}
|
||
|
||
function onSearchKeydown(e: React.KeyboardEvent) {
|
||
// 过滤框自己消化这些键,否则冒泡到弹层会二次执行(方向键走两格、回车来回切换)
|
||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); e.stopPropagation(); move(e.key === 'ArrowDown' ? 1 : -1) }
|
||
else if (e.key === 'Home' || e.key === 'End') { e.stopPropagation() }
|
||
else if (e.key === 'Enter') {
|
||
if (active >= 0) { e.preventDefault(); e.stopPropagation(); choose(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" id={id} disabled={disabled} aria-label={ariaLabel || undefined}
|
||
title={title} aria-haspopup="listbox" aria-expanded={open} data-name={name}
|
||
aria-activedescendant={open && active >= 0 ? `${uid}-o${active}` : undefined}
|
||
className={triggerCls({ open, size, disabled })}
|
||
onClick={() => toggle()} onKeyDown={onKeydown}>
|
||
<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-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}>
|
||
{searchable && (
|
||
<div className={filterBarCls}>
|
||
<input ref={searchRef} type="search" value={query} className={filterInputCls} placeholder="过滤选项…"
|
||
aria-label={`${ariaLabel || '选项'}:过滤`}
|
||
onChange={(e) => setQuery(e.target.value)} onKeyDown={onSearchKeydown} />
|
||
<span className="flex-none text-tiny text-faint whitespace-nowrap">
|
||
{view.length === opts.length ? `${opts.length} 项` : `${view.length} / ${opts.length} 项`}
|
||
</span>
|
||
</div>
|
||
)}
|
||
<div ref={listRef} className={listCls}>
|
||
{view.map((i) => {
|
||
const o: SelectOption = opts[i]
|
||
return (
|
||
<div key={`${o.value}-${i}`} id={`${uid}-o${i}`} role="option" aria-selected={sameValue(o.value, value)}
|
||
data-act={i === active ? '1' : '0'}
|
||
className={itemCls({ on: sameValue(o.value, value), act: i === active, off: o.disabled })}
|
||
onMouseEnter={() => setActive(i)}
|
||
onClick={() => choose(i)}>
|
||
<span className={tickCls} style={{ opacity: sameValue(o.value, value) ? 1 : 0 }} aria-hidden>✓</span>
|
||
<span className="min-w-0 break-anywhere">{o.label}</span>
|
||
</div>
|
||
)
|
||
})}
|
||
{!opts.length && <div className={noneCls}>无可选项</div>}
|
||
{!!opts.length && !view.length && <div className={noneCls}>没有匹配的选项</div>}
|
||
</div>
|
||
</div>, document.body)}
|
||
</span>
|
||
)
|
||
}
|
||
|
||
/** 常用出口:把字典/枚举直接转成 options */
|
||
export { toOptions, sameValue, summaryOf }
|
||
export type { SelectOption }
|