67 lines
1.8 KiB
TypeScript
67 lines
1.8 KiB
TypeScript
import { pinyin } from 'pinyin-pro'
|
|
|
|
/**
|
|
* 获取中文字符串的全拼(不带声调,空格分隔)
|
|
* 例如: "张三" -> "zhang san"
|
|
*/
|
|
export function getFullPinyin(text: string): string {
|
|
if (!text) return ''
|
|
return pinyin(text, { toneType: 'none', type: 'array' }).join(' ')
|
|
}
|
|
|
|
/**
|
|
* 获取中文字符串的全拼(不带声调,无空格)
|
|
* 例如: "张三" -> "zhangsan"
|
|
*/
|
|
export function getFullPinyinNoSpace(text: string): string {
|
|
if (!text) return ''
|
|
return pinyin(text, { toneType: 'none', type: 'array' }).join('')
|
|
}
|
|
|
|
/**
|
|
* 获取中文字符串的拼音首字母
|
|
* 例如: "张三" -> "zs"
|
|
*/
|
|
export function getPinyinInitials(text: string): string {
|
|
if (!text) return ''
|
|
return pinyin(text, { pattern: 'first', toneType: 'none', type: 'array' }).join('')
|
|
}
|
|
|
|
/**
|
|
* 检查查询字符串是否匹配目标文本(支持中文、全拼、首字母)
|
|
* @param query 用户输入的查询字符串
|
|
* @param target 目标文本(如成员姓名)
|
|
* @returns 是否匹配
|
|
*/
|
|
export function matchesPinyin(query: string, target: string): boolean {
|
|
if (!query || !target) return false
|
|
|
|
const lowerQuery = query.toLowerCase().trim()
|
|
const lowerTarget = target.toLowerCase()
|
|
|
|
// 1. 直接匹配中文
|
|
if (lowerTarget.includes(lowerQuery)) {
|
|
return true
|
|
}
|
|
|
|
// 2. 全拼匹配(无空格)
|
|
const targetFullPinyin = getFullPinyinNoSpace(target).toLowerCase()
|
|
if (targetFullPinyin.includes(lowerQuery)) {
|
|
return true
|
|
}
|
|
|
|
// 3. 首字母匹配
|
|
const targetInitials = getPinyinInitials(target).toLowerCase()
|
|
if (targetInitials.includes(lowerQuery)) {
|
|
return true
|
|
}
|
|
|
|
// 4. 全拼匹配(带空格,用于部分匹配)
|
|
const targetFullPinyinSpaced = getFullPinyin(target).toLowerCase()
|
|
if (targetFullPinyinSpaced.includes(lowerQuery)) {
|
|
return true
|
|
}
|
|
|
|
return false
|
|
}
|