values.js 7.79 KB
/** 表单 values 读写与隐藏字段清理 — @see packageDynamicForm/docs/ARCHITECTURE.md */
import {
	getVisibleList,
	resolveEffectiveRowFields,
	getVisibleGroupChildFields
} from './visibility.js'
import {
	listSubforms,
	listStaticGroups,
	getStaticGroupChildren,
	getSubformRowTemplate,
	getSubformRowTemplateForAdd
} from './field-types.js'
import { failsStructuralPersistVisibility } from './json-content-persist.js'
import { getGroupRows } from './group-values.js'
import { normalizeFieldValueByType } from './field-types/registry.js'
import { normalizeSelectValuesInMap } from './select-value.js'
import {
	coerceMultipleSelectValue,
	normalizeMultipleSelectValuesInMap
} from './multiple-select-value.js'
import { extractSubformValuesFromField } from './group-row-adapter.js'
import {
	filterMultipleSelectValueByVisibleOptions,
	hasFieldOptionVisibilityConditions
} from './option-visibility.js'
function isMeaningfulValue(field, value) {
	if (value === undefined || value === null || value === '') {
		return false
	}
	if (Array.isArray(value) && value.length === 0) {
		return false
	}
	return true
}

/** 从 schema list 提取初始 values(含 subform、group、radio/select 归一化) */
export function buildInitialValues(list = []) {
	const values = {}
	;(list || []).forEach(field => {
		if (field.type === 'subform') {
			const maps = extractSubformValuesFromField(field)
			if (maps?.length) {
				values[field.key] = maps
			}
			return
		}
		if (field.type === 'group') {
			getStaticGroupChildren(field).forEach(child => {
				if (isMeaningfulValue(child, child.value)) {
					values[child.key] = normalizeFieldValueByType(child, child.value, 'initial')
				}
			})
			return
		}
		if (!isMeaningfulValue(field, field.value)) {
			return
		}
		let nextValue =
			field.type === 'multipleSelect'
				? coerceMultipleSelectValue(field.value)
				: normalizeFieldValueByType(field, field.value, 'initial')
		if (field.type === 'multipleSelect' && (!Array.isArray(nextValue) || !nextValue.length)) {
			return
		}
		values[field.key] = nextValue
	})
	return normalizeMultipleSelectValuesInMap(list, normalizeSelectValuesInMap(list, values))
}

/** strip 前合并 schema 模板默认(含 numberInput 0);详情 initialValues 优先 */
export function mergeTemplateDefaultsIntoInitialValues(schemaList = [], initialValues = {}) {
	const templateDefaults = buildInitialValues(schemaList)
	return { ...templateDefaults, ...initialValues }
}

/** 用详情回显 initialValues 覆盖 buildInitialValues 结果(schema 不带 .value) */
export function applyInitialValues(values = {}, initialValues = {}) {
	if (!initialValues || typeof initialValues !== 'object') {
		return values
	}
	const next = { ...values }
	Object.keys(initialValues).forEach(key => {
		if (initialValues[key] !== undefined) {
			next[key] = initialValues[key]
		}
	})
	return next
}

/** @param {object} values - 当前 values
 *  @param {string} key - 字段 key
 *  @returns {*} 字段值 */
export function getFieldValue(values, key) {
	return values[key]
}

/** 设置顶层字段值,空值会从 values 中删除对应 key
 *  @returns {object} 新的 values 对象 */
export function setFieldValue(values, key, value) {
	if (
		value === '' ||
		value === null ||
		value === undefined ||
		(Array.isArray(value) && value.length === 0)
	) {
		const nextValues = { ...values }
		delete nextValues[key]
		return nextValues
	}
	return {
		...values,
		[key]: value
	}
}

/** 清除静态 group / 顶层字段中因场景、品牌不匹配的 values(对齐 App 跨场景不入库) */
export function clearHiddenStaticGroupChildValues(list, ctx, values) {
	const visibilityOptions = { schemaList: list }
	const nextValues = { ...values }
	let changed = false

	const clearIfStructuralMismatch = field => {
		if (!field?.key) {
			return
		}
		if (!failsStructuralPersistVisibility(field, ctx, nextValues, visibilityOptions)) {
			return
		}
		if (nextValues[field.key] !== undefined) {
			delete nextValues[field.key]
			changed = true
		}
	}

	;(list || []).forEach(field => {
		if (field.type === 'group' || field.type === 'subform' || field.type === 'divider') {
			return
		}
		clearIfStructuralMismatch(field)
	})

	listStaticGroups(list).forEach(group => {
		getStaticGroupChildren(group).forEach(clearIfStructuralMismatch)
	})

	return changed ? nextValues : values
}

