Network map enhancements and fixes

This commit is contained in:
2026-06-05 16:42:56 +08:00
parent e2ddc9a3ae
commit d813ee45a2
14 changed files with 2473 additions and 395 deletions
+100 -83
View File
@@ -1,17 +1,12 @@
import 'package:flutter/material.dart';
import '../../../models/network/network_device.dart';
import 'network_device_icon.dart';
/// A styled node representing one network device on the topology canvas.
///
/// Designed to feel solid at ~120-160dp wide so it remains legible at the
/// "good for 200 nodes" zoom level called out in the V1 spec.
///
/// The node has three visual states beyond its default rest:
/// - [isSelected]: stronger primary-tinted background + 2dp primary border.
/// - [isHighlighted]: softer secondary tint + primary outline, used when an
/// edge touching this device is hovered on the canvas.
/// - [isSelected] takes precedence over [isHighlighted].
/// Accepts an explicit [nodeSize] so role-based sizing can be applied by the
/// canvas without this widget needing to know the layout strategy.
class DeviceNode extends StatelessWidget {
const DeviceNode({
super.key,
@@ -19,6 +14,7 @@ class DeviceNode extends StatelessWidget {
this.portCount,
this.isSelected = false,
this.isHighlighted = false,
this.nodeSize = const Size(160, 110),
this.onTap,
});
@@ -26,29 +22,9 @@ class DeviceNode extends StatelessWidget {
final int? portCount;
final bool isSelected;
final bool isHighlighted;
final Size nodeSize;
final VoidCallback? onTap;
IconData _iconForKind(NetworkDeviceKind kind) {
switch (kind) {
case NetworkDeviceKind.router:
return Icons.router_outlined;
case NetworkDeviceKind.switchDevice:
return Icons.hub_outlined;
case NetworkDeviceKind.ap:
return Icons.wifi_outlined;
case NetworkDeviceKind.firewall:
return Icons.security_outlined;
case NetworkDeviceKind.server:
return Icons.dns_outlined;
case NetworkDeviceKind.endpoint:
return Icons.devices_outlined;
case NetworkDeviceKind.patchPanel:
return Icons.view_module_outlined;
case NetworkDeviceKind.other:
return Icons.device_unknown_outlined;
}
}
Color _accentForRole(ColorScheme cs, NetworkDeviceRole? role) {
switch (role) {
case NetworkDeviceRole.core:
@@ -65,11 +41,25 @@ class DeviceNode extends StatelessWidget {
}
}
Color? _statusColor(ColorScheme cs, NetworkDeviceStatus status) {
switch (status) {
case NetworkDeviceStatus.online:
return const Color(0xFF34A853); // Google green — universally understood
case NetworkDeviceStatus.offline:
return cs.error;
case NetworkDeviceStatus.warning:
return const Color(0xFFFBBC04); // Amber
case NetworkDeviceStatus.unknown:
return null; // No dot shown
}
}
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
final tt = Theme.of(context).textTheme;
final accent = _accentForRole(cs, device.role);
final statusColor = _statusColor(cs, device.status);
final bgColor = isSelected
? cs.primaryContainer
@@ -105,67 +95,94 @@ class DeviceNode extends StatelessWidget {
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(16),
child: Container(
width: 160,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
child: Stack(
children: [
Container(
width: nodeSize.width,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Icon(_iconForKind(device.kind), size: 18, color: accent),
const SizedBox(width: 6),
Expanded(
child: Text(
device.kind.label,
style: tt.labelSmall?.copyWith(color: accent),
Row(
children: [
NetworkDeviceIcon(
kind: device.kind,
color: accent,
size: 20,
),
const SizedBox(width: 6),
Expanded(
child: Text(
device.kind.label,
style: tt.labelSmall?.copyWith(color: accent),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
const SizedBox(height: 4),
Text(
device.name,
style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
if (device.vendor != null || device.model != null) ...[
const SizedBox(height: 2),
Text(
[
if (device.vendor != null) device.vendor,
if (device.model != null) device.model,
].whereType<String>().join(''),
style: tt.labelSmall?.copyWith(
color: cs.onSurfaceVariant),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
const SizedBox(height: 4),
Text(
device.name,
style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
if (device.vendor != null || device.model != null) ...[
const SizedBox(height: 2),
Text(
[
if (device.vendor != null) device.vendor,
if (device.model != null) device.model,
].whereType<String>().join(''),
style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
if (portCount != null) ...[
const SizedBox(height: 4),
Row(
children: [
Icon(
Icons.cable_outlined,
size: 12,
color: cs.onSurfaceVariant,
),
const SizedBox(width: 4),
Text(
'$portCount ports',
style: tt.labelSmall?.copyWith(
color: cs.onSurfaceVariant,
),
],
if (portCount != null) ...[
const SizedBox(height: 4),
Row(
children: [
Icon(
Icons.cable_outlined,
size: 12,
color: cs.onSurfaceVariant,
),
const SizedBox(width: 4),
Text(
'$portCount ports',
style: tt.labelSmall?.copyWith(
color: cs.onSurfaceVariant,
),
),
],
),
],
],
),
),
// Status dot — top-right, only shown when status is not unknown
if (statusColor != null)
Positioned(
top: 8,
right: 8,
child: Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: statusColor,
shape: BoxShape.circle,
border: Border.all(
color: bgColor,
width: 1.5,
),
),
),
],
],
),
),
],
),
),
),
@@ -0,0 +1,191 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../models/network/network_link.dart';
import '../../../models/network/network_port.dart';
import '../../../providers/network_map/network_devices_provider.dart';
/// Opens an M3 dialog to connect [portId] to a port on another device.
///
/// Returns true if a link was successfully created.
Future<bool> showLinkEditDialog({
required BuildContext context,
required WidgetRef ref,
required String portId,
required String currentDeviceId,
}) async {
final result = await showDialog<bool>(
context: context,
builder: (_) => _LinkEditDialog(
portId: portId,
currentDeviceId: currentDeviceId,
),
);
return result == true;
}
class _LinkEditDialog extends ConsumerStatefulWidget {
const _LinkEditDialog({
required this.portId,
required this.currentDeviceId,
});
final String portId;
final String currentDeviceId;
@override
ConsumerState<_LinkEditDialog> createState() => _LinkEditDialogState();
}
class _LinkEditDialogState extends ConsumerState<_LinkEditDialog> {
String? _selectedDeviceId;
String? _selectedPortId;
NetworkLinkKind? _linkKind;
final _cableLabelCtrl = TextEditingController();
bool _saving = false;
@override
void dispose() {
_cableLabelCtrl.dispose();
super.dispose();
}
Future<void> _save() async {
final portA = widget.portId;
final portB = _selectedPortId;
if (portB == null) return;
setState(() => _saving = true);
try {
ref.invalidate(networkLinksProvider);
final controller = ref.read(networkDevicesControllerProvider);
await controller.createLink(
portA: portA,
portB: portB,
linkKind: _linkKind,
cableLabel: _cableLabelCtrl.text.trim().isEmpty
? null
: _cableLabelCtrl.text.trim(),
);
if (mounted) Navigator.of(context).pop(true);
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to create link: $e'),
backgroundColor: Theme.of(context).colorScheme.error,
),
);
}
} finally {
if (mounted) setState(() => _saving = false);
}
}
@override
Widget build(BuildContext context) {
final devicesAsync = ref.watch(networkDevicesProvider);
final portsAsync = _selectedDeviceId != null
? ref.watch(networkPortsByDeviceProvider(_selectedDeviceId!))
: const AsyncValue<List<NetworkPort>>.data([]);
final allLinksAsync = ref.watch(networkLinksProvider);
final otherDevices = (devicesAsync.valueOrNull ?? const [])
.where((d) => d.id != widget.currentDeviceId)
.toList()
..sort((a, b) => a.name.compareTo(b.name));
final allLinks = allLinksAsync.valueOrNull ?? const [];
final usedPortIds = <String>{
for (final link in allLinks) ...[link.portA, link.portB],
};
final devicePorts = portsAsync.valueOrNull ?? const [];
final availablePorts =
devicePorts.where((p) => !usedPortIds.contains(p.id)).toList();
final canSave = _selectedPortId != null && !_saving;
return AlertDialog(
title: const Text('Connect port'),
content: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 420),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
DropdownButtonFormField<String>(
initialValue: _selectedDeviceId,
decoration:
const InputDecoration(labelText: 'Remote device *'),
items: [
for (final d in otherDevices)
DropdownMenuItem(value: d.id, child: Text(d.name)),
],
onChanged: (v) => setState(() {
_selectedDeviceId = v;
_selectedPortId = null;
}),
),
const SizedBox(height: 12),
DropdownButtonFormField<String>(
key: ValueKey(_selectedDeviceId),
initialValue: _selectedPortId,
decoration: InputDecoration(
labelText: 'Remote port *',
helperText: _selectedDeviceId == null
? 'Select a device first'
: availablePorts.isEmpty
? 'No available ports on this device'
: null,
),
items: [
for (final p in availablePorts)
DropdownMenuItem(
value: p.id,
child: Text(p.portNumber),
),
],
onChanged: _selectedDeviceId == null
? null
: (v) => setState(() => _selectedPortId = v),
),
const SizedBox(height: 12),
DropdownButtonFormField<NetworkLinkKind?>(
initialValue: _linkKind,
decoration: const InputDecoration(labelText: 'Link type'),
items: [
const DropdownMenuItem<NetworkLinkKind?>(
value: null,
child: Text('(unknown)'),
),
for (final k in NetworkLinkKind.values)
DropdownMenuItem(value: k, child: Text(k.label)),
],
onChanged: (v) => setState(() => _linkKind = v),
),
const SizedBox(height: 12),
TextField(
controller: _cableLabelCtrl,
decoration: const InputDecoration(
labelText: 'Cable label',
helperText: 'e.g. "CAT6-01", "SMF-A3" (optional)',
),
),
],
),
),
),
actions: [
TextButton(
onPressed: _saving ? null : () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
FilledButton(
onPressed: canSave ? _save : null,
child: Text(_saving ? 'Saving…' : 'Connect'),
),
],
);
}
}
@@ -0,0 +1,374 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../../../models/network/network_device.dart';
/// Custom-painted network equipment icon for each [NetworkDeviceKind].
///
/// Draws simplified but recognizable symbols matching professional network
/// topology diagram conventions (Cisco-style silhouettes).
class NetworkDeviceIcon extends StatelessWidget {
const NetworkDeviceIcon({
super.key,
required this.kind,
required this.color,
this.size = 20,
});
final NetworkDeviceKind kind;
final Color color;
final double size;
@override
Widget build(BuildContext context) {
return SizedBox(
width: size,
height: size,
child: CustomPaint(
painter: _DeviceIconPainter(kind: kind, color: color),
),
);
}
}
class _DeviceIconPainter extends CustomPainter {
_DeviceIconPainter({required this.kind, required this.color});
final NetworkDeviceKind kind;
final Color color;
@override
void paint(Canvas canvas, Size size) {
switch (kind) {
case NetworkDeviceKind.router:
_drawRouter(canvas, size);
case NetworkDeviceKind.switchDevice:
_drawSwitch(canvas, size);
case NetworkDeviceKind.ap:
_drawAp(canvas, size);
case NetworkDeviceKind.firewall:
_drawFirewall(canvas, size);
case NetworkDeviceKind.server:
_drawServer(canvas, size);
case NetworkDeviceKind.endpoint:
_drawEndpoint(canvas, size);
case NetworkDeviceKind.patchPanel:
_drawPatchPanel(canvas, size);
case NetworkDeviceKind.other:
_drawOther(canvas, size);
}
}
Paint get _stroke => Paint()
..color = color
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..strokeWidth = 1.4;
Paint get _fill => Paint()
..color = color
..style = PaintingStyle.fill;
// ─── Router: cylinder body + 4 arrows ─────────────────────────────────────
void _drawRouter(Canvas canvas, Size s) {
final cx = s.width / 2;
final cy = s.height / 2;
final r = s.width * 0.28;
final p = _stroke;
// Circle body
canvas.drawCircle(Offset(cx, cy), r, p);
// 4 directional arrows at N/S/E/W
const arrowLen = 0.22;
const arrowHead = 0.1;
for (var i = 0; i < 4; i++) {
final angle = i * math.pi / 2;
final ax = cx + math.cos(angle) * (r + s.width * arrowLen);
final ay = cy + math.sin(angle) * (r + s.width * arrowLen);
final bx = cx + math.cos(angle) * (r + 1);
final by = cy + math.sin(angle) * (r + 1);
canvas.drawLine(Offset(bx, by), Offset(ax, ay), p);
// Arrowhead
final perp = angle + math.pi / 2;
final hw = s.width * arrowHead;
canvas.drawPath(
Path()
..moveTo(ax, ay)
..lineTo(
ax - math.cos(angle) * hw + math.cos(perp) * hw / 2,
ay - math.sin(angle) * hw + math.sin(perp) * hw / 2,
)
..lineTo(
ax - math.cos(angle) * hw - math.cos(perp) * hw / 2,
ay - math.sin(angle) * hw - math.sin(perp) * hw / 2,
)
..close(),
_fill,
);
}
}
// ─── Switch: rectangle + port lines ───────────────────────────────────────
void _drawSwitch(Canvas canvas, Size s) {
final w = s.width * 0.86;
final h = s.height * 0.42;
final left = (s.width - w) / 2;
final top = (s.height - h) / 2;
final p = _stroke;
// Body
canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(left, top, w, h),
const Radius.circular(2),
),
p,
);
// Port lines (8 evenly spaced)
const ports = 8;
final portSpacing = w / (ports + 1);
final portH = h * 0.5;
final portTop = top + h * 0.2;
for (var i = 1; i <= ports; i++) {
final px = left + portSpacing * i;
canvas.drawLine(
Offset(px, portTop),
Offset(px, portTop + portH),
p,
);
}
// Two legs at bottom center
final legX1 = s.width * 0.38;
final legX2 = s.width * 0.62;
final bodyBottom = top + h;
canvas.drawLine(
Offset(legX1, bodyBottom),
Offset(legX1, s.height * 0.85),
p,
);
canvas.drawLine(
Offset(legX2, bodyBottom),
Offset(legX2, s.height * 0.85),
p,
);
canvas.drawLine(
Offset(legX1, s.height * 0.85),
Offset(legX2, s.height * 0.85),
p,
);
}
// ─── AP: semicircle waves + stem ──────────────────────────────────────────
void _drawAp(Canvas canvas, Size s) {
final cx = s.width / 2;
final base = s.height * 0.72;
final p = _stroke;
// Stem
canvas.drawLine(Offset(cx, base), Offset(cx, s.height * 0.88), p);
canvas.drawLine(
Offset(cx - s.width * 0.15, s.height * 0.88),
Offset(cx + s.width * 0.15, s.height * 0.88),
p,
);
// 3 concentric arcs from narrow to wide
for (var i = 1; i <= 3; i++) {
final r = s.width * 0.13 * i;
final rect = Rect.fromCircle(center: Offset(cx, base), radius: r);
canvas.drawArc(rect, math.pi, -math.pi, false, p);
}
}
// ─── Firewall: brick-wall grid ─────────────────────────────────────────────
void _drawFirewall(Canvas canvas, Size s) {
final w = s.width * 0.8;
final h = s.height * 0.72;
final left = (s.width - w) / 2;
final top = (s.height - h) / 2;
final p = _stroke;
// Outer rect
canvas.drawRect(Rect.fromLTWH(left, top, w, h), p);
// 3 rows, 2 staggered bricks each
final rowH = h / 3;
for (var row = 0; row < 3; row++) {
final rowTop = top + row * rowH;
// horizontal mortar line
if (row > 0) {
canvas.drawLine(
Offset(left, rowTop),
Offset(left + w, rowTop),
p,
);
}
// vertical mortar — offset every other row by half a brick
final offset = (row % 2 == 0) ? w / 2 : w / 4;
canvas.drawLine(
Offset(left + offset, rowTop),
Offset(left + offset, rowTop + rowH),
p,
);
}
}
// ─── Server: rack unit with LED dots ──────────────────────────────────────
void _drawServer(Canvas canvas, Size s) {
final w = s.width * 0.72;
final h = s.height * 0.78;
final left = (s.width - w) / 2;
final top = (s.height - h) / 2;
final p = _stroke;
final fp = _fill;
// Body
canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(left, top, w, h),
const Radius.circular(2),
),
p,
);
// 3 horizontal rack-unit dividers + LED dots
final unitH = h / 3;
for (var i = 0; i < 3; i++) {
final unitTop = top + i * unitH;
if (i > 0) {
canvas.drawLine(
Offset(left, unitTop),
Offset(left + w, unitTop),
p,
);
}
// Small LED dot on right side of each unit
canvas.drawCircle(
Offset(left + w - w * 0.15, unitTop + unitH / 2),
s.width * 0.05,
fp,
);
}
}
// ─── Endpoint: monitor + stand ─────────────────────────────────────────────
void _drawEndpoint(Canvas canvas, Size s) {
final monW = s.width * 0.76;
final monH = s.height * 0.52;
final left = (s.width - monW) / 2;
final top = s.height * 0.08;
final p = _stroke;
// Monitor bezel
canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(left, top, monW, monH),
const Radius.circular(2),
),
p,
);
// Screen inner (inset 2dp)
canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(left + 3, top + 3, monW - 6, monH - 6),
const Radius.circular(1),
),
p,
);
// Neck
final neckX = s.width / 2;
final neckTop = top + monH;
canvas.drawLine(
Offset(neckX, neckTop),
Offset(neckX, neckTop + s.height * 0.18),
p,
);
// Base
canvas.drawLine(
Offset(s.width * 0.25, s.height * 0.88),
Offset(s.width * 0.75, s.height * 0.88),
p,
);
}
// ─── Patch panel: flat rect with 2 rows of port circles ──────────────────
void _drawPatchPanel(Canvas canvas, Size s) {
final w = s.width * 0.9;
final h = s.height * 0.44;
final left = (s.width - w) / 2;
final top = (s.height - h) / 2;
final p = _stroke;
// Body
canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(left, top, w, h),
const Radius.circular(2),
),
p,
);
// 2 rows × 5 port circles
const cols = 5;
const rows = 2;
final colSpacing = w / (cols + 1);
final rowSpacing = h / (rows + 1);
final dotR = s.width * 0.04;
for (var row = 1; row <= rows; row++) {
for (var col = 1; col <= cols; col++) {
canvas.drawCircle(
Offset(left + colSpacing * col, top + rowSpacing * row),
dotR,
p,
);
}
}
}
// ─── Other: circle with question mark ─────────────────────────────────────
void _drawOther(Canvas canvas, Size s) {
final cx = s.width / 2;
final cy = s.height / 2;
final r = s.width * 0.42;
final p = _stroke;
canvas.drawCircle(Offset(cx, cy), r, p);
// "?" drawn as a small arc + dot
final tp = TextPainter(
text: TextSpan(
text: '?',
style: TextStyle(
fontSize: s.width * 0.52,
fontWeight: FontWeight.w700,
color: color,
height: 1,
),
),
textDirection: TextDirection.ltr,
)..layout();
tp.paint(
canvas,
Offset(cx - tp.width / 2, cy - tp.height / 2),
);
}
@override
bool shouldRepaint(covariant _DeviceIconPainter old) =>
old.kind != kind || old.color != color;
}
@@ -2,6 +2,8 @@ import 'package:flutter/material.dart';
import '../../../models/network/network_port.dart';
enum _PortAction { editPort, connect, disconnect, deletePort }
class PortListTile extends StatelessWidget {
const PortListTile({
super.key,
@@ -10,6 +12,8 @@ class PortListTile extends StatelessWidget {
this.linkedPortLabel,
this.canEdit = false,
this.onTap,
this.onConnect,
this.onDisconnect,
this.onDelete,
});
@@ -18,6 +22,8 @@ class PortListTile extends StatelessWidget {
final String? linkedPortLabel;
final bool canEdit;
final VoidCallback? onTap;
final void Function(BuildContext)? onConnect;
final void Function(BuildContext)? onDisconnect;
final VoidCallback? onDelete;
@override
@@ -64,10 +70,56 @@ class PortListTile extends StatelessWidget {
],
),
trailing: canEdit
? IconButton(
icon: const Icon(Icons.delete_outline),
tooltip: 'Delete port',
onPressed: onDelete,
? PopupMenuButton<_PortAction>(
tooltip: 'Port actions',
onSelected: (action) {
switch (action) {
case _PortAction.editPort:
onTap?.call();
case _PortAction.connect:
onConnect?.call(context);
case _PortAction.disconnect:
onDisconnect?.call(context);
case _PortAction.deletePort:
onDelete?.call();
}
},
itemBuilder: (_) => [
const PopupMenuItem(
value: _PortAction.editPort,
child: ListTile(
leading: Icon(Icons.edit_outlined),
title: Text('Edit port'),
contentPadding: EdgeInsets.zero,
),
),
if (!isLinked)
const PopupMenuItem(
value: _PortAction.connect,
child: ListTile(
leading: Icon(Icons.add_link),
title: Text('Connect to…'),
contentPadding: EdgeInsets.zero,
),
),
if (isLinked)
const PopupMenuItem(
value: _PortAction.disconnect,
child: ListTile(
leading: Icon(Icons.link_off),
title: Text('Disconnect'),
contentPadding: EdgeInsets.zero,
),
),
const PopupMenuItem(
value: _PortAction.deletePort,
child: ListTile(
leading: Icon(Icons.delete_outline),
title: Text('Delete port'),
contentPadding: EdgeInsets.zero,
),
),
],
)
: null,
);
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,245 @@
import 'package:flutter/material.dart';
import '../../../models/network/network_device.dart';
import '../../../models/network/network_link.dart';
/// Collapsible legend overlay explaining device role border colours and link
/// type colours. Positioned at the bottom-left of the topology canvas view.
class TopologyLegend extends StatefulWidget {
const TopologyLegend({super.key});
@override
State<TopologyLegend> createState() => _TopologyLegendState();
}
class _TopologyLegendState extends State<TopologyLegend>
with SingleTickerProviderStateMixin {
bool _expanded = false;
late final AnimationController _anim;
late final Animation<double> _fade;
@override
void initState() {
super.initState();
_anim = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 200),
);
_fade = CurvedAnimation(parent: _anim, curve: Curves.easeOut);
}
@override
void dispose() {
_anim.dispose();
super.dispose();
}
void _toggle() {
setState(() => _expanded = !_expanded);
if (_expanded) {
_anim.forward();
} else {
_anim.reverse();
}
}
Color _roleColor(ColorScheme cs, NetworkDeviceRole role) {
switch (role) {
case NetworkDeviceRole.core:
return cs.error;
case NetworkDeviceRole.distribution:
return cs.tertiary;
case NetworkDeviceRole.access:
return cs.primary;
case NetworkDeviceRole.edge:
return cs.secondary;
case NetworkDeviceRole.endpoint:
return cs.outline;
}
}
Color _linkColor(ColorScheme cs, NetworkLinkKind kind) {
switch (kind) {
case NetworkLinkKind.copper:
return cs.primary;
case NetworkLinkKind.fiber:
return cs.tertiary;
case NetworkLinkKind.wireless:
return cs.secondary;
case NetworkLinkKind.virtual:
return cs.outline;
case NetworkLinkKind.unknown:
return cs.outline;
}
}
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
final tt = Theme.of(context).textTheme;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Expand/collapse toggle chip
Material(
color: cs.surfaceContainerHigh,
borderRadius: BorderRadius.circular(20),
elevation: 2,
child: InkWell(
onTap: _toggle,
borderRadius: BorderRadius.circular(20),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.legend_toggle_outlined,
size: 16,
color: cs.onSurfaceVariant,
),
const SizedBox(width: 6),
Text(
'Legend',
style: tt.labelSmall?.copyWith(
color: cs.onSurfaceVariant,
fontWeight: FontWeight.w600,
),
),
const SizedBox(width: 4),
AnimatedRotation(
turns: _expanded ? 0.5 : 0,
duration: const Duration(milliseconds: 200),
child: Icon(
Icons.expand_more,
size: 16,
color: cs.onSurfaceVariant,
),
),
],
),
),
),
),
// Expandable panel
FadeTransition(
opacity: _fade,
child: SizeTransition(
sizeFactor: _fade,
axisAlignment: -1,
child: Padding(
padding: const EdgeInsets.only(top: 6),
child: Material(
color: cs.surfaceContainerHigh,
borderRadius: BorderRadius.circular(12),
elevation: 3,
child: Padding(
padding: const EdgeInsets.all(12),
child: SizedBox(
width: 200,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// ── Device Roles ─────────────────────────────
Text(
'Device Roles',
style: tt.labelSmall?.copyWith(
color: cs.onSurfaceVariant,
fontWeight: FontWeight.w700,
letterSpacing: 0.8,
),
),
const SizedBox(height: 6),
for (final role in NetworkDeviceRole.values)
_LegendRow(
color: _roleColor(cs, role),
label: role.label,
isLine: false,
),
const SizedBox(height: 10),
Divider(
height: 1,
color: cs.outlineVariant.withValues(alpha: 0.5)),
const SizedBox(height: 10),
// ── Link Types ───────────────────────────────
Text(
'Link Types',
style: tt.labelSmall?.copyWith(
color: cs.onSurfaceVariant,
fontWeight: FontWeight.w700,
letterSpacing: 0.8,
),
),
const SizedBox(height: 6),
for (final kind in NetworkLinkKind.values)
_LegendRow(
color: _linkColor(cs, kind),
label: kind.label,
isLine: true,
),
],
),
),
),
),
),
),
),
],
);
}
}
class _LegendRow extends StatelessWidget {
const _LegendRow({
required this.color,
required this.label,
required this.isLine,
});
final Color color;
final String label;
final bool isLine;
@override
Widget build(BuildContext context) {
final tt = Theme.of(context).textTheme;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Row(
children: [
if (isLine)
// Coloured line segment for link types
Container(
width: 20,
height: 3,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(2),
),
)
else
// Coloured square for device roles (border indicator)
Container(
width: 12,
height: 12,
decoration: BoxDecoration(
border: Border.all(color: color, width: 2),
borderRadius: BorderRadius.circular(3),
),
),
const SizedBox(width: 8),
Text(
label,
style: tt.labelSmall?.copyWith(
color: Theme.of(context).colorScheme.onSurface,
),
),
],
),
);
}
}
@@ -0,0 +1,248 @@
import 'package:flutter/material.dart';
import '../../../models/network/network_device.dart';
import '../../../models/network/topology_graph.dart';
/// Scaled-down overview of the topology canvas with a viewport indicator.
///
/// Shows all device nodes as small colour-coded rectangles and all edges as
/// thin lines. A semi-transparent white rectangle indicates the current
/// viewport within the full canvas. Tapping on the minimap pans the main
/// canvas to centre on that point.
class TopologyMinimap extends StatefulWidget {
const TopologyMinimap({
super.key,
required this.graph,
required this.nodePositions,
required this.canvasSize,
required this.controller,
required this.viewportSize,
});
final TopologyGraph graph;
/// Current interpolated node positions (top-left corners) from the canvas.
final Map<String, Offset> nodePositions;
final Size canvasSize;
final TransformationController controller;
final Size viewportSize;
static const Size _minimapSize = Size(160, 100);
@override
State<TopologyMinimap> createState() => _TopologyMinimapState();
}
class _TopologyMinimapState extends State<TopologyMinimap> {
@override
void initState() {
super.initState();
widget.controller.addListener(_onTransformChanged);
}
@override
void didUpdateWidget(covariant TopologyMinimap oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) {
oldWidget.controller.removeListener(_onTransformChanged);
widget.controller.addListener(_onTransformChanged);
}
}
@override
void dispose() {
widget.controller.removeListener(_onTransformChanged);
super.dispose();
}
void _onTransformChanged() => setState(() {});
double get _scaleX {
if (widget.canvasSize.width == 0) return 1;
return TopologyMinimap._minimapSize.width / widget.canvasSize.width;
}
double get _scaleY {
if (widget.canvasSize.height == 0) return 1;
return TopologyMinimap._minimapSize.height / widget.canvasSize.height;
}
double get _scale => _scaleX < _scaleY ? _scaleX : _scaleY;
Offset _toMinimap(Offset canvasPoint) {
final s = _scale;
final offsetX = (TopologyMinimap._minimapSize.width - widget.canvasSize.width * s) / 2;
final offsetY = (TopologyMinimap._minimapSize.height - widget.canvasSize.height * s) / 2;
return Offset(canvasPoint.dx * s + offsetX, canvasPoint.dy * s + offsetY);
}
/// Convert a tap on the minimap to a canvas point, then pan the main canvas
/// so that point appears at the viewport centre.
void _onTap(Offset localPos) {
final s = _scale;
if (s == 0) return;
final offsetX = (TopologyMinimap._minimapSize.width - widget.canvasSize.width * s) / 2;
final offsetY = (TopologyMinimap._minimapSize.height - widget.canvasSize.height * s) / 2;
final canvasX = (localPos.dx - offsetX) / s;
final canvasY = (localPos.dy - offsetY) / s;
final currentScale = widget.controller.value.getMaxScaleOnAxis();
final tx = widget.viewportSize.width / 2 - canvasX * currentScale;
final ty = widget.viewportSize.height / 2 - canvasY * currentScale;
final result = Matrix4.translationValues(tx, ty, 0);
result.multiply(Matrix4.diagonal3Values(currentScale, currentScale, 1.0));
widget.controller.value = result;
}
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return GestureDetector(
onTapDown: (d) => _onTap(d.localPosition),
child: Material(
color: cs.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
elevation: 2,
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: SizedBox(
width: TopologyMinimap._minimapSize.width,
height: TopologyMinimap._minimapSize.height,
child: CustomPaint(
painter: _MinimapPainter(
graph: widget.graph,
nodePositions: widget.nodePositions,
canvasSize: widget.canvasSize,
controller: widget.controller,
viewportSize: widget.viewportSize,
colorScheme: cs,
scale: _scale,
toMinimap: _toMinimap,
),
),
),
),
),
);
}
}
class _MinimapPainter extends CustomPainter {
_MinimapPainter({
required this.graph,
required this.nodePositions,
required this.canvasSize,
required this.controller,
required this.viewportSize,
required this.colorScheme,
required this.scale,
required this.toMinimap,
});
final TopologyGraph graph;
final Map<String, Offset> nodePositions;
final Size canvasSize;
final TransformationController controller;
final Size viewportSize;
final ColorScheme colorScheme;
final double scale;
final Offset Function(Offset) toMinimap;
static const Size _nodeRectSize = Size(8, 5);
Color _roleColor(NetworkDeviceRole? role) {
switch (role) {
case NetworkDeviceRole.core:
return colorScheme.error;
case NetworkDeviceRole.distribution:
return colorScheme.tertiary;
case NetworkDeviceRole.access:
return colorScheme.primary;
case NetworkDeviceRole.edge:
return colorScheme.secondary;
case NetworkDeviceRole.endpoint:
case null:
return colorScheme.outline;
}
}
@override
void paint(Canvas canvas, Size size) {
// Edges
final edgePaint = Paint()
..color = colorScheme.outline.withValues(alpha: 0.4)
..strokeWidth = 0.6
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round;
for (final edge in graph.edges) {
final fromPos = nodePositions[edge.fromDeviceId];
final toPos = nodePositions[edge.toDeviceId];
if (fromPos == null || toPos == null) continue;
// Use node centres
final from = toMinimap(fromPos + const Offset(80, 55));
final to = toMinimap(toPos + const Offset(80, 55));
canvas.drawLine(from, to, edgePaint);
}
// Device nodes
for (final node in graph.nodes) {
final pos = nodePositions[node.device.id];
if (pos == null) continue;
final minimapPos = toMinimap(pos);
final rect = Rect.fromLTWH(
minimapPos.dx - _nodeRectSize.width / 2,
minimapPos.dy - _nodeRectSize.height / 2,
_nodeRectSize.width,
_nodeRectSize.height,
);
canvas.drawRRect(
RRect.fromRectAndRadius(rect, const Radius.circular(1.5)),
Paint()
..color = _roleColor(node.device.role)
..style = PaintingStyle.fill,
);
}
// Viewport rectangle
final m = controller.value;
final currentScale = m.getMaxScaleOnAxis();
if (currentScale > 0) {
// The translation is in the 3rd column of the matrix
final tx = m.getTranslation().x;
final ty = m.getTranslation().y;
// Viewport in canvas coordinates
final vpLeft = -tx / currentScale;
final vpTop = -ty / currentScale;
final vpWidth = viewportSize.width / currentScale;
final vpHeight = viewportSize.height / currentScale;
final tl = toMinimap(Offset(vpLeft, vpTop));
final br = toMinimap(Offset(vpLeft + vpWidth, vpTop + vpHeight));
final vpRect = Rect.fromPoints(tl, br);
// Fill
canvas.drawRect(
vpRect,
Paint()
..color = colorScheme.primary.withValues(alpha: 0.08)
..style = PaintingStyle.fill,
);
// Border
canvas.drawRect(
vpRect,
Paint()
..color = colorScheme.primary.withValues(alpha: 0.6)
..strokeWidth = 1.0
..style = PaintingStyle.stroke,
);
}
}
@override
bool shouldRepaint(covariant _MinimapPainter old) => true;
}
@@ -0,0 +1,130 @@
import 'package:flutter/material.dart';
/// Vertical +//fit-to-view zoom controls for the topology canvas.
/// Requires a [TransformationController] shared with the [InteractiveViewer].
class ZoomControls extends StatelessWidget {
const ZoomControls({
super.key,
required this.controller,
required this.canvasSize,
required this.viewportSize,
});
final TransformationController controller;
/// Full canvas size (from [computeSugiyamaLayout] result).
final Size canvasSize;
/// Viewport widget size (the screen area the canvas is displayed in).
final Size viewportSize;
static const double _zoomIn = 1.25;
static const double _zoomOut = 0.8;
static const double _minScale = 0.2;
static const double _maxScale = 2.5;
void _applyZoom(double factor) {
final current = controller.value.getMaxScaleOnAxis();
final next = (current * factor).clamp(_minScale, _maxScale);
final scale = next / current;
final cx = viewportSize.width / 2;
final cy = viewportSize.height / 2;
// Compose: T(cx,cy) * Scale(s) * T(-cx,-cy) * currentTransform
final result = Matrix4.translationValues(cx, cy, 0);
result.multiply(Matrix4.diagonal3Values(scale, scale, 1.0));
result.multiply(Matrix4.translationValues(-cx, -cy, 0));
result.multiply(controller.value);
controller.value = result;
}
void _fitToView() {
if (canvasSize.isEmpty) return;
final scaleX = viewportSize.width / canvasSize.width;
final scaleY = viewportSize.height / canvasSize.height;
final scale = (scaleX < scaleY ? scaleX : scaleY).clamp(_minScale, _maxScale);
final tx = (viewportSize.width - canvasSize.width * scale) / 2;
final ty = (viewportSize.height - canvasSize.height * scale) / 2;
// Build: T(tx,ty,0) * Scale(s,s,1) — maps canvas (0,0) → (tx,ty) on screen
final result = Matrix4.translationValues(tx, ty, 0);
result.multiply(Matrix4.diagonal3Values(scale, scale, 1.0));
controller.value = result;
}
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return Material(
color: cs.surfaceContainerHigh,
borderRadius: BorderRadius.circular(12),
elevation: 2,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_ZoomButton(
icon: Icons.add,
tooltip: 'Zoom in',
onTap: () => _applyZoom(_zoomIn),
),
_Divider(color: cs.outlineVariant.withValues(alpha: 0.4)),
_ZoomButton(
icon: Icons.remove,
tooltip: 'Zoom out',
onTap: () => _applyZoom(_zoomOut),
),
_Divider(color: cs.outlineVariant.withValues(alpha: 0.4)),
_ZoomButton(
icon: Icons.fit_screen_outlined,
tooltip: 'Fit to view',
onTap: _fitToView,
),
],
),
),
);
}
}
class _ZoomButton extends StatelessWidget {
const _ZoomButton({
required this.icon,
required this.tooltip,
required this.onTap,
});
final IconData icon;
final String tooltip;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return Tooltip(
message: tooltip,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(8),
child: SizedBox(
width: 40,
height: 40,
child: Icon(icon, size: 18, color: cs.onSurfaceVariant),
),
),
);
}
}
class _Divider extends StatelessWidget {
const _Divider({required this.color});
final Color color;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Divider(height: 1, color: color),
);
}
}