/** * Pure maths for the process canvas: node metrics, edge geometry, layered * auto-layout and the designer-side mirror of the engine's validation rules. * * Nothing here touches Vue so the designer stays thin and this file stays * testable. The persisted shape (activities with x/y, routes) is unchanged. */ import type { IconName } from '@/components/icons/Icon.vue' import type { Activity, ActivityType, CcRule, FormFieldDef, RouteDef } from '@/types' export const NODE_W = 208 export const NODE_H = 92 export const CANVAS_GRID = 8 export const MIN_ZOOM = 0.3 export const MAX_ZOOM = 2.4 /** Palette grouping, mirrors the order the engine lists activity types. */ export const PALETTE_GROUPS: { key: string; types: ActivityType[] }[] = [ { key: 'basic', types: ['begin', 'manual', 'end', 'cancel'] }, { key: 'branch', types: ['choice', 'parallel', 'merge', 'split'] }, { key: 'automation', types: ['script', 'invoke', 'embed', 'delay'] } ] export const TYPE_ICONS: Record = { begin: 'play', manual: 'userCheck', choice: 'gitBranch', parallel: 'shuffle', merge: 'gitMerge', split: 'list', script: 'terminal', invoke: 'globe', embed: 'cube', delay: 'clock', end: 'flag', cancel: 'ban' } /** Header / accent colour per activity type (Langflow colours by component). */ export const TYPE_COLORS: Record = { begin: '#059669', end: '#dc2626', cancel: '#64748b', manual: '#0d9488', choice: '#d97706', parallel: '#7c3aed', merge: '#7c3aed', split: '#7c3aed', script: '#2563eb', invoke: '#2563eb', embed: '#2563eb', delay: '#0891b2' } /** Types the palette can create; begin/end exist once per process. */ export const ADDABLE_TYPES: ActivityType[] = [ 'manual', 'choice', 'parallel', 'merge', 'split', 'script', 'invoke', 'embed', 'delay', 'begin', 'end', 'cancel' ] export type Side = 'in' | 'out' export interface Point { x: number y: number } export function typeColor(type: string): string { return TYPE_COLORS[type] ?? '#64748b' } /** Where a port sits in world coordinates. */ export function portPoint(node: Activity, side: Side): Point { return { x: side === 'out' ? node.x + NODE_W : node.x, y: node.y + NODE_H / 2 } } /** * Port for the `index`-th of `total` edges on the same side of a node. * * Spreading the ports instead of stacking every edge on the midpoint is what * keeps a fan-out readable: five lines leaving one step read as five lines * rather than one thick rope that splits somewhere over the canvas. */ export function portAt(node: Activity, side: Side, index: number, total: number): Point { const ratio = (Math.max(1, total) === 1 ? 1 : index + 1) / (Math.max(1, total) + 1) return { x: side === 'out' ? node.x + NODE_W : node.x, y: node.y + NODE_H * ratio } } /** Snap a dragged position to the canvas grid, never off-canvas. */ export function snapPosition(x: number, y: number, step = CANVAS_GRID): Point { return { x: Math.max(0, Math.round(x / step) * step), y: Math.max(0, Math.round(y / step) * step) } } /** * First spot near `want` that does not sit on top of an existing node, so a * palette click never buries the new step under the one behind it. */ export function freePosition(activities: Activity[], want: Point, step = 32): Point { const blocked = (x: number, y: number) => activities.some((item) => Math.abs(item.x - x) < NODE_W - 16 && Math.abs(item.y - y) < NODE_H - 12) const target = { x: Math.max(0, Math.round(want.x)), y: Math.max(0, Math.round(want.y)) } if (!blocked(target.x, target.y)) return target for (let ring = 1; ring <= 10; ring += 1) { for (let dx = -ring; dx <= ring; dx += 1) { for (let dy = -ring; dy <= ring; dy += 1) { if (Math.max(Math.abs(dx), Math.abs(dy)) !== ring) continue const x = target.x + dx * step const y = target.y + dy * step if (x < 0 || y < 0) continue if (!blocked(x, y)) return { x, y } } } } return target } /** * How the designer draws a connection between two steps. * * `orthogonal` is the default: right-angle segments routed through the gaps * between nodes, which is what every mainstream OA designer does once a graph * grows past a handful of steps. `straight` is a bare ruler line and `curve` * is the old bezier look, kept for people who like it. */ export type EdgeStyle = 'orthogonal' | 'straight' | 'curve' export const EDGE_STYLES: EdgeStyle[] = ['orthogonal', 'straight', 'curve'] export const DEFAULT_EDGE_STYLE: EdgeStyle = 'orthogonal' /** 折线拐角圆角半径;0 就是纯直角。 */ export const EDGE_CORNER_RADIUS = 8 /** 出线先直走这么远再拐弯,线头不至于贴着节点边框。 */ export const EDGE_STUB = 20 /** 绕障碍时与节点框保持的呼吸距离。 */ export const EDGE_GUTTER = 16 /** 两条线想用同一条通道时的错车距离。 */ export const EDGE_LANE_STEP = 14 export interface Rectangle { x: number y: number w: number h: number } export interface EdgeOptions { style?: EdgeStyle radius?: number } export function nodeRect(node: Activity): Rectangle { return { x: node.x, y: node.y, w: NODE_W, h: NODE_H } } function rectRight(rect: Rectangle): number { return rect.x + rect.w } function rectBottom(rect: Rectangle): number { return rect.y + rect.h } function inflate(rect: Rectangle, pad: number): Rectangle { return { x: rect.x - pad, y: rect.y - pad, w: rect.w + pad * 2, h: rect.h + pad * 2 } } /** Axis-aligned segment vs rectangle. Every orthogonal segment is one of the two. */ function segmentHitsRect(a: Point, b: Point, rect: Rectangle): boolean { if (a.x === b.x) { const x = a.x const top = Math.min(a.y, b.y) const bottom = Math.max(a.y, b.y) return x > rect.x && x < rectRight(rect) && top < rectBottom(rect) && bottom > rect.y } if (a.y === b.y) { const y = a.y const left = Math.min(a.x, b.x) const right = Math.max(a.x, b.x) return y > rect.y && y < rectBottom(rect) && left < rectRight(rect) && right > rect.x } return false } /** * Midpoints of the empty vertical bands between obstacle columns, narrowest gap * first is not the order we want, so callers sort by distance from their own * ideal channel. `reach` merges overlapping columns into occupied bands. */ function bandCentres(rects: Rectangle[], primary: 'x' | 'y'): number[] { if (!rects.length) return [] const spans = rects .map((rect) => ({ start: primary === 'x' ? rect.x : rect.y, end: primary === 'x' ? rectRight(rect) : rectBottom(rect) })) .sort((a, b) => a.start - b.start) const out: number[] = [] let reach = spans[0].end spans.slice(1).forEach((span) => { if (span.start - reach > EDGE_LANE_STEP * 2) out.push((reach + span.start) / 2) reach = Math.max(reach, span.end) }) return out } function dedupe(points: Point[]): Point[] { const out: Point[] = [] points.forEach((point) => { const last = out[out.length - 1] if (last && Math.abs(last.x - point.x) < 0.5 && Math.abs(last.y - point.y) < 0.5) return const prev = out[out.length - 2] if (prev) { const collinear = (Math.abs(prev.x - last.x) < 0.5 && Math.abs(last.x - point.x) < 0.5) || (Math.abs(prev.y - last.y) < 0.5 && Math.abs(last.y - point.y) < 0.5) if (collinear) { out[out.length - 1] = point return } } out.push(point) }) return out } /** * Right-angle waypoints from an outgoing port to an incoming port. * * Forward edges drop into a vertical channel between the two steps; when the * channel is blocked by a node they pick the next free one. Anything that is * not clearly forward (a reject back to the apply step, two steps in the same * column) takes a horizontal lane above or below the graph instead of cutting * through the middle. `laneOffset` lets the caller nudge edges that would * otherwise sit exactly on top of each other. */ /** * Right-angle waypoints from an outgoing port to an incoming port. * * 排布顺序:先试最省事的"出线 -> 中间竖直通道 -> 进线"三段折;通道被节点占住就 * 换成"绕到上一行/下一行的空档再下来"的五段折;两条都找不到干净走法才退回中线, * 宁可交叉也不把线画到画布外面去。 */ export function edgePolyline(from: Point, to: Point, obstacles: Rectangle[] = [], laneOffset = 0): Point[] { const padded = obstacles.map((rect) => inflate(rect, EDGE_GUTTER)) const clear = (a: Point, b: Point) => !padded.some((rect) => segmentHitsRect(a, b, rect)) const clean = (shape: Point[]) => { for (let i = 0; i < shape.length - 1; i += 1) { if (!clear(shape[i], shape[i + 1])) return false } return true } const stub = Math.max(6, Math.min(EDGE_STUB, Math.abs(to.x - from.x) / 2 || EDGE_STUB)) if (Math.abs(from.y - to.y) < 0.5 && to.x > from.x) return [from, to] // 绕行走廊:整张图最上面/最下面的空行,再加上各列之间已有的横向空档。 const outX = from.x + Math.max(12, Math.min(EDGE_STUB, Math.abs(to.x - from.x) / 2 || EDGE_STUB)) const inX = to.x - Math.max(12, Math.min(EDGE_STUB, Math.abs(to.x - from.x) / 2 || EDGE_STUB)) const tops = [...padded.map((rect) => rect.y), from.y, to.y] const bottoms = [...padded.map(rectBottom), from.y, to.y] const above = Math.min(...tops) - EDGE_GUTTER * 2 + laneOffset const below = Math.max(...bottoms) + EDGE_GUTTER * 2 + laneOffset const lanesAround = padded.flatMap((rect) => [rect.y - 8, rectBottom(rect) + 8]) const shared = [...new Set([...bandCentres(padded, 'y'), ...lanesAround].map((y) => y + laneOffset))] const lanes = from.y <= to.y ? [above, ...shared, below] : [below, ...shared, above] const laneShape = (lane: number): Point[] => [ from, { x: outX, y: from.y }, { x: outX, y: lane }, { x: inX, y: lane }, { x: inX, y: to.y }, to ] if (to.x - from.x >= EDGE_STUB * 2 + 8) { const ideal = (from.x + to.x) / 2 + laneOffset const around = padded.flatMap((rect) => [rect.x - 8, rectRight(rect) + 8]) const candidates = [...new Set([ideal, ...bandCentres(padded, 'x'), ...around].map((x) => x + laneOffset))] .filter((x) => x > from.x + stub && x < to.x - stub) .sort((a, b) => Math.abs(a - ideal) - Math.abs(b - ideal)) for (const x of candidates) { const cornerA = { x, y: from.y } const cornerB = { x, y: to.y } if (clear(from, cornerA) && clear(cornerA, cornerB) && clear(cornerB, to)) { return dedupe([from, cornerA, cornerB, to]) } } // 中间没有一条干净的竖直通道:绕上下空行,别硬穿节点。 for (const lane of lanes) { if (clean(laneShape(lane))) return dedupe(laneShape(lane)) } return dedupe([from, { x: ideal, y: from.y }, { x: ideal, y: to.y }, to]) } for (const lane of lanes) { if (clean(laneShape(lane))) return dedupe(laneShape(lane)) } return dedupe(laneShape(above)) } function distance(a: Point, b: Point): number { return Math.hypot(b.x - a.x, b.y - a.y) } function towards(from: Point, to: Point, length: number): Point { const total = distance(from, to) || 1 const ratio = length / total return { x: from.x + (to.x - from.x) * ratio, y: from.y + (to.y - from.y) * ratio } } /** Polyline as an SVG path, with optional rounded corners. */ export function polylinePath(points: Point[], radius = EDGE_CORNER_RADIUS): string { if (points.length < 2) return '' let d = `M ${points[0].x} ${points[0].y}` for (let i = 1; i < points.length - 1; i += 1) { const previous = points[i - 1] const current = points[i] const next = points[i + 1] const bend = Math.max(0, Math.min(radius, distance(previous, current) / 2, distance(current, next) / 2)) if (bend < 1) { d += ` L ${current.x} ${current.y}` continue } d += ` L ${towards(current, previous, bend).x} ${towards(current, previous, bend).y}` d += ` Q ${current.x} ${current.y} ${towards(current, next, bend).x} ${towards(current, next, bend).y}` } const tail = points[points.length - 1] return `${d} L ${tail.x} ${tail.y}` } /** Midpoint of the longest run: the label sits somewhere calm. */ export function polylineLabelPoint(points: Point[]): Point { if (points.length < 2) return points[0] ?? { x: 0, y: 0 } let best = 0 let bestLength = -1 for (let i = 0; i < points.length - 1; i += 1) { const length = distance(points[i], points[i + 1]) if (length > bestLength) { bestLength = length best = i } } return { x: (points[best].x + points[best + 1].x) / 2, y: (points[best].y + points[best + 1].y) / 2 } } /** Legacy bezier between two ports, still used by the `curve` style. */ function bezierEdgePath(from: Point, to: Point, back: boolean): string { const dx = Math.max(72, Math.abs(to.x - from.x) * 0.48) if (!back) { return `M ${from.x} ${from.y} C ${from.x + dx} ${from.y}, ${to.x - dx} ${to.y}, ${to.x} ${to.y}` } const lift = from.y <= to.y ? -1 : 1 const offset = 96 + Math.abs(to.x - from.x) * 0.12 const peak = Math.min(from.y, to.y) + lift * offset return [ `M ${from.x} ${from.y}`, `C ${from.x + 120} ${from.y}, ${from.x + 120} ${peak}, ${(from.x + to.x) / 2} ${peak}`, `C ${to.x - 120} ${peak}, ${to.x - 120} ${to.y}, ${to.x} ${to.y}` ].join(' ') } /** * Drawable `d` attribute for one connection. * * The signature keeps the old `(from, to, back)` call sites working: with no * style argument it still produces the bezier, so anything that has not been * taught about edge styles keeps rendering as before. */ export function edgePath( from: Point, to: Point, back = false, style: EdgeStyle = 'curve', radius = EDGE_CORNER_RADIUS, obstacles: Rectangle[] = [] ): string { if (style === 'straight') return `M ${from.x} ${from.y} L ${to.x} ${to.y}` if (style === 'orthogonal') return polylinePath(edgePolyline(from, to, obstacles), radius) return bezierEdgePath(from, to, back) } export interface EdgeGeometry { id: string route: RouteDef path: string /** Waypoints of the drawn line; empty for the bezier style. */ points: Point[] labelX: number labelY: number back: boolean } /** * Build the drawable edge list. Routes pointing at missing nodes are dropped. * * Ports are spread per node and lanes are shared out, which is the difference * between "a nest of spaghetti" and "a readable tree" once a process has a * couple of dozen steps on it. */ export function buildEdges(activities: Activity[], routes: RouteDef[], options: EdgeOptions = {}): EdgeGeometry[] { const style = options.style ?? DEFAULT_EDGE_STYLE const radius = options.radius ?? EDGE_CORNER_RADIUS const byId = new Map(activities.map((item) => [item.id, item])) const live = routes.filter((route) => byId.has(route.from_activity) && byId.has(route.to_activity)) const centreY = (id: string) => { const node = byId.get(id) return node ? node.y + NODE_H / 2 : 0 } const outIndex = new Map() const inIndex = new Map() const outCount = new Map() const inCount = new Map() live .slice() .sort((a, b) => centreY(a.to_activity) - centreY(b.to_activity) || a.to_activity.localeCompare(b.to_activity)) .forEach((route) => { const key = `${route.from_activity}::${route.id}` outIndex.set(key, outCount.get(route.from_activity) ?? 0) outCount.set(route.from_activity, (outCount.get(route.from_activity) ?? 0) + 1) }) live .slice() .sort((a, b) => centreY(a.from_activity) - centreY(b.from_activity) || a.from_activity.localeCompare(b.from_activity)) .forEach((route) => { const key = `${route.to_activity}::${route.id}` inIndex.set(key, inCount.get(route.to_activity) ?? 0) inCount.set(route.to_activity, (inCount.get(route.to_activity) ?? 0) + 1) }) const takenLanes = new Map() const edges: EdgeGeometry[] = [] live.forEach((route) => { const from = byId.get(route.from_activity)! const to = byId.get(route.to_activity)! const start = portAt(from, 'out', outIndex.get(`${route.from_activity}::${route.id}`) ?? 0, outCount.get(route.from_activity) ?? 1) const end = portAt(to, 'in', inIndex.get(`${route.to_activity}::${route.id}`) ?? 0, inCount.get(route.to_activity) ?? 1) const back = end.x <= start.x const obstacles = activities .filter((item) => item.id !== route.from_activity && item.id !== route.to_activity) .map(nodeRect) const laneKey = `${Math.round(start.x)}:${Math.round(start.y)}:${Math.round(end.y)}:${back ? 'b' : 'f'}` const laneSlot = takenLanes.get(laneKey) ?? 0 takenLanes.set(laneKey, laneSlot + 1) const points = style === 'orthogonal' ? edgePolyline(start, end, obstacles, laneSlot * EDGE_LANE_STEP) : [] const label = style === 'orthogonal' ? polylineLabelPoint(points) : style === 'straight' ? { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 } : back ? { x: (start.x + end.x) / 2, y: Math.min(start.y, end.y) - (96 + Math.abs(end.x - start.x) * 0.12) / 2 } : { x: 0.125 * start.x + 0.375 * (start.x + Math.max(72, Math.abs(end.x - start.x) * 0.48)) + 0.375 * (end.x - Math.max(72, Math.abs(end.x - start.x) * 0.48)) + 0.125 * end.x, y: 0.25 * start.y + 0.25 * end.y } edges.push({ id: route.id || `${route.from_activity}-${route.to_activity}`, route, path: style === 'orthogonal' ? polylinePath(points, radius) : edgePath(start, end, back, style, radius), points, labelX: label.x, labelY: label.y, back }) }) return edges } export interface GraphBounds { minX: number minY: number maxX: number maxY: number } /** Bounding box of the nodes plus padding, for fit-to-view and the minimap. */ export function graphBounds(activities: Activity[], pad = 80): GraphBounds { if (!activities.length) return { minX: 0, minY: 0, maxX: 1200, maxY: 640 } const xs = activities.map((item) => item.x) const ys = activities.map((item) => item.y) return { minX: Math.min(...xs) - pad, minY: Math.min(...ys) - pad, maxX: Math.max(...xs) + NODE_W + pad, maxY: Math.max(...ys) + NODE_H + pad } } export function fitScale(bounds: GraphBounds, width: number, height: number): number { const w = Math.max(bounds.maxX - bounds.minX, 1) const h = Math.max(bounds.maxY - bounds.minY, 1) if (!width || !height) return 1 return Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Math.min(width / w, height / h))) } /** * Remove the edges that close a loop (a "reject back to the start" route is the * usual culprit) so the layered layout sees a DAG. Without this the longest-path * relaxation keeps going round the cycle and throws nodes thousands of pixels away. */ function dropBackEdges(ids: Set, outbound: Map, starts: string[]): Map { const forward = new Map() const seen = new Map() ids.forEach((id) => forward.set(id, [])) starts.forEach((seed) => { if (!ids.has(seed) || seen.has(seed)) return seen.set(seed, 1) const stack: { id: string; cursor: number }[] = [{ id: seed, cursor: 0 }] while (stack.length) { const frame = stack[stack.length - 1] const neighbours = outbound.get(frame.id) ?? [] if (frame.cursor >= neighbours.length) { seen.set(frame.id, 2) stack.pop() continue } const next = neighbours[frame.cursor] frame.cursor += 1 if (next === frame.id) continue const mark = seen.get(next) ?? 0 if (mark === 1) continue if (mark === 0) { seen.set(next, 1) stack.push({ id: next, cursor: 0 }) } forward.get(frame.id)!.push(next) } }) return forward } /** * Layered layout: longest-path levels from the begin node, then two barycenter * sweeps so branches line up with the parents they came from. */ export function autoLayout(activities: Activity[], routes: RouteDef[]): Activity[] { if (!activities.length) return activities const ids = new Set(activities.map((item) => item.id)) const outbound = new Map() const inbound = new Map() ids.forEach((id) => { outbound.set(id, []) inbound.set(id, []) }) routes.forEach((route) => { if (!ids.has(route.from_activity) || !ids.has(route.to_activity)) return outbound.get(route.from_activity)!.push(route.to_activity) inbound.get(route.to_activity)!.push(route.from_activity) }) const roots = activities.filter((item) => item.type === 'begin') const seeds = roots.length ? roots.map((item) => item.id) : [...ids].filter((id) => !inbound.get(id)!.length) const starts = seeds.length ? seeds : [activities[0].id] const forward = dropBackEdges(ids, outbound, starts) const level = new Map() const queue: string[] = [] starts.forEach((id) => { level.set(id, 0) queue.push(id) }) // The levelled graph is acyclic, so this relaxation settles on the longest path. let guard = ids.size * ids.size + ids.size while (queue.length && guard > 0) { guard -= 1 const current = queue.shift()! const depth = (level.get(current) ?? 0) + 1 forward.get(current)?.forEach((next) => { if ((level.get(next) ?? -1) < depth) { level.set(next, depth) queue.push(next) } }) } // Orphans (unreachable drafts) hang off the right-hand side. let orphanLevel = Math.max(0, ...[...level.values()]) + 1 ids.forEach((id) => { if (!level.has(id)) { level.set(id, orphanLevel) orphanLevel += 1 } }) const columns = new Map() activities.forEach((item) => { const depth = level.get(item.id) ?? 0 const list = columns.get(depth) ?? [] list.push(item.id) columns.set(depth, list) }) const depths = [...columns.keys()].sort((a, b) => a - b) depths.forEach((depth) => { columns.set(depth, columns.get(depth)!.sort((a, b) => { const left = activities.find((item) => item.id === a) const right = activities.find((item) => item.id === b) return (left?.y ?? 0) - (right?.y ?? 0) || (left?.x ?? 0) - (right?.x ?? 0) })) }) const rank = new Map() depths.forEach((depth) => columns.get(depth)!.forEach((id, index) => rank.set(id, index))) // Barycenter: order each column by the average slot of its neighbours. for (let pass = 0; pass < 2; pass += 1) { const source = pass === 0 ? inbound : outbound const walk = pass === 0 ? depths : [...depths].reverse() walk.forEach((depth) => { const ordered = columns.get(depth)! .map((id) => { const neighbours = (source.get(id) ?? []).map((other) => rank.get(other)).filter((v): v is number => v !== undefined) const average = neighbours.length ? neighbours.reduce((sum, v) => sum + v, 0) / neighbours.length : rank.get(id) ?? 0 return { id, average, fallback: rank.get(id) ?? 0 } }) .sort((a, b) => a.average - b.average || a.fallback - b.fallback) ordered.forEach((item, index) => rank.set(item.id, index)) columns.set(depth, ordered.map((item) => item.id)) }) } const gapX = NODE_W + 96 const gapY = NODE_H + 40 const tallest = Math.max(...depths.map((depth) => columns.get(depth)!.length)) const canvasHeight = tallest * gapY const placed = new Map() depths.forEach((depth) => { const list = columns.get(depth)! const startY = (canvasHeight - list.length * gapY) / 2 list.forEach((id, index) => { placed.set(id, { x: Math.round(depth * gapX) + 40, y: Math.round(startY + index * gapY) + 40 }) }) }) return activities.map((item) => { const position = placed.get(item.id) return position ? { ...item, x: position.x, y: position.y } : { ...item } }) } export interface GraphIssues { /** Node id -> problems shown as a red badge on that node. */ nodes: Record /** Graph level problems shown in the header strip. */ global: string[] /** * Node id -> hints that still run but almost certainly do not mean what the * designer intended (a fork with no join, a join with no fork...). Shown as an * amber badge: legal to save, worth a second look. */ warn: Record } function push(target: Record, id: string, problem: string) { const list = target[id] ?? [] list.push(problem) target[id] = list } /** * 回头线(退回 / 拒绝)的词表,与后端 `definition.BACK_DECISIONS` 一字不差。 * * 凡是要回答「我前面还有哪些环节」「往前走能到哪」的地方都得绕开它们:一张图上 * 只要有一条没被绕开的驳回线,被它连回来的那个环节后面的整条下游就都成了"上游", * 点退回于是把单子送到了下一步(2026-10 费用报销实单踩过)。 */ export const BACK_DECISIONS = ['goBack', 'reject'] /** 这条出口的决定语义:环节上的 `routeDecisions` 覆盖优先,其次路由自己的 `decision`。 */ export function routeDecisionOf(node: Activity | undefined, route: RouteDef): string { const overrides = (node?.config?.routeDecisions ?? {}) as Record return String(overrides[route.name] || route.decision || '').trim() } /** * 画布上的回头线有没有说清楚,两条口径(与后端 `_check_back_edges` 一致)。 * * 1. **闭了环却没标语义**:把已经标成退回/拒绝的边摘掉再深度优先走一遍,指回还在 * 路径上的那个节点的那条边,就是画布看着像退回、运行时却按审批通过处理的那条。 * 一个环里只点真正回头的那一条,环上其它边是正常往前走的一段。 * 2. **标了退回却指向前面**:退回的执行不看线的终点(落点是上游环节或环节上指定的 * 落点),终点不在上游就是画布在骗人。 */ export function backRouteIssues( activities: Activity[], routes: RouteDef[], label: (key: string, fallback: string) => string ): string[] { const nodes = new Map(activities.map((item) => [item.id, item])) const nameOf = (id: string) => nodes.get(id)?.name || id const decisionOf = (route: RouteDef) => routeDecisionOf(nodes.get(route.from_activity), route) const outbound = new Map() const inbound = new Map() activities.forEach((item) => { outbound.set(item.id, []) inbound.set(item.id, []) }) routes.forEach((route) => { outbound.get(route.from_activity)?.push(route) inbound.get(route.to_activity)?.push(route) }) const isBack = (route: RouteDef) => BACK_DECISIONS.includes(decisionOf(route)) const problems: string[] = [] const state = new Map() activities.forEach((start) => { if (state.get(start.id)) return state.set(start.id, 1) const path: { id: string; index: number }[] = [{ id: start.id, index: 0 }] while (path.length) { const frame = path[path.length - 1] const rows = (outbound.get(frame.id) ?? []).filter((route) => !isBack(route)) if (frame.index >= rows.length) { state.set(frame.id, 2) path.pop() continue } const route = rows[frame.index] frame.index += 1 const target = route.to_activity if (state.get(target) === 1) { if (!decisionOf(route)) { problems.push( `${label( 'issueRouteBackUnmarked', '路由回到了前面的环节却没标路由动作:点它在引擎里算一次审批通过(算一票同意、触发本环节通过后的写回),请标成退回或拒绝' )}:${nameOf(route.from_activity)} → ${route.name} → ${nameOf(target)}` ) } } else if (!state.get(target) && nodes.has(target)) { state.set(target, 1) path.push({ id: target, index: 0 }) } } }) const upstreamCache = new Map>() const upstreamOf = (id: string) => { const cached = upstreamCache.get(id) if (cached) return cached const out = new Set() const queue = [id] while (queue.length) { const current = queue.pop() as string ;(inbound.get(current) ?? []).forEach((route) => { if (isBack(route)) return const src = route.from_activity if (src && !out.has(src)) { out.add(src) queue.push(src) } }) } out.delete(id) upstreamCache.set(id, out) return out } routes.forEach((route) => { if (decisionOf(route) !== 'goBack') return const target = nodes.get(route.to_activity) if (!target || upstreamOf(route.from_activity).has(target.id)) return problems.push( `${label( 'issueRouteBackMisleading', '路由标了退回,指向的却是自己后面的环节:点退回时引擎退的是上游环节,画布这条线到不了那里' )}:${nameOf(route.from_activity)} → ${route.name} → ${target.name}` ) }) return problems } /** * Mirror of `engine/definition.py::validate` plus the designer-only checks * (a manual step with no approver source is legal to save but useless to run). * Keeping both in step means the red badges match the server's verdict. */ /** 环节上的自动抄送规则;形状不对就当没配。 */ function ccRulesOf(node: Activity): CcRule[] { const raw = node.config?.ccRules return Array.isArray(raw) ? (raw as CcRule[]) : [] } /** * 这一环算不算**发起人自己那一环**:开始环节,或勾了「本环节由发起人填写」的起草环节。 * * 前端这一份是后端 ``engine.is_starter_step`` 的镜像,判据一个字都不许多发明:办它叫 * 「提交」(``utils/taskAction``),设计期那条「出口别叫同意」的提醒也认它,两处共用 * 这一把尺。起草环节那一格(``config.first``)以前只有后端建流程的默认骨架会写, * 界面上既看不见也关不掉,所以判据和那一格的开关得长在一起。 */ export function isStarterStep(node: Pick): boolean { return node.type === 'begin' || Boolean(node.config?.first) } export function graphIssues( activities: Activity[], routes: RouteDef[], labels?: Record, options?: { defaultForm?: string; formFields?: (formId: string) => FormFieldDef[] } ): GraphIssues { const nodes: Record = {} const warn: Record = {} const global: string[] = [] const t = (key: string, fallback: string) => labels?.[key] ?? fallback const begins = activities.filter((item) => item.type === 'begin') const ends = activities.filter((item) => item.type === 'end') if (!begins.length) global.push(t('issueNoBegin', '缺少开始环节')) if (begins.length > 1) global.push(t('issueMultiBegin', '只能有一个开始环节')) if (!ends.length) global.push(t('issueNoEnd', '缺少结束环节')) const outbound = new Map() const inbound = new Map() activities.forEach((item) => { outbound.set(item.id, []) inbound.set(item.id, []) }) routes.forEach((route) => { outbound.get(route.from_activity)?.push(route) inbound.get(route.to_activity)?.push(route) }) const gateways = pairGateways(activities, routes) /** merge id -> 这个汇合点最多要等几条支线(配对的并行网关分出去几条)。 */ const feeders = new Map() Object.values(gateways).forEach((pair) => { if (pair.merge) feeders.set(pair.merge, Math.max(feeders.get(pair.merge) ?? 0, pair.branches.length)) }) activities.forEach((node) => { const out = outbound.get(node.id) ?? [] const inRoutes = inbound.get(node.id) ?? [] if (!inRoutes.length && node.type !== 'begin') push(nodes, node.id, t('issueNoInbound', '没有入口路由,走不到这里')) if (node.type === 'manual') { if (!out.length) push(nodes, node.id, t('issueManualNoOut', '人工环节没有出口路由')) const configured = (node.config?.taskValues ?? []).length > 0 || Boolean((node.config?.taskScript ?? '').trim()) if (!configured) push(nodes, node.id, t('issueNoApprover', '未配置处理人来源')) // 环节没选表单时可以沿用流程的默认表单,两边都没有才算没配。 if (!node.form && !(options?.defaultForm ?? '').trim()) { push(nodes, node.id, t('issueNoForm', '未绑定表单,且流程没有默认表单')) } } if ((node.type === 'end' || node.type === 'cancel') && out.length) { push(nodes, node.id, t('issueEndHasOut', '结束类环节不能有出口路由')) } if (node.type === 'choice') { if (out.length < 2) push(nodes, node.id, t('issueChoiceRoutes', '分支环节至少需要两条路由')) if (!out.some((route) => !(route.expression || '').trim())) { push(nodes, node.id, t('issueChoiceDefault', '分支环节需要一条无条件路由作为默认分支')) } } if (node.type === 'parallel' && out.length < 2) push(nodes, node.id, t('issueParallelRoutes', '并行网关至少需要两条路由')) if (node.type === 'merge' && inRoutes.length < 2) push(nodes, node.id, t('issueMergeInbound', '汇总网关至少需要两条入口路由')) if (node.type === 'split' && !(node.config?.dataPath ?? '').trim()) push(nodes, node.id, t('issueSplitPath', '数据拆分需要填写数据路径')) // 下面这些都能跑,但多半不是设计者想的意思,用琥珀色提醒而不是当错误。 if ((node.type === 'parallel' || node.type === 'split') && !gateways[node.id]?.merge) { push(warn, node.id, t('issueNoPairedMerge', '后面没有汇总网关,几条支线不会互相等待')) } if (node.type === 'split' && out.length > 1) { push(warn, node.id, t('issueSplitSingleRoute', '数据拆分只认第一条出口路由,其余的不会用到')) } if (node.type === 'merge') { if (!feeders.has(node.id)) { push(warn, node.id, t('issueMergeNoGateway', '上面没有对应的并行网关,支线到这里不会等齐,会直接往下走')) } const passCount = Number(node.config?.passCount ?? 0) const expected = feeders.get(node.id) ?? inRoutes.length if (passCount > expected) { push( warn, node.id, `${t('issueMergeQuotaOver', '要求放行的票数比支线还多,引擎按全到处理')}:${passCount} > ${expected}` ) } } // 发起人那一环的出口名,从前直接就是待办上那颗主按钮的名字。画成「同意」,单子被驳回 // 回到发起人手上时就成了一颗「同意」钮——人以为自己在批自己的申请,其实只是把改过的单子 // 重新交上去。运行时现在按环节改口(见 utils/taskAction),但线上那句「提交」才是画这条 // 线的人本来想说的话。 // 起草环节挨这一句是因为勾了「本环节由发起人填写」:这一层不点破,看的人只会去改连线 // 名字,改完这一环还是发起人自己那一环(出差备案那条「审阅人」就是这么绕了一圈)。 if (isStarterStep(node)) { const voteLike = out .filter((route) => route.decision !== 'goBack' && route.decision !== 'reject') .filter((route) => /(同意|通过|批准|approve|agree)/i.test((route.name ?? '').trim())) .map((route) => (route.name ?? '').trim()) if (voteLike.length) { // 两种落点给两句话:开始环节那一环天生是发起人自己的,起草环节是这一勾换来的, // 该说的是「把勾取消掉」,不是让人去改一条本来就该叫同意的线。 const text = node.type === 'begin' ? t('issueStarterRouteVote', '发起环节的出口叫「同意」这类表态词:驳回之后回到发起人手上,那颗钮会像在批自己的单,建议改成「提交」') : t( 'issueStarterRouteVoteDraft', '这一环勾了「本环节由发起人填写」,算发起人自己那一环:出口叫「同意」这类表态词,被驳回回到手上时那颗钮像在批自己的单。改成「提交」,或者到「处理人与审批」里取消那个勾选' ) push(warn, node.id, `${text}:${[...new Set(voteLike)].join('、')}`) } } if (node.type === 'script' && !(node.config?.script ?? '').trim()) push(nodes, node.id, t('issueScriptEmpty', '脚本环节还没有脚本')) if (node.type === 'invoke' && !(node.config?.url ?? '').trim()) push(nodes, node.id, t('issueInvokeUrl', '服务调用还没有填写 URL')) if (node.type === 'embed' && !(node.config?.process ?? '').trim()) push(nodes, node.id, t('issueEmbedProcess', '子流程还没有选择流程')) // 字段权限自相矛盾:环节把一个字段标成必填,又把它藏起来,单子一定卡死。 if (node.type === 'manual') { const perms = (node.config?.formPerms ?? {}) as Record const fields = options?.formFields?.(node.form || options?.defaultForm || '') ?? [] const blocked = fields.filter((item) => perms[item.key] === 'hidden' && (item.required || perms[item.key] === 'required')) if (blocked.length) { push(nodes, node.id, t('issuePermConflict', '有字段既设为必填又被隐藏')) } const requiredHidden = fields.filter((item) => perms[item.key] === 'hidden' && item.required) if (requiredHidden.length) { push(nodes, node.id, `${t('issuePermHiddenRequired', '本环节隐藏了表单里的必填字段')}:${requiredHidden.map((item) => item.label || item.key).join('、')}`) } } ccRulesOf(node).forEach((rule) => { const targeted = (rule?.taskValues ?? []).length > 0 || Boolean((rule?.taskScript ?? '').trim()) if (!targeted) push(nodes, node.id, t('issueCcNoTarget', '有抄送设置还没选抄送对象')) }) if (!(node.name || '').trim()) push(nodes, node.id, t('issueNoName', '环节名称不能为空')) }) // 同名出口是允许的:待办上它们就是同一个按钮,走哪一条由路由自己写的条件决定。 // 所以这里不再一律报「同名路由」,只挑两种真会出事的写法,口径与后端 // engine/definition.py 的 _check_route_names 一致。 const sameName = new Map() routes.forEach((route) => { if (!outbound.has(route.from_activity) || !inbound.has(route.to_activity)) { global.push(t('issueDanglingRoute', '存在指向已删除环节的路由')) return } const key = `${route.from_activity}::${route.name}` const rows = sameName.get(key) if (rows) rows.push(route) else sameName.set(key, [route]) }) const typeOf = new Map(activities.map((item) => [item.id, item.type])) sameName.forEach((rows) => { if (rows.length < 2) return const name = rows[0].name // 并联/拆分环节条条出口都要走,引擎不在其中挑,同名无所谓 if (['parallel', 'split'].includes(String(typeOf.get(rows[0].from_activity) ?? ''))) return if (new Set(rows.map((row) => (row.decision || '').trim())).size > 1) { global.push(`${t('issueRouteDecisionConflict', '同名路由的语义不一致:同一个按钮不能既是同意又是退回')}:${name}`) } if (rows.filter((row) => !(row.expression || '').trim()).length > 1) { global.push(`${t('issueRouteAmbiguous', '同名路由都没写条件,流转时分不出该走哪条')}:${name}`) } }) // 回头线要说清楚:这一族「点退回却走到下一步」的问题,画布上就能看出来 global.push(...backRouteIssues(activities, routes, t)) const begin = begins[0] ?? activities[0] if (begin) { const reached = new Set([begin.id]) const stack = [begin.id] while (stack.length) { const current = stack.pop()! ;(outbound.get(current) ?? []).forEach((route) => { if (!reached.has(route.to_activity)) { reached.add(route.to_activity) stack.push(route.to_activity) } }) } activities.forEach((node) => { if (!reached.has(node.id)) push(nodes, node.id, t('issueUnreachable', '从开始环节不可达')) }) } return { nodes, global, warn } } /** One row in the palette's issue list; `nodeId` makes the row jump to that node. */ export interface PaletteIssue { key: string nodeId?: string nodeName?: string text: string /** error 挡住发布,warn 只是提醒;默认 error */ level?: 'error' | 'warn' } export interface SummaryLine { label: string value: string tone?: 'default' | 'warn' } /** 把 `{n}` 这类占位符换成实参,纯文案工具,不依赖 i18n 实例。 */ function interpolate(text: string, params?: Record): string { if (!params) return text return text.replace(/\{(\w+)\}/g, (match, key: string) => String(params[key] ?? match)) } /** * Two or three lines that tell the designer what a step actually does without * opening the inspector. `formName` resolves the bound form id to its name. */ function nodeSummaryLines( node: Activity, ctx: { routes: RouteDef[] activities: Activity[] labels: Record formName?: (id: string) => string /** 流程默认表单的名字:沿用时卡片上要说得出是哪一张 */ defaultFormName?: string inboundCount?: number /** 已算好的网关配对,省得每张卡片都重新遍历一遍图。 */ pairs?: Record /** 带参数的文案由调用方用 i18n 渲染;缺了就退回 labels 里的模板。 */ fmt?: (key: string, params?: Record) => string /** 这一环是不是「流程编号在这一刻生成」的那一环;由调用方算好话术传进来。 */ serialHere?: SummaryLine | null /** 这一环是不是「发起人过了这儿就不能终止」的那一环;同样由调用方算好话术。 */ terminateHere?: SummaryLine | null } ): SummaryLine[] { const labels = ctx.labels const out = ctx.routes.filter((route) => route.from_activity === node.id) const lines: SummaryLine[] = [] const label = (key: string, fallback: string) => labels[key] ?? fallback const say = (key: string, params?: Record) => interpolate(ctx.fmt?.(key, params) ?? (labels[key] ?? ''), params) if (node.type === 'manual') { const mode = node.config?.mode === 'all' ? label('modeAll', '会签') : label('modeAny', '或签') const values = node.config?.taskValues ?? [] const sources = values.length ? values.map((item) => label(`approverKind_${item.type}`, item.type)).join('、') : (node.config?.taskScript ?? '').trim() ? label('approverKind_script', '脚本计算') : '' lines.push({ label: label('summaryApprover', '处理人'), value: sources || label('summaryUnset', '未配置'), tone: sources ? 'default' : 'warn' }) lines.push({ label: mode, value: node.config?.expireValue ? `${node.config.expireValue} min` : label('summaryNoTimer', '不计时') }) const ownForm = node.form ? ctx.formName?.(node.form) || label('summaryFormMissing', '表单已删除') : '' // 沿用是常态,卡片上顺带说清沿用的是哪一张,省得回流程信息里翻 const form = ownForm || (ctx.defaultFormName ? say('summaryInheritFormNamed', { name: ctx.defaultFormName }) : label('summaryInheritForm', '沿用默认表单')) lines.push({ label: label('summaryForm', '表单'), value: form || label('summaryInheritForm', '沿用默认表单') }) return lines.slice(0, 3) } // 分支与网关只报路由条数看不出用途,卡片上直接讲「走几条、等不等、收在哪里」。 if (isGateway(node.type)) { const pairs = ctx.pairs ?? pairGateways(ctx.activities, ctx.routes) const info = gatewayInfo(node, { activities: ctx.activities, routes: ctx.routes, pairs }) if (!info) return lines if (node.type === 'choice') { lines.push({ label: label('summaryBranches', '分支'), value: say('summaryTakeOne', { n: out.length }), tone: out.length >= 2 ? 'default' : 'warn' }) const ready = info.outbound.some((row) => !row.expression) lines.push({ label: label('summaryDefaultRoute', '默认出口'), value: ready ? label('summaryDefaultReady', '已留') : label('summaryDefaultMissing', '还差一条'), tone: ready ? 'default' : 'warn' }) return lines } if (node.type === 'parallel' || node.type === 'split') { if (node.type === 'split') { lines.push({ label: 'dataPath', value: info.dataPath || label('summaryUnset', '未配置'), tone: info.dataPath ? 'default' : 'warn' }) } else { lines.push({ label: label('summaryTakeAll', '同时走'), value: `${out.length}`, tone: out.length >= 2 ? 'default' : 'warn' }) } lines.push({ label: label('summaryCloseAt', '收口于'), value: info.pairedMergeName || label('summaryNoClose', '没有,不互等'), tone: info.pairedMerge ? 'default' : 'warn' }) return lines } const total = info.expected const wait = info.passCount ? say('summaryWaitCount', { n: Math.min(info.passCount, total), total }) : info.passRatio ? say('summaryWaitRatio', { ratio: info.passRatio > 1 ? Math.round(info.passRatio) : Math.round(info.passRatio * 100), total }) : say('summaryWaitAll', { n: total }) lines.push({ label: label('summaryMergeWait', '等齐'), value: wait, tone: total >= 2 ? 'default' : 'warn' }) lines.push({ label: label('summaryFedBy', '分叉自'), value: info.pairedGatewayName || label('summaryNoFork', '上面没分叉'), tone: info.pairedGateway ? 'default' : 'warn' }) return lines } if (node.type === 'script') { const script = (node.config?.script ?? '').trim() return [{ label: label('summaryScript', '脚本'), value: script ? script.split('\n')[0].slice(0, 42) : label('summaryUnset', '未配置'), tone: script ? 'default' : 'warn' }] } if (node.type === 'invoke') { const url = (node.config?.url ?? '').trim() return [{ label: 'URL', value: url ? url.replace(/^https?:\/\//, '').slice(0, 40) : label('summaryUnset', '未配置'), tone: url ? 'default' : 'warn' }] } if (node.type === 'embed') { const id = (node.config?.process ?? '').trim() const child = ctx.activities.find((item) => item.id === id) return [{ label: label('summaryChild', '子流程'), value: child?.name || id || label('summaryUnset', '未配置'), tone: id ? 'default' : 'warn' }] } if (node.type === 'delay') { return [{ label: label('summaryWait', '等待'), value: `${node.config?.minutes ?? 0} min` }] } if (node.type === 'begin') { return [{ label: label('summaryStarter', '发起人'), value: label('summaryStarterValue', '填写人发起') }] } if (node.type === 'cancel') { return [{ label: label('summaryEffect', '效果'), value: label('summaryCancelValue', '流程作废') }] } if (node.type === 'end') { return [{ label: label('summaryEffect', '效果'), value: label('summaryEndValue', '流程归档') }] } return lines } /** * 卡片上的两三行摘要,末尾再挂一句「编号在这一环生成」。 * * 编号时机配在流程信息面板里,画布上不给个记号,设计者站在流程图前根本想不起来 * 那一档配置存不存在、指的是哪一环。这一行不参与 ``slice(0, 3)`` 的截断—— * 它是被特意加上来的,加它的人已经知道这张卡片要说三行还是四行。 */ export function nodeSummary( node: Activity, ctx: Parameters[1] ): SummaryLine[] { const lines = nodeSummaryLines(node, ctx) if (ctx.serialHere) lines.push(ctx.serialHere) if (ctx.terminateHere) lines.push(ctx.terminateHere) return lines } // --------------------------------------------------------------- 分支与网关 /** 需要解释「怎么分、怎么合」的四种环节。 */ export const GATEWAY_TYPES: ActivityType[] = ['choice', 'parallel', 'merge', 'split'] export function isGateway(type: string): boolean { return GATEWAY_TYPES.includes(type as ActivityType) } /** 一对配好对的网关:a 是分叉(并行/拆分),b 是收口(汇总)。 */ export interface GatewayPairHint { a: string b: string label: string } export interface GatewayPair { /** 收拢这批支线的汇总网关,找不到就是空串 */ merge: string /** 分叉环节直接连到的环节 id(数据拆分只会用到第一条) */ branches: string[] } /** 和引擎 routes_from 同一条口径:先按排序号,再按名字。画布上的「支线 1/2/3」也照这个数。 */ export function sortedRoutes(routes: RouteDef[], id: string): RouteDef[] { return routes .filter((route) => route.from_activity === id) .sort((a, b) => (a.order_number - b.order_number) || a.name.localeCompare(b.name)) } /** 从某条支线出发做广度优先,找到的第一个汇总网关就是收口点。 */ function firstMerge( next: (activityId: string) => string[], typeOf: (activityId: string) => string, start: string, exclude: string ): string { const seen = new Set([exclude, start]) const queue = [start] while (queue.length) { const current = queue.shift() as string if (typeOf(current) === 'merge') return current next(current).forEach((target) => { if (!seen.has(target)) { seen.add(target) queue.push(target) } }) } return '' } /** * 每个并行网关 / 数据拆分对应哪个汇总网关。 * * 与后端 ``engine.pair_gateways`` 同一条规则:从每条支线出发做广度优先,第一个碰到的 * 汇总网关就是收口点;找不到就没有收口,支线之间不会互相等待。设计器靠它回答 * 「这个汇总到底在等哪几条线」这个最容易看错的问题。 */ export function pairGateways(activities: Activity[], routes: RouteDef[]): Record { const next = (id: string) => sortedRoutes(routes, id).map((route) => route.to_activity) const typeOf = (id: string) => activities.find((item) => item.id === id)?.type ?? '' const pairs: Record = {} activities.forEach((node) => { if (node.type !== 'parallel' && node.type !== 'split') return const branches = next(node.id) let merge = '' branches.some((branch) => { merge = firstMerge(next, typeOf, branch, node.id) return Boolean(merge) }) pairs[node.id] = { merge, branches } }) return pairs } export interface GatewayRouteRow { id: string /** 路由名,画布上的线标签 */ name: string /** 对端环节(出口是去向,入口是来源) */ peer: string peerName: string /** 判定条件;空表示无条件(分支环节的默认走向) */ expression: string } export interface GatewayInfo { kind: ActivityType /** 出口路由,按引擎判定顺序排好 */ outbound: GatewayRouteRow[] inbound: GatewayRouteRow[] pairedMerge: string pairedMergeName: string pairedGateway: string pairedGatewayName: string /** 这个汇合点要等几条支线;只在汇总环节上有意义 */ expected: number passCount: number passRatio: number dataPath: string } /** * 网关环节的「现在连成了什么样」:给右侧属性面板照着讲人话。 * 非网关环节返回 null。 */ export function gatewayInfo( node: Activity, ctx: { activities: Activity[]; routes: RouteDef[]; pairs?: Record } ): GatewayInfo | null { if (!isGateway(node.type)) return null const nameOf = (id: string) => ctx.activities.find((item) => item.id === id)?.name || id const outbound: GatewayRouteRow[] = sortedRoutes(ctx.routes, node.id).map((route) => ({ id: route.id, name: route.name, peer: route.to_activity, peerName: nameOf(route.to_activity), expression: (route.expression || '').trim() })) const inbound: GatewayRouteRow[] = ctx.routes .filter((route) => route.to_activity === node.id) .map((route) => ({ id: route.id, name: route.name, peer: route.from_activity, peerName: nameOf(route.from_activity), expression: (route.expression || '').trim() })) const pairs = ctx.pairs ?? pairGateways(ctx.activities, ctx.routes) const pairedMerge = node.type === 'parallel' || node.type === 'split' ? pairs[node.id]?.merge ?? '' : '' const feeder = Object.entries(pairs).find(([, pair]) => pair.merge === node.id) const config = node.config ?? {} return { kind: node.type, outbound, inbound, pairedMerge, pairedMergeName: pairedMerge ? nameOf(pairedMerge) : '', pairedGateway: feeder ? feeder[0] : '', pairedGatewayName: feeder ? nameOf(feeder[0]) : '', expected: feeder ? Math.max(pairs[feeder[0]].branches.length, 1) : inbound.length, passCount: Number(config.passCount ?? 0) || 0, passRatio: Number(config.passRatio ?? 0) || 0, dataPath: String(config.dataPath ?? config.splitPath ?? '').trim() } } // ---------------------------------------------------- 一键补齐:把最常画错的两种线接上 /** 一键补出来的汇总网关该放哪儿、要连哪几条支线;补不了会说清为什么补不了。 */ export type ForkFixPlan = | { ok: true; x: number; y: number; tips: string[] } | { ok: false; reason: 'paired' | 'deadBranch' | 'fewTips' } /** * 「补一个汇总网关」的施工图。 * * 沿着每条支线往下走到走不动为止,那些末端环节就是要接到汇总上的线头;汇总放在 * 它们右边一列、竖直居中。有两种情况不能替用户决定:有条支线直接走到了结束环节 * (这条支线永远回不到汇总,硬补只会补出一个死等的汇总),以及能连的线头不足两条。 */ export function forkFixPlan(activities: Activity[], routes: RouteDef[], forkId: string): ForkFixPlan { const fork = activities.find((item) => item.id === forkId) if (!fork || (fork.type !== 'parallel' && fork.type !== 'split')) return { ok: false, reason: 'fewTips' } if (pairGateways(activities, routes)[forkId]?.merge) return { ok: false, reason: 'paired' } const next = (id: string) => sortedRoutes(routes, id).map((route) => route.to_activity) const typeOf = (id: string) => activities.find((item) => item.id === id)?.type ?? '' const visited = new Set([forkId]) const perBranch = next(forkId).map((branch) => { const tips: string[] = [] const queue = [branch] while (queue.length) { const current = queue.shift() as string if (visited.has(current)) continue visited.add(current) // 已经有个汇总在收口了,那条线不归这次补的汇总管。 if (typeOf(current) === 'merge') continue const outs = next(current) if (!outs.length) { tips.push(current) continue } outs.forEach((target) => { if (!visited.has(target)) queue.push(target) }) } return tips }) const live = (id: string) => typeOf(id) !== 'end' && typeOf(id) !== 'cancel' if (perBranch.some((tips) => !tips.some(live))) return { ok: false, reason: 'deadBranch' } const tips = [...new Set(perBranch.flat())].filter(live) if (tips.length < 2) return { ok: false, reason: 'fewTips' } const nodes = tips.map((id) => activities.find((item) => item.id === id)).filter((item): item is Activity => Boolean(item)) const want = { x: Math.max(...nodes.map((item) => item.x)) + NODE_W + 96, y: Math.round(nodes.reduce((sum, item) => sum + item.y, 0) / nodes.length) } const at = snapPosition(want.x, want.y) return { ok: true, x: at.x, y: at.y, tips } } /** * 「补一条默认出口」该连到哪儿。 * * 条件都不成立时最常见的意图就是到此为止,所以连到结束环节;没有结束环节、 * 或者已经连过去了,就不替用户编一个去向。 */ export function defaultRouteFix(activities: Activity[], routes: RouteDef[], choiceId: string): { to: string } | null { const node = activities.find((item) => item.id === choiceId) if (!node || node.type !== 'choice') return null const outs = routes.filter((route) => route.from_activity === choiceId) if (outs.some((route) => !(route.expression || '').trim())) return null const target = activities.find((item) => item.type === 'end' && !outs.some((route) => route.to_activity === item.id)) return target ? { to: target.id } : null } /** * 「在这条线中间加一步」时新环节该落在哪儿。 * * 先按现在的画法把这条线走一遍,取标签所在的位置(那本来就是节点之间比较空的一段), * 再用 freePosition 把压住别人的位置挪开。新环节因此是长在这条线上的, * 而不是凭空出现在画布空白处。 */ export function insertPointFor(activities: Activity[], routes: RouteDef[], route: RouteDef): Point | null { const from = activities.find((item) => item.id === route.from_activity) const to = activities.find((item) => item.id === route.to_activity) if (!from || !to) return null // 端口是按这条线在两端环节上的排位散开的,照同样的排位才算得准。 const sameName = (item: RouteDef) => item.id === route.id || (item.from_activity === route.from_activity && item.to_activity === route.to_activity) const outs = sortedRoutes(routes, route.from_activity) const ins = routes.filter((item) => item.to_activity === route.to_activity) const start = portAt(from, 'out', Math.max(0, outs.findIndex(sameName)), outs.length || 1) const end = portAt(to, 'in', Math.max(0, ins.findIndex(sameName)), ins.length || 1) const obstacles = activities.filter((item) => item.id !== from.id && item.id !== to.id).map(nodeRect) const lane = polylineLabelPoint(edgePolyline(start, end, obstacles)) const want = snapPosition(lane.x - NODE_W / 2, lane.y - NODE_H / 2) return freePosition(activities, want, 24) } /** * 这条线在网关上扮演什么角色,画布靠它在标签上挂一个小徽标。 * * 分支环节上那条不填条件的出口(默认走向)和并行/拆分分出去的支线,是最容易看错 * 的两种线,值得在图上直接标出来;其余的线保持原样,别添乱。 */ export function edgeRoleTag(fromType: string, route: RouteDef): 'default' | 'branch' | '' { if (fromType === 'choice') return (route.expression || '').trim() ? '' : 'default' if (fromType === 'parallel' || fromType === 'split') return 'branch' return '' }