picker-value.js 1.17 KB
/** form-picker-popup 选中态纯函数 — 供组件与单测共用 */

/** 将单项(标量或 { id, value } 对象)解析为 option.value 比对用的字符串 key */
function resolvePickerItemKey(item) {
	if (item != null && typeof item === 'object') {
		const key = item.id ?? item.value
		return key == null || key === '' ? '' : String(key)
	}
	return item == null || item === '' ? '' : String(item)
}

/** 将 value 规范为字符串 id 数组,供 draft 与 option 比对(支持详情回显对象数组) */
function normalizePickerValues(value) {
	if (!Array.isArray(value)) {
		if (value == null || value === '') {
			return []
		}
		const key = resolvePickerItemKey(value)
		return key ? [key] : []
	}
	return value.map(resolvePickerItemKey).filter(Boolean)
}

/** 根据 options 与当前 value 生成带 active 的行列表 */
function buildPickerOptionRows(options = [], value) {
	const draftValues = normalizePickerValues(value)
	return (options || []).map(option => ({
		label: option.label,
		value: option.value,
		active: draftValues.includes(String(option.value))
	}))
}

module.exports = {
	resolvePickerItemKey,
	normalizePickerValues,
	buildPickerOptionRows
}