group-show-rule-eval.js 1.33 KB
/**
 * childrenShowRules.result 求值(小程序无 new Function)
 * 内置 fallback 解析:valN == '…'、valN != null,多条件用 && 连接
 */
function evalPart(part = '', ctx = {}) {
	const trimmed = part.trim()
	const eqMatch = trimmed.match(/^val(\d+)\s*==\s*(?:'([^']*)'|"([^"]*)")$/)
	if (eqMatch) {
		const actual = ctx[`val${eqMatch[1]}`]
		const expected = eqMatch[2] != null ? eqMatch[2] : eqMatch[3]
		return actual == expected
	}
	const neNullMatch = trimmed.match(/^val(\d+)\s*!=\s*null$/)
	if (neNullMatch) {
		const actual = ctx[`val${neNullMatch[1]}`]
		return actual != null && actual !== ''
	}
	return false
}

function fallbackEvaluate(expr = '', ctx = {}) {
	if (!expr) return true
	return expr.split('&&').every(part => evalPart(part, ctx))
}

function evaluateShowRule(keys = [], resultExpr = '', rowFields = [], getRowFieldValue) {
	if (!keys.length || !resultExpr) {
		return true
	}
	try {
		const ctx = {}
		keys.forEach((key, index) => {
			ctx[`val${index + 1}`] = getRowFieldValue(rowFields, key)
		})
		return fallbackEvaluate(resultExpr, ctx)
	} catch (error) {
		console.error('[evaluateShowRule] eval error', resultExpr, error)
		return false
	}
}

export { evaluateShowRule, fallbackEvaluate }

if (typeof module !== 'undefined' && module.exports) {
	module.exports = {
		evaluateShowRule,
		fallbackEvaluate
	}
}