select-display.js 2.89 KB
/**
 * select 展示解析 — App 双 key(field.value=展示名,field[field.key]=id/meta)
 * @see packageDynamicForm/docs/field-options-api.md
 */

function resolveMetaId(meta) {
	if (meta == null || meta === '') {
		return ''
	}
	if (typeof meta === 'object' && !Array.isArray(meta)) {
		const id = meta.id ?? meta.value
		return id == null || id === '' ? '' : String(id)
	}
	return String(meta)
}

function resolveValueId(value) {
	if (value == null || value === '') {
		return ''
	}
	if (typeof value === 'object' && !Array.isArray(value)) {
		const id = value.id ?? value.value
		return id == null || id === '' ? '' : String(id)
	}
	return String(value)
}

/**
 * 解析 select 的 optionId 与展示文案(支持 subform 双 key)
 * @param {Object} [field={}] 含 key、optionsKey、field[field.key]
 * @param {*} [value] 组件 value(展示名、id 或 { id, name })
 * @param {Array} [options=[]] 已加载的选项
 * @returns {{ displayLabel: string, optionId: string }}
 */
function resolveSelectFieldState(field = {}, value, options = []) {
	const key = field?.key
	const hasOptionsKey = !!field?.optionsKey
	const meta = key != null ? field[key] : undefined
	const metaId = resolveMetaId(meta)

	let optionId = metaId
	if (!optionId) {
		optionId = resolveValueId(value)
	}

	const valueId = resolveValueId(value)
	const matchedByValue = valueId && options.length
		? options.find(item => [item.value, item.label, item.name]
			.some(alias => alias != null && alias !== '' && String(alias) === String(valueId)))
		: null
	const matchedById = optionId && options.length
		? options.find(item => [item.value, item.id]
			.some(alias => alias != null && alias !== '' && String(alias) === String(optionId)))
		: null
	const isStaticEnumeration = !field?.optionsKey || field.optionsKey === 'options'
	const matched = isStaticEnumeration
		? matchedByValue || matchedById
		: matchedById || matchedByValue
	if (matchedByValue && (isStaticEnumeration || !matchedById)) {
		optionId = matchedByValue.value ?? matchedByValue.id ?? optionId
	}

	let displayLabel = ''

	if (typeof value === 'string' && value !== '') {
		if (metaId && String(value) !== String(metaId)) {
			displayLabel = value
		} else if (matched?.label) {
			displayLabel = matched.label
		} else {
			displayLabel = value
		}
	}

	if (!displayLabel && typeof meta === 'object' && meta !== null && !Array.isArray(meta)) {
		displayLabel = meta.name ?? meta.label ?? ''
	}

	if (!displayLabel && value != null && typeof value === 'object' && !Array.isArray(value)) {
		displayLabel = value.name ?? value.label ?? ''
	}

	if (!displayLabel && matched?.label) {
		displayLabel = matched.label
	}

	if (!displayLabel && !hasOptionsKey && optionId) {
		displayLabel = optionId
	}

	return {
		displayLabel: displayLabel ? String(displayLabel) : '',
		optionId: optionId ? String(optionId) : ''
	}
}

module.exports = {
	resolveSelectFieldState,
	resolveMetaId,
	resolveValueId
}