select-value.js 3 KB
/** select 字段值归一化 — @see packageDynamicForm/docs/ARCHITECTURE.md */
import { flattenFields } from './visibility.js'
import { listSubforms, getSubformRowTemplate } from './field-types.js'
import { getGroupRows } from './group-values.js'

function isSelectObject(rawValue) {
	return rawValue != null && typeof rawValue === 'object' && !Array.isArray(rawValue)
}

/** 将 select 原始值强制为标量字符串(对象取 id/value;数组取首个非空项) */
export function coerceSelectValue(rawValue) {
	if (rawValue == null || rawValue === '') {
		return rawValue
	}
	if (isSelectObject(rawValue)) {
		const id = rawValue.id ?? rawValue.value
		return id == null || id === '' ? '' : String(id)
	}
	if (Array.isArray(rawValue)) {
		const first = rawValue.find(v => v != null && v !== '')
		if (first == null) return ''
		if (isSelectObject(first)) {
			const id = first.id ?? first.value
			return id == null || id === '' ? '' : String(id)
		}
		return String(first)
	}
	return String(rawValue)
}

/** 按 options 将 label/value 归一化为 option.value */
export function resolveSelectOptionValue(field, rawValue) {
	if (rawValue == null || rawValue === '') {
		return rawValue
	}
	if (isSelectObject(rawValue)) {
		if (field?.optionsKey) {
			return rawValue
		}
		return coerceSelectValue(rawValue)
	}
	if (!field?.options?.length) {
		return coerceSelectValue(rawValue)
	}
	const coerced = coerceSelectValue(rawValue)
	if (coerced === '' || coerced == null) {
		return coerced
	}
	const str = String(coerced)
	const byValue = field.options.find(option => String(option.value) === str)
	if (byValue) {
		return byValue.value
	}
	const byLabel = field.options.find(
		option => option.label === rawValue || option.label === str
	)
	if (byLabel) {
		return byLabel.value
	}
	return coerced
}

function normalizeSelectFieldValue(field, rawValue) {
	if (rawValue === undefined) {
		return undefined
	}
	return resolveSelectOptionValue(field, rawValue)
}

/** 批量归一化 values 中所有 select 字段(含 subform 行内) */
export function normalizeSelectValuesInMap(list = [], values = {}) {
	const selectFields = flattenFields(list).filter(field => field.type === 'select')
	if (!selectFields.length && !listSubforms(list).length) {
		return values
	}
	const nextValues = { ...values }

	selectFields.forEach(field => {
		if (nextValues[field.key] === undefined) {
			return
		}
		nextValues[field.key] = normalizeSelectFieldValue(field, nextValues[field.key])
	})

	listSubforms(list).forEach(subform => {
		const childSelects = getSubformRowTemplate(subform).filter(child => child.type === 'select')
		if (!childSelects.length) {
			return
		}
		const rows = getGroupRows(nextValues, subform.key)
		if (!rows.length) {
			return
		}
		nextValues[subform.key] = rows.map(row => {
			const nextRow = { ...row }
			childSelects.forEach(child => {
				if (nextRow[child.key] === undefined) {
					return
				}
				nextRow[child.key] = normalizeSelectFieldValue(child, nextRow[child.key])
			})
			return nextRow
		})
	})

	return nextValues
}