nex_animation/frontend/src/components/forms/options.ts

43 lines
1.8 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.

/**
* 下拉选项的统一形状。
*
* 旧站的下拉把选项写在插槽里的原生 <option> 上,靠一个隐藏的 select 承载
* v-model 语义——那是 Vue 特有的兼容手法。React 侧没有这个问题,
* 直接把 options 当数据传进来:可搜索、可虚拟化、可来自接口的任意数组。
*/
export type SelectOption = { value: any; label: string; disabled?: boolean }
export type OptionLike = SelectOption | string | number | null | undefined
function labelOf(v: unknown) {
return String(v ?? '').replace(/\s+/g, ' ').trim()
}
/** 允许 `['主角','配角']` 这种最省事的写法,也允许标准 {value,label} */
export function toOptions(list: OptionLike[] | null | undefined): SelectOption[] {
return (list || [])
.filter((it) => it !== null && it !== undefined && it !== '')
.map((it: any) => {
if (typeof it === 'object') {
return { value: it.value, label: labelOf(it.label ?? it.name ?? it.text ?? it.value) || String(it.value ?? ''), disabled: !!it.disabled }
}
return { value: it, label: labelOf(it) }
})
}
/**
* 值比较:接口回来的 id 是 number,表单里存的是 string,
* 直接 === 会让「选中项」在重渲染后丢失(旧站靠原生 select 的类型转换掩盖了这点)。
*/
export function sameValue(a: any, b: any): boolean {
if (a === b) return true
if (a === null || a === undefined || b === null || b === undefined) return false
return String(a) === String(b)
}
/** 触发器上那一行回显:太长就退化成「首项 等 N 项」,避免把整行控件撑高 */
export function summaryOf(labels: string[], emptyText = ''): string {
if (!labels.length) return emptyText
const joined = labels.join('、')
return joined.length <= 30 ? joined : `${labels[0]} 等 ${labels.length} 项`
}