Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.
HTML agent-skillsai-agentsarchitecture-diagramclaude-codeclaude-skillscodexcoding-agentsdeepseek-harnessdeveloper-toolsdiagramsdiagrams-as-codedsh-pluginflowchartllmmermaidopencodesequence-diagramsoftware-architecturesystem-designvisualization
fix(erd): keep trunk bridges clear of unrelated routes
To3akaRin801b3026d8eb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 73100ee9..05a5f542 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,8 @@ All notable changes are documented here. Format loosely follows [Keep a Changelo### Fixed+- **ER 图主干桥接隔离(#896)。** 自动总线不再跨越、接触或覆盖无关关系及其他已生成的桥接;存在冲突时保留分离的主干段,避免校验通过的图看起来多出关系。实体位置、显式途经点、关系基数及正常共享主干保持不变。+- **WebM 录制失败清理 (#622)。** 画布、捕获流、编码器启动、逐帧绘制或停止失败时,录制 Promise 现在会拒绝并释放已创建的流、临时 URL、动画帧和定时器;晚到的编码事件不能再将失败录制报告为成功。正常编码与最佳努力的最终片段 flush 行为保持不变。- **类图混合关系的主干冲突(#791)。** 自动继承/实现主干会检查组外路线的端口、走廊和交叉;冲突组回退到独立路由,避免依赖箭头被继承三角覆盖或实线覆盖实现虚线。无冲突主干、显式几何及关系语义保持不变;空 `via: []` 与省略路径点统一处理,避免合法输入在回退后产生非法斜线。diff --git a/archify.zip b/archify.zipindex c267dfb6..8f9b5b82 100644Binary files a/archify.zip and b/archify.zip differdiff --git a/archify/renderers/erd/README.md b/archify/renderers/erd/README.mdindex 295b1684..d7631575 100644--- a/archify/renderers/erd/README.md+++ b/archify/renderers/erd/README.md@@ -100,6 +100,9 @@ renderer:back to the ordinary families and stays unbundled, and anything authored(`route`, `via`, `labelAt`) keeps its own line. Logical routes still traversethe trunk, so every gate, label, and the layout report see the full geometry.+ 自动补出的主干桥接还会检查无关关系及已接受的其他桥接;出现交叉、接触或+ 重叠时保留分离的主干段,避免把独立关系画成同一条总线。这个回退不移动+ 实体、显式途经点或端口,也不改变关系基数;无障碍的同簇分支仍可共享主干。- Entity boxes are opaque obstacles. When a third entity sits between twoaligned anchors, the shared obstacle grid routes around it, and a route thatstill cannot clear an unrelated entity fails withdiff --git a/archify/renderers/erd/render-erd.mjs b/archify/renderers/erd/render-erd.mjsindex fa1dc8ec..5f2a56b4 100644--- a/archify/renderers/erd/render-erd.mjs+++ b/archify/renderers/erd/render-erd.mjs@@ -852,13 +852,17 @@ function bundledTrunkPaths() {const key = `${axis}:${coordinate}:${styleKey}`;const list = clusters.get(key) || [];for (const run of runs) {- list.push({ low: run.low, high: run.high, styleKey });+ list.push({ low: run.low, high: run.high, styleKey, relationship });}clusters.set(key, list);}const paths = [];+ const bridged = [];+ const routed = relationships.filter(renderableRelationship)+ .map((relationship) => ({ relationship, points: pathFor(relationship).points }));for (const [key, runs] of clusters) {const [axis, coordinate] = key.split(':').slice(0, 2).map(Number);+ const members = new Set(runs.map((run) => run.relationship));runs.sort((left, right) => left.low - right.low);const merged = [];for (const run of runs) {@@ -877,7 +881,17 @@ function bundledTrunkPaths() {const probe = axis === 0? { start: [coordinate, last.high], end: [coordinate, segment.low] }: { start: [last.high, coordinate], end: [segment.low, coordinate] };- if (![...entities.values()].some((entity) => segmentIntersectsRect(probe, entity))) {+ // 桥接不在任何逻辑关系中,必须检查它实际增加的墨迹。同簇成员可以共享总线;+ // 无关路线和已补出的其他桥接一旦交叉、相接或重叠,就保留两段独立主干。+ const box = {+ x: probe.start[0], y: probe.start[1],+ width: probe.end[0] - probe.start[0], height: probe.end[1] - probe.start[1],+ };+ const conflicts = routed.some(({ relationship, points }) => !members.has(relationship)+ && points.slice(1).some((end, index) => segmentIntersectsRect({ start: points[index], end }, box)))+ || bridged.some((other) => segmentIntersectsRect(other, box));+ if (!conflicts && ![...entities.values()].some((entity) => segmentIntersectsRect(probe, entity))) {+ bridged.push(probe);last.high = segment.high;continue;}diff --git a/test/erd-trunk-bridges.test.mjs b/test/erd-trunk-bridges.test.mjsnew file mode 100644index 00000000..5a99490c--- /dev/null+++ b/test/erd-trunk-bridges.test.mjs@@ -0,0 +1,137 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { analyzeSvgPath } from '../archify/renderers/shared/svg-path-analysis.mjs';++const cli = fileURLToPath(new URL('../archify/bin/archify.mjs', import.meta.url));+const epsilon = 0.0001;+const attributes = tag => Object.fromEntries([...tag.matchAll(/([\w-]+)="([^"]*)"/g)].map(match => [match[1], match[2]]));++function fixture({ horizontal = false, conflict, dashed = false } = {}) {+ const table = (id, pos, rows = 3) => ({+ id, label: id, pos, width: rows * 20 + 36,+ attributes: Array.from({ length: rows }, (_, index) => ({ name: `f${index}`, type: 'int' })),+ });+ const document = {+ schema_version: 1, diagram_type: 'erd',+ meta: { title: 'Independent relationship beside a shared parent', locale: 'en', quality_profile: 'showcase', legend: { mode: 'hidden' } },+ entities: [table('hub', [40, 80], 4), table('a', [240, 0]), table('b', [240, 280]), table('c', [440, 0]), table('d', [440, 280])],+ relationships: [+ { id: 'a_hub', from: 'a', to: 'hub', fromCardinality: 'many', toCardinality: 'one', fromSide: 'left', toSide: 'right' },+ { id: 'b_hub', from: 'b', to: 'hub', fromCardinality: 'many', toCardinality: 'one', fromSide: 'left', toSide: 'right' },+ ],+ };+ if (conflict) {+ // 两条逻辑主干之间留下 24px 空隙;独立关系的显式 U 形路线进入该空隙。+ // 相切用 16px 回转段,圆角恰好在总线上相接;重叠用 20px 留下真正的直线墨迹。+ const x = conflict === 'crossing' ? 164 : 172;+ const [top, bottom] = conflict === 'touch' ? [130, 146] : [128, 148];+ document.relationships.push({+ id: 'c_d', from: 'c', to: 'd', fromCardinality: 'many', toCardinality: 'one',+ fromSide: 'left', toSide: 'left',+ via: [[400, 48], [400, top], [x, top], [x, bottom], [400, bottom], [400, 328]],+ ...(dashed ? { identifying: false } : {}),+ });+ }+ if (horizontal) {+ // 方形实体的转置保留其尺寸,显式端口和途经点一起转置。+ document.entities.forEach(entity => { entity.pos.reverse(); });+ document.relationships.forEach(relationship => {+ const sides = { left: 'top', right: 'bottom' };+ relationship.fromSide = sides[relationship.fromSide];+ relationship.toSide = sides[relationship.toSide];+ relationship.via?.forEach(point => point.reverse());+ });+ }+ return document;+}++function render(t, document) {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-erd-bridge-'));+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const input = path.join(directory, 'input.erd.json');+ const output = path.join(directory, 'output.html');+ const source = JSON.stringify(document);+ fs.writeFileSync(input, source);+ const result = spawnSync(process.execPath, [cli, 'render', 'erd', input, output], {+ encoding: 'utf8', timeout: 20_000,+ env: { ...process.env, ARCHIFY_UPDATE_CHECK_DISABLED: '1' },+ });+ assert.equal(result.status, 0, `${result.error || ''}\n${result.stdout}\n${result.stderr}`);+ assert.equal(fs.readFileSync(input, 'utf8'), source, '作者输入必须保持原样');+ const svg = fs.readFileSync(output, 'utf8').match(/<svg\b[\s\S]*?<\/svg>/)[0];+ const boxes = new Map([...svg.matchAll(/<g\b[^>]*data-node-id="([^"]+)"[^>]*>[\s\S]*?<rect\b([^>]*)>/g)]+ .map(match => [match[1], attributes(match[2])]));+ for (const entity of document.entities) {+ const box = boxes.get(entity.id);+ assert.deepEqual([Number(box.x), Number(box.y), Number(box.width)], [...entity.pos, entity.width], '显式实体坐标和宽度保持不变');+ }+ const paths = [...svg.matchAll(/<path\b[^>]*data-composition-points="[^"]+"[^>]*>/g)].map(match => {+ const attrs = attributes(match[0]);+ const parsed = analyzeSvgPath(attrs.d);+ assert.equal(parsed.ok, true, attrs.d);+ return { attrs, points: attrs['data-composition-points'].split(';').map(pair => pair.split(',').map(Number)),+ segments: parsed.subpaths.flatMap(subpath => subpath.segments) };+ });+ const trunks = paths.filter(route => Object.hasOwn(route.attrs, 'data-er-trunk'));+ const relationships = paths.filter(route => route.attrs['data-edge-id']);+ assert.ok(trunks.length, '安全的主干段仍然绘制');+ assert.equal(relationships.length, document.relationships.length, '所有关系及其基数均须保留');+ for (const authored of document.relationships) {+ const route = relationships.find(candidate => candidate.attrs['data-edge-id'] === authored.id);+ assert.deepEqual([route.attrs['data-edge-from'], route.attrs['data-edge-to']], [authored.from, authored.to]);+ assert.equal(route.attrs['marker-start'], `url(#er-${authored.fromCardinality}-start)`);+ assert.equal(route.attrs['marker-end'], `url(#er-${authored.toCardinality}-end)`);+ assert.equal(route.attrs.class, authored.identifying === false ? 'a-dashed' : 'a-default');+ if (authored.via) assert.deepEqual(route.points.slice(1, -1), authored.via, '显式途经点不能为了总线而移动');+ }+ return { trunks, relationships };+}++// 总线为轴对齐直线;从实际 d 的直线和曲线采样判断交叉、端点接触及正长度重叠。+// 不读逻辑 data-composition-points 来代替真实墨迹,否则会漏掉这次额外补出的桥接段。+function hitsTrunk({ start: a, end: b }, { start, end }) {+ const axis = Math.abs(a[0] - b[0]) < epsilon ? 0 : 1;+ const low = Math.min(a[1 - axis], b[1 - axis]);+ const high = Math.max(a[1 - axis], b[1 - axis]);+ if (Math.abs(start[axis] - end[axis]) < epsilon) {+ return Math.abs(start[axis] - a[axis]) < epsilon+ && Math.min(start[1 - axis], end[1 - axis]) <= high + epsilon+ && Math.max(start[1 - axis], end[1 - axis]) >= low - epsilon;+ }+ const amount = (a[axis] - start[axis]) / (end[axis] - start[axis]);+ const position = start[1 - axis] + amount * (end[1 - axis] - start[1 - axis]);+ return amount >= -epsilon && amount <= 1 + epsilon && position >= low - epsilon && position <= high + epsilon;+}++for (const scenario of [+ { conflict: 'crossing', dashed: true },+ { conflict: 'touch' },+ { conflict: 'overlap', horizontal: true },+]) {+ test(`ERD ${scenario.horizontal ? 'horizontal' : 'vertical'} trunk bridges avoid an independent ${scenario.conflict}`, t => {+ const { trunks, relationships } = render(t, fixture(scenario));+ const independent = relationships.find(route => route.attrs['data-edge-id'] === 'c_d');+ for (const trunk of trunks) {+ assert.ok(trunk.segments.every(bus => independent.segments.every(segment => !hitsTrunk(bus, segment))),+ '额外桥接不能把无关关系画成总线的分支');+ }+ });+}++test('ERD clear vertical and horizontal fan-in gaps retain one continuous shared trunk', t => {+ for (const horizontal of [false, true]) {+ const { trunks, relationships } = render(t, fixture({ horizontal }));+ const ports = relationships.map(route => route.points.at(-1));+ const along = horizontal ? 0 : 1;+ assert.ok(trunks.some(trunk => {+ const values = trunk.points.map(point => point[along]);+ return Math.min(...values) <= Math.min(...ports.map(point => point[along]))+ && Math.max(...values) >= Math.max(...ports.map(point => point[along]));+ }), '同一总线的合法分支间隙仍须连通');+ }+});