group-values.js 7.93 KB
import {
	cloneRowTemplate,
	cloneRowTemplateForAdd,
	rowFieldsToValueMap,
	rowsToValueMaps
} from './group-row-adapter.js'
import { listSubforms, getSubformRowTemplate, getStaticGroupChildren } from './field-types.js'
import { flattenFields } from './visibility.js'
import { parseFieldDataEchoValue } from './field-submit-value.js'
import { resolveSubformMaxRows } from './subform-limits.js'

function buildFieldKeyMap(list = []) {
	const map = new Map()
	flattenFields(list).forEach(field => {
		if (field?.key) {
			map.set(field.key, field)
		}
	})
	return map
}

function echoFieldDataValue(fieldKey, coercedValue, fieldKeyMap) {
	const field = fieldKeyMap.get(fieldKey)
	if (!field) {
		return coercedValue
	}
	return parseFieldDataEchoValue(field, coercedValue)
}

/** subform 多行子表单 values 工具 — @see packageDynamicForm/docs/ARCHITECTURE.md */

/** 构建 subform 行内字段的错误 key */
export function buildGroupErrorKey(groupKey, rowIndex, childKey) {
	return `${groupKey}__${rowIndex}__${childKey}`
}

/** 解析 buildGroupErrorKey 生成的错误 key
 *  @returns {{ groupKey: string, rowIndex: number, childKey: string }|null} */
export function parseGroupErrorKey(errorKey = '') {
	const match = String(errorKey).match(/^(.+)__(\d+)__(.+)$/)
	if (!match) return null
	return {
		groupKey: match[1],
		rowIndex: Number(match[2]),
		childKey: match[3]
	}
}

/** @returns {Array} schema 中所有 subform 字段 */
export function listGroups(list = []) {
	return listSubforms(list)
}

/** @returns {Array<object>} subform 行 valueMap 数组的浅拷贝 */
export function getGroupRows(values = {}, groupKey = '') {
	const rows = values[groupKey]
	if (!Array.isArray(rows)) {
		return []
	}
	return rows.map(row => (row && typeof row === 'object' ? { ...row } : {}))
}

function normalizeChildValue(value) {
	if (
		value === '' ||
		value === null ||
		value === undefined ||
		(Array.isArray(value) && value.length === 0)
	) {
		return undefined
	}
	return value
}

/** 设置 subform 行内子字段值
 *  @returns {object} 新的 values 对象 */
export function setGroupFieldValue(values = {}, groupKey, rowIndex, childKey, value) {
	const rows = getGroupRows(values, groupKey)
	while (rows.length <= rowIndex) {
		rows.push({})
	}
	const row = { ...rows[rowIndex] }
	const normalized = normalizeChildValue(value)
	if (normalized === undefined) {
		delete row[childKey]
	} else {
		row[childKey] = normalized
	}
	rows[rowIndex] = row
	return {
		...values,
		[groupKey]: rows
	}
}

/** 新增 subform 行(受 maxRows 限制)
 *  @returns {{ values: object, rowIndex: number }} */
export function addGroupRow(values = {}, group = {}) {
	const groupKey = group.key
	const maxRows = group.rules?.maxRows ?? 20
	const rows = getGroupRows(values, groupKey)
	if (rows.length >= maxRows) {
		return { values, rowIndex: Math.max(0, rows.length - 1) }
	}
	rows.push(rowFieldsToValueMap(cloneRowTemplateForAdd(group)))
	return {
		values: {
			...values,
			[groupKey]: rows
		},
		rowIndex: rows.length - 1,
		added: true
	}
}

/** 删除 subform 指定行
 *  @returns {object} 新的 values 对象 */
export function removeGroupRow(values = {}, groupKey, rowIndex) {
	const rows = getGroupRows(values, groupKey)
	rows.splice(rowIndex, 1)
	const next = { ...values }
	if (rows.length) {
		next[groupKey] = rows
	} else {
		delete next[groupKey]
	}
	return next
}

/** 整行 FormField[] 回写为 valueMap
 *  @returns {object} 新的 values 对象 */
export function replaceGroupRow(values = {}, groupKey, rowIndex, rowFields = []) {
	const rows = getGroupRows(values, groupKey)
	while (rows.length <= rowIndex) {
		rows.push({})
	}
	rows[rowIndex] = rowFieldsToValueMap(rowFields)
	return {
		...values,
		[groupKey]: rows
	}
}

/** fieldDataList 含 groupKey/rowIndex 时还原为 values 嵌套结构
 *  fieldDataList 覆盖 jsonContent(后端 normalized 列表为准)
 *  扁平 subform 子 key(无 groupKey)按 rowIndex 0 兜底写入
 *  @returns {object} 合并后的 values */
