unis-oa/frontend/src/utils/designDiff.ts

81 lines
3.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* 「还有几处没保存到服务器」这笔账怎么算。
*
* 设计器一次保存送出去的是整张图:环节、路由、默认表单、流程级审批规则,外加流程信息。
* 只告诉用户「有未保存的修改」不够 —— 挪动一个角标和画了半小时看上去一模一样,
* 于是谁都不敢点离开。这里把两份快照摆在一起数一数,说清是哪几类东西还留在浏览器里。
*
* 纯函数:不碰响应式,也不认得 Vue,方便单独测。
*/
export interface DesignItemLike {
id: string
[key: string]: unknown
}
export interface DesignSnapshotLike {
activities?: DesignItemLike[]
routes?: DesignItemLike[]
latestForm?: string
approval?: Record<string, unknown>
meta?: Record<string, unknown>
/** 连线样式与圆角:也在这一次保存里落库,所以也得算进「没保存」这笔账 */
edgeStyle?: string
edgeRadius?: number
}
export type DesignDiffKey = 'nodes' | 'routes' | 'form' | 'approval' | 'display' | 'meta'
export interface DesignDiff {
total: number
parts: Record<DesignDiffKey, number>
/** 只留下真有改动的分组,顺序就是界面上列出来的顺序。 */
groups: { key: DesignDiffKey; count: number }[]
}
const ORDER: DesignDiffKey[] = ['nodes', 'routes', 'form', 'approval', 'display', 'meta']
function sameValue(a: unknown, b: unknown): boolean {
return JSON.stringify(a ?? null) === JSON.stringify(b ?? null)
}
/** 一条列表改了几处:新增 + 删除 + 内容有变的,都算一处。 */
function diffList(before: DesignItemLike[] = [], after: DesignItemLike[] = []): number {
const beforeById = new Map(before.map((item) => [item.id, item]))
const afterIds = new Set(after.map((item) => item.id))
let count = 0
after.forEach((item) => {
const previous = beforeById.get(item.id)
if (!previous || !sameValue(previous, item)) count += 1
})
before.forEach((item) => {
if (!afterIds.has(item.id)) count += 1
})
return count
}
/** 流程信息按字段数:改了名称和说明是两处,不是"这一栏动过"一处。 */
function diffRecord(before: Record<string, unknown> = {}, after: Record<string, unknown> = {}): number {
const keys = new Set([...Object.keys(before), ...Object.keys(after)])
let count = 0
keys.forEach((key) => {
if (!sameValue(before[key], after[key])) count += 1
})
return count
}
export function diffDesign(before: DesignSnapshotLike, after: DesignSnapshotLike): DesignDiff {
const parts: Record<DesignDiffKey, number> = {
nodes: diffList(before.activities, after.activities),
routes: diffList(before.routes, after.routes),
form: sameValue(before.latestForm, after.latestForm) ? 0 : 1,
approval: sameValue(before.approval, after.approval) ? 0 : 1,
// 画布摆法合成一处:换了连线样式、动了圆角,都是一次"我要存一下",不该拆成两条吓人
display:
sameValue(before.edgeStyle, after.edgeStyle) && sameValue(before.edgeRadius, after.edgeRadius) ? 0 : 1,
meta: diffRecord(before.meta, after.meta)
}
const groups = ORDER.filter((key) => parts[key] > 0).map((key) => ({ key, count: parts[key] }))
return { total: groups.reduce((sum, item) => sum + item.count, 0), parts, groups }
}