group-visibility.js 2.28 KB
/** 行内子字段显隐 childrenShowRules(对齐 gl_tape EditForm.itemShow) */
import { evaluateShowRule } from './group-show-rule-eval.js'
import { resolveShowRuleContextValue } from './show-rule-context.js'

function normalizeShowRuleValue(value) {
	if (Array.isArray(value)) {
		const aliases = []
		value.forEach(item => {
			if (item && typeof item === 'object' && !Array.isArray(item)) {
				;[item.value, item.id, item.name, item.label].forEach(alias => {
					if (alias != null && alias !== '' && !Array.isArray(alias)) {
						aliases.push(String(alias))
					}
				})
				return
			}
			if (item != null && item !== '') aliases.push(String(item))
		})
		return [...new Set(aliases)]
	}
	if (value && typeof value === 'object') {
		const alias = value.name ?? value.label ?? value.text ?? value.value ?? value.id
		return alias === undefined ? value : normalizeShowRuleValue(alias)
	}
	return value
}

function getRowFieldValue(rowFields = [], key = '', rowMap = null) {
	const field = (rowFields || []).find(item => item.key === key)
	if (field) {
		if (field.value != null && field.value !== '') {
			return normalizeShowRuleValue(field.value)
		}
		const metaKey = field.key
		if (metaKey != null && field[metaKey] != null && field[metaKey] !== '') {
			return normalizeShowRuleValue(field[metaKey])
		}
	}
	if (rowMap && rowMap[key] != null && rowMap[key] !== '') {
		return normalizeShowRuleValue(rowMap[key])
	}
	return null
}

function isGroupChildVisibleInRow(
	group = {},
	child = {},
	rowFields = [],
	rowMap = null,
	pageContext = {}
) {
	const rules = group.childrenShowRules
	if (!rules || !child?.key) {
		return true
	}
	const rule = rules[child.key]
	if (!rule) {
		return true
	}
	const keys = rule.keys || []
	const resultExpr = rule.result
	if (!keys.length || !resultExpr) {
		return true
	}
	return evaluateShowRule(keys, resultExpr, rowFields, (rf, k) => {
		const contextValue = resolveShowRuleContextValue(k, pageContext)
		return contextValue !== undefined ? contextValue : getRowFieldValue(rf, k, rowMap)
	})
}

function filterVisibleRowFields(group = {}, rowFields = [], rowMap = null, pageContext = {}) {
	return (rowFields || []).filter(field =>
		isGroupChildVisibleInRow(group, field, rowFields, rowMap, pageContext)
	)
}

export { isGroupChildVisibleInRow, filterVisibleRowFields }