group-rows-cache.js 9.04 KB
/** subform 行 FormField[] 缓存 — @see packageDynamicForm/docs/ARCHITECTURE.md */
import {
	cloneRowTemplateForAdd,
	cloneRowFieldsList,
	rowFieldsToValueMap,
	rowsToValueMaps,
	valueMapToRowFieldsFromOrigin,
	valueMapsToRowFieldsFromOrigin
} from './group-row-adapter.js'
import { getSubformRowTemplateForAdd } from './field-types.js'
import { normalizeOptionRecord } from './field-submit-value.js'
import { getGroupRows, listGroups } from './group-values.js'
import { clearHiddenFieldValues, clearHiddenSubformRowValues } from './values.js'
import { filterVisibleRowFields } from './group-visibility.js'
import {
	resolveEffectiveRowFields,
	filterSubformRowFieldsByVisibility,
	getVisibleList
} from './visibility.js'
import { listSubforms } from './field-types.js'
import { resolveSubformMaxRows } from './subform-limits.js'

/** 从 values 构建 groupRowsCache(FormField[][])
 *  @returns {object} groupKey → FormField[][] */
export function buildGroupRowsCache(list = [], values = {}) {
	const cache = {}
	listGroups(list).forEach(group => {
		const columnTemplate = cloneRowTemplateForAdd(group)
		const maps = getGroupRows(values, group.key)
		if (!columnTemplate.length || !maps.length) {
			cache[group.key] = []
			return
		}
		cache[group.key] = valueMapsToRowFieldsFromOrigin(columnTemplate, maps)
	})
	return cache
}

/** 将 cache 中某 subform 的行数据同步回 values
 *  @returns {object} 新的 values 对象 */
export function syncValuesFromGroupCache(values = {}, groupKey, rowFieldsList = []) {
	return {
		...values,
		[groupKey]: rowsToValueMaps(rowFieldsList)
	}
}

function isEmptyRowFields(rowFields) {
	return !Array.isArray(rowFields) || !rowFields.length
}

/** values 有行而 cache 行快照为空时,从 valueMap 补全 cache(校验前防御) */
export function repairGroupRowsCacheFromValues(list = [], values = {}, cache = {}) {
	const next = { ...cache }
	listGroups(list).forEach(group => {
		const groupKey = group.key
		if (!groupKey) return
		const columnTemplate = getSubformRowTemplateForAdd(group)
		if (!columnTemplate.length) return
		const maps = getGroupRows(values, groupKey)
		if (!maps.length) return
		const rowList = cloneRowFieldsList(next[groupKey] || [])
		while (rowList.length < maps.length) {
			rowList.push([])
		}
		let changed = false
		maps.forEach((valueMap, rowIndex) => {
			if (isEmptyRowFields(rowList[rowIndex])) {
				rowList[rowIndex] = valueMapToRowFieldsFromOrigin(
					columnTemplate,
					valueMap || {}
				)
				changed = true
			}
		})
		if (changed || rowList.length) {
			next[groupKey] = rowList
		}
	})
	return next
}

/** rebuild 后剔除不可见 cell(可见块:场景 spec + childrenShowRules;隐藏块:仅 childrenShowRules) */
export function stripHiddenSubformCellsFromCache(list = [], ctx = {}, values = {}, cache = {}) {
	const visibleSubformKeys = new Set(
		getVisibleList(list, ctx, values)
			.filter(field => field.type === 'subform')
			.map(field => field.key)
	)
	const next = { ...cache }
	listSubforms(list).forEach(group => {
		const groupKey = group.key
		const rowList = next[groupKey]
		if (!groupKey || !Array.isArray(rowList) || !rowList.length) {
			return
		}
		const maps = getGroupRows(values, groupKey)
		next[groupKey] = rowList.map((rowFields, rowIndex) => {
			const rowMap = maps[rowIndex] || {}
			const effective = resolveEffectiveRowFields(group, rowFields, rowMap)
			if (!visibleSubformKeys.has(groupKey)) {
				return filterVisibleRowFields(group, effective, rowMap, ctx)
			}
			return filterSubformRowFieldsByVisibility(
				group,
				effective,
				rowMap,
				ctx,
				values,
				list
			)
		})
	})
	return next
}

/** 校验/提交前:以 groupRowsCache 为准回写全部 subform 行,避免 values 与 cache 脱节导致误通过 */
export function syncSubformValuesFromCache(values = {}, groupRowsCache = {}, list = [], ctx = {}) {
	let next = { ...values }
	listGroups(list).forEach(group => {
		const rowFieldsList = groupRowsCache[group.key]
		if (Array.isArray(rowFieldsList) && rowFieldsList.length) {
			next = syncValuesFromGroupCache(next, group.key, rowFieldsList)
		}
	})
	return clearHiddenSubformRowValues(
		list,
		ctx,
		clearHiddenFieldValues(list, ctx, next)
	)
}

/** @returns {Array} 指定行的 FormField[] 深拷贝 */
export function getRowFieldsFromCache(cache = {}, groupKey, rowIndex = 0) {
	const list = cache[groupKey]
	if (!Array.isArray(list) || !list.length) {
		return []
	}
	const index = Math.min(Math.max(0, rowIndex), list.length - 1)
	return cloneRowFieldsList(list[index] || [])
}

/** 向 cache 新增 subform 行(受 maxRows 限制)
 *  @returns {{ cache: object, rowIndex: number }} */
