v1.3.13: 模块化注册架构 + PDS流程设计套件更名 + 依赖/圆周交互修复

- 模块化:EdcModule 契约 + registry + 模块独立目录;发布包增加 modules/registry.json
- 更名:PDS流程设计套件 / ProcessDesignSuite;同步构建、发布脚本与文档
- 时序图:依赖偏移以时间显示/编辑;紧贴依赖隐藏箭头并在接缝显示标签;动作条磁吸
- 圆周:依赖标签沿圆弧方向、环间空隙;动作旋转磁吸增强;短弧标签优先动作名
- 清理:release 移至源码同级(本地不入库);tool 合并到 tools;发布说明迁移 docs/release-notes
This commit is contained in:
2026-11-22 10:02:48 +08:00
parent afc4dc6dd7
commit 0a3f2c5cc6
105 changed files with 6309 additions and 3577 deletions
-225
View File
@@ -1,225 +0,0 @@
/// drawio 导出写入器:把流程图序列化为 diagrams.net(draw.io)可编辑的 `.drawio` 文件。
///
/// 架构位置:
/// - 仅流程图视图支持(条形 / 圆周视图只有 SVG / PNG 两种导出);
/// - 几何完全复用 [FlowLayout](与屏幕画布、SVG 导出同一套坐标与走线),
/// 保证三种载体(画布 / drawio / SVG)内容一致;
/// - 输出标准 `<mxfile>` 文档:节点保留动作颜色与「时长 · 工位」语义,
/// 连线保留 FS / SS 类型与偏移角标签,泳道为背景带、相位为竖排文字带,
/// 导入 draw.io 后可直接继续排布与编辑。
///
/// 输出约定:
/// - 坐标与原画布 1:1(不缩放),原点同样在左上角;
/// - 页面尺寸按内容范围自动设置,四边各留 [_pad] 留白,整体平移到页内;
/// - 不写入时间戳等易变字段,保证同一工程多次导出结果稳定(便于测试与归档)。
library;
import 'dart:ui';
import '../layout/flow_layout.dart';
import '../model/models.dart';
import '../theme/tokens.dart';
import 'export_fit.dart';
/// drawio 文档写入器。
///
/// 通过内部 [StringBuffer] 逐段拼接 XML,最终由 [build] 返回完整文档。
class DrawioWriter {
/// 创建写入器。
///
/// 参数:
/// - [project]:数据源(动作、依赖、相位分区、单位);
/// - [tokens]:配色令牌(内部转为导出专用纯白主题,与 SVG / PNG 一致)。
///
/// 构造时不生成任何内容;调用 [build] 才写出文档。
DrawioWriter({required this.project, required Tokens tokens})
: tokens = exportTokens(tokens);
/// 数据源工程。
final Project project;
/// 导出专用配色令牌。
final Tokens tokens;
/// 页内留白(四周各留的空白,逻辑像素)。
static const double _pad = 40;
/// 输出缓冲区,累积 XML 文本片段。
final StringBuffer _b = StringBuffer();
/// 生成完整 drawio 文档字符串。
///
/// 返回:以 `<mxfile>` 开头、`</mxfile>` 结尾的字符串。
/// 副作用:会持续向内部缓冲区追加内容;约定每次导出新建实例。
String build() {
final FlowLayout layout = FlowLayout(project);
if (layout.nodes.isEmpty) {
return '<mxfile host="app.diagrams.net"><diagram id="flow" name="流程图">'
'<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root>'
'</mxGraphModel></diagram></mxfile>';
}
// 平移到页内:原点统一挪到 (pad, pad),页面尺寸随内容自适应。
final double ox = _pad - layout.bounds.left;
final double oy = _pad - layout.bounds.top;
final int pageW = (layout.bounds.width + _pad * 2).ceil();
final int pageH = (layout.bounds.height + _pad * 2).ceil();
_b.write('<mxfile host="app.diagrams.net" agent="Sequence Diagram Studio" '
'version="24.7.8" type="device">');
_b.write('<diagram id="flow" name="${_esc(project.name.isEmpty ? '流程图' : project.name)}">');
_b.write('<mxGraphModel dx="1600" dy="900" grid="1" gridSize="10" guides="1" '
'tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" '
'pageWidth="$pageW" pageHeight="$pageH" math="0" shadow="0">');
_b.write('<root>');
_b.write('<mxCell id="0"/>');
_b.write('<mxCell id="1" parent="0"/>');
_lanes(layout, ox, oy);
_phases(layout, ox, oy);
_edges(layout);
_nodes(layout, ox, oy);
_b.write('</root></mxGraphModel></diagram></mxfile>');
return _b.toString();
}
/// 写入泳道背景带与轨道标题(原样平移)。
void _lanes(FlowLayout layout, double ox, double oy) {
final double lanePitch = FlowLayout.nodeW + FlowLayout.laneGap;
final double top = layout.bounds.top + 20 + oy;
final double bottom = layout.bounds.bottom - 20 + oy;
for (int i = 0; i < layout.lanes.length; i++) {
final double cx = FlowLayout.marginX + i * lanePitch + FlowLayout.nodeW / 2 + ox;
_rectCell(
'lane-${layout.lanes[i]}',
'轨道 L${i + 1}',
cx - FlowLayout.nodeW / 2 - 26,
top,
FlowLayout.nodeW + 52,
bottom - top,
'rounded=0;whiteSpace=wrap;html=1;verticalAlign=top;fontSize=11;fontStyle=1;'
'fillColor=${_hex(i.isEven ? tokens.ringA : tokens.ringB)};fillOpacity=55;'
'strokeColor=none;fontColor=${_hex(tokens.sub)};',
);
}
}
/// 写入相位竖带:竖排文字(`horizontal=0`)+ 低透明度填充,台阶错位保持一致。
void _phases(FlowLayout layout, double ox, double oy) {
final double rowPitch = FlowLayout.nodeH + FlowLayout.rankGap;
for (int i = 0; i < layout.spans.length; i++) {
final FlowPhaseSpan s = layout.spans[i];
final double top = FlowLayout.marginY + s.rankTop * rowPitch - 6 + oy;
final double bottom =
FlowLayout.marginY + s.rankBottom * rowPitch + FlowLayout.nodeH + 6 + oy;
final double left = FlowLayout.railX + s.slot * FlowLayout.railStep + ox;
_rectCell(
'phase-$i',
s.zone.name,
left,
top,
FlowLayout.railW,
bottom - top,
'rounded=1;whiteSpace=wrap;html=1;horizontal=0;fontSize=10;fontStyle=1;'
'fillColor=${_hex(tokens.accent)};fillOpacity=10;'
'strokeColor=${_hex(tokens.accent)};strokeOpacity=45;fontColor=${_hex(tokens.sub)};',
);
}
}
/// 写入动作节点与开始 / 结束胶囊。
void _nodes(FlowLayout layout, double ox, double oy) {
for (final FlowNode n in layout.nodes) {
final Rect r = n.rect;
if (n.isStart || n.isEnd) {
_rectCell(
_cellId(n.id),
n.title,
r.left + ox,
r.top + oy,
r.width,
r.height,
'ellipse;whiteSpace=wrap;html=1;fontSize=13;fontStyle=1;'
'fillColor=${_hex(tokens.panel2)};strokeColor=${_hex(tokens.accent)};'
'fontColor=${_hex(tokens.accent)};',
);
continue;
}
final Action a = n.action!;
// 节点两行文字:标题(序号. 名称)+ 副标题(时长 · 工位)。
_rectCell(
_cellId(n.id),
'${n.title}\n${n.subtitle}',
r.left + ox,
r.top + oy,
r.width,
r.height,
'rounded=1;absoluteArcSize=1;arcSize=10;whiteSpace=wrap;html=1;fontSize=12;fontStyle=1;'
'fillColor=${_hex(Color(a.color))};fillOpacity=92;'
'strokeColor=${_hex(tokens.selOutline)};strokeOpacity=25;'
'fontColor=${_hex(tokens.arcText)};',
);
}
}
/// 写入依赖连线:以 source / target 引用节点,drawio 自动正交布线并可再编辑。
///
/// 样式与画布一致:FS 绿实线、SS 琥珀虚线(标签标注偏移角)、关键路径加粗。
void _edges(FlowLayout layout) {
int i = 0;
for (final FlowEdge e in layout.edges) {
i++;
final bool fs = e.type == DepType.fs;
final String col =
_hex(e.type == null ? tokens.sub : (fs ? tokens.fs : tokens.ss));
final String label = switch (e.type) {
null => '',
DepType.fs => 'FS',
DepType.ss => 'SS+${e.offset.toStringAsFixed(0)}°',
DepType.ff => 'FF',
DepType.sf => 'SF',
};
_b.write('<mxCell id="edge-$i-${_cellId(e.fromId)}-${_cellId(e.toId)}" '
'value="${_esc(label)}" '
'style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;jettySize=auto;'
'orthogonalLoop=1;endArrow=block;endFill=1;'
'strokeWidth=${e.critical ? 2.4 : 1.3};strokeColor=$col;'
'${e.type == DepType.ss ? 'dashed=1;dashPattern=6 4;' : ''}'
'fontSize=9;fontColor=$col;labelBackgroundColor=${_hex(tokens.bg)};" '
'edge="1" parent="1" source="${_cellId(e.fromId)}" target="${_cellId(e.toId)}">'
'<mxGeometry relative="1" as="geometry"/></mxCell>');
}
}
/// 写入一个顶点(矩形 / 胶囊 / 竖带)单元格。
void _rectCell(String id, String value, double x, double y, double w, double h,
String style) {
_b.write('<mxCell id="$id" value="${_esc(value)}" '
'style="$style" vertex="1" parent="1">'
'<mxGeometry x="${x.toStringAsFixed(1)}" y="${y.toStringAsFixed(1)}" '
'width="${w.toStringAsFixed(1)}" height="${h.toStringAsFixed(1)}" as="geometry"/>'
'</mxCell>');
}
/// 节点 id → drawio 单元格 id:开始 / 结束用可读短名,其余原样保留。
static String _cellId(String nodeId) {
if (nodeId == FlowNode.startId) return 'flow-start';
if (nodeId == FlowNode.endId) return 'flow-end';
return nodeId.replaceAll(RegExp(r'[^A-Za-z0-9_-]'), '_');
}
/// 转义 XML 文本 / 属性中的特殊字符;换行转为 `&#10;`(drawio 多行标签约定)。
static String _esc(String s) => s
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll('\n', '&#10;');
/// 把 Flutter [Color] 转为 `#rrggbb` 字符串(忽略 alpha)。
static String _hex(Color c) {
final int r = (c.r * 255).round();
final int g = (c.g * 255).round();
final int b = (c.b * 255).round();
return '#${r.toRadixString(16).padLeft(2, '0')}${g.toRadixString(16).padLeft(2, '0')}${b.toRadixString(16).padLeft(2, '0')}';
}
}
-144
View File
@@ -1,144 +0,0 @@
/// 导出适配:固定 1920×1080 画布下,把时序图内容缩放到内容区并居中,
/// 供 PNG 渲染器与 SVG 写入器共用,保证两种导出几何完全一致。
///
/// 约定:
/// - 画布固定 1920×1080;
/// - 标题固定在左上角(标题区 0–128px);
/// - 内容区 = (48, 128) → (1872, 1016),图例固定左下角;
/// - 内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。
library;
import 'dart:math' as math;
import 'package:flutter/material.dart' hide Action;
import '../layout/layout.dart';
import '../layout/flow_layout.dart';
import '../model/models.dart';
import '../model/units.dart';
import '../render/bar_painter.dart';
import '../theme/tokens.dart';
/// 导出画布尺寸(固定,逻辑单位)。
const Size kExportSize = Size(1920, 1080);
/// 导出渲染像素比:按 2 倍像素渲染(3840×2160),保证高分辨率屏幕下清晰锐利。
const double kExportPixelRatio = 2.0;
/// 内容区(标题下方、图例上方)。
const Rect kExportContentArea = Rect.fromLTRB(48, 128, 1872, 1016);
/// 导出适配结果:内容变换 `scale` + `translate(tx, ty)`。
class ExportFit {
/// 构造适配结果。
const ExportFit(this.scale, this.tx, this.ty);
/// 缩放系数。
final double scale;
/// 水平平移。
final double tx;
/// 垂直平移。
final double ty;
/// SVG transform 属性值。
String get svgTransform =>
'translate(${tx.toStringAsFixed(1)} ${ty.toStringAsFixed(1)}) scale(${scale.toStringAsFixed(4)})';
}
/// 计算内容在 [area] 内的适配变换。
///
/// 先以 1920×1080 为参考画布求内容包围盒,再等比缩放并居中。
ExportFit computeExportFit(Project project, ViewMode mode, Rect area) {
Rect bounds;
if (mode == ViewMode.bar) {
final BarLayout l = BarLayout(project, kExportSize);
final int n = l.lanes.length;
final double bottom = n == 0 ? BarLayout.topPad + BarLayout.rowVisual : l.plotBottom + 8;
bounds = Rect.fromLTRB(12, BarPainter.phaseBandTop - 14, l.plotRight + 120, bottom);
} else if (mode == ViewMode.circular) {
final CircularLayout l = CircularLayout(project, kExportSize);
final double rExt = l.tickR + 100;
bounds = Rect.fromLTRB(l.center.dx - rExt, l.center.dy - rExt, l.center.dx + rExt, l.center.dy + rExt);
} else {
// 流程图:直接使用布局层给出的内容范围(含泳道、阶段栏与连线)。
final FlowLayout l = FlowLayout(project);
bounds = l.nodes.isEmpty ? const Rect.fromLTWH(0, 0, 800, 600) : l.bounds;
}
if (bounds.width <= 1 || bounds.height <= 1) {
return const ExportFit(1, 0, 0);
}
final double s = math.min(area.width / bounds.width, area.height / bounds.height).clamp(0.2, 1.6);
final double tx = area.left + (area.width - bounds.width * s) / 2 - bounds.left * s;
final double ty = area.top + (area.height - bounds.height * s) / 2 - bounds.top * s;
return ExportFit(s, tx, ty);
}
/// 导出标题(与画布浮层一致)。
String exportTitle(ViewMode mode) => switch (mode) {
ViewMode.bar => '条形时序视图',
ViewMode.circular => '圆周时序视图',
ViewMode.flow => '流程图视图',
};
/// 导出副标题:仅保留括号内的线型图例(与画布标题后方的说明一致)。
///
/// 更完整的视图语义(同心圆环 / 循环换算等)见应用内「帮助」。
String exportSubtitle(ViewMode mode) => switch (mode) {
ViewMode.bar => '(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)',
ViewMode.circular => '(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)',
// 流程图不重复线型说明,导出仅保留标题(与画布浮层一致)。
ViewMode.flow => '',
};
/// 导出图例(左下角固定)。
String exportLegend(Project project) =>
'时序图设计 · ${project.name} · 循环 ${tfmt(project.cycle.durationMs, project.units)} = 360°';
/// 导出专用令牌:始终使用浅色、**纯白背景**(印刷 / 工艺卡导向),
/// 文字、语义色与屏幕浅色主题保持一致。
///
/// 无论当前屏幕主题是深是浅,导出的 PNG / SVG 背景都是纯白、文字深色,
/// 避免「导出背景不是纯白」的问题。
Tokens exportTokens(Tokens base) {
return Tokens(
brightness: Brightness.light,
bg: Colors.white,
canvas1: Colors.white,
canvas2: Colors.white,
chrome: base.chrome,
panel: Colors.white,
panel2: Colors.white,
dialog: Colors.white,
line: base.line,
line2: base.line2,
text: base.text,
text2: base.text2,
sub: base.sub,
dim: base.dim,
accent: base.accent,
accent2: base.accent2,
ok: base.ok,
warn: base.warn,
danger: base.danger,
fs: base.fs,
ss: base.ss,
crit: base.crit,
chip: Colors.white,
dial: Colors.white,
arcText: base.arcText,
onAccent: base.onAccent,
ringA: base.ringA,
ringB: base.ringB,
ringEdge: base.ringEdge,
ringLabel: base.ringLabel,
info: Colors.white,
track: base.track,
sel: base.sel,
grid: base.grid,
shadow: base.shadow,
shadowOp: 0.10,
selOutline: base.selOutline,
overlay: base.overlay,
tailOp: base.tailOp,
);
}
+84
View File
@@ -0,0 +1,84 @@
/// 导出画布的共享几何约束:固定 1920×1080、2 倍像素比、内容区与
/// 缩放/平移结果 [ExportFit]。
///
/// 架构位置:`lib/export/` 为共享导出层,不依赖任何具体模块;时序图与
/// 架构图模块各自的导出逻辑都复用这里的常量与 [ExportFit]。
library;
import 'package:flutter/material.dart';
import 'package:sequence_diagram/theme/tokens.dart';
/// 导出画布尺寸(固定逻辑尺寸)。
const Size kExportSize = Size(1920, 1080);
/// 导出渲染像素比:按 2 倍渲染成 3840×2160,保证高分辨率打印清晰。
const double kExportPixelRatio = 2.0;
/// 导出内容区域(标题/图例之外的内容区)。
const Rect kExportContentArea = Rect.fromLTRB(48, 128, 1872, 1016);
/// 导出内容变换:`scale` + `translate(tx, ty)`。
class ExportFit {
/// 构造内容变换。
const ExportFit(this.scale, this.tx, this.ty);
/// 缩放系数。
final double scale;
/// 水平平移。
final double tx;
/// 垂直平移。
final double ty;
/// SVG transform 属性值。
String get svgTransform =>
'translate(${tx.toStringAsFixed(1)} ${ty.toStringAsFixed(1)}) scale(${scale.toStringAsFixed(4)})';
}
/// 导出专用令牌:始终使用浅色、纯白背景(印刷 / 工艺卡导向),
/// 文字、语义色与屏幕浅色主题保持一致。
Tokens exportTokens(Tokens base) {
return Tokens(
brightness: Brightness.light,
bg: Colors.white,
canvas1: Colors.white,
canvas2: Colors.white,
chrome: base.chrome,
panel: Colors.white,
panel2: Colors.white,
dialog: Colors.white,
line: base.line,
line2: base.line2,
text: base.text,
text2: base.text2,
sub: base.sub,
dim: base.dim,
accent: base.accent,
accent2: base.accent2,
ok: base.ok,
warn: base.warn,
danger: base.danger,
fs: base.fs,
ss: base.ss,
crit: base.crit,
chip: Colors.white,
dial: Colors.white,
arcText: base.arcText,
onAccent: base.onAccent,
ringA: base.ringA,
ringB: base.ringB,
ringEdge: base.ringEdge,
ringLabel: base.ringLabel,
info: Colors.white,
track: base.track,
sel: base.sel,
grid: base.grid,
shadow: base.shadow,
shadowOp: 0.10,
selOutline: base.selOutline,
overlay: base.overlay,
tailOp: base.tailOp,
);
}
-115
View File
@@ -1,115 +0,0 @@
/// PNG 导出渲染器:把时序图渲染为固定 1920×1080 的位图。
///
/// 与 SVG 导出共用同一套适配计算([computeExportFit]),保证两种格式几何一致:
/// - 背景铺满 1920×1080;
/// - 标题固定在左上角、图例固定在左下角;
/// - 内容(条形 / 圆周)按自身包围盒等比缩放并居中到内容区。
library;
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart' hide Action;
import '../model/models.dart';
import '../render/bar_painter.dart';
import '../render/circular_painter.dart';
import '../render/flow_painter.dart';
import '../theme/tokens.dart';
import 'export_fit.dart';
/// 渲染导出 PNG 并返回字节。
///
/// 参数:
/// - [project]:数据源;
/// - [tokens]:配色令牌(内部转为导出专用纯白主题);
/// - [criticalActions]/[criticalDeps]:关键路径高亮(与屏幕一致)。
///
/// 输出:3840×2160 像素(1920×1080 逻辑画布 × 2 倍像素比),
/// 保证平板 / 2K / 4K 屏幕上查看清晰锐利。
Future<Uint8List> renderExportPng({
required Project project,
required Tokens tokens,
required Set<String> criticalActions,
required Set<String> criticalDeps,
}) async {
// 导出专用令牌:纯白背景、浅色文字。
final Tokens et = exportTokens(tokens);
final ui.PictureRecorder recorder = ui.PictureRecorder();
final Canvas canvas = Canvas(recorder);
final double w = kExportSize.width;
final double h = kExportSize.height;
// 2 倍像素比:整体放大绘制,矢量内容保持锐利。
canvas.scale(kExportPixelRatio);
// 背景铺满(纯白)。
canvas.drawRect(Rect.fromLTWH(0, 0, w, h), Paint()..color = et.bg);
// 标题:固定左上角。
final ViewMode mode = project.viewState.mode;
_text(canvas, exportTitle(mode), const Offset(48, 36),
color: et.text, size: 34, weight: FontWeight.w700);
_text(canvas, exportSubtitle(mode), const Offset(48, 88),
color: et.sub, size: 16, weight: FontWeight.w400);
// 内容:适配缩放并居中到内容区。
final ExportFit fit = computeExportFit(project, mode, kExportContentArea);
canvas.save();
canvas.translate(fit.tx, fit.ty);
canvas.scale(fit.scale);
if (mode == ViewMode.bar) {
BarPainter(
project: project,
tokens: et,
criticalActions: criticalActions,
criticalDeps: criticalDeps,
selectedIds: const <String>{},
).paint(canvas, kExportSize);
} else if (mode == ViewMode.flow) {
FlowchartPainter(
project: project,
tokens: et,
criticalActions: criticalActions,
criticalDeps: criticalDeps,
selectedIds: const <String>{},
).paint(canvas, kExportSize);
} else {
CircularPainter(
project: project,
tokens: et,
criticalActions: criticalActions,
criticalDeps: criticalDeps,
selectedIds: const <String>{},
).paint(canvas, kExportSize);
}
canvas.restore();
// 图例:固定左下角。
_text(canvas, exportLegend(project), Offset(48, h - 38),
color: et.sub, size: 15, weight: FontWeight.w400);
final ui.Image image = await recorder
.endRecording()
.toImage((w * kExportPixelRatio).toInt(), (h * kExportPixelRatio).toInt());
final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png);
return data!.buffer.asUint8List();
}
/// 用统一字体绘制单行文本。
void _text(Canvas canvas, String s, Offset at,
{required Color color, required double size, required FontWeight weight}) {
final TextPainter tp = TextPainter(
text: TextSpan(
text: s,
style: TextStyle(
color: color,
fontSize: size,
fontWeight: weight,
fontFamily: 'Microsoft YaHei UI',
fontFamilyFallback: const <String>['Microsoft YaHei', 'Noto Sans SC', 'sans-serif'],
),
),
textDirection: ui.TextDirection.ltr,
)..layout();
tp.paint(canvas, Offset(at.dx, at.dy - tp.height / 2));
}
-446
View File
@@ -1,446 +0,0 @@
/// SVG 导出写入器。
///
/// 职责:把当前 [Project] 序列化为独立、可缩放、带语义标注的 SVG 文档,
/// 用于归档、打印,或与前端 / EDA 工具交换。
///
/// 架构位置:
/// - 与渲染层 `BarPainter`/`CircularPainter` 共用 [BarLayout]/[CircularLayout]
/// 的几何算法,确保屏幕显示与导出结果一致。
/// - 颜色取自 [Tokens],并通过 [_hex] 转为 `#rrggbb`。
/// - 每个逻辑分组写成 `<g id="...">`(背景、标尺、动作、标签、依赖、图例),
/// 动作组与依赖组额外附带 `data-*` 属性,便于下游脚本解析。
///
/// 输出约定(与 PNG 导出一致):
/// - 画布固定 1920×1080,通过 `viewBox` 支持无损缩放;
/// - 标题固定在左上角、图例固定在左下角;
/// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。
/// - 所有文本内联 [_font] 字体栈,保证跨平台字形一致。
library;
import 'dart:math' as math;
import 'dart:ui';
import '../layout/layout.dart';
import '../layout/flow_layout.dart';
import '../model/models.dart';
import '../model/units.dart';
import '../theme/tokens.dart';
import 'export_fit.dart';
/// SVG 文档写入器。
///
/// 通过内部 [StringBuffer] 逐段拼接字符串,最终由 [build] 返回完整文档。
class SvgWriter {
/// 创建 SVG 写入器。
///
/// 参数:
/// - [project]:数据源(动作、依赖、视图开关、单位)。
/// - [tokens]:配色令牌。
/// - [mode]:视图模式,决定生成条形还是圆形布局。
///
/// 构造时不生成任何内容;调用 [build] 才写出 SVG。
///
/// [tokens] 会经 [exportTokens] 转为导出专用令牌(纯白背景、浅色文字)。
SvgWriter({required this.project, required Tokens tokens, required this.mode})
: tokens = exportTokens(tokens);
/// 数据源工程。
final Project project;
/// 配色令牌。
final Tokens tokens;
/// 导出所用的视图模式。
final ViewMode mode;
/// 输出缓冲区,累积 SVG 文本片段。
final StringBuffer _b = StringBuffer();
/// 统一字体栈常量。
static const String _font = "'Microsoft YaHei','Noto Sans SC','Segoe UI',sans-serif";
/// 生成完整 SVG 文档字符串。
///
/// 输出约定(与 PNG 导出一致):
/// - 画布固定 1920×1080;
/// - 标题固定在左上角、图例固定在左下角;
/// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。
///
/// 返回:以 `<svg ...>` 开头、`</svg>` 结尾的字符串。
/// 副作用:会持续向内部缓冲区追加内容;重复调用不会自动清空缓冲区,
/// 因此约定每次导出都新建一个 [SvgWriter] 实例。
String build() {
const double w = 1920;
const double h = 1080;
_b.write('<svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">');
// 先写箭头 marker 定义,供后续依赖路径引用。
_defs();
// 背景层:铺满整张画布。
_b.write('<g id="background">');
_rect(0, 0, w, h, fill: _hex(tokens.bg));
_b.write('</g>');
// 标题:固定左上角。
_b.write('<g id="title">');
_text(48, 60, exportTitle(mode), color: _hex(tokens.text), size: 34, weight: '700');
_text(48, 104, exportSubtitle(mode), color: _hex(tokens.sub), size: 16);
_b.write('</g>');
// 内容:适配缩放并居中到内容区。
final ExportFit fit = computeExportFit(project, mode, kExportContentArea);
_b.write('<g id="content" transform="${fit.svgTransform}">');
if (mode == ViewMode.bar) {
_barView(const Size(w, h));
} else if (mode == ViewMode.circular) {
_circularView(const Size(w, h));
} else {
_flowView();
}
_b.write('</g>');
// 图例:固定左下角。
_b.write('<g id="legend">');
_text(48, h - 36, exportLegend(project), color: _hex(tokens.sub), size: 15);
_b.write('</g>');
_b.write('</svg>');
return _b.toString();
}
/// 写入 `<defs>` 段,定义 FS / SS 两种箭头 marker。
///
/// marker 通过 id `arrow-fs`、`arrow-ss` 被依赖路径的 `marker-end` 引用;
/// `orient="auto"` 使箭头自动跟随路径末端方向。
void _defs() {
_b.write('<defs>');
_b.write('<marker id="arrow-fs" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto">'
'<path d="M0,0 L8,3 L0,6 z" fill="${_hex(tokens.fs)}"/></marker>');
_b.write('<marker id="arrow-ss" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto">'
'<path d="M0,0 L8,3 L0,6 z" fill="${_hex(tokens.ss)}"/></marker>');
_b.write('</defs>');
}
/// 生成条形视图的 SVG 内容。
///
/// 参数 [size] 用于构建与屏幕一致的 [BarLayout]。
/// 依次输出四个分组:
/// - `g#ruler`:角度/时间双轴标尺(`data-axis="angle"`)。
/// - `g#actions`:每个动作一个 `g`,带 `data-action/start/duration/layer/station`。
/// - `g#labels`:左侧动作标识与工位/驱动文本。
/// - `g#dependencies`(可选):依赖正交折线。
void _barView(Size size) {
final BarLayout layout = BarLayout(project, size);
final UnitSettings u = project.units;
final double cycle = project.cycle.durationMs;
final double top = BarLayout.topPad - 62;
// 标尺分组:下排为相位角,上排为等价时间;data-axis 标记角度轴语义。
_b.write('<g id="ruler" data-axis="angle">');
_rect(layout.plotLeft, top, layout.span, 26, fill: _hex(tokens.accent), opacity: 0.07);
for (int d = 0; d <= 360; d += 30) {
final double x = layout.xFor(d.toDouble());
_line(x, top + 26, x, top + 44, stroke: _hex(tokens.line2), sw: 1);
_text(x, top - 10, tvalStr(d / 360 * cycle, u, dec: 1), color: _hex(tokens.dim), size: 11, anchor: 'middle');
_text(x, top + 58, pfmt(d.toDouble(), u, dec: 0), color: _hex(tokens.accent), size: 11, anchor: 'middle');
}
_b.write('</g>');
// 动作分组:每个动作一个 <g>,附带 data-* 语义属性,便于下游解析。
_b.write('<g id="actions">');
final List<Action> ordered = layout.ordered;
for (int i = 0; i < ordered.length; i++) {
final Action a = ordered[i];
final Rect r = layout.rectFor(a);
final Color c = Color(a.color);
_b.write('<g id="${_esc(a.id)}" data-action="${_esc(a.id)}" data-start="${a.startAngle}" '
'data-duration="${a.durationAngle}" data-layer="${a.layer}" data-station="${_esc(a.stationId)}">');
_rect(r.left, r.top, r.width, r.height, fill: _hex(c), rx: 3, opacity: 0.92);
_text(r.left + 8, r.center.dy + 4, '${a.name} ${tfmt(a.durationAngle / 360 * cycle, u)}',
color: _hex(tokens.arcText), size: 12, weight: '700');
_b.write('</g>');
}
_b.write('</g>');
// 标签分组:左侧动作标识与工位/驱动信息。
_b.write('<g id="labels">');
for (int i = 0; i < ordered.length; i++) {
final Action a = ordered[i];
final double y = layout.yForSlot(a.layer, layout.slotOf(a));
_text(BarLayout.leftGutter + 6, y + 8, '${a.id} ${a.name}', color: _hex(tokens.text), size: 13, weight: '600');
_text(BarLayout.leftGutter + 6, y + 24, '${a.stationId} · ${a.driver}', color: _hex(tokens.dim), size: 10.5);
}
_b.write('</g>');
// 依赖分组:正交折线;FS 为实线,SS 为虚线并带偏移角语义。
if (project.viewState.showDeps) {
_b.write('<g id="dependencies">');
final Map<String, int> index = <String, int>{};
for (int i = 0; i < ordered.length; i++) {
index[ordered[i].id] = i;
}
for (final Action to in ordered) {
for (final Dependency d in to.deps) {
final Action? from = project.actionById(d.fromId);
if (from == null) continue;
final Rect ra = layout.rectFor(from);
final Rect rb = layout.rectFor(to);
final bool fs = d.type == DepType.fs;
final Color col = fs ? tokens.fs : tokens.ss;
final double sx = fs ? ra.right : ra.left;
final double sy = ra.center.dy;
final double tx = rb.left + 12;
final double ty = rb.center.dy - 10;
final String dPath = 'M $sx $sy L $sx ${(sy + ty) / 2} L $tx ${(sy + ty) / 2} L $tx $ty';
_b.write('<path id="dep-${_esc(d.fromId)}-${_esc(d.toId)}" data-type="${d.type.name.toUpperCase()}" '
'd="$dPath" fill="none" stroke="${_hex(col)}" stroke-width="2" '
'${fs ? '' : 'stroke-dasharray="6 4" '}marker-end="url(#arrow-${fs ? 'fs' : 'ss'})"/>');
}
}
_b.write('</g>');
}
}
/// 生成圆形视图的 SVG 内容。
///
/// 参数 [size] 用于构建 [CircularLayout]。
/// 依次输出:
/// - `g#layers`:同心圆环背景(奇偶层交替着色)。
/// - `g#ruler`:每 30° 的刻度与度数。
/// - `g#actions`:动作弧,跨循环动作经 [splitArcs] 拆成多段。
/// - `g#dependencies`(可选):沿半径与圆弧的依赖路径。
void _circularView(Size size) {
final CircularLayout layout = CircularLayout(project, size);
final Offset c = layout.center;
final double th = layout.th;
// 圆环层背景分组。
_b.write('<g id="layers">');
for (int i = 0; i <= project.maxLayer; i++) {
final double r = layout.radiusFor(i);
_circle(c.dx, c.dy, r, stroke: _hex(i.isEven ? tokens.ringA : tokens.ringB), sw: th);
}
_b.write('</g>');
// 角度刻度分组,data-axis 标记角度轴语义。
_b.write('<g id="ruler" data-axis="angle">');
for (int d = 0; d < 360; d += 30) {
final Offset p1 = polar(c, layout.tickR, d.toDouble());
final Offset p2 = polar(c, layout.tickR + 16, d.toDouble());
_line(p1.dx, p1.dy, p2.dx, p2.dy, stroke: _hex(tokens.line2), sw: 1);
final Offset lp = polar(c, layout.tickR + 34, d.toDouble());
_text(lp.dx, lp.dy, '$d°', color: _hex(tokens.sub), size: 11, anchor: 'middle');
}
_b.write('</g>');
// 动作弧分组:跨循环动作由 splitArcs 拆段,逐段写 <path>。
_b.write('<g id="actions">');
for (final Action a in project.actions) {
final double r = layout.radiusFor(a.layer);
final Color col = Color(a.color);
_b.write('<g id="${_esc(a.id)}" data-action="${_esc(a.id)}" data-start="${a.startAngle}" '
'data-duration="${a.durationAngle}" data-layer="${a.layer}" data-station="${_esc(a.stationId)}">');
for (final List<double> s in splitArcs(a.startAngle, a.endAngle)) {
final String d = _arc(c, r, s[0], s[1]);
_b.write('<path d="$d" fill="none" stroke="${_hex(col)}" stroke-width="$th" stroke-linecap="butt"/>');
}
final Offset mp = polar(c, r, (a.startAngle + a.endAngle) / 2);
_text(mp.dx, mp.dy, '${a.id} ${a.name}', color: _hex(tokens.arcText), size: 12, anchor: 'middle', weight: '700');
_b.write('</g>');
}
_b.write('</g>');
// 依赖分组:路径由“半径 → 圆弧 → 半径”三段构成,与屏幕渲染一致。
if (project.viewState.showDeps) {
_b.write('<g id="dependencies">');
for (final Action to in project.actions) {
for (final Dependency d in to.deps) {
final Action? A = project.actionById(d.fromId);
final Action? B = project.actionById(d.toId);
if (A == null || B == null) continue;
final double rA = layout.radiusFor(A.layer);
final double rB = layout.radiusFor(B.layer);
final double aEnd = math.min(A.endAngle, 360);
final double aStart = B.startAngle;
final bool skip = (A.layer - B.layer).abs() > 1;
final double rC = skip ? layout.rMax + 24 : (rA + rB) / 2;
final Offset p0 = polar(c, rA, aEnd);
final Offset p1 = polar(c, rC, aEnd);
final Offset p2 = polar(c, rC, aStart);
final double rTip = rC < rB ? rB - th / 2 - 4 : rB + th / 2 + 4;
final Offset p3 = polar(c, rTip, aStart);
final bool fs = d.type == DepType.fs;
final Color col = fs ? tokens.fs : tokens.ss;
final String dd = 'M ${p0.dx.toStringAsFixed(1)} ${p0.dy.toStringAsFixed(1)} '
'L ${p1.dx.toStringAsFixed(1)} ${p1.dy.toStringAsFixed(1)} '
'A $rC $rC 0 0 ${aStart >= aEnd ? 1 : 0} ${p2.dx.toStringAsFixed(1)} ${p2.dy.toStringAsFixed(1)} '
'L ${p3.dx.toStringAsFixed(1)} ${p3.dy.toStringAsFixed(1)}';
_b.write('<path id="dep-${_esc(d.fromId)}-${_esc(d.toId)}" data-type="${d.type.name.toUpperCase()}" '
'd="$dd" fill="none" stroke="${_hex(col)}" stroke-width="2" '
'${fs ? '' : 'stroke-dasharray="7 5" '}marker-end="url(#arrow-${fs ? 'fs' : 'ss'})"/>');
}
}
_b.write('</g>');
}
}
/// 生成流程图视图的 SVG 内容。
///
/// 几何完全复用 [FlowLayout](与屏幕画布、drawio 导出共用同一套走线),
/// 依次输出:
/// - `g#lanes`:泳道背景带与轨道标题;
/// - `g#phases`:左侧相位竖带(分区名旋转 90°,重叠分区台阶错位);
/// - `g#edges`:依赖折线(FS 实线 / SS 虚线,带箭头与 FS/SS 标签);
/// - `g#actions`:动作节点与开始 / 结束胶囊(带 data-* 语义属性)。
void _flowView() {
final FlowLayout layout = FlowLayout(project);
if (layout.nodes.isEmpty) return;
// 泳道背景带(与画布一致:环带色 55% 透明度 + 轨道标题)。
_b.write('<g id="lanes">');
final double lanePitch = FlowLayout.nodeW + FlowLayout.laneGap;
final double top = layout.bounds.top + 20;
final double bottom = layout.bounds.bottom - 20;
for (int i = 0; i < layout.lanes.length; i++) {
final double cx = FlowLayout.marginX + i * lanePitch + FlowLayout.nodeW / 2;
_rect(cx - FlowLayout.nodeW / 2 - 26, top, FlowLayout.nodeW + 52, bottom - top,
fill: _hex(i.isEven ? tokens.ringA : tokens.ringB), rx: 14, opacity: 0.55);
_text(cx, top + 16, '轨道 L${i + 1}',
color: _hex(tokens.sub), size: 11, anchor: 'middle', weight: '700');
}
_b.write('</g>');
// 相位竖带:窄带 + 旋转 90° 分区名,纵向对齐流程行、重叠分区台阶错位。
_b.write('<g id="phases">');
final double rowPitch = FlowLayout.nodeH + FlowLayout.rankGap;
for (final FlowPhaseSpan s in layout.spans) {
final double pTop = FlowLayout.marginY + s.rankTop * rowPitch - 6;
final double pBottom =
FlowLayout.marginY + s.rankBottom * rowPitch + FlowLayout.nodeH + 6;
final double left = FlowLayout.railX + s.slot * FlowLayout.railStep;
_rect(left, pTop, FlowLayout.railW, pBottom - pTop,
fill: _hex(tokens.accent), rx: 9, opacity: 0.10);
_rect(left, pTop, FlowLayout.railW, pBottom - pTop,
fill: 'none', rx: 9, stroke: _hex(tokens.accent), sw: 1, opacity: 0.45);
final double tx = left + FlowLayout.railW / 2;
final double ty = (pTop + pBottom) / 2;
_b.write('<text transform="translate(${tx.toStringAsFixed(1)} ${ty.toStringAsFixed(1)}) rotate(-90)" '
'font-family="$_font" font-size="10.5" fill="${_hex(tokens.sub)}" text-anchor="middle" '
'dominant-baseline="middle" font-weight="700">${_esc(s.zone.name)}</text>');
}
_b.write('</g>');
// 依赖折线:FS 实线 / SS 虚线,带箭头与 FS/SS 标签。
_b.write('<g id="edges">');
for (final FlowEdgeRoute r in layout.routes) {
final FlowEdge e = r.edge;
final bool fs = e.type == DepType.fs;
final String col = _hex(e.type == null ? tokens.sub : (fs ? tokens.fs : tokens.ss));
final String d = <String>[
for (int i = 0; i < r.points.length; i++)
'${i == 0 ? 'M' : 'L'} ${r.points[i].dx.toStringAsFixed(1)} ${r.points[i].dy.toStringAsFixed(1)}',
].join(' ');
final String marker = e.type == null ? '' : ' marker-end="url(#arrow-${fs ? 'fs' : 'ss'})"';
final String dash = r.dashed ? ' stroke-dasharray="6 4"' : '';
_b.write('<path d="$d" fill="none" stroke="$col" stroke-width="${e.critical ? 2 : 1.3}"'
'$dash$marker/>');
if (e.type != null) {
final String text = switch (e.type!) {
DepType.fs => 'FS',
DepType.ss => 'SS+${e.offset.toStringAsFixed(0)}°',
DepType.ff => 'FF',
DepType.sf => 'SF',
};
_text(r.labelAt.dx, r.labelAt.dy, text,
color: col, size: 9, anchor: 'middle', weight: '600');
}
}
_b.write('</g>');
// 动作节点与开始 / 结束胶囊。
_b.write('<g id="actions">');
for (final FlowNode n in layout.nodes) {
final Rect r = n.rect;
if (n.isStart || n.isEnd) {
_rect(r.left, r.top, r.width, r.height,
fill: _hex(tokens.panel2), rx: r.height / 2, stroke: _hex(tokens.accent), sw: 1.2);
_text(r.center.dx, r.center.dy, n.title,
color: _hex(tokens.accent), size: 13, anchor: 'middle', weight: '700');
continue;
}
final Action a = n.action!;
final Color c = Color(a.color);
_b.write('<g id="${_esc(n.id)}" data-action="${_esc(n.id)}" data-start="${a.startAngle}" '
'data-duration="${a.durationAngle}" data-layer="${a.layer}" data-station="${_esc(a.stationId)}">');
_rect(r.left, r.top, r.width, r.height, fill: _hex(c), rx: 10, opacity: 0.92);
_text(r.center.dx, r.top + 21, n.title,
color: _hex(tokens.arcText), size: 12, anchor: 'middle', weight: '700');
_text(r.center.dx, r.top + 41, n.subtitle,
color: _hex(tokens.arcText), size: 10, anchor: 'middle');
_b.write('</g>');
}
_b.write('</g>');
}
/// 生成一段圆弧的 SVG `d` 路径字符串。
///
/// 参数 [c] 圆心、[r] 半径、[a0]/[a1] 起止角度(度)。
/// 通过 [polar] 求端点,按跨度是否大于 180° 设置 large-arc 标志,
/// sweep 固定为 1(顺时针)。
String _arc(Offset c, double r, double a0, double a1) {
final Offset s = polar(c, r, a0);
final Offset e = polar(c, r, a1);
final int large = (a1 - a0) > 180 ? 1 : 0;
return 'M ${s.dx.toStringAsFixed(1)} ${s.dy.toStringAsFixed(1)} '
'A ${r.toStringAsFixed(1)} ${r.toStringAsFixed(1)} 0 $large 1 ${e.dx.toStringAsFixed(1)} ${e.dy.toStringAsFixed(1)}';
}
/// 写入一个 `<rect>` 元素。
///
/// 参数为位置与尺寸;可选 [fill] 填充色、[rx] 圆角半径、[opacity] 透明度。
void _rect(double x, double y, double w, double h,
{String? fill, double rx = 0, double opacity = 1, String? stroke, double sw = 1}) {
_b.write('<rect x="${x.toStringAsFixed(1)}" y="${y.toStringAsFixed(1)}" width="${w.toStringAsFixed(1)}" '
'height="${h.toStringAsFixed(1)}" rx="$rx" fill="${fill ?? 'none'}" opacity="$opacity"'
'${stroke == null ? '' : ' stroke="$stroke" stroke-width="$sw"'}'
'/>');
}
/// 写入一个 `<circle>` 元素。
///
/// 参数 [cx]/[cy] 圆心、[r] 半径;可选 [stroke] 描边色、[fill] 填充色、
/// [sw] 描边宽度。
void _circle(double cx, double cy, double r, {String? stroke, String? fill, double sw = 1}) {
_b.write('<circle cx="${cx.toStringAsFixed(1)}" cy="${cy.toStringAsFixed(1)}" r="${r.toStringAsFixed(1)}" '
'fill="${fill ?? 'none'}" stroke="${stroke ?? 'none'}" stroke-width="$sw"/>');
}
/// 写入一个 `<line>` 元素。
///
/// 参数为两端点坐标;可选 [stroke] 描边色、[sw] 描边宽度。
void _line(double x1, double y1, double x2, double y2, {String? stroke, double sw = 1}) {
_b.write('<line x1="${x1.toStringAsFixed(1)}" y1="${y1.toStringAsFixed(1)}" x2="${x2.toStringAsFixed(1)}" '
'y2="${y2.toStringAsFixed(1)}" stroke="${stroke ?? 'none'}" stroke-width="$sw"/>');
}
/// 写入一个 `<text>` 元素。
///
/// 参数 [x]/[y] 锚点坐标、[s] 文本内容(会经 [_esc] 转义);
/// 可选 [color] 颜色、[size] 字号、[anchor] 水平锚点、[weight] 字重。
/// 垂直方向统一使用 `dominant-baseline="middle"` 居中。
void _text(double x, double y, String s,
{String? color, double size = 12, String anchor = 'start', String weight = '400'}) {
_b.write('<text x="${x.toStringAsFixed(1)}" y="${y.toStringAsFixed(1)}" font-family="$_font" '
'font-size="$size" fill="${color ?? 'none'}" text-anchor="$anchor" font-weight="$weight" '
'dominant-baseline="middle">${_esc(s)}</text>');
}
/// 把 Flutter [Color] 转为 `#rrggbb` 字符串。
///
/// 忽略 alpha 通道;各通道四舍五入并补零到两位十六进制。
static String _hex(Color c) {
final int r = (c.r * 255).round();
final int g = (c.g * 255).round();
final int b = (c.b * 255).round();
return '#${r.toRadixString(16).padLeft(2, '0')}${g.toRadixString(16).padLeft(2, '0')}${b.toRadixString(16).padLeft(2, '0')}';
}
/// 转义 XML 文本中的特殊字符(`&`、`<`、`>`、`"`),防止破坏 SVG 结构。
static String _esc(String s) => s
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
}