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

159 lines
6.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import { useEffect, useId, useMemo, useRef, useState } from 'react'
import { cn } from '../../lib/cn'
import { Popup, barLayer, emptyLayer, itemCls, listLayer, panelInputLayer, tickSlotLayer, triggerCls, useListbox } from '../primitives'
import { sameValue, summaryOf, toOptions, type OptionLike, type SelectOption } from './options'
import { Caret } from './Caret'
/**
* 全站统一下拉控件(替代原生 <select> 的系统外观)。
*
* 分工:浮层行为在 primitives/Popup(Radix Popover:portal / 跟随锚点 / 翻边 / 外点关闭 / Esc),
* 键盘语义在 primitives/use-listbox,皮肤在 primitives/layers,这里只管「选中谁、怎么选」。
* 页面侧 87 处调用的 props 一个都没动。
*
* 选项超过阈值自动出现过滤框,否则长列表只能靠滚动条盲摸;
* 面板宽度取「至少和触发器一样宽」,不再固定 168px 压住右边的字段标题。
*/
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 listId = `${uid}-list`
const boxRef = useRef<HTMLSpanElement | null>(null)
const triggerRef = useRef<HTMLButtonElement | null>(null)
const searchRef = useRef<HTMLInputElement | null>(null)
const [open, setOpen] = useState(false)
const [query, setQuery] = useState('')
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 lb = useListbox({
view,
isDisabled: (i) => !!opts[i]?.disabled,
labelOf: (i) => opts[i]?.label ?? '',
open,
onPick: chooseIndex,
onOpen: openList,
onClose: closeList,
initialActive: () => (selIndex >= 0 ? selIndex : opts.findIndex((o) => !o.disabled))
})
// 只盯 query:opts/view 每次渲染都是新引用,列进依赖会把高亮反复重置回第一行
useEffect(() => {
if (query) lb.setActive(view.find((i) => !opts[i]?.disabled) ?? -1)
}, [query])
// 面板出现后把焦点交给过滤框(没有过滤框就留在触发器上,键盘不断)
useEffect(() => {
if (!open) return
;(searchable ? searchRef : triggerRef).current?.focus({ preventScroll: true })
}, [open, searchable])
function openList() {
if (disabled) return
setQuery('')
setOpen(true)
lb.prime()
}
/** refocus=false:外点到页面上的别的控件时,别把焦点抢回来,否则点不动下一个字段 */
function closeList(refocus = true) {
setQuery('')
setOpen(false)
if (refocus) triggerRef.current?.focus({ preventScroll: true })
}
function chooseIndex(i: number) {
const o = opts[i]
if (!o || o.disabled) return
onChange(o.value)
setQuery('')
setOpen(false)
triggerRef.current?.focus({ preventScroll: true })
}
const optId = (i: number) => `${uid}-o${i}`
return (
<Popup open={open} onOpenChange={(next) => (next ? openList() : closeList(false))}
anchorRef={boxRef} label={ariaLabel || undefined} onKeyDown={lb.onKeyDown}
anchor={
<span ref={boxRef} className={cn('relative inline-flex w-full min-w-0 align-middle', open && 'z-[401]', className)}>
<button ref={triggerRef} type="button" id={id} role="combobox" disabled={disabled}
aria-label={ariaLabel || undefined} title={title}
aria-haspopup="listbox" aria-expanded={open}
aria-controls={open ? listId : undefined}
aria-activedescendant={open && lb.active >= 0 ? optId(lb.active) : undefined}
data-name={name}
className={triggerCls({ size, open })}
onClick={() => (open ? closeList() : openList())} onKeyDown={lb.onKeyDown}>
<span className={cn('flex-1 min-w-0 truncate whitespace-nowrap', !shown && 'text-faint')}>{shown || placeholder}</span>
<Caret open={open} />
</button>
</span>
}>
{searchable && (
<div className={barLayer}>
<input ref={searchRef} type="search" value={query} className={panelInputLayer} placeholder="过滤选项…"
aria-label={`${ariaLabel || '选项'}:过滤`}
onChange={(e) => setQuery(e.target.value)} onKeyDown={lb.onInputKeyDown} />
<span className="flex-none text-tiny text-faint whitespace-nowrap">
{view.length === opts.length ? `${opts.length} 项` : `${view.length} / ${opts.length} 项`}
</span>
</div>
)}
<div ref={lb.listRef} id={listId} role="listbox" aria-label={ariaLabel || undefined} className={listLayer}>
{view.map((i) => {
const o: SelectOption = opts[i]
const on = sameValue(o.value, value)
return (
<div key={`${o.value}-${i}`} id={optId(i)} role="option" aria-selected={on}
data-active={i === lb.active ? '1' : undefined}
data-on={on ? '1' : undefined}
data-off={o.disabled ? '1' : undefined}
className={itemCls({ mode: 'single' })}
onMouseEnter={() => { if (!o.disabled) lb.setActive(i) }}
onClick={() => chooseIndex(i)}>
<span className={tickSlotLayer} style={{ opacity: on ? 1 : 0 }} aria-hidden>✓</span>
<span className="min-w-0 break-anywhere">{o.label}</span>
</div>
)
})}
{!opts.length && <div className={emptyLayer}>无可选项</div>}
{!!opts.length && !view.length && <div className={emptyLayer}>没有匹配的选项</div>}
</div>
</Popup>
)
}
/** 常用出口:把字典/枚举直接转成 options */
export { toOptions, sameValue, summaryOf }
export type { SelectOption }