feat: 为下拉选择组件添加搜索过滤功能,支持拼音匹配

- 新增 search.ts 搜索工具,支持中文拼音(全拼/首字母)模糊匹配
- 新增 select-search-context.ts,通过 provide/inject 为 radix-vue Select 组件注入搜索能力
- MultiSelect、ModelMultiSelect 组件集成搜索框,选项超过阈值时自动显示
- select-content/select-item 组件支持搜索过滤与空状态提示
- StandaloneKeyFormDialog、UserFormDialog 中手写下拉框替换为复用 MultiSelect 组件
- 引入 pinyin-pro 依赖,按需懒加载

Closes #210

Co-authored-by: AoaoMH <kidxb@vip.qq.com>
This commit is contained in:
fawney19
2026-03-09 19:51:02 +08:00
parent 0258d01ee6
commit 46bab1b97f
10 changed files with 667 additions and 333 deletions

View File

@@ -10,7 +10,32 @@
:align-offset="alignOffset"
>
<SelectViewport :class="viewportClass">
<div
v-if="showSearchInput"
class="sticky top-0 z-10 bg-card/95 px-1 pt-1 pb-2 backdrop-blur supports-[backdrop-filter]:bg-card/85"
>
<div class="relative">
<Search
class="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"
/>
<Input
ref="searchInputRef"
v-model="searchQuery"
:placeholder="searchPlaceholder"
class="h-9 rounded-xl border-border/60 bg-background/80 pl-9 pr-3 text-sm"
@keydown.stop
/>
</div>
</div>
<slot />
<div
v-if="showEmptyState"
class="px-3 py-2 text-sm text-muted-foreground"
>
未找到匹配项
</div>
</SelectViewport>
</SelectContentPrimitive>
</SelectPortal>
@@ -22,9 +47,25 @@ import {
SelectPortal,
SelectViewport,
} from 'radix-vue'
import { Search } from 'lucide-vue-next'
import {
computed,
inject,
nextTick,
onMounted,
onUnmounted,
provide,
ref,
watch,
} from 'vue'
import Input from './input.vue'
import { cn } from '@/lib/utils'
import { computed, inject } from 'vue'
import { DIALOG_CONTEXT_KEY } from './dialog/context'
import {
SELECT_SEARCH_CONTEXT_KEY,
type RegisteredSelectItem,
} from './select-search-context'
import { matchesSearchQuery, preloadPinyin } from '@/utils/search'
interface Props {
class?: string
@@ -34,6 +75,9 @@ interface Props {
align?: 'start' | 'center' | 'end'
alignOffset?: number
disablePortal?: boolean
searchable?: boolean
searchThreshold?: number
searchPlaceholder?: string
}
const props = withDefaults(defineProps<Props>(), {
@@ -44,19 +88,105 @@ const props = withDefaults(defineProps<Props>(), {
align: undefined,
alignOffset: undefined,
disablePortal: false,
searchable: true,
searchThreshold: 8,
searchPlaceholder: '输入关键词搜索...',
})
const isInsideDialog = inject(DIALOG_CONTEXT_KEY, false)
const shouldDisablePortal = computed(() => props.disablePortal || isInsideDialog)
const shouldDisablePortal = computed(
() => props.disablePortal || isInsideDialog,
)
const searchQuery = ref('')
const searchInputRef = ref<InstanceType<typeof Input> | null>(null)
const registeredItems = ref<Record<string, RegisteredSelectItem>>({})
const hiddenValues = computed(() => {
const query = searchQuery.value.trim()
if (!query) return new Set<string>()
const hidden = new Set<string>()
for (const item of Object.values(registeredItems.value)) {
if (!matchesSearchQuery(query, item.value, item.text)) {
hidden.add(item.value)
}
}
return hidden
})
provide(SELECT_SEARCH_CONTEXT_KEY, {
searchQuery,
hiddenValues,
registerItem(id, item) {
registeredItems.value = {
...registeredItems.value,
[id]: item,
}
},
updateItem(id, item) {
const currentItem = registeredItems.value[id]
if (!currentItem) {
return
}
registeredItems.value = {
...registeredItems.value,
[id]: {
...currentItem,
...item,
},
}
},
unregisterItem(id) {
if (!(id in registeredItems.value)) {
return
}
const nextItems = { ...registeredItems.value }
delete nextItems[id]
registeredItems.value = nextItems
},
})
const itemCount = computed(() => Object.keys(registeredItems.value).length)
const showSearchInput = computed(
() => props.searchable && itemCount.value >= props.searchThreshold,
)
const showEmptyState = computed(
() =>
showSearchInput.value &&
searchQuery.value.trim().length > 0 &&
hiddenValues.value.size === itemCount.value,
)
onMounted(() => {
if (props.searchable) {
preloadPinyin()
}
})
watch(showSearchInput, async (visible) => {
if (!visible) {
searchQuery.value = ''
return
}
await nextTick()
searchInputRef.value?.inputRef?.focus()
})
const contentClass = computed(() =>
cn(
'z-[200] max-h-96 min-w-[8rem] overflow-hidden rounded-2xl border border-border bg-card text-foreground shadow-2xl backdrop-blur-xl pointer-events-auto',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
'data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
props.class
)
props.class,
),
)
const viewportClass = 'p-1 max-h-[var(--radix-select-content-available-height)]'
onUnmounted(() => {
searchQuery.value = ''
})
</script>

View File

@@ -1,32 +1,100 @@
<script setup lang="ts">
import { SelectItem as SelectItemPrimitive, SelectItemIndicator, SelectItemText } from 'radix-vue'
import {
SelectItem as SelectItemPrimitive,
SelectItemIndicator,
SelectItemText,
} from 'radix-vue'
import { Check } from 'lucide-vue-next'
import { cn } from '@/lib/utils'
import { computed } from 'vue'
import {
computed,
getCurrentInstance,
inject,
onBeforeUnmount,
onMounted,
useSlots,
watch,
} from 'vue'
import { SELECT_SEARCH_CONTEXT_KEY } from './select-search-context'
interface Props {
class?: string
value: string
disabled?: boolean
textValue?: string
}
const props = defineProps<Props>()
const slots = useSlots()
const searchContext = inject(SELECT_SEARCH_CONTEXT_KEY, null)
const instance = getCurrentInstance()
const itemId = instance?.uid
? `select-item-${instance.uid}`
: `select-item-${Math.random().toString(36).slice(2, 10)}`
function extractText(node: unknown): string {
if (typeof node === 'string' || typeof node === 'number') {
return String(node)
}
if (Array.isArray(node)) {
return node.map(extractText).join(' ')
}
if (node && typeof node === 'object') {
const vnode = node as { children?: unknown }
return extractText(vnode.children)
}
return ''
}
const normalizedText = computed(() => {
const slotText = extractText(slots.default?.()).replace(/\s+/g, ' ').trim()
return (props.textValue ?? slotText ?? props.value).trim()
})
const isHidden = computed(
() => searchContext?.hiddenValues.value.has(props.value) ?? false,
)
const itemClass = computed(() =>
cn(
'relative flex w-full cursor-pointer select-none items-center rounded-lg py-1.5 pl-8 pr-2 text-sm outline-none',
'data-[highlighted]:bg-accent focus:bg-accent text-foreground',
'transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
props.class
)
isHidden.value && 'hidden',
props.class,
),
)
onMounted(() => {
searchContext?.registerItem(itemId, {
value: props.value,
text: normalizedText.value,
})
})
watch(
() => [props.value, normalizedText.value] as const,
([value, text]) => {
searchContext?.updateItem(itemId, {
value,
text,
})
},
)
onBeforeUnmount(() => {
searchContext?.unregisterItem(itemId)
})
</script>
<template>
<SelectItemPrimitive
:class="itemClass"
:value="value"
:disabled="disabled"
:disabled="disabled || isHidden"
:text-value="normalizedText"
>
<span class="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectItemIndicator>

View File

@@ -0,0 +1,17 @@
import type { InjectionKey, Ref } from 'vue'
export interface RegisteredSelectItem {
value: string
text: string
}
export interface SelectSearchContext {
searchQuery: Ref<string>
hiddenValues: Ref<Set<string>>
registerItem: (id: string, item: RegisteredSelectItem) => void
updateItem: (id: string, item: Partial<RegisteredSelectItem>) => void
unregisterItem: (id: string) => void
}
export const SELECT_SEARCH_CONTEXT_KEY: InjectionKey<SelectSearchContext> =
Symbol('select-search-context')