export function addRowToCache(cache = {}, group = {}) {
	const groupKey = group.key
	const maxRows = resolveSubformMaxRows(group)
	const list = cache[groupKey] ? [...cache[groupKey]] : []
	if (list.length >= maxRows) {
		return { cache: { ...cache, [groupKey]: list }, rowIndex: Math.max(0, list.length - 1) }
	}
	list.push(cloneRowTemplateForAdd(group))
	return {
		cache: { ...cache, [groupKey]: list },
		rowIndex: list.length - 1
	}
}

/** 从 cache 删除 subform 指定行
 *  @returns {object} 新的 cache */
export function removeRowFromCache(cache = {}, groupKey, rowIndex) {
	const list = [...(cache[groupKey] || [])]
	list.splice(rowIndex, 1)
	const next = { ...cache }
	if (list.length) {
		next[groupKey] = list
	} else {
		delete next[groupKey]
	}
	return next
}

function seedEmptyRow(rowTemplate = null) {
	if (rowTemplate?.length) {
		return cloneRowFieldsList([rowTemplate])[0] || []
	}
	return []
}

/** 设置 cache 中某行子字段值
 *  @returns {object} 新的 cache */
export function setRowFieldInCache(cache = {}, groupKey, rowIndex, childKey, value, rowTemplate = null) {
	const list = cloneRowFieldsList(cache[groupKey] || [])
	while (list.length <= rowIndex) {
		list.push(seedEmptyRow(rowTemplate))
	}
	let row = [...(list[rowIndex] || [])]
	let idx = row.findIndex(f => f.key === childKey)
	if (idx === -1 && rowTemplate?.length) {
		const existingMap = rowFieldsToValueMap(row)
		list[rowIndex] = valueMapToRowFieldsFromOrigin(rowTemplate, existingMap)
		row = [...list[rowIndex]]
		idx = row.findIndex(f => f.key === childKey)
	}
	if (idx === -1) {
		return cache
	}
	const field = { ...row[idx] }
	const fieldKey = field.key ?? childKey
	if (
		value === '' ||
		value === null ||
		value === undefined ||
		(Array.isArray(value) && value.length === 0)
	) {
		delete field.value
		if (field.optionsKey && fieldKey != null) {
			delete field[fieldKey]
		}
	} else {
		field.value = value
		if (field.optionsKey && fieldKey != null) {
			if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
				const normalized = normalizeOptionRecord(value) || value
				field[fieldKey] = normalized
				field.value = normalized.name ?? normalized.label ?? field.value
			} else {
				field[fieldKey] = value
			}
		}
	}
	row[idx] = field
	list[rowIndex] = row
	return { ...cache, [groupKey]: list }
}

/** 洽谈 App 双 key:value=展示名,field[key]=id/meta */
export function setNegotiationDualKeyFieldInCache(
	cache = {},
	groupKey,
	rowIndex,
	childKey,
	{ id, displayLabel, metaValue } = {},
	rowTemplate = null
) {
	const list = cloneRowFieldsList(cache[groupKey] || [])
	while (list.length <= rowIndex) {
		list.push(seedEmptyRow(rowTemplate))
	}
	let row = [...(list[rowIndex] || [])]
	let idx = row.findIndex(f => f.key === childKey)
	if (idx === -1 && rowTemplate?.length) {
		const existingMap = rowFieldsToValueMap(row)
		list[rowIndex] = valueMapToRowFieldsFromOrigin(rowTemplate, existingMap)
		row = [...list[rowIndex]]
		idx = row.findIndex(f => f.key === childKey)
	}
	if (idx === -1) {
		return cache
	}

	const field = { ...row[idx] }
	const storedId = metaValue != null ? metaValue : id

	if (
		storedId === '' ||
		storedId === null ||
		storedId === undefined ||
		(Array.isArray(storedId) && storedId.length === 0)
	) {
		delete field.value
		delete field[childKey]
	} else {
		if (displayLabel != null && displayLabel !== '') {
			field.value = displayLabel
		} else if (typeof storedId === 'object' && storedId !== null && !Array.isArray(storedId)) {
			field.value = storedId.name ?? storedId.label ?? storedId.displayText ?? ''
		} else {
			field.value = String(storedId)
		}
		if (
			field.optionsKey &&
			storedId != null &&
			typeof storedId === 'object' &&
			!Array.isArray(storedId)
		) {
			field[childKey] = normalizeOptionRecord(storedId) || storedId
		} else {
			field[childKey] = storedId
		}
	}

	row[idx] = field
	list[rowIndex] = row
	return { ...cache, [groupKey]: list }
}

/** 整行深拷贝回写 cache
 *  @returns {object} 新的 cache */
export function replaceRowInCache(cache = {}, groupKey, rowIndex, rowFields = [], rowTemplate = null) {
	const list = cloneRowFieldsList(cache[groupKey] || [])
	while (list.length <= rowIndex) {
		list.push(seedEmptyRow(rowTemplate))
	}
	list[rowIndex] = cloneRowFieldsList(rowFields)
	return { ...cache, [groupKey]: list }
}

/** @returns {Array} 某 subform 全部行的 FormField[][] 深拷贝 */
export function getGroupRowFieldsList(cache = {}, groupKey) {
	return cloneRowFieldsList(cache[groupKey] || [])
}