unis-oa/frontend/src/components/common/Select.vue

968 lines
35 KiB
Vue
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.

<template>
<div class="relative min-w-0" ref="containerRef">
<button
ref="triggerRef"
type="button"
@click="toggle"
:disabled="disabled"
:aria-expanded="isOpen"
:aria-haspopup="true"
:id="id"
:aria-label="ariaLabel ?? 'Select option'"
:aria-describedby="ariaDescribedby"
:class="[
// 这只盒子的样子在 style.css 的 .field-trigger:跟弹出框选择器共用一份,别各写各的
'field-trigger',
// cell-control 只是让「格子里的控件」这一个口径在样式和测试里都数得着,尺寸以上面那条为准
compact && 'cell-control field-trigger-compact',
isOpen && 'field-trigger-open',
error && 'field-trigger-error',
disabled && 'field-trigger-disabled'
]"
@keydown.down.prevent="onTriggerKeyDown"
@keydown.up.prevent="onTriggerKeyDown"
>
<span class="select-value" :class="multiple ? ['select-value-tags', compact && 'select-value-tight'] : ''">
<!-- 多选:已选的挂在框里,一颗一颗摘;格子太窄时多出来的收进「+N」,不把整行顶高 -->
<template v-if="multiple">
<span v-for="chip in visibleChips" :key="chipKey(chip.value)" class="field-tag select-chip">
<span
v-if="chip.href"
role="link"
tabindex="0"
class="select-chip-label select-chip-link"
:title="linkTitle || chip.label"
data-test="select-chip-link"
@click.stop="openChip(chip.href)"
@mousedown.stop
@keydown.enter.stop.prevent="openChip(chip.href)"
>
{{ chip.label }}
</span>
<span v-else class="select-chip-label">{{ chip.label }}</span>
<span
role="button"
tabindex="-1"
class="select-chip-x"
:aria-label="t('common.delete')"
@click.stop="removeChip(chip.value)"
@mousedown.stop
@keydown.enter.stop.prevent="removeChip(chip.value)"
>
<Icon name="x" class="h-3 w-3" />
</span>
</span>
<span v-if="hiddenCount" class="select-chip-more" :title="t('form.selectMoreHidden', { count: hiddenCount })">
+{{ hiddenCount }}
</span>
<span v-if="!chips.length" class="select-placeholder">{{ placeholderText }}</span>
</template>
<slot v-else name="selected" :option="selectedOption">
{{ selectedLabel }}
</slot>
</span>
<span
v-if="clearable && hasValue && !disabled"
class="select-clear"
role="button"
tabindex="-1"
aria-label="Clear selection"
@click.stop="clearSelection"
@mousedown.stop
@keydown.enter.stop.prevent="clearSelection"
>
<Icon name="x" size="sm" />
</span>
<span class="select-icon">
<Icon
name="chevronDown"
size="md"
:class="['transition-transform duration-200', isOpen && 'rotate-180']"
/>
</span>
</button>
<!-- Teleport dropdown to body to escape stacking context -->
<Teleport to="body">
<Transition name="select-dropdown">
<div
v-if="isOpen"
ref="dropdownRef"
class="select-dropdown-portal"
:class="[instanceId]"
:style="dropdownStyle"
role="listbox"
@click.stop
@mousedown.stop
@keydown="onDropdownKeyDown"
>
<!-- Search input -->
<div v-if="isSearchable" class="select-search">
<Icon name="search" size="sm" class="text-gray-400" />
<input
ref="searchInputRef"
v-model="searchQuery"
type="text"
:placeholder="searchPlaceholderText"
:aria-label="searchPlaceholderText"
class="select-search-input"
@click.stop
@keydown.backspace="onSearchBackspace"
/>
</div>
<!-- Options list -->
<div class="select-options" ref="optionsListRef" :style="optionsListStyle">
<div
v-for="(option, index) in filteredOptions"
:key="`${typeof getOptionValue(option)}:${String(getOptionValue(option) ?? '')}`"
role="option"
:aria-selected="isSelected(option)"
:aria-disabled="isOptionDisabled(option)"
@click.stop="!isOptionDisabled(option) && selectOption(option)"
@mouseenter="handleOptionMouseEnter(option, index)"
:class="[
'select-option',
treeLevel(option) > 0 && 'select-option-tree',
isTreeRoot(option) && 'select-option-tree-root',
isGroupHeaderOption(option) && 'select-option-group',
isSelected(option) && 'select-option-selected',
isOptionDisabled(option) && !isGroupHeaderOption(option) && 'select-option-disabled',
focusedIndex === index && !isGroupHeaderOption(option) && 'select-option-focused'
]"
:style="optionIndentStyle(option)"
>
<!-- 层级引导线:同一父部门的子部门排在一起,这条线就是连着的 -->
<span
v-if="treeLevel(option) > 0"
class="select-option-rail"
:style="optionRailStyle(option)"
aria-hidden="true"
></span>
<!-- 多选:行首一颗勾,一眼看出哪几项已经勾上;末尾那个对勾留给单选 -->
<span
v-if="multiple"
class="select-option-check"
:class="isSelected(option) && 'select-option-check-on'"
aria-hidden="true"
>
<Icon v-if="isSelected(option)" name="check" size="sm" :stroke-width="3" />
</span>
<slot name="option" :option="option" :selected="isSelected(option)">
<Icon
v-if="option._creatable"
name="search"
size="sm"
class="flex-shrink-0 text-gray-400"
/>
<span class="select-option-label" :class="option._creatable && 'italic text-gray-500 dark:text-dark-300'">{{ getOptionLabel(option) }}</span>
<!-- 搜索把父部门筛掉之后,只剩一个科室名读不出是谁家的,这里补一段父路径 -->
<span v-if="option.description && searchQuery" class="select-option-note">{{ option.description }}</span>
<Icon
v-if="isSelected(option) && !multiple"
name="check"
size="sm"
class="text-primary-500"
:stroke-width="2"
/>
</slot>
</div>
<!-- Empty state -->
<div v-if="filteredOptions.length === 0" class="select-empty">
{{ props.loading ? t('common.loading') : emptyTextDisplay }}
</div>
</div>
</div>
</Transition>
</Teleport>
</div>
</template>
<!-- 泛型组件里不许 export(整段 setup 会嵌进泛型函数里),候选项这一份类型挪去普通 script 块,
调用方 import 的写法一个字节都不用改。 -->
<script lang="ts">
export interface SelectOption {
value: string | number | boolean | null
label: string
disabled?: boolean
[key: string]: unknown
}
</script>
<script setup lang="ts" generic="T extends string | number | boolean | null | (string | number | boolean)[]">
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import Icon from '@/components/icons/Icon.vue'
const { t } = useI18n()
// Instance ID for unique click-outside detection
const instanceId = `select-${Math.random().toString(36).substring(2, 9)}`
/** 框里一个值的类型:`multiple` 那一档存的是它的一串。 */
type Scalar = string | number | boolean | null
const props = withDefaults(
defineProps<{
/**
* 选中的值。泛型 `T` 就是它此刻的形状——单选取标量,多选(`multiple`)取一串,
* 回抛的 `update:modelValue` 跟着同一个 `T` 走,两头都不必再 `as` 一次。
*/
modelValue?: T
options: SelectOption[] | Array<Record<string, unknown>>
placeholder?: string
disabled?: boolean
error?: boolean
searchable?: boolean | 'auto'
searchPlaceholder?: string
emptyText?: string
valueKey?: string
labelKey?: string
creatable?: boolean
creatablePrefix?: string
clearable?: boolean
id?: string
ariaLabel?: string
ariaDescribedby?: string
/** 远程搜索模式:输入不在本地过滤 options,而是防抖后 emit('search', query),由父组件请求数据更新 options */
remote?: boolean
/** 明细表格子里用:跟同排输入框等高,圆角也收一档 */
compact?: boolean
/** 远程搜索模式下的加载态:options 为空时下拉显示 loading 文案 */
loading?: boolean
/** 可以挑好几个:行首一颗勾,勾完不关弹层,已选的挂在框里、一颗一颗摘 */
multiple?: boolean
/**
* `options` 之外还报得出名字的那几项。
*
* 远程来源手上永远只有搜出来的这一页,多选又允许人跨着页挑:已选的那几条
* 早就不在候选里了,框里还得念出它叫什么,不能空着一个编码让人以为没选上。
*/
known?: SelectOption[]
/**
* 候选带了 `href`(关联单据那一类)时,框里标签上悬停说的那句话。
*
* 不给就用名字本身当提示——标签会截断,全名总得看得见。
*/
linkTitle?: string
}>(),
{
disabled: false,
error: false,
searchable: 'auto',
creatable: false,
creatablePrefix: '',
clearable: false,
valueKey: 'value',
labelKey: 'label',
compact: false,
remote: false,
loading: false,
multiple: false,
known: () => [],
linkTitle: ''
}
)
const emit = defineEmits<{
(e: 'update:modelValue', value: T): void
(e: 'change', value: T, option: SelectOption | null): void
(e: 'search', query: string): void
}>()
const isOpen = ref(false)
const searchQuery = ref('')
const focusedIndex = ref(-1)
const containerRef = ref<HTMLElement | null>(null)
const triggerRef = ref<HTMLButtonElement | null>(null)
const searchInputRef = ref<HTMLInputElement | null>(null)
const dropdownRef = ref<HTMLElement | null>(null)
const optionsListRef = ref<HTMLElement | null>(null)
const dropdownPosition = ref<'bottom' | 'top'>('bottom')
const triggerRect = ref<DOMRect | null>(null)
const dropdownViewportPadding = 8
const dropdownMinimumWidth = 200
/** 弹层与触发器之间的缝,以及 CSS ``max-h-80`` 那份选项区高度、搜索框占掉的高度。 */
const dropdownGap = 4
const dropdownListHeight = 320
const dropdownSearchHeight = 44
/** 弹层真实宽度:打开后量一次,用来把弹层整体拉回可视区(见 ``placeDropdown``)。 */
const popupWidth = ref(0)
/** 上下都塞不下时才收的选项区高度;0 表示用 CSS 那份 ``max-h-80``。 */
const listMaxHeight = ref(0)
// i18n placeholders
const placeholderText = computed(() => props.placeholder ?? t('common.selectOption'))
const searchPlaceholderText = computed(() => props.searchPlaceholder ?? t('common.searchPlaceholder'))
const emptyTextDisplay = computed(() => props.emptyText ?? t('common.noOptionsFound'))
// 远程搜索的防抖间隔(对齐 OpenAIFastPolicyUserSelector 的 300ms 惯例)。
const REMOTE_SEARCH_DEBOUNCE_MS = 300
let remoteSearchTimer: ReturnType<typeof setTimeout> | null = null
const isSearchable = computed(() => {
// 远程搜索模式始终显示搜索框(选项只是服务端结果的一页)。
if (props.remote) return true
if (props.searchable === 'auto') return props.options.length > 5
return props.searchable
})
/**
* Computed style for teleported dropdown.
*
* 窄侧栏里的下拉最容易撞上的一件事:弹层只肯往触发器右边长,右边放不下就拿宽度去换,
* 选项全称被截成「日期时…」(明细列那种「一列宽」的类型下拉天天撞上)。这里的口径反过来:
* 宽度按「触发器」与「内容」里更宽的那个给足,右侧放不下就整体左移、贴着可视区右边对齐,
* 只有窗口本身比弹层还窄时才收宽度。
*/
const dropdownStyle = computed(() => {
if (!triggerRect.value) return {}
const rect = triggerRect.value
const usableWidth = Math.max(
dropdownMinimumWidth,
window.innerWidth - dropdownViewportPadding * 2
)
const width = Math.min(
Math.max(dropdownMinimumWidth, rect.width, popupWidth.value),
usableWidth
)
const left = Math.max(
dropdownViewportPadding,
Math.min(rect.left, window.innerWidth - dropdownViewportPadding - width)
)
const style: Record<string, string> = {
position: 'fixed',
left: `${left}px`,
minWidth: `${width}px`,
maxWidth: `${usableWidth}px`,
zIndex: '100000020'
}
if (dropdownPosition.value === 'top') {
style.bottom = `${window.innerHeight - rect.top + dropdownGap}px`
} else {
style.top = `${rect.bottom + dropdownGap}px`
}
return style
})
/** 上下都不够高时把选项区收进可视区里自己滚,别让弹层下半截跑到屏幕外。 */
const optionsListStyle = computed(() =>
listMaxHeight.value ? { maxHeight: `${listMaxHeight.value}px` } : undefined
)
const getOptionValue = (option: any): any => {
if (typeof option === 'object' && option !== null) {
return option[props.valueKey]
}
return option
}
const getOptionLabel = (option: any): string => {
if (typeof option === 'object' && option !== null) {
return String(option[props.labelKey] ?? '')
}
return String(option ?? '')
}
const isOptionDisabled = (option: any): boolean => {
if (typeof option === 'object' && option !== null) {
return !!option.disabled
}
return false
}
/**
* 组织树这类有层级的候选项(目前就是表单「部门选择」)的缩进口径:
* 候选项带数字 level 才生效,别的下拉取不到这个字段,排版一律不变。
* 缩进走 padding,不塞进 label——label 还要给选中态、只读回显和搜索用。
*/
const TREE_BASE = 16
const TREE_STEP = 16
// 再深的树也不该把文字顶到面板外,缩进封个顶。
const TREE_MAX_LEVEL = 8
const treeLevel = (option: any): number => {
const raw = typeof option === 'object' && option !== null ? option.level : undefined
if (typeof raw !== 'number' || !Number.isFinite(raw) || raw <= 0) return 0
return Math.min(Math.trunc(raw), TREE_MAX_LEVEL)
}
/** 这一份候选是有层级的树吗(只有部门选择带 level)。根部门加粗一点,一眼能看出枝干在哪。 */
const hasTreeOptions = computed(() =>
(props.options as any[]).some((option) => option && typeof option.level === 'number')
)
// 只给「明确声明自己是根」的行加粗:混排时那条「(无)」不该跟着变粗
const isTreeRoot = (option: any): boolean =>
hasTreeOptions.value && typeof option === 'object' && option !== null && option.level === 0
const optionIndentStyle = (option: any) => {
const level = treeLevel(option)
return level ? { paddingLeft: `${TREE_BASE + level * TREE_STEP}px` } : undefined
}
// 引导线落在父部门文字的起笔处,连续的同级行会把它连成一条竖线
const optionRailStyle = (option: any) => {
const level = treeLevel(option)
return level ? { left: `${TREE_BASE + (level - 1) * TREE_STEP + 4}px` } : undefined
}
const isGroupHeaderOption = (option: any): boolean => {
if (typeof option === 'object' && option !== null) {
return option.kind === 'group'
}
return false
}
/**
* 值比对口径:按字符串比。
*
* 候选的值现在可能来自「这一格选中的那一列」(见 utils/optionMap),列取出来一律是字符串,
* 而老表单里存着的值可能是数字 5。按 === 比就会出现「明明选中了却显示未选择」,
* 这里一律收成字符串;选中时仍然把候选自己那份原值发出去。
*/
const sameValue = (left: unknown, right: unknown): boolean => {
if (left === right) return true
if (left === null || left === undefined || right === null || right === undefined) return false
return String(left) === String(right)
}
/**
* 值 → 名字:先认候选,再认调用方补上的那几项。
*
* 远程来源手上只有搜出来的这一页,多选又允许人跨页挑——已选项早就不在候选里了,
* 框里那句名字只能从 `known` 里取;两处都没有才退回值本身(念个编码也比空着强)。
*/
const labelIndex = computed(() => {
const index = new Map<string, string>()
;[...(props.known ?? []), ...(props.options as any[])].forEach((option) => {
if (option === null || option === undefined) return
index.set(String(getOptionValue(option) ?? ''), getOptionLabel(option))
})
return index
})
const labelOf = (value: Scalar): string => labelIndex.value.get(String(value ?? '')) ?? String(value ?? '')
/** 值 → 点得开的那个地址:只有调用方在候选上写了 `href` 的这几项有(关联单据那一类)。 */
const hrefIndex = computed(() => {
const index = new Map<string, string>()
;[...(props.known ?? []), ...(props.options as any[])].forEach((option) => {
if (option === null || option === undefined) return
const href = String((option as any).href ?? '')
if (href) index.set(String(getOptionValue(option) ?? ''), href)
})
return index
})
/** 框里此刻有哪几项(多选那一串;单选那一格不参与,别拿一个值冒充一串)。 */
const selectedValues = computed<Scalar[]>(() => {
if (!props.multiple) return []
const raw = props.modelValue as Scalar | Scalar[] | null | undefined
if (Array.isArray(raw)) return raw.filter((item) => item !== null && item !== undefined) as Scalar[]
return raw === null || raw === undefined || raw === '' ? [] : [raw]
})
const chips = computed(() =>
selectedValues.value.map((value) => ({
value,
label: labelOf(value),
href: hrefIndex.value.get(String(value ?? '')) ?? ''
}))
)
/** 点开框里那颗标签指向的那张单:新标签页,手上这张不丢。 */
function openChip(href: string) {
if (props.disabled || !href) return
window.open(href, '_blank', 'noopener')
}
/** 明细格子里只留得下一颗标签的位置,多出来的收进「+N」;正常格子摊得开,就不收。 */
const COMPACT_TAG_LIMIT = 1
const visibleChips = computed(() =>
props.compact ? chips.value.slice(0, COMPACT_TAG_LIMIT) : chips.value
)
const hiddenCount = computed(() => chips.value.length - visibleChips.value.length)
const chipKey = (value: Scalar) => `${typeof value}:${String(value ?? '')}`
/** 摘掉框里的一颗标签:与在弹层里再点一次同一件事,只是手伸得更近。 */
function removeChip(value: Scalar) {
if (props.disabled) return
const next = selectedValues.value.filter((item) => !sameValue(item, value))
emit('update:modelValue', next as unknown as T)
emit('change', next as unknown as T, null)
}
/** 搜索框里没敲字时按一下退格:摘掉最后一颗标签,这是多选控件的老习惯。 */
function onSearchBackspace() {
if (!props.multiple || searchQuery.value) return
const last = selectedValues.value[selectedValues.value.length - 1]
if (last !== undefined) removeChip(last)
}
const selectedOption = computed(() => {
const pool = [...(props.known ?? []), ...(props.options as any[])]
return pool.find((opt) => sameValue(getOptionValue(opt), props.modelValue)) || null
})
const selectedLabel = computed(() => {
if (props.multiple) return placeholderText.value
if (selectedOption.value) {
return getOptionLabel(selectedOption.value)
}
// In creatable mode, show the raw value if no matching option
if (props.creatable && props.modelValue) {
return String(props.modelValue)
}
return placeholderText.value
})
const hasValue = computed(() =>
props.multiple
? selectedValues.value.length > 0
: props.modelValue !== null && props.modelValue !== undefined && props.modelValue !== ''
)
const filteredOptions = computed(() => {
let opts = props.options as any[]
// 远程搜索模式不在本地过滤(选项即服务端搜索结果的一页)。
if (isSearchable.value && searchQuery.value && !props.remote) {
const query = searchQuery.value.toLowerCase()
opts = opts.filter((opt) => {
// Match label
if (getOptionLabel(opt).toLowerCase().includes(query)) return true
// Also match description if present
if (opt.description && String(opt.description).toLowerCase().includes(query)) return true
return false
})
// In creatable mode, always prepend a fuzzy search option
if (props.creatable && searchQuery.value.trim()) {
const trimmed = searchQuery.value.trim()
const prefix = props.creatablePrefix || t('common.search')
opts = [{ [props.valueKey]: trimmed, [props.labelKey]: `${prefix} "${trimmed}"`, _creatable: true }, ...opts]
}
}
return opts
})
const isSelected = (option: any): boolean => {
const value = getOptionValue(option)
if (props.multiple) return selectedValues.value.some((item) => sameValue(item, value))
return sameValue(value, props.modelValue)
}
const findNextEnabledIndex = (startIndex: number): number => {
const opts = filteredOptions.value
if (opts.length === 0) return -1
for (let offset = 0; offset < opts.length; offset++) {
const idx = (startIndex + offset) % opts.length
if (!isOptionDisabled(opts[idx])) return idx
}
return -1
}
const findPrevEnabledIndex = (startIndex: number): number => {
const opts = filteredOptions.value
if (opts.length === 0) return -1
for (let offset = 0; offset < opts.length; offset++) {
const idx = (startIndex - offset + opts.length) % opts.length
if (!isOptionDisabled(opts[idx])) return idx
}
return -1
}
const handleOptionMouseEnter = (option: any, index: number) => {
if (isOptionDisabled(option) || isGroupHeaderOption(option)) return
focusedIndex.value = index
}
// Update trigger rect periodically while open to follow scroll/resize
const updateTriggerRect = () => {
if (containerRef.value) {
triggerRect.value = containerRef.value.getBoundingClientRect()
}
}
/**
* 量完真实尺寸再摆:宽度按内容给(CSS ``w-max`` 撑出来的 ``offsetWidth``,量到才写回
* ``left``,所以第一次画是按触发器左边缘),上下哪边空得多就朝哪边开,两边都不够时
* 把选项区收进可视区里自己滚。算高度用的是 ``scrollHeight``(内容自然高,不受
* ``max-height`` 影响),窗口一边 resize 也不会在这两个口径之间来回跳。
*/
const placeDropdown = () => {
if (!containerRef.value) return
updateTriggerRect()
nextTick(() => {
const dropdown = dropdownRef.value
const rect = triggerRect.value
if (!dropdown || !rect) return
const width = dropdown.offsetWidth
if (width && Math.abs(width - popupWidth.value) > 1) popupWidth.value = width
const chrome = (isSearchable.value ? dropdownSearchHeight : 0) + 8
const naturalList = Math.min(optionsListRef.value?.scrollHeight || dropdownListHeight, dropdownListHeight)
const needed = naturalList + chrome
const spaceBelow = window.innerHeight - rect.bottom - dropdownGap
const spaceAbove = rect.top - dropdownGap
const flipUp = spaceBelow < needed && spaceAbove > spaceBelow
dropdownPosition.value = flipUp ? 'top' : 'bottom'
const fit = (flipUp ? spaceAbove : spaceBelow) - chrome
listMaxHeight.value = fit >= naturalList ? 0 : Math.max(120, Math.min(naturalList, fit))
})
}
/** 打开时先滚到选中那一项:二十来类的类型下拉里,要看的那一项常在没露出来的半截里。 */
const scrollToSelected = () => {
nextTick(() => {
const list = optionsListRef.value
if (!list) return
const index = filteredOptions.value.findIndex(isSelected)
if (index < 0) return
const item = list.children[index] as HTMLElement | undefined
if (!item) return
const top = item.offsetTop
if (top >= list.scrollTop && top + item.offsetHeight <= list.scrollTop + list.clientHeight) return
list.scrollTop = Math.max(0, top - list.clientHeight / 2 + item.offsetHeight / 2)
})
}
const toggle = () => {
if (props.disabled) return
isOpen.value = !isOpen.value
}
watch(isOpen, (open) => {
if (open) {
// 每次打开重新量:选项、面板宽度都可能跟上次不一样,留着旧尺寸会摆歪。
popupWidth.value = 0
listMaxHeight.value = 0
placeDropdown()
scrollToSelected()
// Reset focused index to current selection or first item
if (filteredOptions.value.length === 0) {
focusedIndex.value = -1
} else {
const selectedIdx = filteredOptions.value.findIndex(isSelected)
const initialIdx = selectedIdx >= 0 ? selectedIdx : 0
focusedIndex.value = isOptionDisabled(filteredOptions.value[initialIdx])
? findNextEnabledIndex(initialIdx + 1)
: initialIdx
}
if (isSearchable.value) {
nextTick(() => searchInputRef.value?.focus())
}
// Add scroll listener to update position
window.addEventListener('scroll', updateTriggerRect, { capture: true, passive: true })
window.addEventListener('resize', placeDropdown)
} else {
searchQuery.value = ''
focusedIndex.value = -1
// 关闭时取消仍在排队的远程搜索(避免关闭后尾随 emit 一次 search(''))。
if (remoteSearchTimer) {
clearTimeout(remoteSearchTimer)
remoteSearchTimer = null
}
window.removeEventListener('scroll', updateTriggerRect, { capture: true })
window.removeEventListener('resize', placeDropdown)
}
})
// 筛过一轮之后选项少了一半,宽高都可能是另一回事:重新量一次再摆。
watch(searchQuery, () => {
if (!isOpen.value) return
placeDropdown()
// 筛过一轮之后原来那格焦点已经不算数了:回到第一条可选项。
// 留着不动的话,敲完一句话按回车,选中的是筛完排在老位置的那一项;
// creatable 那档第一条就是「用刚敲的这句」,回车正好落下要的东西。
focusedIndex.value = findNextEnabledIndex(0)
scrollToFocused()
})
// 远程搜索:输入防抖后交给父组件请求(!isOpen 抑制关闭重置 searchQuery 触发的空 query)。
watch(searchQuery, (query) => {
if (!props.remote || !isOpen.value) return
if (remoteSearchTimer) clearTimeout(remoteSearchTimer)
remoteSearchTimer = setTimeout(() => {
remoteSearchTimer = null
emit('search', query.trim())
}, REMOTE_SEARCH_DEBOUNCE_MS)
})
const selectOption = (option: any) => {
const value = getOptionValue(option) ?? null
if (props.multiple) {
// 再点一次就是取消勾选。连着挑三项是常态,所以勾完不关弹层、搜索词也留着,
// 否则每勾一项都要重新点开重新敲一遍,多选反倒比单选取舍更费手。
const next = isSelected(option)
? selectedValues.value.filter((item) => !sameValue(item, value))
: [...selectedValues.value, value]
emit('update:modelValue', next as unknown as T)
emit('change', next as unknown as T, option)
return
}
emit('update:modelValue', value as unknown as T)
emit('change', value as unknown as T, option)
isOpen.value = false
triggerRef.value?.focus()
}
const clearSelection = () => {
if (props.disabled) return
const empty = (props.multiple ? [] : null) as unknown as T
emit('update:modelValue', empty)
emit('change', empty, null)
}
/**
* 给表格用:加完一行想把光标送进这一格的下拉。调用方手上只有组件本身,
* 而真正该拿到焦点的是里面那只触发按钮(弹层里那行搜索框要打开之后才存在)。
*/
defineExpose({ focus: () => triggerRef.value?.focus() })
// Keyboards
const onTriggerKeyDown = () => {
if (!isOpen.value) {
isOpen.value = true
}
}
const onDropdownKeyDown = (e: KeyboardEvent) => {
switch (e.key) {
case 'ArrowDown':
e.preventDefault()
focusedIndex.value = findNextEnabledIndex(focusedIndex.value + 1)
if (focusedIndex.value >= 0) scrollToFocused()
break
case 'ArrowUp':
e.preventDefault()
focusedIndex.value = findPrevEnabledIndex(focusedIndex.value - 1)
if (focusedIndex.value >= 0) scrollToFocused()
break
case 'Enter':
e.preventDefault()
if (focusedIndex.value >= 0 && focusedIndex.value < filteredOptions.value.length) {
const opt = filteredOptions.value[focusedIndex.value]
if (!isOptionDisabled(opt)) selectOption(opt)
}
break
case 'Escape':
e.preventDefault()
isOpen.value = false
triggerRef.value?.focus()
break
case 'Tab':
isOpen.value = false
break
}
}
const scrollToFocused = () => {
nextTick(() => {
const list = optionsListRef.value
if (!list) return
const focusedEl = list.children[focusedIndex.value] as HTMLElement
if (!focusedEl) return
if (focusedEl.offsetTop < list.scrollTop) {
list.scrollTop = focusedEl.offsetTop
} else if (focusedEl.offsetTop + focusedEl.offsetHeight > list.scrollTop + list.offsetHeight) {
list.scrollTop = focusedEl.offsetTop + focusedEl.offsetHeight - list.offsetHeight
}
})
}
const handleClickOutside = (event: MouseEvent) => {
const target = event.target as HTMLElement
// Check if click is inside THIS specific instance's dropdown or trigger
const isInDropdown = !!target.closest(`.${instanceId}`)
const isInTrigger = containerRef.value?.contains(target)
if (!isInDropdown && !isInTrigger && isOpen.value) {
isOpen.value = false
}
}
onMounted(() => {
document.addEventListener('click', handleClickOutside)
})
onUnmounted(() => {
document.removeEventListener('click', handleClickOutside)
window.removeEventListener('scroll', updateTriggerRect, { capture: true })
window.removeEventListener('resize', placeDropdown)
if (remoteSearchTimer) {
clearTimeout(remoteSearchTimer)
remoteSearchTimer = null
}
})
</script>
<style scoped>
/* 盒子本体走全局的 .field-trigger(与 ComboTrigger 共用);这里只留框里那几个小件 */
.select-value {
@apply flex-1 truncate text-left;
}
.select-icon {
@apply flex flex-shrink-0 items-center text-gray-400 dark:text-dark-400;
}
.select-clear {
@apply flex flex-shrink-0 cursor-pointer items-center justify-center;
@apply rounded text-gray-400 transition-colors;
@apply hover:text-gray-600 dark:hover:text-gray-200;
}
/* 多选:框里那一排标签(牌子本身用全局的 .field-tag,跟弹出框那一档同一个长相) */
.select-value-tags {
@apply flex min-w-0 flex-wrap items-center gap-1.5;
}
/* 明细格子里的高度是钉死的:标签不许换行,剩下的收进「+N」 */
.select-value-tight {
@apply flex-nowrap;
}
.select-chip-label {
@apply max-w-[12rem] truncate;
}
/* 标签上那个名字点得开(关联单据):颜色跟牌子一致,靠下划线与光标说它不是死文字 */
.select-chip-link {
@apply cursor-pointer underline-offset-2;
@apply hover:underline focus:underline focus:outline-none;
}
/* 牌子上那颗 ×:不能真用 <button>(触发器本身已经是一只按钮,按钮不许套按钮) */
.select-chip-x {
@apply flex flex-shrink-0 cursor-pointer items-center justify-center rounded p-0.5;
@apply text-primary-500 transition-colors;
@apply hover:bg-primary-100 hover:text-primary-700 dark:hover:bg-primary-900/60;
}
.select-chip-more {
@apply flex-shrink-0 text-xs text-gray-400 dark:text-dark-400;
}
.select-placeholder {
@apply min-w-0 truncate text-gray-400 dark:text-dark-400;
}
/* 弹层里行首那颗勾:勾选态一眼看得出来,不靠底色 */
.select-option-check {
@apply flex h-4 w-4 flex-shrink-0 items-center justify-center rounded border;
@apply border-gray-300 text-white dark:border-dark-500;
}
.select-option-check-on {
@apply border-primary-500 bg-primary-500 dark:border-primary-400;
}
</style>
<style>
.select-dropdown-portal {
@apply w-max min-w-[200px];
@apply bg-white dark:bg-dark-800;
@apply rounded-xl;
@apply border border-gray-200 dark:border-dark-700;
@apply shadow-lg shadow-black/10 dark:shadow-black/30;
@apply overflow-hidden;
pointer-events: auto !important;
}
.select-dropdown-portal .select-search {
@apply flex items-center gap-2 px-3 py-2;
@apply border-b border-gray-100 dark:border-dark-700;
}
.select-dropdown-portal .select-search-input {
@apply flex-1 bg-transparent text-sm;
@apply text-gray-900 dark:text-gray-100;
@apply placeholder:text-gray-400 dark:placeholder:text-dark-400;
@apply focus:outline-none;
}
.select-dropdown-portal .select-options {
@apply max-h-80 overflow-y-auto py-1 outline-none;
}
.select-dropdown-portal .select-option {
@apply flex items-center justify-between gap-2;
@apply px-4 py-2.5 text-sm;
@apply text-gray-700 dark:text-gray-300;
@apply cursor-pointer transition-colors duration-150;
@apply hover:bg-gray-50 dark:hover:bg-dark-700;
pointer-events: auto !important;
}
.select-dropdown-portal .select-option-tree {
position: relative;
}
/* 上下不留白:同级行首尾相接,这条引导线才连得起来 */
.select-dropdown-portal .select-option-rail {
@apply absolute inset-y-0 w-px;
@apply bg-gray-200 dark:bg-dark-600;
}
.select-dropdown-portal .select-option-tree-root {
@apply font-medium text-gray-900 dark:text-gray-100;
}
.select-dropdown-portal .select-option-note {
@apply flex-shrink min-w-0 max-w-[45%] truncate text-right text-xs;
@apply text-gray-400 dark:text-dark-500;
}
.select-dropdown-portal .select-option-selected {
@apply bg-primary-50 dark:bg-primary-900/20;
@apply text-primary-700 dark:text-primary-300;
}
.select-dropdown-portal .select-option-focused {
@apply bg-gray-100 dark:bg-dark-700;
}
.select-dropdown-portal .select-option-disabled {
@apply cursor-not-allowed opacity-40;
}
.select-dropdown-portal .select-option-group {
@apply cursor-default select-none;
@apply bg-gray-50 dark:bg-dark-900;
@apply text-[11px] font-bold uppercase tracking-wider;
@apply text-gray-500 dark:text-gray-400;
}
.select-dropdown-portal .select-option-group:hover {
@apply bg-gray-50 dark:bg-dark-900;
}
.select-dropdown-portal .select-option-label {
@apply flex-1 min-w-0 truncate text-left;
}
.select-dropdown-portal .select-empty {
@apply px-4 py-8 text-center text-sm;
@apply text-gray-500 dark:text-dark-400;
}
.select-dropdown-enter-active,
.select-dropdown-leave-active {
transition: all 0.2s ease;
}
.select-dropdown-enter-from,
.select-dropdown-leave-to {
opacity: 0;
transform: translateY(-8px);
}
</style>