/** 清除误挂在顶层的 subform 列 key;跨场景(baseSceneCode/品牌)不匹配字段一并清理 */
export function clearHiddenFieldValues(list, ctx, values) {
	const subformChildKeys = new Set()
	listSubforms(list).forEach(subform => {
		getSubformRowTemplate(subform).forEach(child => {
			if (child?.key) subformChildKeys.add(child.key)
		})
	})

	const nextValues = { ...values }
	Object.keys(nextValues).forEach(key => {
		if (subformChildKeys.has(key)) {
			delete nextValues[key]
		}
	})
	return clearHiddenStaticGroupChildValues(list, ctx, nextValues)
}

/** 清除 subform 行内不可见 cell 的值(场景 spec + childrenShowRules) */
function filterConditionalMultipleSelectValue(field, value, ctx) {
	if (
		field?.type !== 'multipleSelect' ||
		!hasFieldOptionVisibilityConditions(field) ||
		!Array.isArray(value)
	) {
		return value
	}
	return filterMultipleSelectValueByVisibleOptions(field, value, ctx)
}

/** 清除因选项声明式显隐上下文变化而不可再选择的 multipleSelect 值。 */
export function clearUnavailableOptionValues(list, ctx, values) {
	const nextValues = { ...values }
	let changed = false

	const filterValue = (field, valueMap) => {
		if (!field?.key || valueMap[field.key] === undefined) return false
		const previous = valueMap[field.key]
		const filtered = filterConditionalMultipleSelectValue(field, previous, ctx)
		if (filtered === previous || filtered.length === previous.length) return false
		if (filtered.length) valueMap[field.key] = filtered
		else delete valueMap[field.key]
		changed = true
		return true
	}

	;(list || []).forEach(field => {
		if (field.type !== 'group' && field.type !== 'subform' && field.type !== 'divider') {
			filterValue(field, nextValues)
		}
	})
	listStaticGroups(list).forEach(group => {
		getStaticGroupChildren(group).forEach(child => filterValue(child, nextValues))
	})
	listSubforms(list).forEach(group => {
		const template = getSubformRowTemplateForAdd(group)
		if (!template.length) return
		const rows = getGroupRows(nextValues, group.key)
		if (!rows.length) return
		let rowsChanged = false
		const nextRows = rows.map(row => {
			const nextRow = { ...row }
			template.forEach(child => {
				if (filterValue(child, nextRow)) rowsChanged = true
			})
			return nextRow
		})
		if (rowsChanged) nextValues[group.key] = nextRows
	})

	return changed ? nextValues : values
}

export function clearHiddenSubformRowValues(list, ctx, values) {
	const visibleSubformKeys = new Set(
		getVisibleList(list, ctx, values)
			.filter(field => field.type === 'subform')
			.map(field => field.key)
	)
	const nextValues = { ...values }

	listSubforms(list).forEach(group => {
		const groupKey = group.key
		if (!groupKey || !visibleSubformKeys.has(groupKey)) {
			return
		}
		const template = getSubformRowTemplateForAdd(group)
		if (!template.length) {
			return
		}
		const rows = getGroupRows(nextValues, groupKey)
		if (!rows.length) {
			return
		}

		let changed = false
		const nextRows = rows.map(rowMap => {
			const rowFields = resolveEffectiveRowFields(group, [], rowMap)
			const visibleKeys = new Set(
				getVisibleGroupChildFields(group, ctx, nextValues, list, rowFields, rowMap).map(
					field => field.key
				)
			)
			const nextRow = { ...rowMap }
			template.forEach(child => {
				if (!child?.key || visibleKeys.has(child.key)) {
					return
				}
				if (nextRow[child.key] !== undefined) {
					delete nextRow[child.key]
					changed = true
				}
			})
			return nextRow
		})

		if (changed) {
			nextValues[groupKey] = nextRows
		}
	})

	return nextValues
}