group-row-snapshot.js 2.71 KB
/** 供小程序组件使用:从 groupRowsCache 深拷贝当前行,避免 wxs 直引导致多行/多 group 串联 */

import { filterVisibleRowFields } from './group-visibility.js'
import { filterSubformRowFieldsByVisibility } from './visibility.js'
import { rowFieldsToValueMap } from './group-row-adapter.js'

function cloneJson(data) {
	return JSON.parse(JSON.stringify(data))
}

function resolveRowIndex(activeIndex, rowLength) {
	let idx = Number(activeIndex)
	if (Number.isNaN(idx) || idx < 0) idx = 0
	if (rowLength > 0 && idx >= rowLength) idx = rowLength - 1
	return idx
}

export function getRowFieldsSnapshot(cache = {}, groupKey = '', activeIndex = 0) {
	const list = cache[groupKey]
	if (!Array.isArray(list) || !list.length) {
		return []
	}
	const idx = resolveRowIndex(activeIndex, list.length)
	return cloneJson(list[idx] || [])
}

export function getGroupRowTotal(cache = {}, groupKey = '', values = {}) {
	const list = cache[groupKey]
	if (Array.isArray(list) && list.length) {
		return list.length
	}
	const rows = values[groupKey]
	return rows && rows.length ? rows.length : 0
}

export function buildVisibleRowFields(
	group = {},
	rowFields = [],
	activeIndex = 0,
	rowTotal = 0,
	visibilityContext = null
) {
	const groupKey = group.key || ''
	const index = resolveRowIndex(activeIndex, rowTotal)
	let visible = rowFields
	try {
		const ctx = visibilityContext?.ctx
		const list = visibilityContext?.list
		const values = visibilityContext?.values ?? {}
		if (ctx && Array.isArray(list)) {
			const rowMap = rowFieldsToValueMap(rowFields)
			visible = filterSubformRowFieldsByVisibility(
				group,
				rowFields,
				rowMap,
				ctx,
				values,
				list
			)
		} else if (typeof filterVisibleRowFields === 'function') {
			visible = filterVisibleRowFields(group, rowFields)
		}
	} catch (error) {
		console.error('[group-row-snapshot] buildVisibleRowFields', error)
	}
	const withKeys = (visible || []).map((field, fieldIdx) => ({
		...field,
		_wxRowKey: `${groupKey}_${index}_${field.key || fieldIdx}`
	}))
	return cloneJson(withKeys)
}

export function buildGroupRowViewMaps(
	groupFields = [],
	cache = {},
	activeMap = {},
	values = {},
	visibilityContext = null
) {
	const groupRowFieldsMap = {}
	const groupRowVisibleMap = {}
	const groupRowTotalMap = {}
	;(groupFields || []).forEach(group => {
		const key = group?.key
		if (!key) return
		const rowTotal = getGroupRowTotal(cache, key, values)
		const rowFields = getRowFieldsSnapshot(cache, key, activeMap[key])
		groupRowFieldsMap[key] = rowFields
		groupRowTotalMap[key] = rowTotal
		groupRowVisibleMap[key] = buildVisibleRowFields(
			group,
			rowFields,
			activeMap[key],
			rowTotal,
			visibilityContext
		)
	})
	return { groupRowFieldsMap, groupRowVisibleMap, groupRowTotalMap }
}