export function mergeFieldDataListIntoValues(list = [], fieldDataList = [], values = {}) {
	let next = { ...values }
	const fieldKeyMap = buildFieldKeyMap(list)
	const groupChildKeySet = new Map()
	const childKeyToGroup = new Map()
	listSubforms(list).forEach(group => {
		const keys = new Set(getSubformRowTemplate(group).map(c => c.key))
		groupChildKeySet.set(group.key, keys)
		getSubformRowTemplate(group).forEach(child => {
			if (child?.key) {
				childKeyToGroup.set(child.key, group.key)
			}
		})
	})

	function writeSubformCell(groupKey, rowIndex, fieldKey, coercedValue) {
		if (coercedValue === undefined) {
			return
		}
		if (!Array.isArray(next[groupKey])) {
			next[groupKey] = []
		}
		while (next[groupKey].length <= rowIndex) {
			next[groupKey].push({})
		}
		const row = { ...next[groupKey][rowIndex] }
		row[fieldKey] = coercedValue
		next[groupKey][rowIndex] = row
		if (groupChildKeySet.get(groupKey)?.has(fieldKey)) {
			delete next[fieldKey]
		}
	}

	fieldDataList.forEach(item => {
		if (!item?.fieldKey) return
		const coercedValue = echoFieldDataValue(
			item.fieldKey,
			coerceFieldDataListItemValue(item),
			fieldKeyMap
		)
		const groupKey = item.groupKey
		const rowIndexRaw = item.rowIndex
		if (groupKey != null && rowIndexRaw != null && groupChildKeySet.has(groupKey)) {
			const rowIndex = Number(rowIndexRaw)
			if (Number.isNaN(rowIndex) || rowIndex < 0) {
				return
			}
			writeSubformCell(groupKey, rowIndex, item.fieldKey, coercedValue)
			return
		}
		if (coercedValue !== undefined) {
			const parentGroupKey = childKeyToGroup.get(item.fieldKey)
			if (parentGroupKey) {
				const rowIndexRawFlat = item.rowIndex
				const rowIndex =
					rowIndexRawFlat != null && rowIndexRawFlat !== ''
						? Number(rowIndexRawFlat)
						: 0
				if (!Number.isNaN(rowIndex) && rowIndex >= 0) {
					writeSubformCell(parentGroupKey, rowIndex, item.fieldKey, coercedValue)
				}
				return
			}
			next[item.fieldKey] = coercedValue
		}
	})
	return next
}

/** subformDataList 还原为 values[parentFieldKey][rowIndex][columnFieldKey]
 *  subformDataList 覆盖 jsonContent 同 cell(二次编辑后端 jsonContent 可能滞后)
 *  @returns {object} 合并后的 values */
export function mergeSubformDataListIntoValues(list = [], subformDataList = [], values = {}) {
	let next = { ...values }
	const fieldKeyMap = buildFieldKeyMap(list)
	const subformKeySet = new Set(listSubforms(list).map(group => group.key))
	const hasSchema = subformKeySet.size > 0

	subformDataList.forEach(item => {
		const parentFieldKey = item?.parentFieldKey
		const columnFieldKey = item?.columnFieldKey
		const rowIndexRaw = item?.rowIndex
		if (!parentFieldKey || !columnFieldKey || rowIndexRaw == null) {
			return
		}
		const rowIndex = Number(rowIndexRaw)
		if (Number.isNaN(rowIndex) || rowIndex < 0) {
			return
		}
		if (hasSchema && !subformKeySet.has(parentFieldKey)) {
			return
		}
		const coercedValue = echoFieldDataValue(
			columnFieldKey,
			coerceFieldDataListItemValue(item),
			fieldKeyMap
		)
		if (coercedValue === undefined) {
			return
		}
		if (!Array.isArray(next[parentFieldKey])) {
			next[parentFieldKey] = []
		}
		while (next[parentFieldKey].length <= rowIndex) {
			next[parentFieldKey].push({})
		}
		const row = { ...next[parentFieldKey][rowIndex] }
		row[columnFieldKey] = coercedValue
		next[parentFieldKey][rowIndex] = row
	})
	return next
}

function coerceFieldDataListItemValue(item = {}) {
	const { fieldValue, fieldType } = item
	if (fieldValue === undefined || fieldValue === null || fieldValue === '') {
		return undefined
	}
	if (fieldType === 'JSON' && typeof fieldValue === 'string') {
		try {
			return JSON.parse(fieldValue)
		} catch (error) {
			return fieldValue
		}
	}
	if (fieldType === 'INT' || fieldType === 'DECIMAL') {
		if (typeof fieldValue === 'string') {
			const num = Number(fieldValue)
			return Number.isNaN(num) ? fieldValue : num
		}
	}
	if (fieldType === 'BOOL' && typeof fieldValue === 'string') {
		if (fieldValue === 'true') return true
		if (fieldValue === 'false') return false
	}
	return fieldValue
}