subform-invariants.js
1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 子表 cache / values 对齐断言(开发态与单测)
* @see packageDynamicForm/docs/ARCHITECTURE.md § 子表双状态不变式
*/
import { rowsToValueMaps } from './group-row-adapter.js'
import { getGroupRows } from './group-values.js'
function mapsEqual(a = [], b = []) {
if (a.length !== b.length) return false
return a.every((row, i) => {
const other = b[i] || {}
const keys = new Set([...Object.keys(row), ...Object.keys(other)])
return [...keys].every(k => JSON.stringify(row[k]) === JSON.stringify(other[k]))
})
}
/**
* @param {object} values
* @param {object} groupRowsCache
* @param {string} groupKey
* @throws {Error} 未对齐时
*/
export function assertSubformCacheValuesAligned(values, groupRowsCache, groupKey) {
const fromValues = getGroupRows(values, groupKey)
const rowList = groupRowsCache[groupKey]
if (!rowList?.length && !fromValues.length) return
const fromCache = rowsToValueMaps(rowList || [])
if (!mapsEqual(fromValues, fromCache)) {
throw new Error(
`subform ${groupKey}: values 与 groupRowsCache 未对齐(行数 ${fromValues.length} vs ${fromCache.length})`
)
}
}
/** @param {object} engine createFormEngine 实例 */
export function assertEngineSubformsAligned(engine) {
const values = engine.getValues?.() || {}
const cache = engine.getGroupRowsCache?.() || {}
const root = engine.getSchemaRoot?.() || {}
const list = root.list || []
list
.filter(f => f.type === 'subform' && f.key)
.forEach(f => assertSubformCacheValuesAligned(values, cache, f.key))
}