516 lines
13 KiB
Vue
516 lines
13 KiB
Vue
<template>
|
|
<span
|
|
ref="root"
|
|
class="searchable-select"
|
|
:class="{ 'is-open': open, 'is-disabled': disabled, 'is-multiple': multiple }"
|
|
:style="rootStyle"
|
|
>
|
|
<select
|
|
ref="nativeSelect"
|
|
class="searchable-select__native"
|
|
:name="name"
|
|
:required="required"
|
|
:disabled="disabled"
|
|
:multiple="multiple"
|
|
tabindex="-1"
|
|
aria-hidden="true"
|
|
@invalid="handleInvalid"
|
|
>
|
|
<slot />
|
|
</select>
|
|
|
|
<input
|
|
:id="id"
|
|
ref="input"
|
|
v-bind="inputAttrs"
|
|
:class="attrs.class"
|
|
:value="query"
|
|
type="text"
|
|
role="combobox"
|
|
aria-autocomplete="list"
|
|
:aria-controls="listboxId"
|
|
:aria-expanded="open"
|
|
:aria-multiselectable="multiple || undefined"
|
|
:disabled="disabled"
|
|
:required="required"
|
|
:placeholder="placeholder || '输入关键字搜索'"
|
|
autocomplete="off"
|
|
@focus="openOptions"
|
|
@input="searchOptions"
|
|
@blur="handleBlur"
|
|
@keydown="handleKeydown"
|
|
>
|
|
<button
|
|
class="searchable-select__toggle"
|
|
type="button"
|
|
tabindex="-1"
|
|
:disabled="disabled"
|
|
aria-label="展开选项"
|
|
@mousedown.prevent
|
|
@click="toggleOptions"
|
|
>
|
|
<span aria-hidden="true">⌄</span>
|
|
</button>
|
|
|
|
<ul
|
|
v-if="open"
|
|
:id="listboxId"
|
|
ref="listbox"
|
|
class="searchable-select__options"
|
|
:style="dropdownStyle"
|
|
role="listbox"
|
|
:aria-multiselectable="multiple || undefined"
|
|
>
|
|
<li v-for="option in filteredOptions" :key="option.key">
|
|
<button
|
|
type="button"
|
|
role="option"
|
|
:aria-selected="isSelected(option.value)"
|
|
:disabled="option.disabled"
|
|
@mousedown.prevent
|
|
@click="chooseOption(option)"
|
|
>
|
|
<span class="searchable-select__option-label">{{ option.label }}</span>
|
|
<small v-if="option.group">{{ option.group }}</small>
|
|
<b v-if="isSelected(option.value)" aria-label="已选择">✓</b>
|
|
</button>
|
|
</li>
|
|
<li v-if="!filteredOptions.length" class="searchable-select__empty">没有匹配选项</li>
|
|
</ul>
|
|
</span>
|
|
</template>
|
|
|
|
<script setup lang="ts">
|
|
import {
|
|
computed,
|
|
getCurrentInstance,
|
|
nextTick,
|
|
onBeforeUnmount,
|
|
onMounted,
|
|
onUpdated,
|
|
ref,
|
|
useAttrs,
|
|
watch,
|
|
} from 'vue'
|
|
|
|
defineOptions({ inheritAttrs: false })
|
|
|
|
type SelectValue = string | number | null | undefined
|
|
type SearchableOption = {
|
|
key: string
|
|
value: string
|
|
label: string
|
|
group: string
|
|
disabled: boolean
|
|
}
|
|
|
|
const props = withDefaults(defineProps<{
|
|
modelValue?: SelectValue | SelectValue[]
|
|
modelModifiers?: { number?: boolean }
|
|
value?: SelectValue | SelectValue[]
|
|
id?: string
|
|
name?: string
|
|
placeholder?: string
|
|
disabled?: boolean
|
|
required?: boolean
|
|
multiple?: boolean
|
|
}>(), {
|
|
disabled: false,
|
|
required: false,
|
|
multiple: false,
|
|
})
|
|
|
|
const emit = defineEmits<{
|
|
'update:modelValue': [value: SelectValue | SelectValue[]]
|
|
change: [event: Event]
|
|
input: [event: Event]
|
|
}>()
|
|
|
|
const attrs = useAttrs()
|
|
const root = ref<HTMLElement | null>(null)
|
|
const input = ref<HTMLInputElement | null>(null)
|
|
const listbox = ref<HTMLElement | null>(null)
|
|
const nativeSelect = ref<HTMLSelectElement | null>(null)
|
|
const options = ref<SearchableOption[]>([])
|
|
const optionsSignature = ref('')
|
|
const query = ref('')
|
|
const open = ref(false)
|
|
const searching = ref(false)
|
|
const dropdownStyle = ref<Record<string, string>>({})
|
|
const listboxId = `searchable-select-${getCurrentInstance()?.uid ?? Math.random().toString(36).slice(2)}`
|
|
|
|
const inputAttrs = computed(() => {
|
|
const { class: _class, style: _style, ...rest } = attrs
|
|
return rest
|
|
})
|
|
const rootStyle = computed(() => attrs.style as string | Record<string, string> | undefined)
|
|
const controlledValue = computed(() => props.modelValue !== undefined ? props.modelValue : props.value)
|
|
const selectedValues = computed(() => {
|
|
const value = controlledValue.value
|
|
if (props.multiple) return (Array.isArray(value) ? value : value == null ? [] : [value]).map(item => String(item))
|
|
return [value == null ? '' : String(value)]
|
|
})
|
|
const selectedLabels = computed(() => options.value
|
|
.filter(option => selectedValues.value.includes(option.value))
|
|
.map(option => option.label))
|
|
const displayValue = computed(() => selectedLabels.value.join('、'))
|
|
const normalizedTerms = computed(() => query.value.toLocaleLowerCase().split(/\s+/).filter(Boolean))
|
|
const filteredOptions = computed(() => options.value.filter(option => {
|
|
if (!searching.value || !normalizedTerms.value.length) return true
|
|
const source = `${option.label} ${option.value} ${option.group}`.toLocaleLowerCase()
|
|
return normalizedTerms.value.every(term => source.includes(term))
|
|
}))
|
|
|
|
const syncNativeSelection = (values: string[]) => {
|
|
if (!nativeSelect.value) return
|
|
Array.from(nativeSelect.value.options).forEach(option => { option.selected = values.includes(option.value) })
|
|
}
|
|
|
|
const refreshOptions = () => {
|
|
const select = nativeSelect.value
|
|
if (!select) return
|
|
const next = Array.from(select.options).map((option, index) => ({
|
|
key: `${index}-${option.value}`,
|
|
value: option.value,
|
|
label: option.label || option.textContent?.trim() || option.value,
|
|
group: option.parentElement instanceof HTMLOptGroupElement ? option.parentElement.label : '',
|
|
disabled: option.disabled || (option.parentElement instanceof HTMLOptGroupElement && option.parentElement.disabled),
|
|
}))
|
|
const signature = JSON.stringify(next)
|
|
if (signature !== optionsSignature.value) {
|
|
optionsSignature.value = signature
|
|
options.value = next
|
|
}
|
|
syncNativeSelection(selectedValues.value)
|
|
}
|
|
|
|
const convertValue = (value: string): SelectValue => {
|
|
if (!props.modelModifiers?.number || value === '') return value
|
|
const numberValue = Number(value)
|
|
return Number.isNaN(numberValue) ? value : numberValue
|
|
}
|
|
|
|
const positionDropdown = () => {
|
|
const field = input.value
|
|
if (!field) return
|
|
const rect = field.getBoundingClientRect()
|
|
const viewportGap = 8
|
|
const width = Math.min(Math.max(rect.width, 180), window.innerWidth - viewportGap * 2)
|
|
const left = Math.min(Math.max(viewportGap, rect.left), window.innerWidth - width - viewportGap)
|
|
const below = window.innerHeight - rect.bottom - viewportGap
|
|
const above = rect.top - viewportGap
|
|
const maxHeight = Math.max(120, Math.min(280, Math.max(below, above) - 6))
|
|
const top = below >= Math.min(180, maxHeight)
|
|
? rect.bottom + 4
|
|
: Math.max(viewportGap, rect.top - maxHeight - 4)
|
|
dropdownStyle.value = {
|
|
top: `${Math.round(top)}px`,
|
|
left: `${Math.round(left)}px`,
|
|
width: `${Math.round(width)}px`,
|
|
maxHeight: `${Math.round(maxHeight)}px`,
|
|
}
|
|
}
|
|
|
|
const handleOutsidePointer = (event: PointerEvent) => {
|
|
if (root.value?.contains(event.target as Node)) return
|
|
closeOptions()
|
|
}
|
|
|
|
const handleBlur = () => {
|
|
window.setTimeout(() => {
|
|
if (!root.value?.contains(document.activeElement)) closeOptions()
|
|
}, 0)
|
|
}
|
|
const addOpenListeners = () => {
|
|
window.addEventListener('resize', positionDropdown)
|
|
window.addEventListener('scroll', positionDropdown, true)
|
|
document.addEventListener('pointerdown', handleOutsidePointer, true)
|
|
}
|
|
const removeOpenListeners = () => {
|
|
window.removeEventListener('resize', positionDropdown)
|
|
window.removeEventListener('scroll', positionDropdown, true)
|
|
document.removeEventListener('pointerdown', handleOutsidePointer, true)
|
|
}
|
|
|
|
const openOptions = async () => {
|
|
if (props.disabled) return
|
|
refreshOptions()
|
|
searching.value = false
|
|
query.value = displayValue.value
|
|
if (!open.value) {
|
|
open.value = true
|
|
addOpenListeners()
|
|
}
|
|
await nextTick()
|
|
positionDropdown()
|
|
input.value?.select()
|
|
}
|
|
|
|
const closeOptions = (restoreDisplay = true) => {
|
|
if (!open.value) return
|
|
open.value = false
|
|
searching.value = false
|
|
removeOpenListeners()
|
|
if (restoreDisplay) query.value = displayValue.value
|
|
}
|
|
|
|
const toggleOptions = () => {
|
|
if (open.value) {
|
|
closeOptions()
|
|
return
|
|
}
|
|
input.value?.focus()
|
|
void openOptions()
|
|
}
|
|
|
|
const searchOptions = (event: Event) => {
|
|
query.value = (event.target as HTMLInputElement).value
|
|
searching.value = true
|
|
if (!open.value) {
|
|
open.value = true
|
|
addOpenListeners()
|
|
}
|
|
void nextTick(positionDropdown)
|
|
}
|
|
|
|
const dispatchSelectionEvents = () => {
|
|
const select = nativeSelect.value
|
|
if (!select) return
|
|
const inputEvent = new Event('input', { bubbles: true })
|
|
select.dispatchEvent(inputEvent)
|
|
emit('input', inputEvent)
|
|
const changeEvent = new Event('change', { bubbles: true })
|
|
select.dispatchEvent(changeEvent)
|
|
emit('change', changeEvent)
|
|
}
|
|
|
|
const isSelected = (value: string) => selectedValues.value.includes(value)
|
|
const chooseOption = (option: SearchableOption) => {
|
|
if (option.disabled) return
|
|
let values: string[]
|
|
if (props.multiple) {
|
|
values = isSelected(option.value)
|
|
? selectedValues.value.filter(value => value !== option.value)
|
|
: [...selectedValues.value, option.value]
|
|
} else {
|
|
values = [option.value]
|
|
}
|
|
syncNativeSelection(values)
|
|
emit('update:modelValue', props.multiple ? values.map(convertValue) : convertValue(option.value))
|
|
dispatchSelectionEvents()
|
|
if (props.multiple) {
|
|
searching.value = false
|
|
query.value = ''
|
|
void nextTick(positionDropdown)
|
|
} else {
|
|
query.value = option.label
|
|
closeOptions(false)
|
|
input.value?.focus()
|
|
}
|
|
}
|
|
|
|
const handleKeydown = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') {
|
|
event.preventDefault()
|
|
closeOptions()
|
|
input.value?.select()
|
|
return
|
|
}
|
|
if (event.key === 'ArrowDown') {
|
|
event.preventDefault()
|
|
if (!open.value) void openOptions()
|
|
else listbox.value?.querySelector<HTMLButtonElement>('button:not(:disabled)')?.focus()
|
|
return
|
|
}
|
|
if (event.key === 'Enter' && open.value) {
|
|
const first = filteredOptions.value.find(option => !option.disabled)
|
|
if (first) {
|
|
event.preventDefault()
|
|
chooseOption(first)
|
|
}
|
|
}
|
|
}
|
|
|
|
const handleInvalid = (event: Event) => {
|
|
event.preventDefault()
|
|
input.value?.focus()
|
|
void openOptions()
|
|
}
|
|
|
|
watch([() => controlledValue.value, optionsSignature], () => {
|
|
syncNativeSelection(selectedValues.value)
|
|
if (!open.value || !searching.value) query.value = displayValue.value
|
|
}, { deep: true, flush: 'post' })
|
|
|
|
watch(() => props.disabled, disabled => {
|
|
if (disabled) closeOptions()
|
|
})
|
|
|
|
onMounted(() => {
|
|
refreshOptions()
|
|
query.value = displayValue.value
|
|
})
|
|
onUpdated(refreshOptions)
|
|
onBeforeUnmount(removeOpenListeners)
|
|
</script>
|
|
|
|
<style scoped>
|
|
.searchable-select {
|
|
position: relative;
|
|
display: inline-block;
|
|
width: 100%;
|
|
min-width: 0;
|
|
max-width: 100%;
|
|
vertical-align: middle;
|
|
}
|
|
|
|
.searchable-select__native {
|
|
position: absolute;
|
|
width: 1px;
|
|
height: 1px;
|
|
margin: 0;
|
|
padding: 0;
|
|
border: 0;
|
|
opacity: 0;
|
|
pointer-events: none;
|
|
}
|
|
|
|
.searchable-select > input {
|
|
width: 100%;
|
|
min-width: 0;
|
|
min-height: var(--control-height, 40px);
|
|
box-sizing: border-box;
|
|
padding: 8px 34px 8px 12px;
|
|
border: 1px solid var(--line-strong, #cfd7e3);
|
|
border-radius: 6px;
|
|
background: #fff;
|
|
color: var(--text, #172033);
|
|
font: inherit;
|
|
cursor: text;
|
|
}
|
|
|
|
.searchable-select > input:focus {
|
|
border-color: var(--blue, #0057d9);
|
|
outline: none;
|
|
box-shadow: 0 0 0 3px rgba(0, 87, 217, 0.12);
|
|
}
|
|
|
|
.searchable-select > input:disabled {
|
|
cursor: not-allowed;
|
|
border-color: #d3dae2;
|
|
background: var(--disabled-soft, #f3f5f7);
|
|
color: var(--disabled, #8994a3);
|
|
}
|
|
|
|
.searchable-select__toggle {
|
|
position: absolute;
|
|
top: 50%;
|
|
right: 4px;
|
|
display: grid;
|
|
width: 30px;
|
|
height: calc(100% - 8px);
|
|
padding: 0;
|
|
transform: translateY(-50%);
|
|
place-items: center;
|
|
border: 0;
|
|
background: transparent;
|
|
color: var(--muted, #667085);
|
|
cursor: pointer;
|
|
}
|
|
|
|
.is-open .searchable-select__toggle span {
|
|
transform: rotate(180deg);
|
|
}
|
|
|
|
.searchable-select__options {
|
|
position: fixed;
|
|
z-index: 2147483000;
|
|
display: grid;
|
|
gap: 3px;
|
|
margin: 0;
|
|
padding: 6px;
|
|
overflow: auto;
|
|
border: 1px solid var(--line-strong, #cfd7e3);
|
|
border-radius: 8px;
|
|
background: #fff;
|
|
box-shadow: 0 14px 36px rgba(15, 23, 42, 0.18);
|
|
list-style: none;
|
|
}
|
|
|
|
.searchable-select__options li {
|
|
margin: 0;
|
|
padding: 0;
|
|
}
|
|
|
|
.searchable-select__options button {
|
|
display: grid;
|
|
grid-template-columns: minmax(0, 1fr) auto auto;
|
|
align-items: center;
|
|
width: 100%;
|
|
min-height: 36px;
|
|
gap: 8px;
|
|
padding: 7px 9px;
|
|
border: 0;
|
|
border-radius: 6px;
|
|
background: transparent;
|
|
color: var(--text, #172033);
|
|
text-align: left;
|
|
cursor: pointer;
|
|
}
|
|
|
|
.searchable-select__options button:hover:not(:disabled),
|
|
.searchable-select__options button:focus-visible,
|
|
.searchable-select__options button[aria-selected="true"] {
|
|
outline: 0;
|
|
background: var(--blue-soft, #edf4ff);
|
|
}
|
|
|
|
.searchable-select__options button:disabled {
|
|
opacity: 0.48;
|
|
cursor: not-allowed;
|
|
}
|
|
|
|
.searchable-select__option-label {
|
|
min-width: 0;
|
|
overflow: hidden;
|
|
text-overflow: ellipsis;
|
|
white-space: nowrap;
|
|
}
|
|
|
|
.searchable-select__options small {
|
|
color: var(--muted, #667085);
|
|
}
|
|
|
|
.searchable-select__options b {
|
|
color: var(--blue, #0057d9);
|
|
}
|
|
|
|
.searchable-select__empty {
|
|
padding: 18px 12px !important;
|
|
color: var(--muted, #667085);
|
|
text-align: center;
|
|
}
|
|
|
|
:global(.compatibility-card) .searchable-select {
|
|
width: 132px;
|
|
min-width: 112px;
|
|
flex: 0 0 132px;
|
|
}
|
|
|
|
:global(.amount-control.has-currency) > .searchable-select {
|
|
width: 96px;
|
|
min-width: 0;
|
|
}
|
|
|
|
:global(.amount-control.has-currency) > .searchable-select > input {
|
|
min-height: 40px;
|
|
padding-inline: 9px 28px;
|
|
border: 0;
|
|
border-left: 1px solid var(--line, #d9dee8);
|
|
border-radius: 0;
|
|
background: var(--surface, #f7f9fb);
|
|
box-shadow: none;
|
|
}
|
|
|
|
</style>
|