feat(app): graph pan, zoom and expanded view
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import 'graph_viewport.dart';
|
||||
import 'graph_viewport_controller.dart';
|
||||
|
||||
/// The expanded presentation's close wording (`Close`).
|
||||
const String graphExpandedClose = 'Close';
|
||||
|
||||
/// Builds the same canvas for another viewport, with the selection that
|
||||
/// presentation is showing.
|
||||
typedef GraphExpandedCanvasBuilder =
|
||||
Widget Function(
|
||||
BuildContext context,
|
||||
String? selectedStage,
|
||||
ValueChanged<String> onSelected,
|
||||
);
|
||||
|
||||
/// A native full-screen presentation of one graph canvas.
|
||||
///
|
||||
/// It fits the graph into the larger box (as the web does when its panel
|
||||
/// expands), keeps the selected node selected, and lets a tap in the larger
|
||||
/// canvas update that selection through [onSelected]. Closing pops the route;
|
||||
/// the inline canvas was never changed, so it returns to its previous state.
|
||||
class GraphExpandedView extends StatefulWidget {
|
||||
const GraphExpandedView({
|
||||
super.key,
|
||||
required this.contentSize,
|
||||
required this.canvasBuilder,
|
||||
required this.title,
|
||||
required this.onSelected,
|
||||
this.selectedStage,
|
||||
this.header,
|
||||
});
|
||||
|
||||
/// The measured graph extent, as in the inline canvas.
|
||||
final Size contentSize;
|
||||
|
||||
final GraphExpandedCanvasBuilder canvasBuilder;
|
||||
|
||||
/// The presentation's native title, e.g. `Run graph`.
|
||||
final String title;
|
||||
|
||||
/// Reports a node activated in the expanded canvas.
|
||||
final ValueChanged<String> onSelected;
|
||||
|
||||
/// Optional fixed content above the canvas, e.g. a legend that explains the
|
||||
/// graph's marks. It stays outside the pan/zoom transform.
|
||||
final Widget? header;
|
||||
|
||||
final String? selectedStage;
|
||||
|
||||
@override
|
||||
State<GraphExpandedView> createState() => _GraphExpandedViewState();
|
||||
}
|
||||
|
||||
class _GraphExpandedViewState extends State<GraphExpandedView> {
|
||||
final GraphViewportController _controller = GraphViewportController();
|
||||
late String? _selected = widget.selectedStage;
|
||||
|
||||
@override
|
||||
void didUpdateWidget(GraphExpandedView oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.selectedStage != oldWidget.selectedStage) {
|
||||
_selected = widget.selectedStage;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _select(String key) {
|
||||
setState(() => _selected = key);
|
||||
widget.onSelected(key);
|
||||
}
|
||||
|
||||
void _close() => Navigator.of(context).maybePop();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final viewport = GraphViewport(
|
||||
key: const Key('graph-expanded-viewport'),
|
||||
controller: _controller,
|
||||
contentSize: widget.contentSize,
|
||||
// The larger box fits the whole graph, as the web does when its panel
|
||||
// expands; a later resize re-fits until the reader pans or zooms, then
|
||||
// only clamps.
|
||||
child: widget.canvasBuilder(context, _selected, _select),
|
||||
);
|
||||
final body = widget.header == null
|
||||
? viewport
|
||||
: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
widget.header!,
|
||||
Expanded(child: viewport),
|
||||
],
|
||||
);
|
||||
if (usesCupertinoHost(context)) {
|
||||
return CupertinoPageScaffold(
|
||||
navigationBar: CupertinoNavigationBar(
|
||||
automaticallyImplyLeading: false,
|
||||
middle: Text(widget.title),
|
||||
trailing: CupertinoButton(
|
||||
key: const Key('graph-expanded-close'),
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: _close,
|
||||
child: const Text(graphExpandedClose),
|
||||
),
|
||||
),
|
||||
child: SafeArea(child: body),
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(widget.title),
|
||||
automaticallyImplyLeading: false,
|
||||
actions: [
|
||||
TextButton(
|
||||
key: const Key('graph-expanded-close'),
|
||||
onPressed: _close,
|
||||
child: const Text(graphExpandedClose),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: SafeArea(child: body),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pushes [GraphExpandedView] with the host's native full-screen transition.
|
||||
///
|
||||
/// This is the seam a Graph tab or run detail can call: pass the measured
|
||||
/// content size and a builder that draws the same canvas for the supplied
|
||||
/// selection. The expanded canvas fits that size; the inline canvas is
|
||||
/// untouched.
|
||||
Future<void> openGraphExpanded(
|
||||
BuildContext context, {
|
||||
required Size contentSize,
|
||||
required GraphExpandedCanvasBuilder canvasBuilder,
|
||||
required String title,
|
||||
required ValueChanged<String> onSelected,
|
||||
String? selectedStage,
|
||||
Widget? header,
|
||||
}) {
|
||||
final page = GraphExpandedView(
|
||||
contentSize: contentSize,
|
||||
canvasBuilder: canvasBuilder,
|
||||
title: title,
|
||||
onSelected: onSelected,
|
||||
selectedStage: selectedStage,
|
||||
header: header,
|
||||
);
|
||||
final route = usesCupertinoHost(context)
|
||||
? CupertinoPageRoute<void>(fullscreenDialog: true, builder: (_) => page)
|
||||
: MaterialPageRoute<void>(fullscreenDialog: true, builder: (_) => page);
|
||||
return Navigator.of(context).push(route);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import 'graph_viewport_controller.dart';
|
||||
|
||||
/// The fit control's web wording (`Fit graph to view`).
|
||||
const String graphFitLabel = 'Fit graph to view';
|
||||
|
||||
/// The expand control's web wording (`Expand graph`).
|
||||
const String graphExpandLabel = 'Expand graph';
|
||||
|
||||
/// A bounded graph canvas with the host's own pan, pinch, wheel and trackpad
|
||||
/// zoom, plus a fit control and an optional expanded presentation.
|
||||
///
|
||||
/// [controller] owns the transform, so a caller can read or restore a
|
||||
/// [GraphViewportSnapshot]. Gestures are consumed only inside this widget's
|
||||
/// box: an ancestor scroll view keeps scrolling everywhere else, and a tap
|
||||
/// that does not move still reaches the native node under the pointer.
|
||||
class GraphViewport extends StatefulWidget {
|
||||
const GraphViewport({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.contentSize,
|
||||
required this.child,
|
||||
this.onExpand,
|
||||
});
|
||||
|
||||
final GraphViewportController controller;
|
||||
|
||||
/// The measured graph extent; the canvas never invents a fixed size.
|
||||
final Size contentSize;
|
||||
|
||||
/// The measured, already-routed graph content.
|
||||
final Widget child;
|
||||
|
||||
/// Opens the expanded presentation. Null hides the expand control.
|
||||
final VoidCallback? onExpand;
|
||||
|
||||
@override
|
||||
State<GraphViewport> createState() => _GraphViewportState();
|
||||
}
|
||||
|
||||
class _GraphViewportState extends State<GraphViewport> {
|
||||
Size? _scheduledViewport;
|
||||
Size? _scheduledContent;
|
||||
|
||||
@override
|
||||
void didUpdateWidget(GraphViewport oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.controller != widget.controller) {
|
||||
_scheduledViewport = null;
|
||||
_scheduledContent = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Attaches the current extents after layout, never during build.
|
||||
void _scheduleAttach(Size viewport) {
|
||||
if (viewport == _scheduledViewport &&
|
||||
widget.contentSize == _scheduledContent) {
|
||||
return;
|
||||
}
|
||||
_scheduledViewport = viewport;
|
||||
_scheduledContent = widget.contentSize;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
widget.controller.attach(viewport: viewport, content: widget.contentSize);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final viewport =
|
||||
constraints.hasBoundedWidth && constraints.hasBoundedHeight
|
||||
? constraints.biggest
|
||||
: widget.contentSize;
|
||||
if (!widget.controller.isAttached) {
|
||||
// The very first layout has no `InteractiveViewer` listening yet, so
|
||||
// fitting here applies before the first paint instead of flashing an
|
||||
// identity transform for one frame.
|
||||
widget.controller.attach(
|
||||
viewport: viewport,
|
||||
content: widget.contentSize,
|
||||
);
|
||||
_scheduledViewport = viewport;
|
||||
_scheduledContent = widget.contentSize;
|
||||
} else {
|
||||
_scheduleAttach(viewport);
|
||||
}
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: InteractiveViewer(
|
||||
key: const Key('graph-viewport'),
|
||||
transformationController: widget.controller.transformation,
|
||||
constrained: false,
|
||||
// The graph owns its own bounds (fit and the visible-pan clamp),
|
||||
// so the viewer must not impose a second, cover-the-viewport
|
||||
// boundary that would fight the fit scale.
|
||||
boundaryMargin: const EdgeInsets.all(double.infinity),
|
||||
minScale: widget.controller.minScale,
|
||||
maxScale: widget.controller.maxScale,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: SizedBox.fromSize(
|
||||
size: widget.contentSize,
|
||||
child: widget.child,
|
||||
),
|
||||
),
|
||||
),
|
||||
PositionedDirectional(
|
||||
top: 8,
|
||||
end: 8,
|
||||
child: Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
_ViewportButton(
|
||||
buttonKey: const Key('graph-fit'),
|
||||
icon: _fitIcon(context),
|
||||
label: graphFitLabel,
|
||||
onPressed: widget.controller.fitToViewport,
|
||||
),
|
||||
if (widget.onExpand != null)
|
||||
_ViewportButton(
|
||||
buttonKey: const Key('graph-expand'),
|
||||
icon: _expandIcon(context),
|
||||
label: graphExpandLabel,
|
||||
onPressed: widget.onExpand,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
IconData _fitIcon(BuildContext context) =>
|
||||
usesCupertinoHost(context) ? CupertinoIcons.resize : Icons.fit_screen;
|
||||
|
||||
IconData _expandIcon(BuildContext context) =>
|
||||
usesCupertinoHost(context) ? CupertinoIcons.fullscreen : Icons.fullscreen;
|
||||
}
|
||||
|
||||
/// One native graph control: a tinted icon button on either host.
|
||||
///
|
||||
/// The label and the button's own tap action must reach the same semantics
|
||||
/// node: the icon is the only excluded child, and [MergeSemantics] folds the
|
||||
/// host button's action into the labelled node, so a screen reader can activate
|
||||
/// Fit and Expand on either host. A hand-written `Semantics` sibling around an
|
||||
/// excluded button would announce the control with no action at all.
|
||||
class _ViewportButton extends StatelessWidget {
|
||||
const _ViewportButton({
|
||||
required this.buttonKey,
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.onPressed,
|
||||
});
|
||||
|
||||
final Key buttonKey;
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final VoidCallback? onPressed;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MergeSemantics(
|
||||
child: Semantics(
|
||||
button: true,
|
||||
label: label,
|
||||
child: usesCupertinoHost(context)
|
||||
? CupertinoButton.tinted(
|
||||
key: buttonKey,
|
||||
padding: const EdgeInsets.all(8),
|
||||
onPressed: onPressed,
|
||||
child: ExcludeSemantics(child: Icon(icon)),
|
||||
)
|
||||
: Tooltip(
|
||||
message: label,
|
||||
// The merged node already carries the label; the tooltip is
|
||||
// only the pointer affordance.
|
||||
excludeFromSemantics: true,
|
||||
child: IconButton.filledTonal(
|
||||
key: buttonKey,
|
||||
onPressed: onPressed,
|
||||
icon: ExcludeSemantics(child: Icon(icon)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'graph_viewport_math.dart';
|
||||
|
||||
/// One graph viewport's scale and offset, independent of any viewport size.
|
||||
///
|
||||
/// A snapshot is what the expanded presentation carries over: the same scale
|
||||
/// and offset the inline canvas is showing, so opening and closing it never
|
||||
/// loses the reader's place.
|
||||
@immutable
|
||||
class GraphViewportSnapshot {
|
||||
const GraphViewportSnapshot({required this.scale, required this.offset});
|
||||
|
||||
final double scale;
|
||||
final Offset offset;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is GraphViewportSnapshot &&
|
||||
other.scale == scale &&
|
||||
other.offset == offset;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(scale, offset);
|
||||
|
||||
@override
|
||||
String toString() => 'GraphViewportSnapshot(scale: $scale, offset: $offset)';
|
||||
}
|
||||
|
||||
/// Owns one graph canvas's transform.
|
||||
///
|
||||
/// Pan and pinch stay the host's own gestures ([InteractiveViewer] drives the
|
||||
/// [transformation]); this controller only supplies the graph's bounds: a fit
|
||||
/// with padding, the min/max scale and a pan clamp that keeps part of the graph
|
||||
/// visible. It never changes a node, route or label. A snapshot lets a caller
|
||||
/// read or restore a place; the expanded presentation owns its own controller,
|
||||
/// so closing it leaves this transform exactly as it was.
|
||||
class GraphViewportController extends ChangeNotifier {
|
||||
GraphViewportController({
|
||||
this.minScale = graphMinScale,
|
||||
this.maxScale = graphMaxScale,
|
||||
this.fitPadding = graphFitPadding,
|
||||
this.minVisible = graphMinVisible,
|
||||
}) : assert(minScale > 0),
|
||||
assert(maxScale >= minScale),
|
||||
_transformation = TransformationController() {
|
||||
_transformation.addListener(_handleTransform);
|
||||
}
|
||||
|
||||
/// The native pan/zoom transform handed to [InteractiveViewer].
|
||||
final TransformationController _transformation;
|
||||
|
||||
TransformationController get transformation => _transformation;
|
||||
|
||||
final double minScale;
|
||||
final double maxScale;
|
||||
final double fitPadding;
|
||||
final double minVisible;
|
||||
|
||||
Size? _viewport;
|
||||
Size? _content;
|
||||
bool _userAdjusted = false;
|
||||
bool _applying = false;
|
||||
|
||||
/// The current uniform scale (`getMaxScaleOnAxis` of the transform).
|
||||
double get scale => _transformation.value.getMaxScaleOnAxis();
|
||||
|
||||
/// The current graph-space translation of the transform.
|
||||
Offset get offset {
|
||||
final translation = _transformation.value.getTranslation();
|
||||
return Offset(translation.x, translation.y);
|
||||
}
|
||||
|
||||
GraphViewportSnapshot get snapshot =>
|
||||
GraphViewportSnapshot(scale: scale, offset: offset);
|
||||
|
||||
/// Whether this controller has seen a viewport and content extent yet.
|
||||
bool get isAttached => _viewport != null && _content != null;
|
||||
|
||||
/// Records the current viewport and content extents.
|
||||
///
|
||||
/// The first attach (and any later resize before the reader interacts) fits
|
||||
/// the graph with [fitPadding]. Once the reader has panned or zoomed, a
|
||||
/// resize keeps their place and only re-clamps it.
|
||||
void attach({required Size viewport, required Size content}) {
|
||||
if (viewport == _viewport && content == _content) return;
|
||||
_viewport = viewport;
|
||||
_content = content;
|
||||
if (!_userAdjusted) {
|
||||
fitToViewport();
|
||||
} else {
|
||||
_clamp();
|
||||
}
|
||||
}
|
||||
|
||||
/// Fits the whole graph in the current viewport and clears the user-adjusted
|
||||
/// flag, so a later resize fits again.
|
||||
void fitToViewport() {
|
||||
final viewport = _viewport;
|
||||
final content = _content;
|
||||
if (viewport == null || content == null) return;
|
||||
final scale = graphFitScale(
|
||||
viewport,
|
||||
content,
|
||||
padding: fitPadding,
|
||||
minScale: minScale,
|
||||
maxScale: maxScale,
|
||||
);
|
||||
final scaled = Size(content.width * scale, content.height * scale);
|
||||
_apply(
|
||||
graphClampOffset(
|
||||
graphCenteredOffset(scaled, viewport),
|
||||
scaled,
|
||||
viewport,
|
||||
minVisible: minVisible,
|
||||
),
|
||||
scale,
|
||||
);
|
||||
_userAdjusted = false;
|
||||
}
|
||||
|
||||
/// Applies an explicit snapshot, e.g. when a caller restores a viewport.
|
||||
void applySnapshot(GraphViewportSnapshot snapshot) {
|
||||
_userAdjusted = true;
|
||||
_apply(snapshot.offset, snapshot.scale.clamp(minScale, maxScale));
|
||||
}
|
||||
|
||||
void _apply(Offset offset, double scale) {
|
||||
_applying = true;
|
||||
_transformation.value = graphViewportMatrix(offset, scale);
|
||||
_applying = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Keeps every externally driven transform (a gesture, a wheel or a trackpad
|
||||
/// pinch) inside the graph's scale and pan bounds.
|
||||
void _handleTransform() {
|
||||
if (_applying) return;
|
||||
_userAdjusted = true;
|
||||
_clamp();
|
||||
}
|
||||
|
||||
void _clamp() {
|
||||
final viewport = _viewport;
|
||||
final content = _content;
|
||||
if (viewport == null || content == null) return;
|
||||
final currentScale = scale;
|
||||
final boundedScale = currentScale.clamp(minScale, maxScale);
|
||||
final scaled = Size(
|
||||
content.width * boundedScale,
|
||||
content.height * boundedScale,
|
||||
);
|
||||
final currentOffset = offset;
|
||||
final boundedOffset = graphClampOffset(
|
||||
currentOffset,
|
||||
scaled,
|
||||
viewport,
|
||||
minVisible: minVisible,
|
||||
);
|
||||
if (boundedScale != currentScale || boundedOffset != currentOffset) {
|
||||
_apply(boundedOffset, boundedScale);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_transformation.removeListener(_handleTransform);
|
||||
_transformation.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/widgets.dart' show Matrix4, Offset, Size;
|
||||
|
||||
/// The smallest scale a graph viewport may reach (`MIN_SCALE`).
|
||||
const double graphMinScale = 0.3;
|
||||
|
||||
/// The largest scale a graph viewport may reach (`MAX_SCALE`).
|
||||
const double graphMaxScale = 3;
|
||||
|
||||
/// Padding kept around a fitted graph, in graph-space pixels
|
||||
/// (`GRAPH_FIT_PADDING`).
|
||||
const double graphFitPadding = 24;
|
||||
|
||||
/// The least amount of the scaled graph kept inside the viewport on each axis,
|
||||
/// so a pan can never leave an empty canvas (`GRAPH_MIN_VISIBLE`).
|
||||
const double graphMinVisible = 40;
|
||||
|
||||
/// The transform that draws graph space at `offset + point * scale`.
|
||||
Matrix4 graphViewportMatrix(Offset offset, double scale) => Matrix4.identity()
|
||||
..translateByDouble(offset.dx, offset.dy, 0, 1)
|
||||
..scaleByDouble(scale, scale, scale, 1);
|
||||
|
||||
/// Uniform scale that fits [content] inside [viewport] with [padding] on every
|
||||
/// side, never upscaling above 1:1 and never leaving the scale bounds.
|
||||
///
|
||||
/// Degenerate or non-finite sizes return 1 rather than dividing by zero, so no
|
||||
/// NaN or infinity ever reaches a transform. This is the web graph's
|
||||
/// `fitScale` rule.
|
||||
double graphFitScale(
|
||||
Size viewport,
|
||||
Size content, {
|
||||
double padding = graphFitPadding,
|
||||
double minScale = graphMinScale,
|
||||
double maxScale = graphMaxScale,
|
||||
}) {
|
||||
final availableWidth = viewport.width - 2 * padding;
|
||||
final availableHeight = viewport.height - 2 * padding;
|
||||
final finite =
|
||||
viewport.width.isFinite &&
|
||||
viewport.height.isFinite &&
|
||||
content.width.isFinite &&
|
||||
content.height.isFinite;
|
||||
if (!finite ||
|
||||
content.width <= 0 ||
|
||||
content.height <= 0 ||
|
||||
availableWidth <= 0 ||
|
||||
availableHeight <= 0) {
|
||||
return 1;
|
||||
}
|
||||
final scale = math.min(
|
||||
1.0,
|
||||
math.min(availableWidth / content.width, availableHeight / content.height),
|
||||
);
|
||||
return scale.clamp(minScale, maxScale);
|
||||
}
|
||||
|
||||
/// Bounds [offset] so at least [minVisible] pixels of the already scaled
|
||||
/// [scaledContent] stay inside [viewport] on each axis.
|
||||
///
|
||||
/// The web graph's `clampOffset`: `offset.x` stays in
|
||||
/// `[minVisible - width, viewport.width - minVisible]`. Degenerate content or
|
||||
/// an empty range returns the input unchanged.
|
||||
Offset graphClampOffset(
|
||||
Offset offset,
|
||||
Size scaledContent,
|
||||
Size viewport, {
|
||||
double minVisible = graphMinVisible,
|
||||
}) {
|
||||
if (scaledContent.width <= 0 ||
|
||||
scaledContent.height <= 0 ||
|
||||
!scaledContent.width.isFinite ||
|
||||
!scaledContent.height.isFinite ||
|
||||
!viewport.width.isFinite ||
|
||||
!viewport.height.isFinite) {
|
||||
return offset;
|
||||
}
|
||||
final minX = minVisible - scaledContent.width;
|
||||
final maxX = viewport.width - minVisible;
|
||||
final minY = minVisible - scaledContent.height;
|
||||
final maxY = viewport.height - minVisible;
|
||||
return Offset(
|
||||
minX <= maxX ? offset.dx.clamp(minX, maxX) : offset.dx,
|
||||
minY <= maxY ? offset.dy.clamp(minY, maxY) : offset.dy,
|
||||
);
|
||||
}
|
||||
|
||||
/// The centered offset that puts [scaledContent] in the middle of [viewport].
|
||||
Offset graphCenteredOffset(Size scaledContent, Size viewport) => Offset(
|
||||
(viewport.width - scaledContent.width) / 2,
|
||||
(viewport.height - scaledContent.height) / 2,
|
||||
);
|
||||
@@ -0,0 +1,76 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../domain/graph_definition.dart';
|
||||
import '../layout/layout_models.dart';
|
||||
import '../painting/graph_edge_layer.dart';
|
||||
import '../routing/route_models.dart';
|
||||
import 'graph_canvas_style.dart';
|
||||
import 'graph_stage_node.dart';
|
||||
|
||||
/// The measured definition canvas at any viewport size and selection.
|
||||
///
|
||||
/// Used by both the inline [GraphViewport] and the expanded presentation: the
|
||||
/// passive edge layer paints behind the native nodes and outcome labels, and
|
||||
/// every node reports selection through [onSelected].
|
||||
class DefinitionGraphCanvas extends StatelessWidget {
|
||||
const DefinitionGraphCanvas({
|
||||
super.key,
|
||||
required this.nodes,
|
||||
required this.layout,
|
||||
required this.routing,
|
||||
required this.style,
|
||||
required this.selectedStage,
|
||||
required this.onSelected,
|
||||
});
|
||||
|
||||
final List<GraphNode> nodes;
|
||||
final GraphLayout layout;
|
||||
final GraphRouting routing;
|
||||
final GraphCanvasStyle style;
|
||||
final String? selectedStage;
|
||||
final ValueChanged<String> onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final nodesByKey = <String, GraphNode>{
|
||||
for (final node in nodes) node.key: node,
|
||||
};
|
||||
final size = Size(routing.width, routing.height);
|
||||
return Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
// The passive layer comes first so every edge paints behind the native
|
||||
// nodes and labels without taking their input.
|
||||
Positioned.fill(
|
||||
child: GraphEdgeLayer(
|
||||
routes: routing.routes,
|
||||
canvasSize: size,
|
||||
color: style.edgeColor,
|
||||
strokeWidth: style.edgeWidth,
|
||||
),
|
||||
),
|
||||
for (final box in layout.nodes)
|
||||
Positioned(
|
||||
left: box.x,
|
||||
top: box.y,
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
child: GraphStageNode(
|
||||
node: nodesByKey[box.key]!,
|
||||
selected: box.key == selectedStage,
|
||||
onSelected: onSelected,
|
||||
),
|
||||
),
|
||||
for (final label in routing.labels)
|
||||
Positioned(
|
||||
left: label.x,
|
||||
top: label.y,
|
||||
child: Text(
|
||||
routing.routeFor(label.edgeId)!.label,
|
||||
style: style.labelStyle,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,23 +5,29 @@ import '../../../core/api_gateway.dart';
|
||||
import '../domain/graph_definition.dart';
|
||||
import '../layout/graph_node_layout.dart';
|
||||
import '../layout/layout_models.dart';
|
||||
import '../painting/graph_edge_layer.dart';
|
||||
import '../routing/graph_edge_routing.dart';
|
||||
import '../routing/route_models.dart';
|
||||
import '../viewport/graph_expanded_view.dart';
|
||||
import '../viewport/graph_viewport.dart';
|
||||
import '../viewport/graph_viewport_controller.dart';
|
||||
import 'definition_graph_canvas.dart';
|
||||
import 'graph_canvas_style.dart';
|
||||
import 'graph_stage_node.dart';
|
||||
import 'graph_measurements.dart';
|
||||
|
||||
/// The definition's own empty-state wording (web `PIPELINE_GRAPH_EMPTY`).
|
||||
const String definitionGraphEmpty = 'This pipeline has no stages.';
|
||||
|
||||
/// The expanded definition presentation's title.
|
||||
const String definitionGraphExpandedTitle = 'Pipeline graph';
|
||||
|
||||
/// One pipeline definition as a readable native graph: measured stage nodes,
|
||||
/// routed passive edges behind them and native outcome labels on their boxes.
|
||||
///
|
||||
/// [selectedStage] is a node key (including `#success`/`#failure`) and
|
||||
/// [onSelected] reports the exact key activated. Nothing reads run evidence:
|
||||
/// nodes show no status and terminals stay plain, so no visit is implied. The
|
||||
/// view fills bounded caller constraints with a stock [InteractiveViewer].
|
||||
/// view fills bounded caller constraints with a pan/zoom [GraphViewport] and can
|
||||
/// present the same canvas full screen without losing the selection.
|
||||
class DefinitionGraphView extends StatefulWidget {
|
||||
const DefinitionGraphView({
|
||||
super.key,
|
||||
@@ -41,9 +47,16 @@ class DefinitionGraphView extends StatefulWidget {
|
||||
class _DefinitionGraphViewState extends State<DefinitionGraphView> {
|
||||
final Map<String, Size> _nodeSizes = {};
|
||||
final Map<String, Size> _labelSizes = {};
|
||||
final GraphViewportController _viewport = GraphViewportController();
|
||||
TextScaler? _scaler;
|
||||
bool _rebuildScheduled = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_viewport.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
@@ -159,56 +172,22 @@ class _DefinitionGraphViewState extends State<DefinitionGraphView> {
|
||||
GraphRouting routing,
|
||||
GraphCanvasStyle style,
|
||||
) {
|
||||
final nodesByKey = <String, GraphNode>{
|
||||
for (final node in nodes) node.key: node,
|
||||
};
|
||||
final size = Size(routing.width, routing.height);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Expanded(
|
||||
child: InteractiveViewer(
|
||||
constrained: false,
|
||||
minScale: 0.3,
|
||||
maxScale: 3,
|
||||
child: SizedBox.fromSize(
|
||||
size: size,
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
// The passive layer comes first so every edge paints behind
|
||||
// the native nodes and labels without taking their input.
|
||||
Positioned.fill(
|
||||
child: GraphEdgeLayer(
|
||||
routes: routing.routes,
|
||||
canvasSize: size,
|
||||
color: style.edgeColor,
|
||||
strokeWidth: style.edgeWidth,
|
||||
),
|
||||
),
|
||||
for (final box in layout.nodes)
|
||||
Positioned(
|
||||
left: box.x,
|
||||
top: box.y,
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
child: GraphStageNode(
|
||||
node: nodesByKey[box.key]!,
|
||||
selected: box.key == widget.selectedStage,
|
||||
onSelected: widget.onSelected,
|
||||
),
|
||||
),
|
||||
for (final label in routing.labels)
|
||||
Positioned(
|
||||
left: label.x,
|
||||
top: label.y,
|
||||
child: Text(
|
||||
routing.routeFor(label.edgeId)!.label,
|
||||
style: style.labelStyle,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: GraphViewport(
|
||||
controller: _viewport,
|
||||
contentSize: size,
|
||||
onExpand: () => _openExpanded(nodes, layout, routing, size),
|
||||
child: DefinitionGraphCanvas(
|
||||
nodes: nodes,
|
||||
layout: layout,
|
||||
routing: routing,
|
||||
style: style,
|
||||
selectedStage: widget.selectedStage,
|
||||
onSelected: widget.onSelected,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -228,4 +207,28 @@ class _DefinitionGraphViewState extends State<DefinitionGraphView> {
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Opens the same measured canvas full screen, keeping the selection.
|
||||
void _openExpanded(
|
||||
List<GraphNode> nodes,
|
||||
GraphLayout layout,
|
||||
GraphRouting routing,
|
||||
Size size,
|
||||
) {
|
||||
openGraphExpanded(
|
||||
context,
|
||||
contentSize: size,
|
||||
title: definitionGraphExpandedTitle,
|
||||
selectedStage: widget.selectedStage,
|
||||
onSelected: widget.onSelected,
|
||||
canvasBuilder: (context, selected, onSelected) => DefinitionGraphCanvas(
|
||||
nodes: nodes,
|
||||
layout: layout,
|
||||
routing: routing,
|
||||
style: GraphCanvasStyle.of(context),
|
||||
selectedStage: selected,
|
||||
onSelected: onSelected,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,7 +159,8 @@ class RunGraphEdgePainter extends CustomPainter {
|
||||
/// outcome labels only for routes the run actually took.
|
||||
///
|
||||
/// [layout] and [routing] are the caller's measured geometry. The canvas never
|
||||
/// changes them and never assumes a node size.
|
||||
/// changes them and never assumes a node size; the caller supplies the pan/zoom
|
||||
/// viewport around this content.
|
||||
class RunGraphCanvas extends StatelessWidget {
|
||||
const RunGraphCanvas({
|
||||
super.key,
|
||||
@@ -202,55 +203,47 @@ class RunGraphCanvas extends StatelessWidget {
|
||||
final executedColor = cupertino
|
||||
? CupertinoTheme.of(context).primaryColor
|
||||
: Theme.of(context).colorScheme.primary;
|
||||
return InteractiveViewer(
|
||||
constrained: false,
|
||||
minScale: 0.3,
|
||||
maxScale: 3,
|
||||
child: SizedBox.fromSize(
|
||||
size: size,
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: RunGraphEdgeLayer(
|
||||
executedRoutes: executed,
|
||||
untakenRoutes: untaken,
|
||||
canvasSize: size,
|
||||
executedColor: executedColor,
|
||||
untakenColor: style.edgeColor,
|
||||
strokeWidth: style.edgeWidth,
|
||||
return Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: RunGraphEdgeLayer(
|
||||
executedRoutes: executed,
|
||||
untakenRoutes: untaken,
|
||||
canvasSize: size,
|
||||
executedColor: executedColor,
|
||||
untakenColor: style.edgeColor,
|
||||
strokeWidth: style.edgeWidth,
|
||||
),
|
||||
),
|
||||
for (final box in layout.nodes)
|
||||
Positioned(
|
||||
left: box.x,
|
||||
top: box.y,
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
child: RunGraphNode(
|
||||
node: nodesByKey[box.key]!,
|
||||
recordedStatus: recordedStatuses[box.key],
|
||||
selected: box.key == selectedStage,
|
||||
opensVisit:
|
||||
!nodesByKey[box.key]!.terminal &&
|
||||
state.isStageVisited(box.key),
|
||||
onSelected: onStageSelected,
|
||||
),
|
||||
),
|
||||
// A run labels only the routes that actually happened.
|
||||
for (final label in routing.labels)
|
||||
if (executedIds.contains(label.edgeId))
|
||||
Positioned(
|
||||
left: label.x,
|
||||
top: label.y,
|
||||
child: Text(
|
||||
routing.routeFor(label.edgeId)!.label,
|
||||
style: style.labelStyle,
|
||||
),
|
||||
),
|
||||
for (final box in layout.nodes)
|
||||
Positioned(
|
||||
left: box.x,
|
||||
top: box.y,
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
child: RunGraphNode(
|
||||
node: nodesByKey[box.key]!,
|
||||
recordedStatus: recordedStatuses[box.key],
|
||||
selected: box.key == selectedStage,
|
||||
opensVisit:
|
||||
!nodesByKey[box.key]!.terminal &&
|
||||
state.isStageVisited(box.key),
|
||||
onSelected: onStageSelected,
|
||||
),
|
||||
),
|
||||
// A run labels only the routes that actually happened.
|
||||
for (final label in routing.labels)
|
||||
if (executedIds.contains(label.edgeId))
|
||||
Positioned(
|
||||
left: label.x,
|
||||
top: label.y,
|
||||
child: Text(
|
||||
routing.routeFor(label.edgeId)!.label,
|
||||
style: style.labelStyle,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../domain/run_graph_state.dart';
|
||||
import 'graph_canvas_style.dart';
|
||||
|
||||
/// The run legend's route-class words (web graph legend).
|
||||
const String runGraphExecuted = 'Executed';
|
||||
const String runGraphNotExecuted = 'Not executed';
|
||||
|
||||
/// The run canvas' fixed header: the route legend, plus the elapsed line while
|
||||
/// the run is still executing.
|
||||
///
|
||||
/// It is shared by the inline view and the full-screen presentation so the
|
||||
/// expanded canvas explains its solid and dashed routes the way the web keeps
|
||||
/// its legend inside the graph panel.
|
||||
class RunGraphHeader extends StatelessWidget {
|
||||
const RunGraphHeader({
|
||||
super.key,
|
||||
required this.state,
|
||||
required this.style,
|
||||
this.now,
|
||||
});
|
||||
|
||||
final RunGraphState state;
|
||||
final GraphCanvasStyle style;
|
||||
|
||||
/// Injectable clock for deterministic elapsed labels; defaults to now.
|
||||
final DateTime Function()? now;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
final executedColor = cupertino
|
||||
? CupertinoTheme.of(context).primaryColor
|
||||
: Theme.of(context).colorScheme.primary;
|
||||
final mutedColor = style.edgeColor;
|
||||
final active = state.activeStage;
|
||||
return Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(12, 8, 12, 0),
|
||||
child: Wrap(
|
||||
spacing: 16,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
Semantics(
|
||||
container: true,
|
||||
label: 'Route kinds',
|
||||
child: Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
_LegendEntry(
|
||||
icon: cupertino
|
||||
? CupertinoIcons.arrow_right
|
||||
: Icons.arrow_forward,
|
||||
label: runGraphExecuted,
|
||||
color: executedColor,
|
||||
),
|
||||
_LegendEntry(
|
||||
icon: cupertino ? CupertinoIcons.minus : Icons.remove,
|
||||
label: runGraphNotExecuted,
|
||||
color: mutedColor,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (active != null)
|
||||
_elapsed(context, active, state.currentStageStartedAt),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _elapsed(BuildContext context, String active, String? startedAt) {
|
||||
final started = startedAt == null ? null : DateTime.tryParse(startedAt);
|
||||
final duration = started == null
|
||||
? null
|
||||
: _formatElapsed((now ?? DateTime.now)().difference(started));
|
||||
final text = duration == null
|
||||
? 'Current stage $active'
|
||||
: 'Current stage $active · elapsed $duration';
|
||||
return Text(text, style: GraphCanvasStyle.of(context).labelStyle);
|
||||
}
|
||||
}
|
||||
|
||||
class _LegendEntry extends StatelessWidget {
|
||||
const _LegendEntry({
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.color,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final Color color;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Wrap(
|
||||
spacing: 4,
|
||||
runSpacing: 2,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
ExcludeSemantics(child: Icon(icon, color: color)),
|
||||
Text(label),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _formatElapsed(Duration duration) {
|
||||
final seconds = duration.inSeconds < 0 ? 0 : duration.inSeconds;
|
||||
if (seconds < 60) return '${seconds}s';
|
||||
if (seconds < 3600) return '${seconds ~/ 60}m ${seconds % 60}s';
|
||||
return '${seconds ~/ 3600}h ${(seconds % 3600) ~/ 60}m';
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../domain/graph_definition.dart';
|
||||
import '../domain/run_graph_state.dart';
|
||||
import '../domain/stage_visits.dart';
|
||||
@@ -10,15 +8,20 @@ import '../layout/graph_node_layout.dart';
|
||||
import '../layout/layout_models.dart';
|
||||
import '../routing/graph_edge_routing.dart';
|
||||
import '../routing/route_models.dart';
|
||||
import '../viewport/graph_expanded_view.dart';
|
||||
import '../viewport/graph_viewport.dart';
|
||||
import '../viewport/graph_viewport_controller.dart';
|
||||
import 'graph_canvas_style.dart';
|
||||
import 'run_graph_canvas.dart';
|
||||
import 'run_graph_header.dart';
|
||||
|
||||
export 'run_graph_header.dart' show runGraphExecuted, runGraphNotExecuted;
|
||||
|
||||
/// The run tab's exact missing-graph wording (web `RUN_GRAPH_MISSING`).
|
||||
const String runGraphMissing = 'This server did not include the run graph.';
|
||||
|
||||
/// The run legend's route-class words (web graph legend).
|
||||
const String runGraphExecuted = 'Executed';
|
||||
const String runGraphNotExecuted = 'Not executed';
|
||||
/// The expanded run presentation's title.
|
||||
const String runGraphExpandedTitle = 'Run graph';
|
||||
|
||||
/// One run's definition drawn as evidence: visited stages carry their recorded
|
||||
/// status, only taken routes are solid and arrowed, and every other route stays
|
||||
@@ -32,9 +35,10 @@ const String runGraphNotExecuted = 'Not executed';
|
||||
/// shown with the outcome that resolved there but have no recorded visit to
|
||||
/// open, so they stay non-interactive.
|
||||
///
|
||||
/// The view fills its bounded constraints with a stock [InteractiveViewer] for
|
||||
/// pan and zoom; the elapsed line appears only while the run is executing and
|
||||
/// is static (no invented progress or timer).
|
||||
/// The view fills its bounded constraints with a pan/zoom [GraphViewport]; the
|
||||
/// elapsed line appears only while the run is executing and is static (no
|
||||
/// invented progress or timer). The same canvas can be opened full screen with
|
||||
/// its selection preserved and the route legend still explaining its marks.
|
||||
class RunGraphView extends StatefulWidget {
|
||||
const RunGraphView({
|
||||
super.key,
|
||||
@@ -67,9 +71,16 @@ class _RunGraphViewState extends State<RunGraphView> {
|
||||
final Map<String, Size> _nodeSizes = {};
|
||||
final Map<String, Size> _labelSizes = {};
|
||||
final Map<String, String?> _measuredStatuses = {};
|
||||
final GraphViewportController _viewport = GraphViewportController();
|
||||
TextScaler? _scaler;
|
||||
bool _rebuildScheduled = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_viewport.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
@@ -188,21 +199,32 @@ class _RunGraphViewState extends State<RunGraphView> {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_header(state, style),
|
||||
RunGraphHeader(state: state, style: style, now: widget.now),
|
||||
Expanded(
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
if (geometry != null)
|
||||
RunGraphCanvas(
|
||||
nodes: nodes,
|
||||
layout: geometry.$1,
|
||||
routing: geometry.$2,
|
||||
state: state,
|
||||
style: style,
|
||||
recordedStatuses: statuses,
|
||||
selectedStage: widget.selectedStage,
|
||||
onStageSelected: widget.onStageSelected,
|
||||
GraphViewport(
|
||||
controller: _viewport,
|
||||
contentSize: Size(geometry.$2.width, geometry.$2.height),
|
||||
onExpand: () => _openExpanded(
|
||||
nodes,
|
||||
geometry.$1,
|
||||
geometry.$2,
|
||||
state,
|
||||
statuses,
|
||||
),
|
||||
child: _runCanvas(
|
||||
nodes: nodes,
|
||||
layout: geometry.$1,
|
||||
routing: geometry.$2,
|
||||
state: state,
|
||||
style: style,
|
||||
statuses: statuses,
|
||||
selectedStage: widget.selectedStage,
|
||||
onStageSelected: widget.onStageSelected,
|
||||
),
|
||||
)
|
||||
else
|
||||
const SizedBox.shrink(),
|
||||
@@ -245,87 +267,58 @@ class _RunGraphViewState extends State<RunGraphView> {
|
||||
),
|
||||
);
|
||||
|
||||
Widget _header(RunGraphState state, GraphCanvasStyle style) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
final executedColor = cupertino
|
||||
? CupertinoTheme.of(context).primaryColor
|
||||
: Theme.of(context).colorScheme.primary;
|
||||
final mutedColor = style.edgeColor;
|
||||
final active = state.activeStage;
|
||||
return Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(12, 8, 12, 0),
|
||||
child: Wrap(
|
||||
spacing: 16,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
Semantics(
|
||||
container: true,
|
||||
label: 'Route kinds',
|
||||
child: Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
_LegendEntry(
|
||||
icon: cupertino
|
||||
? CupertinoIcons.arrow_right
|
||||
: Icons.arrow_forward,
|
||||
label: runGraphExecuted,
|
||||
color: executedColor,
|
||||
),
|
||||
_LegendEntry(
|
||||
icon: cupertino ? CupertinoIcons.minus : Icons.remove,
|
||||
label: runGraphNotExecuted,
|
||||
color: mutedColor,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (active != null) _elapsed(active, state.currentStageStartedAt),
|
||||
],
|
||||
/// The same measured run canvas at any viewport size and selection, used by
|
||||
/// the inline viewport and the expanded presentation.
|
||||
Widget _runCanvas({
|
||||
required List<GraphNode> nodes,
|
||||
required GraphLayout layout,
|
||||
required GraphRouting routing,
|
||||
required RunGraphState state,
|
||||
required GraphCanvasStyle style,
|
||||
required Map<String, String?> statuses,
|
||||
required String? selectedStage,
|
||||
required ValueChanged<String> onStageSelected,
|
||||
}) => RunGraphCanvas(
|
||||
nodes: nodes,
|
||||
layout: layout,
|
||||
routing: routing,
|
||||
state: state,
|
||||
style: style,
|
||||
recordedStatuses: statuses,
|
||||
selectedStage: selectedStage,
|
||||
onStageSelected: onStageSelected,
|
||||
);
|
||||
|
||||
void _openExpanded(
|
||||
List<GraphNode> nodes,
|
||||
GraphLayout layout,
|
||||
GraphRouting routing,
|
||||
RunGraphState state,
|
||||
Map<String, String?> statuses,
|
||||
) {
|
||||
openGraphExpanded(
|
||||
context,
|
||||
contentSize: Size(routing.width, routing.height),
|
||||
title: runGraphExpandedTitle,
|
||||
selectedStage: widget.selectedStage,
|
||||
onSelected: widget.onStageSelected,
|
||||
// The full-screen canvas draws solid and dashed routes; the legend that
|
||||
// explains them must travel with it, as it does on the web.
|
||||
header: RunGraphHeader(
|
||||
state: state,
|
||||
style: GraphCanvasStyle.of(context),
|
||||
now: widget.now,
|
||||
),
|
||||
canvasBuilder: (context, selected, onSelected) => _runCanvas(
|
||||
nodes: nodes,
|
||||
layout: layout,
|
||||
routing: routing,
|
||||
state: state,
|
||||
style: GraphCanvasStyle.of(context),
|
||||
statuses: statuses,
|
||||
selectedStage: selected,
|
||||
onStageSelected: onSelected,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _elapsed(String active, String? startedAt) {
|
||||
final started = startedAt == null ? null : DateTime.tryParse(startedAt);
|
||||
final duration = started == null
|
||||
? null
|
||||
: _formatElapsed((widget.now ?? DateTime.now)().difference(started));
|
||||
final text = duration == null
|
||||
? 'Current stage $active'
|
||||
: 'Current stage $active · elapsed $duration';
|
||||
return Text(text, style: GraphCanvasStyle.of(context).labelStyle);
|
||||
}
|
||||
}
|
||||
|
||||
class _LegendEntry extends StatelessWidget {
|
||||
const _LegendEntry({
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.color,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final Color color;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Wrap(
|
||||
spacing: 4,
|
||||
runSpacing: 2,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
ExcludeSemantics(child: Icon(icon, color: color)),
|
||||
Text(label),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _formatElapsed(Duration duration) {
|
||||
final seconds = duration.inSeconds < 0 ? 0 : duration.inSeconds;
|
||||
if (seconds < 60) return '${seconds}s';
|
||||
if (seconds < 3600) return '${seconds ~/ 60}m ${seconds % 60}s';
|
||||
return '${seconds ~/ 3600}h ${(seconds % 3600) ~/ 60}m';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
# Graph viewport: pan, zoom, fit and expanded
|
||||
|
||||
The measured definition/run canvases now share one viewport layer. Nothing in
|
||||
the graph's wiring changed: `DefinitionGraphView` and `RunGraphView` keep their
|
||||
existing props and call sites, and the pipeline Graph tab / run detail open the
|
||||
expanded presentation without edits to those tabs.
|
||||
|
||||
## Landed
|
||||
|
||||
- `lib/features/graph/viewport/graph_viewport_math.dart` — the web graph's
|
||||
`fitScale`/`clampOffset` rules (padding 24, min 0.3, max 3, at least 40px of
|
||||
the scaled graph visible) plus the `offset + point * scale` matrix.
|
||||
- `lib/features/graph/viewport/graph_viewport_controller.dart` — owns the
|
||||
`TransformationController`, auto-fits on first layout, re-fits a resize only
|
||||
before the reader interacts, clamps every later transform, and round-trips a
|
||||
`GraphViewportSnapshot`.
|
||||
- `lib/features/graph/viewport/graph_viewport.dart` — the bounded canvas: the
|
||||
host's `InteractiveViewer` gestures (drag, pinch, wheel, trackpad) with an
|
||||
infinite boundary margin so the graph's own fit/bounds win, plus native Fit
|
||||
and Expand controls (`Fit graph to view`, `Expand graph`).
|
||||
- `lib/features/graph/viewport/graph_expanded_view.dart` — a native full-screen
|
||||
presentation (`Scaffold`/`CupertinoPageScaffold`) with one visible `Close`
|
||||
action, `openGraphExpanded()` as the widget/callback seam, and an optional
|
||||
fixed `header` above the canvas. It fits the larger box exactly as the web
|
||||
re-fits when its panel expands, keeps the selected node selected, re-fits a
|
||||
resize until the reader interacts and clamps one afterwards. It owns a
|
||||
separate controller, so closing restores the inline transform exactly.
|
||||
- `DefinitionGraphView`/`RunGraphView` now wrap their measured content in
|
||||
`GraphViewport`; `RunGraphCanvas` is the passive content only (the viewer
|
||||
moved out of it). `DefinitionGraphCanvas` owns the measured definition
|
||||
composition, and `RunGraphHeader` owns the route legend + elapsed line and is
|
||||
carried into the expanded run presentation. Node sizes, routing,
|
||||
executed/unvisited evidence, labels and legend are unchanged.
|
||||
|
||||
## Behavior and bounds
|
||||
|
||||
- The graph is fitted on first layout with 24px padding and never upscaled past
|
||||
1:1, before the first paint: the first layout attaches synchronously, when
|
||||
nothing is listening to the transform yet, rather than flashing an identity
|
||||
transform for a frame.
|
||||
- Scale is clamped to 0.3–3 and a drag can never leave an empty viewport
|
||||
(40px minimum visible per axis).
|
||||
- Pinch/wheel zoom anchors the graph point under the moving focal point; a tap
|
||||
that does not move still reaches the native node under the pointer because
|
||||
hit-testing follows the same transform.
|
||||
- Fit and Expand are stock host buttons with one accessible name and the
|
||||
button's own tap action on both hosts. The icon is the only excluded child
|
||||
and `MergeSemantics` folds the real button action into the labelled node; a
|
||||
hand-written sibling `Semantics` around an `ExcludeSemantics`d button would
|
||||
announce the control with no action at all.
|
||||
- Single taps select nodes; dragging over a node pans instead of selecting.
|
||||
- The canvas consumes gestures only inside its own box. An ancestor scroll view
|
||||
keeps scrolling for gestures outside the canvas, and the canvas never pans
|
||||
from a drag that starts outside it.
|
||||
- Expanded draws the same canvas at its own fit, keeps the legend (run graph),
|
||||
keeps the selection, and leaves the inline canvas untouched.
|
||||
|
||||
## Checks (final tree)
|
||||
|
||||
From `app/` with Flutter 3.44.6 / Dart 3.12.2:
|
||||
|
||||
- `flutter analyze` — **No issues found**.
|
||||
- `flutter test` — **1025 tests pass** (1m 06s in this run).
|
||||
- `flutter test test/features/graph` — **175 pass**.
|
||||
- `flutter test test/features/graph/viewport` — **20 tests pass**
|
||||
(8 math/controller, 9 viewport widget, 3 expanded), covering:
|
||||
- drag pans and pan stays bounded;
|
||||
- pinch clamps at 0.3 and 3;
|
||||
- zoom keeps the graph point under the moving focal point;
|
||||
- the first painted frame is already fitted;
|
||||
- Fit restores the fitted scale/offset;
|
||||
- tap selects the node visually under the pointer after a transform (synthetic
|
||||
targets and real `DefinitionGraphView` nodes);
|
||||
- ancestor scroll is not hijacked outside the canvas;
|
||||
- Fit and Expand are labelled buttons with a tap action on Material and
|
||||
Cupertino, and performing that action runs the real callback;
|
||||
- 320px/2x on Material and dark Cupertino;
|
||||
- expanded fits the larger canvas, preserves selection and returns the inline
|
||||
state exactly;
|
||||
- a rotation re-clamps the expanded transform into the new box.
|
||||
- `flutter build web` — succeeds for the app and the probe target.
|
||||
- Real Chrome probe (`tool/graph_zoom_probe.dart` + `tool/graph_zoom_probe.mjs`,
|
||||
loopback server, OS-assigned port) re-run against this final source, 7 runs:
|
||||
- pipeline graph: Material light 1280x800 1x, Material light 320x700 2x,
|
||||
Cupertino dark 390x844 1x, Cupertino dark 320x700 2x;
|
||||
- run graph: Material light 1280x800 1x, Material dark 320x700 2x,
|
||||
Cupertino dark 390x844 1x.
|
||||
Each asserted a real drag moved a node, wheel zoom grew it, Fit restored it,
|
||||
Expand opened the titled full-screen canvas with the selected node still
|
||||
announced selected, and Close returned to the same inline place and selection.
|
||||
42 captures (initial/panned/zoomed/fitted/expanded/restored per run) were
|
||||
regenerated after the last source edit and are in
|
||||
`/Users/alan/.local/share/pipelines/data/artifacts/101/public/graph-zoom-captures/`.
|
||||
- `dart format --output=none --set-exit-if-changed` on the changed Dart files —
|
||||
0 changed; `git diff --check` — clean.
|
||||
|
||||
## Corrections from actual checks
|
||||
|
||||
- The transform's z axis must be scaled with x/y: `getMaxScaleOnAxis` otherwise
|
||||
reported 1.0 for a 0.8 fit and InteractiveViewer's own pinch math used the
|
||||
wrong scale. Fixed in `graphViewportMatrix`.
|
||||
- Two existing measurement tests compared on-screen rectangles, which now
|
||||
include the fit scale. They divide by the current scale and assert the
|
||||
measured graph-space extent instead; the assertions about wrapping and
|
||||
overlap are unchanged.
|
||||
- Cupertino's full-screen route added its own `Cancel` leading button next to
|
||||
the explicit Close; `automaticallyImplyLeading: false` leaves the one Close
|
||||
action.
|
||||
- `tester.drag` can lose the pre-acceptance movement to the pan slop; gesture
|
||||
tests warm up past the slop and measure from the accepted transform, and the
|
||||
browser probe pans with eight real pointer moves.
|
||||
- The first implementation excluded the whole Cupertino button from semantics
|
||||
and put the label on a sibling node: VoiceOver/TalkBack saw a labelled button
|
||||
with no tap action. The exclusion now covers only the icon and
|
||||
`MergeSemantics` merges the host button's action; the regression test performs
|
||||
the semantics action itself, not a pointer tap.
|
||||
- Material controls previously had only a tooltip as their accessible name. Both
|
||||
hosts now expose one explicit label (`Fit graph to view` / `Expand graph`);
|
||||
Material keeps the tooltip for pointer hover, excluded from semantics so the
|
||||
name is not duplicated.
|
||||
- The inline canvas used to paint one identity-transform frame before the
|
||||
post-frame fit. The first layout now attaches before its child viewer exists,
|
||||
and the regression test pumps exactly once.
|
||||
- Expanded used to keep the small inline scale, unlike the web, which calls
|
||||
`fit()` after growing the panel. It now fits its own canvas and re-clamps (or
|
||||
re-fits) on resize; the inline place/selection still return unchanged on
|
||||
Close.
|
||||
- The expanded run canvas had no route legend; `RunGraphHeader` now travels
|
||||
with it.
|
||||
|
||||
## Limits
|
||||
|
||||
- Inside an ancestor scroll view, a **vertical** drag that starts on the canvas
|
||||
is claimed by the scrollable (Flutter's gesture arena gives the 18px vertical
|
||||
drag the win over the 36px pan slop); horizontal drags and pinch stay with the
|
||||
canvas. The graph is not inside a scrollable in either current tab. Outside
|
||||
the canvas the list scrolls normally, which is the accepted behavior here.
|
||||
- Opening expanded fits the graph rather than keeping the inline place (web
|
||||
behavior); closing still restores the inline transform exactly.
|
||||
- Web only: Android/iOS builds, device gestures and OS behavior are unverified.
|
||||
- `run_graph_view.dart` remains over the 250-line aim (324 lines: measurement,
|
||||
evidence and viewport composition; the legend/header and definition canvas
|
||||
were split out). The new viewport files and viewport test files are all under
|
||||
250 lines.
|
||||
@@ -0,0 +1,213 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_expanded_view.dart';
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_viewport_math.dart';
|
||||
import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart';
|
||||
import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
|
||||
|
||||
import '../domain/graph_fixtures.dart';
|
||||
|
||||
Widget _materialHost({
|
||||
required JsonMap graph,
|
||||
required String? selected,
|
||||
required ValueChanged<String> onSelected,
|
||||
}) => MaterialApp(
|
||||
home: Scaffold(
|
||||
body: DefinitionGraphView(
|
||||
graph: graph,
|
||||
selectedStage: selected,
|
||||
onSelected: onSelected,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Finder _node(String key) => find.byWidgetPredicate(
|
||||
(widget) => widget is GraphStageNode && widget.node.key == key,
|
||||
);
|
||||
|
||||
Finder _inExpanded(Finder finder) =>
|
||||
find.descendant(of: find.byType(GraphExpandedView), matching: finder);
|
||||
|
||||
Future<void> _settle(WidgetTester tester) async {
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
TransformationController _inlineTransform(WidgetTester tester) => tester
|
||||
.widget<InteractiveViewer>(find.byType(InteractiveViewer))
|
||||
.transformationController!;
|
||||
|
||||
void main() {
|
||||
testWidgets(
|
||||
'expanded fits the larger canvas and returns to the inline state',
|
||||
(tester) async {
|
||||
tester.view.physicalSize = const Size(900, 700);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
final picked = <String>[];
|
||||
await tester.pumpWidget(
|
||||
_materialHost(
|
||||
graph: linearGraph(),
|
||||
selected: 'build',
|
||||
onSelected: picked.add,
|
||||
),
|
||||
);
|
||||
await _settle(tester);
|
||||
|
||||
final inline = _inlineTransform(tester);
|
||||
final inlineMatrix = Matrix4.copy(inline.value);
|
||||
final inlineRect = tester.getRect(_node('build'));
|
||||
|
||||
await tester.tap(find.byKey(const Key('graph-expand')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byType(GraphExpandedView), findsOneWidget);
|
||||
expect(find.text(definitionGraphExpandedTitle), findsOneWidget);
|
||||
final expanded = _inExpanded(find.byType(InteractiveViewer));
|
||||
expect(expanded, findsOneWidget);
|
||||
final expandedController = tester
|
||||
.widget<InteractiveViewer>(expanded)
|
||||
.transformationController!;
|
||||
final expandedView = tester.widget<GraphExpandedView>(
|
||||
find.byType(GraphExpandedView),
|
||||
);
|
||||
final canvas = tester.getRect(
|
||||
_inExpanded(find.byKey(const Key('graph-viewport'))),
|
||||
);
|
||||
// The web re-fits when its panel expands: the larger canvas fits the
|
||||
// whole graph instead of keeping the small inline scale.
|
||||
expect(
|
||||
expandedController.value.getMaxScaleOnAxis(),
|
||||
closeTo(graphFitScale(canvas.size, expandedView.contentSize), 1e-9),
|
||||
);
|
||||
expect(
|
||||
canvas.contains(tester.getCenter(_inExpanded(_node('build')))),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
tester.widget<GraphStageNode>(_inExpanded(_node('build'))).selected,
|
||||
isTrue,
|
||||
);
|
||||
|
||||
// A tap in the larger canvas follows the same transform and updates the
|
||||
// presentation's own selection.
|
||||
await tester.tap(_inExpanded(_node('plan')));
|
||||
await tester.pump();
|
||||
expect(picked, ['plan']);
|
||||
expect(
|
||||
tester.widget<GraphStageNode>(_inExpanded(_node('plan'))).selected,
|
||||
isTrue,
|
||||
);
|
||||
|
||||
await tester.tap(find.byKey(const Key('graph-expanded-close')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byType(GraphExpandedView), findsNothing);
|
||||
// The inline canvas was never changed: same selection, same place.
|
||||
expect(tester.widget<GraphStageNode>(_node('build')).selected, isTrue);
|
||||
expect(tester.getRect(_node('build')), inlineRect);
|
||||
expect(inline.value.storage, orderedEquals(inlineMatrix.storage));
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('a rotation re-clamps the expanded transform into the new box', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(900, 700);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
await tester.pumpWidget(
|
||||
_materialHost(
|
||||
graph: linearGraph(),
|
||||
selected: 'build',
|
||||
onSelected: (_) {},
|
||||
),
|
||||
);
|
||||
await _settle(tester);
|
||||
await tester.tap(find.byKey(const Key('graph-expand')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final expanded = _inExpanded(find.byType(InteractiveViewer));
|
||||
final controller = tester
|
||||
.widget<InteractiveViewer>(expanded)
|
||||
.transformationController!;
|
||||
final canvas = find.descendant(
|
||||
of: find.byType(GraphExpandedView),
|
||||
matching: find.byKey(const Key('graph-viewport')),
|
||||
);
|
||||
// Pan far enough that the wide canvas' clamp is the only limit.
|
||||
await tester.drag(canvas, const Offset(500, 0));
|
||||
await tester.pumpAndSettle();
|
||||
final wide = tester.getRect(canvas);
|
||||
final panned = controller.value.getTranslation().x;
|
||||
expect(panned, lessThanOrEqualTo(wide.width - graphMinVisible + 0.5));
|
||||
|
||||
// Rotating to a narrow box must keep the graph inside it, not leave the
|
||||
// reader's old place hanging outside until Fit is pressed.
|
||||
tester.view.physicalSize = const Size(320, 700);
|
||||
await tester.pumpAndSettle();
|
||||
await _settle(tester);
|
||||
final narrow = tester.getRect(canvas);
|
||||
expect(narrow.width, lessThan(wide.width));
|
||||
final clamped = controller.value.getTranslation().x;
|
||||
expect(
|
||||
clamped,
|
||||
lessThanOrEqualTo(narrow.width - graphMinVisible + 0.5),
|
||||
reason: 'a resize must re-clamp the existing transform',
|
||||
);
|
||||
expect(clamped, lessThan(panned));
|
||||
});
|
||||
|
||||
testWidgets('320px at 2x opens and closes on the dark Cupertino host', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(320, 700);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
final picked = <String>[];
|
||||
await tester.pumpWidget(
|
||||
CupertinoApp(
|
||||
theme: const CupertinoThemeData(brightness: Brightness.dark),
|
||||
home: CupertinoPageScaffold(
|
||||
child: Builder(
|
||||
builder: (context) => MediaQuery(
|
||||
data: MediaQuery.of(
|
||||
context,
|
||||
).copyWith(textScaler: const TextScaler.linear(2)),
|
||||
child: DefinitionGraphView(
|
||||
graph: linearGraph(),
|
||||
selectedStage: 'build',
|
||||
onSelected: picked.add,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await _settle(tester);
|
||||
final inline = _inlineTransform(tester);
|
||||
final inlineMatrix = Matrix4.copy(inline.value);
|
||||
|
||||
await tester.tap(find.byKey(const Key('graph-expand')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(GraphExpandedView), findsOneWidget);
|
||||
expect(_inExpanded(find.text(graphExpandedClose)), findsOneWidget);
|
||||
expect(
|
||||
tester.widget<GraphStageNode>(_inExpanded(_node('build'))).selected,
|
||||
isTrue,
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
|
||||
await tester.tap(find.byKey(const Key('graph-expanded-close')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(GraphExpandedView), findsNothing);
|
||||
expect(tester.widget<GraphStageNode>(_node('build')).selected, isTrue);
|
||||
expect(inline.value.storage, orderedEquals(inlineMatrix.storage));
|
||||
expect(picked, isEmpty);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart';
|
||||
|
||||
import 'graph_viewport_fixtures.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('Fit and Expand stay labelled, activatable buttons on both hosts', (
|
||||
tester,
|
||||
) async {
|
||||
for (final cupertino in [false, true]) {
|
||||
final host = cupertino ? 'cupertino' : 'material';
|
||||
final controller = GraphViewportController();
|
||||
addTearDown(controller.dispose);
|
||||
var expands = 0;
|
||||
await tester.pumpWidget(
|
||||
viewportHost(
|
||||
controller: controller,
|
||||
child: viewportTargets([]),
|
||||
cupertino: cupertino,
|
||||
onExpand: () => expands += 1,
|
||||
),
|
||||
);
|
||||
await settleViewport(tester);
|
||||
final fitted = controller.snapshot;
|
||||
|
||||
for (final control in viewportControls().entries) {
|
||||
final node = tester.getSemantics(find.byKey(control.key));
|
||||
final data = node.getSemanticsData();
|
||||
expect(
|
||||
data.label,
|
||||
control.value,
|
||||
reason: '$host ${control.key} must have the web name',
|
||||
);
|
||||
expect(
|
||||
data.flagsCollection.isButton,
|
||||
isTrue,
|
||||
reason: '$host ${control.key} must be announced as a button',
|
||||
);
|
||||
// A labelled button with no action is unusable with VoiceOver/TalkBack;
|
||||
// this is the regression the excluded-button wrapper introduced.
|
||||
expect(
|
||||
data.hasAction(SemanticsAction.tap),
|
||||
isTrue,
|
||||
reason: '$host ${control.key} must expose a tap action',
|
||||
);
|
||||
}
|
||||
|
||||
// The exposed action must run the real callback, not just be announced.
|
||||
await pinchViewport(tester, const Offset(200, 150), 2);
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.snapshot, isNot(fitted));
|
||||
performViewportTap(tester, find.byKey(const Key('graph-fit')));
|
||||
await tester.pump();
|
||||
expect(controller.scale, closeTo(fitted.scale, 1e-9));
|
||||
|
||||
performViewportTap(tester, find.byKey(const Key('graph-expand')));
|
||||
await tester.pump();
|
||||
expect(expands, 1, reason: '$host Expand must activate');
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('320px at 2x keeps native controls and gestures on both hosts', (
|
||||
tester,
|
||||
) async {
|
||||
for (final cupertino in [false, true]) {
|
||||
final controller = GraphViewportController();
|
||||
addTearDown(controller.dispose);
|
||||
await tester.pumpWidget(
|
||||
viewportHost(
|
||||
controller: controller,
|
||||
child: viewportTargets([]),
|
||||
cupertino: cupertino,
|
||||
dark: cupertino,
|
||||
textScale: 2,
|
||||
viewport: const Size(320, 300),
|
||||
onExpand: () {},
|
||||
),
|
||||
);
|
||||
await settleViewport(tester);
|
||||
expect(find.byKey(const Key('graph-fit')), findsOneWidget);
|
||||
expect(find.byKey(const Key('graph-expand')), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
|
||||
final before = controller.offset;
|
||||
await dragViewport(
|
||||
tester,
|
||||
find.byKey(const Key('graph-viewport')),
|
||||
const Offset(-30, -10),
|
||||
);
|
||||
expect(controller.offset, isNot(before));
|
||||
await pinchViewport(tester, const Offset(160, 150), 2);
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.scale, greaterThan(0.3));
|
||||
expect(tester.takeException(), isNull);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_viewport.dart';
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart';
|
||||
|
||||
/// Shared fixture for the graph viewport widget tests.
|
||||
///
|
||||
/// One 1200x900 graph in a 400x300 box unless a test asks for another size.
|
||||
const Size viewportContent = Size(1200, 900);
|
||||
const Size defaultViewportSize = Size(400, 300);
|
||||
|
||||
/// Two native tap targets at known graph coordinates; a tap reports its key so
|
||||
/// hit-testing can be checked against the visible transform.
|
||||
Widget viewportTargets(List<String> picked) => Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
Positioned(
|
||||
left: 60,
|
||||
top: 60,
|
||||
width: 120,
|
||||
height: 60,
|
||||
child: GestureDetector(
|
||||
key: const Key('target-a'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: () => picked.add('a'),
|
||||
child: const ColoredBox(color: Color(0xFF3366CC)),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
left: 900,
|
||||
top: 700,
|
||||
width: 160,
|
||||
height: 80,
|
||||
child: GestureDetector(
|
||||
key: const Key('target-b'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: () => picked.add('b'),
|
||||
child: const ColoredBox(color: Color(0xFFCC6633)),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
Widget viewportHost({
|
||||
required GraphViewportController controller,
|
||||
required Widget child,
|
||||
VoidCallback? onExpand,
|
||||
bool cupertino = false,
|
||||
bool dark = false,
|
||||
double textScale = 1,
|
||||
Size viewport = defaultViewportSize,
|
||||
}) {
|
||||
final graph = MediaQuery(
|
||||
data: MediaQueryData(textScaler: TextScaler.linear(textScale)),
|
||||
child: SizedBox.fromSize(
|
||||
size: viewport,
|
||||
child: GraphViewport(
|
||||
controller: controller,
|
||||
contentSize: viewportContent,
|
||||
onExpand: onExpand,
|
||||
child: child,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (cupertino) {
|
||||
return CupertinoApp(
|
||||
theme: CupertinoThemeData(
|
||||
brightness: dark ? Brightness.dark : Brightness.light,
|
||||
),
|
||||
home: CupertinoPageScaffold(child: Center(child: graph)),
|
||||
);
|
||||
}
|
||||
return MaterialApp(
|
||||
theme: dark ? ThemeData.dark() : ThemeData.light(),
|
||||
home: Scaffold(body: Center(child: graph)),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> settleViewport(WidgetTester tester) async {
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
/// Two-pointer pinch around [center]; [factor] > 1 zooms in.
|
||||
Future<void> pinchViewport(
|
||||
WidgetTester tester,
|
||||
Offset center,
|
||||
double factor, {
|
||||
double half = 20,
|
||||
}) async {
|
||||
final origin = viewportGlobal(tester, center);
|
||||
final left = await tester.startGesture(origin - Offset(half, 0));
|
||||
final right = await tester.startGesture(origin + Offset(half, 0));
|
||||
await tester.pump();
|
||||
const steps = 8;
|
||||
final end = half * factor;
|
||||
for (var step = 1; step <= steps; step += 1) {
|
||||
final spread = half + (end - half) * step / steps;
|
||||
await left.moveTo(origin - Offset(spread, 0));
|
||||
await right.moveTo(origin + Offset(spread, 0));
|
||||
await tester.pump();
|
||||
}
|
||||
await left.up();
|
||||
await right.up();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Offset viewportScreenOf(
|
||||
GraphViewportController controller,
|
||||
Offset graphPoint,
|
||||
) => MatrixUtils.transformPoint(controller.transformation.value, graphPoint);
|
||||
|
||||
/// Viewport-local coordinates to the test screen, where gestures are dispatched.
|
||||
Offset viewportGlobal(WidgetTester tester, Offset local) =>
|
||||
tester.getTopLeft(find.byKey(const Key('graph-viewport'))) + local;
|
||||
|
||||
/// Starts a drag and moves past the pan slop, so the canvas owns the gesture.
|
||||
///
|
||||
/// The viewer only pans movement after it accepts the gesture, so tests record
|
||||
/// their reference offset after this warm-up rather than at pointer down.
|
||||
Future<TestGesture> startViewportDrag(
|
||||
WidgetTester tester,
|
||||
Finder finder, {
|
||||
Offset warmUp = const Offset(-10, -10),
|
||||
}) async {
|
||||
final gesture = await tester.startGesture(tester.getCenter(finder));
|
||||
for (var step = 0; step < 4; step += 1) {
|
||||
await gesture.moveBy(warmUp);
|
||||
await tester.pump();
|
||||
}
|
||||
return gesture;
|
||||
}
|
||||
|
||||
Future<void> dragViewport(
|
||||
WidgetTester tester,
|
||||
Finder finder,
|
||||
Offset delta, {
|
||||
Offset warmUp = const Offset(-10, -10),
|
||||
}) async {
|
||||
final gesture = await startViewportDrag(tester, finder, warmUp: warmUp);
|
||||
for (var step = 0; step < 4; step += 1) {
|
||||
await gesture.moveBy(delta / 4);
|
||||
await tester.pump();
|
||||
}
|
||||
await gesture.up();
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
/// Activates a control the way a screen reader does: through its semantics
|
||||
/// action, not pointer input.
|
||||
void performViewportTap(WidgetTester tester, Finder finder) {
|
||||
final node = tester.getSemantics(finder);
|
||||
tester.binding.renderViews.first.owner!.semanticsOwner!.performAction(
|
||||
node.id,
|
||||
SemanticsAction.tap,
|
||||
);
|
||||
}
|
||||
|
||||
/// The controls' accessible names, in the order they are shown.
|
||||
Map<Key, String> viewportControls() => <Key, String>{
|
||||
const Key('graph-fit'): graphFitLabel,
|
||||
const Key('graph-expand'): graphExpandLabel,
|
||||
};
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart';
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_viewport_math.dart';
|
||||
|
||||
void main() {
|
||||
test('fit keeps the padding and never upscales a small graph', () {
|
||||
final scale = graphFitScale(
|
||||
const Size(400, 300),
|
||||
const Size(1000, 800),
|
||||
padding: 20,
|
||||
);
|
||||
// 360/1000 and 260/800 both fit; the smaller axis wins.
|
||||
expect(scale, closeTo(0.325, 1e-9));
|
||||
expect(graphFitScale(const Size(400, 300), const Size(100, 80)), 1);
|
||||
});
|
||||
|
||||
test('fit clamps to the graph scale bounds', () {
|
||||
expect(
|
||||
graphFitScale(const Size(400, 300), const Size(10000, 10000)),
|
||||
graphMinScale,
|
||||
);
|
||||
expect(
|
||||
graphFitScale(const Size(400, 300), const Size(1000, 800), minScale: 0.9),
|
||||
0.9,
|
||||
);
|
||||
});
|
||||
|
||||
test('degenerate sizes never divide by zero', () {
|
||||
expect(graphFitScale(Size.zero, const Size(100, 100)), 1);
|
||||
expect(graphFitScale(const Size(400, 300), Size.zero), 1);
|
||||
expect(
|
||||
graphFitScale(const Size(400, 300), const Size(100, 100), padding: 200),
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
test('pan clamp keeps part of the scaled graph visible', () {
|
||||
const viewport = Size(400, 300);
|
||||
const scaled = Size(800, 600);
|
||||
expect(
|
||||
graphClampOffset(const Offset(5000, 5000), scaled, viewport),
|
||||
const Offset(400 - graphMinVisible, 300 - graphMinVisible),
|
||||
);
|
||||
expect(
|
||||
graphClampOffset(const Offset(-5000, -5000), scaled, viewport),
|
||||
Offset(graphMinVisible - 800, graphMinVisible - 600),
|
||||
);
|
||||
// Inside the bounds the offset is untouched.
|
||||
expect(
|
||||
graphClampOffset(const Offset(-100, -50), scaled, viewport),
|
||||
const Offset(-100, -50),
|
||||
);
|
||||
});
|
||||
|
||||
test('clamp leaves degenerate content and empty ranges alone', () {
|
||||
expect(
|
||||
graphClampOffset(const Offset(12, 34), Size.zero, const Size(400, 300)),
|
||||
const Offset(12, 34),
|
||||
);
|
||||
// The viewport is narrower than twice the minimum visible part: the range
|
||||
// is empty, so the input survives rather than being pinned to a bad value.
|
||||
expect(
|
||||
graphClampOffset(
|
||||
const Offset(500, 500),
|
||||
const Size(1, 1),
|
||||
const Size(40, 40),
|
||||
),
|
||||
const Offset(500, 500),
|
||||
);
|
||||
});
|
||||
|
||||
test('the transform draws graph points at offset + point * scale', () {
|
||||
final matrix = graphViewportMatrix(const Offset(30, 20), 0.5);
|
||||
expect(
|
||||
MatrixUtils.transformPoint(matrix, const Offset(100, 80)),
|
||||
const Offset(80, 60),
|
||||
);
|
||||
expect(matrix.getMaxScaleOnAxis(), 0.5);
|
||||
});
|
||||
|
||||
test('controller fits, centers and round-trips a snapshot', () {
|
||||
final controller = GraphViewportController();
|
||||
addTearDown(controller.dispose);
|
||||
controller.attach(
|
||||
viewport: const Size(400, 300),
|
||||
content: const Size(1000, 800),
|
||||
);
|
||||
final fitted = controller.snapshot;
|
||||
expect(fitted.scale, closeTo(0.315, 1e-9));
|
||||
expect(fitted.offset.dx, greaterThan(0));
|
||||
expect(fitted.offset.dy, greaterThan(0));
|
||||
expect(
|
||||
fitted.offset,
|
||||
graphCenteredOffset(
|
||||
Size(1000 * fitted.scale, 800 * fitted.scale),
|
||||
const Size(400, 300),
|
||||
),
|
||||
);
|
||||
|
||||
controller.applySnapshot(
|
||||
const GraphViewportSnapshot(scale: 2, offset: Offset(-100, -80)),
|
||||
);
|
||||
expect(
|
||||
controller.snapshot,
|
||||
const GraphViewportSnapshot(scale: 2, offset: Offset(-100, -80)),
|
||||
);
|
||||
|
||||
// A resize after the reader adjusted keeps their scale, only clamping the
|
||||
// offset into the new bounds.
|
||||
controller.attach(
|
||||
viewport: const Size(200, 200),
|
||||
content: const Size(1000, 800),
|
||||
);
|
||||
expect(controller.scale, 2);
|
||||
});
|
||||
|
||||
test('controller fit clamps a graph that cannot fit at the minimum', () {
|
||||
final controller = GraphViewportController();
|
||||
addTearDown(controller.dispose);
|
||||
controller.attach(
|
||||
viewport: const Size(400, 300),
|
||||
content: const Size(10000, 10000),
|
||||
);
|
||||
expect(controller.scale, graphMinScale);
|
||||
final scaled = 10000 * graphMinScale;
|
||||
expect(
|
||||
controller.offset.dx,
|
||||
greaterThanOrEqualTo(graphMinVisible - scaled),
|
||||
);
|
||||
expect(controller.offset.dx, lessThanOrEqualTo(400 - graphMinVisible));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_viewport.dart';
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart';
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_viewport_math.dart';
|
||||
|
||||
import 'graph_viewport_fixtures.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('drag pans the canvas and the pan stays bounded', (tester) async {
|
||||
final controller = GraphViewportController();
|
||||
addTearDown(controller.dispose);
|
||||
await tester.pumpWidget(
|
||||
viewportHost(controller: controller, child: viewportTargets([])),
|
||||
);
|
||||
await settleViewport(tester);
|
||||
|
||||
expect(controller.scale, lessThan(1));
|
||||
final finder = find.byKey(const Key('graph-viewport'));
|
||||
|
||||
final gesture = await startViewportDrag(tester, finder);
|
||||
final before = controller.offset;
|
||||
for (var step = 0; step < 4; step += 1) {
|
||||
await gesture.moveBy(const Offset(-10, -5));
|
||||
await tester.pump();
|
||||
}
|
||||
await gesture.up();
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.offset.dx, closeTo(before.dx - 40, 1));
|
||||
expect(controller.offset.dy, closeTo(before.dy - 20, 1));
|
||||
|
||||
// A huge drag can never leave an empty canvas: at least the minimum part
|
||||
// of the scaled graph stays inside the viewport.
|
||||
final out = await startViewportDrag(tester, finder);
|
||||
await out.moveBy(const Offset(5000, 5000));
|
||||
await tester.pump();
|
||||
await out.up();
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
controller.offset.dx,
|
||||
lessThanOrEqualTo(defaultViewportSize.width - graphMinVisible + 0.01),
|
||||
);
|
||||
expect(
|
||||
controller.offset.dy,
|
||||
lessThanOrEqualTo(defaultViewportSize.height - graphMinVisible + 0.01),
|
||||
);
|
||||
final back = await startViewportDrag(tester, finder);
|
||||
await back.moveBy(const Offset(-10000, -10000));
|
||||
await tester.pump();
|
||||
await back.up();
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
controller.offset.dx,
|
||||
greaterThanOrEqualTo(
|
||||
graphMinVisible - viewportContent.width * controller.scale - 0.01,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('pinch zoom clamps at the graph scale bounds', (tester) async {
|
||||
final controller = GraphViewportController();
|
||||
addTearDown(controller.dispose);
|
||||
await tester.pumpWidget(
|
||||
viewportHost(controller: controller, child: viewportTargets([])),
|
||||
);
|
||||
await settleViewport(tester);
|
||||
expect(controller.scale, lessThan(1));
|
||||
|
||||
await pinchViewport(tester, const Offset(200, 150), 10);
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.scale, graphMaxScale);
|
||||
|
||||
await pinchViewport(tester, const Offset(200, 150), 0.01);
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.scale, graphMinScale);
|
||||
});
|
||||
|
||||
testWidgets('zoom keeps the graph point under the moving focal point', (
|
||||
tester,
|
||||
) async {
|
||||
final controller = GraphViewportController();
|
||||
addTearDown(controller.dispose);
|
||||
await tester.pumpWidget(
|
||||
viewportHost(controller: controller, child: viewportTargets([])),
|
||||
);
|
||||
await settleViewport(tester);
|
||||
|
||||
const focal = Offset(150, 120);
|
||||
final before = controller.transformation.toScene(focal);
|
||||
await pinchViewport(tester, focal, 1.6);
|
||||
await tester.pumpAndSettle();
|
||||
final after = controller.transformation.toScene(focal);
|
||||
// A gesture is not pixel-exact: the focal point keeps its graph point
|
||||
// within a few graph pixels while the transform scales.
|
||||
expect(after.dx, closeTo(before.dx, 4));
|
||||
expect(after.dy, closeTo(before.dy, 4));
|
||||
expect(controller.scale, greaterThan(0.3));
|
||||
});
|
||||
|
||||
testWidgets('the first painted frame is already fitted', (tester) async {
|
||||
final controller = GraphViewportController();
|
||||
addTearDown(controller.dispose);
|
||||
// No extra pump: the fit must land during the first layout, not one frame
|
||||
// later over an identity transform.
|
||||
await tester.pumpWidget(
|
||||
viewportHost(controller: controller, child: viewportTargets([])),
|
||||
);
|
||||
|
||||
expect(
|
||||
controller.scale,
|
||||
closeTo(graphFitScale(defaultViewportSize, viewportContent), 1e-9),
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('the fit control restores the fitted scale and offset', (
|
||||
tester,
|
||||
) async {
|
||||
final controller = GraphViewportController();
|
||||
addTearDown(controller.dispose);
|
||||
await tester.pumpWidget(
|
||||
viewportHost(controller: controller, child: viewportTargets([])),
|
||||
);
|
||||
await settleViewport(tester);
|
||||
final fitted = controller.snapshot;
|
||||
|
||||
await pinchViewport(tester, const Offset(200, 150), 2);
|
||||
await dragViewport(
|
||||
tester,
|
||||
find.byKey(const Key('graph-viewport')),
|
||||
const Offset(-30, -10),
|
||||
);
|
||||
expect(controller.snapshot, isNot(fitted));
|
||||
|
||||
await tester.tap(find.byKey(const Key('graph-fit')));
|
||||
await tester.pump();
|
||||
expect(controller.scale, closeTo(fitted.scale, 1e-9));
|
||||
expect(controller.offset.dx, closeTo(fitted.offset.dx, 1e-9));
|
||||
expect(controller.offset.dy, closeTo(fitted.offset.dy, 1e-9));
|
||||
});
|
||||
|
||||
testWidgets('a tap selects the node visually under the pointer', (
|
||||
tester,
|
||||
) async {
|
||||
final picked = <String>[];
|
||||
final controller = GraphViewportController();
|
||||
addTearDown(controller.dispose);
|
||||
await tester.pumpWidget(
|
||||
viewportHost(controller: controller, child: viewportTargets(picked)),
|
||||
);
|
||||
await settleViewport(tester);
|
||||
|
||||
// Bring target b to the middle, then zoom in around it. Its graph point
|
||||
// stays under the focal point while the transform scales.
|
||||
const targetCenter = Offset(980, 740);
|
||||
final finder = find.byKey(const Key('graph-viewport'));
|
||||
final gesture = await startViewportDrag(tester, finder);
|
||||
final start = viewportScreenOf(controller, targetCenter);
|
||||
final delta = const Offset(200, 150) - start;
|
||||
for (var step = 0; step < 4; step += 1) {
|
||||
await gesture.moveBy(delta / 4);
|
||||
await tester.pump();
|
||||
}
|
||||
await gesture.up();
|
||||
await tester.pumpAndSettle();
|
||||
await pinchViewport(tester, const Offset(200, 150), 2.4);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final underPointer = viewportScreenOf(controller, targetCenter);
|
||||
final viewportRect = tester.getRect(
|
||||
find.byKey(const Key('graph-viewport')),
|
||||
);
|
||||
expect(viewportRect.contains(underPointer), isTrue);
|
||||
expect(controller.scale, greaterThan(0.3));
|
||||
|
||||
await tester.tapAt(viewportGlobal(tester, underPointer));
|
||||
await tester.pump();
|
||||
expect(picked, ['b']);
|
||||
});
|
||||
|
||||
testWidgets('an ancestor scroll view keeps scrolling outside the canvas', (
|
||||
tester,
|
||||
) async {
|
||||
final controller = GraphViewportController();
|
||||
final scroll = ScrollController();
|
||||
addTearDown(controller.dispose);
|
||||
addTearDown(scroll.dispose);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ListView(
|
||||
controller: scroll,
|
||||
children: [
|
||||
Container(key: const Key('scroll-header'), height: 400),
|
||||
SizedBox(
|
||||
height: 300,
|
||||
child: GraphViewport(
|
||||
controller: controller,
|
||||
contentSize: viewportContent,
|
||||
child: viewportTargets([]),
|
||||
),
|
||||
),
|
||||
Container(height: 800),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await settleViewport(tester);
|
||||
|
||||
// A drag outside the canvas scrolls the ancestor and never pans the graph.
|
||||
await tester.dragFrom(const Offset(400, 60), const Offset(0, -120));
|
||||
await tester.pumpAndSettle();
|
||||
expect(scroll.offset, greaterThan(0));
|
||||
final scrolled = scroll.offset;
|
||||
final graphBefore = controller.offset;
|
||||
expect(controller.offset, graphBefore);
|
||||
|
||||
// Inside its own box the canvas consumes the drag: the graph pans and the
|
||||
// list keeps its position.
|
||||
await dragViewport(
|
||||
tester,
|
||||
find.byKey(const Key('graph-viewport')),
|
||||
const Offset(-40, 0),
|
||||
warmUp: const Offset(-10, 0),
|
||||
);
|
||||
expect(scroll.offset, scrolled);
|
||||
expect(controller.offset.dx, lessThan(graphBefore.dx));
|
||||
|
||||
// Scrolling outside still works afterwards and leaves the graph place alone.
|
||||
final panned = controller.offset;
|
||||
await tester.dragFrom(const Offset(400, 60), const Offset(0, -80));
|
||||
await tester.pumpAndSettle();
|
||||
expect(scroll.offset, greaterThan(scrolled));
|
||||
expect(controller.offset, panned);
|
||||
});
|
||||
}
|
||||
@@ -82,6 +82,22 @@ Finder _node(String key) => find.byWidgetPredicate(
|
||||
(widget) => widget is GraphStageNode && widget.node.key == key,
|
||||
);
|
||||
|
||||
/// The graph-space extent of a placed node.
|
||||
///
|
||||
/// The viewport fits the measured graph into the available box, so an onstage
|
||||
/// node's rectangle is its measured extent times the current scale. Dividing
|
||||
/// the rectangle by that scale keeps these assertions about measurement rather
|
||||
/// than about the viewport transform.
|
||||
Size _measuredNodeSize(WidgetTester tester, String key) {
|
||||
final scale = tester
|
||||
.widget<InteractiveViewer>(find.byType(InteractiveViewer))
|
||||
.transformationController!
|
||||
.value
|
||||
.getMaxScaleOnAxis();
|
||||
final rect = _nodeRect(tester, key);
|
||||
return Size(rect.width / scale, rect.height / scale);
|
||||
}
|
||||
|
||||
Rect _nodeRect(WidgetTester tester, String key) => tester.getRect(_node(key));
|
||||
|
||||
Future<void> _tapNode(WidgetTester tester, String key) async {
|
||||
@@ -123,11 +139,11 @@ void main() {
|
||||
addTearDown(tester.view.reset);
|
||||
await tester.pumpWidget(_materialHost(_longKeyGraph()));
|
||||
await _settle(tester);
|
||||
final wide = _nodeRect(tester, _longKey);
|
||||
final wide = _measuredNodeSize(tester, _longKey);
|
||||
tester.view.physicalSize = const Size(320, 700);
|
||||
await tester.pump();
|
||||
await _settle(tester);
|
||||
final narrow = _nodeRect(tester, _longKey);
|
||||
final narrow = _measuredNodeSize(tester, _longKey);
|
||||
expect(narrow.width, lessThan(wide.width));
|
||||
expect(narrow.width, lessThanOrEqualTo(320));
|
||||
expect(narrow.height, greaterThan(wide.height));
|
||||
@@ -156,6 +172,42 @@ void main() {
|
||||
expect(picked, ['plan', '#success']);
|
||||
});
|
||||
|
||||
testWidgets('a tap after zoom selects the node under the pointer', (
|
||||
tester,
|
||||
) async {
|
||||
final picked = <String>[];
|
||||
await tester.pumpWidget(
|
||||
_materialHost(linearGraph(), onSelected: picked.add),
|
||||
);
|
||||
await _settle(tester);
|
||||
final controller = tester
|
||||
.widget<InteractiveViewer>(find.byType(InteractiveViewer))
|
||||
.transformationController!;
|
||||
final fitted = controller.value.getMaxScaleOnAxis();
|
||||
|
||||
// Scale about the node's own on-screen point, as a pinch there would.
|
||||
final viewportRect = tester.getRect(find.byType(InteractiveViewer));
|
||||
final anchor = _nodeRect(tester, 'build').center - viewportRect.topLeft;
|
||||
final zoom = Matrix4.identity()
|
||||
..translateByDouble(anchor.dx, anchor.dy, 0, 1)
|
||||
..scaleByDouble(1.6, 1.6, 1.6, 1)
|
||||
..translateByDouble(-anchor.dx, -anchor.dy, 0, 1);
|
||||
controller.value = zoom * controller.value;
|
||||
await tester.pump();
|
||||
expect(controller.value.getMaxScaleOnAxis(), greaterThan(fitted));
|
||||
|
||||
// The node's on-screen rectangle already carries the transform, so this
|
||||
// tap lands where the node is drawn rather than at its graph coordinate.
|
||||
final build = _nodeRect(tester, 'build');
|
||||
expect(
|
||||
tester.getRect(find.byType(InteractiveViewer)).contains(build.center),
|
||||
isTrue,
|
||||
);
|
||||
await tester.tapAt(build.center);
|
||||
await tester.pump();
|
||||
expect(picked, ['build']);
|
||||
});
|
||||
|
||||
testWidgets('nodes use measured native sizes and never overlap', (
|
||||
tester,
|
||||
) async {
|
||||
@@ -194,13 +246,13 @@ void main() {
|
||||
final graph = linearGraph();
|
||||
await tester.pumpWidget(_materialHost(graph));
|
||||
await _settle(tester);
|
||||
final oneX = _nodeRect(tester, 'plan');
|
||||
final oneX = _measuredNodeSize(tester, 'plan');
|
||||
final oneXLabel = tester.getRect(find.text('error*'));
|
||||
|
||||
await tester.pumpWidget(_materialHost(graph, scale: 2));
|
||||
await _settle(tester);
|
||||
|
||||
final twoX = _nodeRect(tester, 'plan');
|
||||
final twoX = _measuredNodeSize(tester, 'plan');
|
||||
expect(twoX.height, greaterThan(oneX.height));
|
||||
expect(twoX.width, greaterThan(oneX.width));
|
||||
expect(
|
||||
@@ -248,7 +300,13 @@ void main() {
|
||||
);
|
||||
await _settle(tester);
|
||||
|
||||
expect(find.byType(CupertinoButton), findsNWidgets(5));
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byType(GraphStageNode),
|
||||
matching: find.byType(CupertinoButton),
|
||||
),
|
||||
findsNWidgets(5),
|
||||
);
|
||||
expect(find.byType(Card), findsNothing);
|
||||
_expectNoOverlaps(tester);
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
|
||||
import 'package:pipelines_app/features/graph/viewport/graph_expanded_view.dart';
|
||||
import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
|
||||
import 'package:pipelines_app/features/graph/widgets/run_graph_canvas.dart';
|
||||
import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart';
|
||||
@@ -203,6 +204,24 @@ void main() {
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('the expanded run graph keeps the route legend', (tester) async {
|
||||
await tester.pumpWidget(_materialHost(linearGraph(), _runningRun()));
|
||||
await _settle(tester);
|
||||
await tester.tap(find.byKey(const Key('graph-expand')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final expanded = find.byType(GraphExpandedView);
|
||||
expect(expanded, findsOneWidget);
|
||||
for (final label in [runGraphExecuted, runGraphNotExecuted]) {
|
||||
expect(
|
||||
find.descendant(of: expanded, matching: find.text(label)),
|
||||
findsOneWidget,
|
||||
reason: 'the full-screen canvas must explain its routes: $label',
|
||||
);
|
||||
}
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('only routes the run took are executed and labelled', (
|
||||
tester,
|
||||
) async {
|
||||
@@ -439,7 +458,13 @@ void main() {
|
||||
await _settle(tester);
|
||||
|
||||
expect(find.byType(Card), findsNothing);
|
||||
expect(find.byType(CupertinoButton), findsNWidgets(5));
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byType(GraphStageNode),
|
||||
matching: find.byType(CupertinoButton),
|
||||
),
|
||||
findsNWidgets(5),
|
||||
);
|
||||
expect(find.text(runGraphExecuted), findsOneWidget);
|
||||
expect(find.text(runGraphNotExecuted), findsOneWidget);
|
||||
expect(
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
// Isolated browser fixture for the graph viewport (pan/zoom/expanded).
|
||||
//
|
||||
// Build and probe (from app/):
|
||||
// flutter build web -t tool/graph_zoom_probe.dart \
|
||||
// --output build/probe-graph-zoom
|
||||
// PROBE_VARIANT=material OPENCODE_ARTIFACT_DIR=DIR node tool/graph_zoom_probe.mjs
|
||||
//
|
||||
// Server-shaped fixtures only; no server, run or operator session is touched.
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart';
|
||||
import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart';
|
||||
|
||||
const String _longKey = 'implementer-with-an-unusually-long-stage-label';
|
||||
|
||||
JsonMap _definition() => <String, dynamic>{
|
||||
'name': 'Viewport probe',
|
||||
'stages': <dynamic>[
|
||||
<String, dynamic>{
|
||||
'key': 'plan',
|
||||
'type': 'model',
|
||||
'edges': <String, String?>{'success': 'build', 'error': '#'},
|
||||
'fallback_error': true,
|
||||
},
|
||||
<String, dynamic>{
|
||||
'key': 'build',
|
||||
'type': 'model',
|
||||
'edges': <String, String?>{'success': _longKey, 'retry': 'build'},
|
||||
},
|
||||
<String, dynamic>{
|
||||
'key': _longKey,
|
||||
'type': 'model',
|
||||
'edges': <String, String?>{'success': 'audit', 'blocked': '#failure'},
|
||||
},
|
||||
<String, dynamic>{
|
||||
'key': 'audit',
|
||||
'type': 'model',
|
||||
'edges': <String, String?>{'success': '#success', 'error': '#failure'},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
JsonMap _run() => <String, dynamic>{
|
||||
'id': 701,
|
||||
'title': 'Viewport probe',
|
||||
'status': 'succeeded',
|
||||
'executing': false,
|
||||
'graph': _definition(),
|
||||
'steps': <dynamic>[
|
||||
<String, dynamic>{
|
||||
'stage': 'plan',
|
||||
'sequence': 1,
|
||||
'status': 'completed',
|
||||
'outcome': 'success',
|
||||
'target': 'build',
|
||||
},
|
||||
<String, dynamic>{
|
||||
'stage': 'build',
|
||||
'sequence': 2,
|
||||
'status': 'completed',
|
||||
'outcome': 'success',
|
||||
'target': _longKey,
|
||||
},
|
||||
],
|
||||
'current_stage': '',
|
||||
};
|
||||
|
||||
void main() {
|
||||
final parameters = Uri.base.queryParameters;
|
||||
runApp(
|
||||
_ProbeApp(
|
||||
runMode: parameters['view'] == 'run',
|
||||
cupertino: parameters['style'] == 'cupertino',
|
||||
scale: double.tryParse(parameters['scale'] ?? '') ?? 1,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _ProbeApp extends StatelessWidget {
|
||||
const _ProbeApp({
|
||||
required this.runMode,
|
||||
required this.cupertino,
|
||||
required this.scale,
|
||||
});
|
||||
|
||||
final bool runMode;
|
||||
final bool cupertino;
|
||||
final double scale;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final page = _ProbePage(runMode: runMode, scale: scale);
|
||||
if (cupertino) {
|
||||
return CupertinoApp(
|
||||
theme: const CupertinoThemeData(brightness: Brightness.dark),
|
||||
home: CupertinoPageScaffold(
|
||||
navigationBar: const CupertinoNavigationBar(
|
||||
middle: Text('Graph viewport'),
|
||||
),
|
||||
child: SafeArea(child: page),
|
||||
),
|
||||
);
|
||||
}
|
||||
return MaterialApp(
|
||||
theme: ThemeData(platform: TargetPlatform.android),
|
||||
darkTheme: ThemeData(
|
||||
platform: TargetPlatform.android,
|
||||
brightness: Brightness.dark,
|
||||
),
|
||||
themeMode: ThemeMode.system,
|
||||
home: Scaffold(
|
||||
appBar: AppBar(title: const Text('Graph viewport')),
|
||||
body: SafeArea(child: page),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ProbePage extends StatefulWidget {
|
||||
const _ProbePage({required this.runMode, required this.scale});
|
||||
|
||||
final bool runMode;
|
||||
final double scale;
|
||||
|
||||
@override
|
||||
State<_ProbePage> createState() => _ProbePageState();
|
||||
}
|
||||
|
||||
class _ProbePageState extends State<_ProbePage> {
|
||||
String? _selected = 'build';
|
||||
|
||||
void _select(String key) => setState(() => _selected = key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final runMode = widget.runMode;
|
||||
final view = runMode
|
||||
? RunGraphView(
|
||||
graph: _definition(),
|
||||
run: _run(),
|
||||
selectedStage: _selected,
|
||||
onStageSelected: _select,
|
||||
)
|
||||
: DefinitionGraphView(
|
||||
graph: _definition(),
|
||||
selectedStage: _selected,
|
||||
onSelected: _select,
|
||||
);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Selected: ${_selected ?? 'none'}'),
|
||||
const SizedBox(height: 8),
|
||||
Expanded(
|
||||
child: MediaQuery(
|
||||
data: MediaQuery.of(
|
||||
context,
|
||||
).copyWith(textScaler: TextScaler.linear(widget.scale)),
|
||||
child: view,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
// Real-browser acceptance for the graph viewport (pan, zoom, expanded).
|
||||
//
|
||||
// Serves the probe build (`flutter build web -t tool/graph_zoom_probe.dart`) on
|
||||
// an OS-assigned loopback port, drives a real headless Chrome against the
|
||||
// actual DefinitionGraphView / RunGraphView, and asserts that a drag pans, a
|
||||
// wheel zooms, Fit restores the fitted scale, Expand opens the same canvas with
|
||||
// the selected node, and Close returns to the previous place and selection.
|
||||
//
|
||||
// PROBE_VARIANT=material|cupertino PROBE_VIEW=pipeline|run \
|
||||
// PROBE_SCHEME=dark|light PROBE_SCALE=1|2 PROBE_WIDTH=1280 PROBE_HEIGHT=800 \
|
||||
// PROBE_WEB_ROOT=<probe build> OPENCODE_ARTIFACT_DIR=<dir> \
|
||||
// node tool/graph_zoom_probe.mjs
|
||||
import { createServer } from 'node:http';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { join, extname, resolve, sep } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
|
||||
const root = resolve(
|
||||
process.env.PROBE_WEB_ROOT ?? join(process.cwd(), 'build/probe-graph-zoom'),
|
||||
);
|
||||
const variant = process.env.PROBE_VARIANT ?? 'material';
|
||||
const view = process.env.PROBE_VIEW ?? 'pipeline';
|
||||
const scheme = process.env.PROBE_SCHEME ?? 'dark';
|
||||
const scale = process.env.PROBE_SCALE ?? '1';
|
||||
const width = Number(process.env.PROBE_WIDTH ?? 1280);
|
||||
const height = Number(process.env.PROBE_HEIGHT ?? 800);
|
||||
const artifactDir =
|
||||
process.env.OPENCODE_ARTIFACT_DIR ?? join(tmpdir(), 'graph-zoom-capture');
|
||||
const chromePath =
|
||||
process.env.CHROME_PATH ??
|
||||
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
|
||||
const title = view === 'run' ? 'Run graph' : 'Pipeline graph';
|
||||
const prefix = `${view}-${variant}-${scheme}-${scale}x-${width}x${height}`;
|
||||
const mime = {
|
||||
'.html': 'text/html',
|
||||
'.js': 'text/javascript',
|
||||
'.json': 'application/json',
|
||||
'.wasm': 'application/wasm',
|
||||
'.png': 'image/png',
|
||||
'.ico': 'image/x-icon',
|
||||
'.otf': 'font/otf',
|
||||
'.ttf': 'font/ttf',
|
||||
};
|
||||
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
const path = resolve(
|
||||
root,
|
||||
'.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname),
|
||||
);
|
||||
if (path !== root && !path.startsWith(root + sep)) {
|
||||
return res.writeHead(403).end();
|
||||
}
|
||||
const filePath =
|
||||
path === root || path.endsWith('/') ? join(path, 'index.html') : path;
|
||||
const file = await readFile(filePath);
|
||||
res
|
||||
.writeHead(200, {
|
||||
'content-type': mime[extname(filePath)] ?? 'application/octet-stream',
|
||||
})
|
||||
.end(file);
|
||||
} catch {
|
||||
res.writeHead(404).end('not found');
|
||||
}
|
||||
});
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
const port = server.address().port;
|
||||
const profile = await mkdtemp(join(tmpdir(), 'graph-zoom-chrome-'));
|
||||
const chrome = spawn(
|
||||
chromePath,
|
||||
[
|
||||
'--headless=new',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--disable-gpu',
|
||||
'--remote-debugging-port=0',
|
||||
`--user-data-dir=${profile}`,
|
||||
'about:blank',
|
||||
],
|
||||
{ stdio: ['ignore', 'ignore', 'pipe'] },
|
||||
);
|
||||
let stderr = '';
|
||||
chrome.stderr.on('data', (data) => {
|
||||
stderr += data;
|
||||
});
|
||||
const waitFor = async (fn) => {
|
||||
for (let i = 0; i < 120; i++) {
|
||||
const value = await fn();
|
||||
if (value) return value;
|
||||
await delay(100);
|
||||
}
|
||||
throw new Error('Timed out waiting for Chrome DevTools');
|
||||
};
|
||||
|
||||
let ws;
|
||||
try {
|
||||
const endpoint = await waitFor(() =>
|
||||
stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1],
|
||||
);
|
||||
ws = new WebSocket(endpoint);
|
||||
await once(ws, 'open');
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
ws.addEventListener('message', (event) => {
|
||||
const msg = JSON.parse(event.data);
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
pending.get(msg.id)(msg);
|
||||
pending.delete(msg.id);
|
||||
}
|
||||
});
|
||||
const send = (method, params = {}, sessionId) =>
|
||||
new Promise((done) => {
|
||||
const callId = ++id;
|
||||
pending.set(callId, done);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
id: callId,
|
||||
method,
|
||||
params,
|
||||
...(sessionId ? { sessionId } : {}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
const created = await send('Target.createTarget', { url: 'about:blank' });
|
||||
const target = created.result.targetId;
|
||||
const session = (
|
||||
await send('Target.attachToTarget', { targetId: target, flatten: true })
|
||||
).result.sessionId;
|
||||
await send('Page.enable', {}, session);
|
||||
await send('Runtime.enable', {}, session);
|
||||
await send(
|
||||
'Emulation.setEmulatedMedia',
|
||||
{ features: [{ name: 'prefers-color-scheme', value: scheme }] },
|
||||
session,
|
||||
);
|
||||
const url =
|
||||
`http://127.0.0.1:${port}/?style=${variant}&view=${view}` +
|
||||
`&scale=${scale}`;
|
||||
const navigation = await send('Page.navigate', { url }, session);
|
||||
if (navigation.error || navigation.result?.errorText) {
|
||||
throw new Error(JSON.stringify(navigation));
|
||||
}
|
||||
await send(
|
||||
'Emulation.setDeviceMetricsOverride',
|
||||
{ width, height, deviceScaleFactor: 1, mobile: width < 600 },
|
||||
session,
|
||||
);
|
||||
const evaluate = async (expression) => {
|
||||
const response = await send(
|
||||
'Runtime.evaluate',
|
||||
{ expression, returnByValue: true, awaitPromise: true },
|
||||
session,
|
||||
);
|
||||
if (response.error) {
|
||||
throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`);
|
||||
}
|
||||
return response.result?.result?.value;
|
||||
};
|
||||
await delay(4000);
|
||||
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
||||
await delay(2000);
|
||||
|
||||
const semantics = () =>
|
||||
evaluate(
|
||||
"[...document.querySelectorAll('flt-semantics')].map(x=>({label:(x.getAttribute('aria-label')||x.innerText||'').trim(), current:x.getAttribute('aria-current')}))",
|
||||
);
|
||||
const nodeAt = (needle) =>
|
||||
`[...document.querySelectorAll('flt-semantics')].find(x => { const l=(x.getAttribute('aria-label')||x.innerText||'').trim(); return l === ${JSON.stringify(needle)} || l.startsWith(${JSON.stringify(needle + ' ')}) || l.startsWith(${JSON.stringify(needle + '\n')}); })`;
|
||||
const rectOf = async (needle) =>
|
||||
evaluate(
|
||||
`(() => { const e=${nodeAt(needle)}; if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()`,
|
||||
);
|
||||
const clickLabel = async (label, startsWith = false) => {
|
||||
const point = await evaluate(
|
||||
`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => { const l=(x.getAttribute('aria-label')||x.innerText||'').trim(); return ${startsWith ? `l.startsWith(${JSON.stringify(label)})` : `l === ${JSON.stringify(label)}`}; }); if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`,
|
||||
);
|
||||
if (!point) throw new Error(`No semantics control ${label}`);
|
||||
await send(
|
||||
'Input.dispatchMouseEvent',
|
||||
{ type: 'mousePressed', ...point, button: 'left', clickCount: 1 },
|
||||
session,
|
||||
);
|
||||
await send(
|
||||
'Input.dispatchMouseEvent',
|
||||
{ type: 'mouseReleased', ...point, button: 'left', clickCount: 1 },
|
||||
session,
|
||||
);
|
||||
await delay(700);
|
||||
};
|
||||
// Activates the control through its own semantics DOM element, the path a
|
||||
// screen reader uses. A labelled node without a tap action does nothing.
|
||||
const semanticsClick = async (label) => {
|
||||
const clicked = await evaluate(
|
||||
`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => { const l=(x.getAttribute('aria-label')||x.innerText||'').trim(); return l === ${JSON.stringify(label)}; }); if (!e) return false; e.click(); return true; })()`,
|
||||
);
|
||||
if (!clicked) throw new Error(`No semantics control ${label}`);
|
||||
await delay(700);
|
||||
};
|
||||
const drag = async (start, dx, dy) => {
|
||||
await send(
|
||||
'Input.dispatchMouseEvent',
|
||||
{ type: 'mousePressed', ...start, button: 'left', buttons: 1, clickCount: 1 },
|
||||
session,
|
||||
);
|
||||
for (let step = 1; step <= 8; step += 1) {
|
||||
await send(
|
||||
'Input.dispatchMouseEvent',
|
||||
{
|
||||
type: 'mouseMoved',
|
||||
x: start.x + (dx * step) / 8,
|
||||
y: start.y + (dy * step) / 8,
|
||||
button: 'left',
|
||||
buttons: 1,
|
||||
},
|
||||
session,
|
||||
);
|
||||
await delay(30);
|
||||
}
|
||||
await send(
|
||||
'Input.dispatchMouseEvent',
|
||||
{
|
||||
type: 'mouseReleased',
|
||||
x: start.x + dx,
|
||||
y: start.y + dy,
|
||||
button: 'left',
|
||||
clickCount: 1,
|
||||
},
|
||||
session,
|
||||
);
|
||||
await delay(500);
|
||||
};
|
||||
const wheel = async (point, deltaY) => {
|
||||
await send(
|
||||
'Input.dispatchMouseEvent',
|
||||
{ type: 'mouseWheel', ...point, deltaX: 0, deltaY },
|
||||
session,
|
||||
);
|
||||
await delay(600);
|
||||
};
|
||||
const capture = async (name) => {
|
||||
const data = (
|
||||
await send(
|
||||
'Page.captureScreenshot',
|
||||
{ format: 'png', captureBeyondViewport: false },
|
||||
session,
|
||||
)
|
||||
).result.data;
|
||||
const file = `${prefix}-${name}.png`;
|
||||
await writeFile(`${artifactDir}/${file}`, Buffer.from(data, 'base64'));
|
||||
return file;
|
||||
};
|
||||
const currentSelection = async () => {
|
||||
const items = await semantics();
|
||||
const current = items.find((item) => item.current === 'true');
|
||||
if (!current) throw new Error(`No selected node announced: ${JSON.stringify(items)}`);
|
||||
return current.label;
|
||||
};
|
||||
const body = await evaluate('document.body.innerText');
|
||||
if (!body.includes('Selected: build')) {
|
||||
throw new Error(`Initial selection missing: ${body}`);
|
||||
}
|
||||
const selected = await currentSelection();
|
||||
if (!selected.startsWith('build')) {
|
||||
throw new Error(`build is not announced selected: ${selected}`);
|
||||
}
|
||||
const initial = await rectOf('build');
|
||||
if (!initial || initial.width <= 0) throw new Error('build node is not visible');
|
||||
const captures = [await capture('initial')];
|
||||
|
||||
// Pan: a real drag inside the canvas moves the node.
|
||||
const start = { x: width / 2, y: height * 0.6 };
|
||||
await drag(start, 80, 40);
|
||||
const panned = await rectOf('build');
|
||||
if (
|
||||
!panned ||
|
||||
(Math.abs(panned.x - initial.x) < 20 && Math.abs(panned.y - initial.y) < 20)
|
||||
) {
|
||||
throw new Error(`Drag did not pan: ${JSON.stringify({ initial, panned })}`);
|
||||
}
|
||||
captures.push(await capture('panned'));
|
||||
if (!(await currentSelection()).startsWith('build')) {
|
||||
throw new Error('Panning lost the selected node');
|
||||
}
|
||||
|
||||
// Zoom: the host wheel zooms about the pointer.
|
||||
await wheel(
|
||||
{ x: panned.x + panned.width / 2, y: panned.y + panned.height / 2 },
|
||||
-120,
|
||||
);
|
||||
const zoomed = await rectOf('build');
|
||||
if (!zoomed || zoomed.width <= panned.width * 1.05) {
|
||||
throw new Error(`Wheel did not zoom: ${JSON.stringify({ panned, zoomed })}`);
|
||||
}
|
||||
captures.push(await capture('zoomed'));
|
||||
if (!(await currentSelection()).startsWith('build')) {
|
||||
throw new Error('Zooming lost the selected node');
|
||||
}
|
||||
|
||||
// Fit restores the fitted scale. This activation goes through the control's
|
||||
// semantics element, so a labelled button with no tap action fails here (the
|
||||
// Cupertino regression).
|
||||
await semanticsClick('Fit graph to view');
|
||||
const fitted = await rectOf('build');
|
||||
if (!fitted || Math.abs(fitted.width - initial.width) > initial.width * 0.03) {
|
||||
throw new Error(`Fit did not restore: ${JSON.stringify({ initial, fitted })}`);
|
||||
}
|
||||
captures.push(await capture('fitted'));
|
||||
|
||||
// Expanded opens the same canvas with the same selection.
|
||||
const beforeExpand = await rectOf('build');
|
||||
await clickLabel('Expand graph');
|
||||
const expandedBody = await evaluate('document.body.innerText');
|
||||
if (!expandedBody.includes(title)) {
|
||||
throw new Error(`Expanded title missing: ${expandedBody}`);
|
||||
}
|
||||
const expandedSelection = await currentSelection();
|
||||
if (!expandedSelection.startsWith('build')) {
|
||||
throw new Error(`Expanded lost the selection: ${expandedSelection}`);
|
||||
}
|
||||
if (!(await rectOf('build'))) {
|
||||
throw new Error('Expanded canvas did not draw the graph');
|
||||
}
|
||||
captures.push(await capture('expanded'));
|
||||
|
||||
// Close returns to the inline canvas, selection and place intact.
|
||||
await clickLabel('Close');
|
||||
const closedBody = await evaluate('document.body.innerText');
|
||||
if (closedBody.includes(title)) {
|
||||
throw new Error(`Expanded presentation stayed open: ${closedBody}`);
|
||||
}
|
||||
if (!(await currentSelection()).startsWith('build')) {
|
||||
throw new Error('Closing the expanded view lost the selected node');
|
||||
}
|
||||
const restored = await rectOf('build');
|
||||
if (
|
||||
!restored ||
|
||||
Math.abs(restored.x - beforeExpand.x) > 2 ||
|
||||
Math.abs(restored.y - beforeExpand.y) > 2
|
||||
) {
|
||||
throw new Error(
|
||||
`Closing did not restore the inline place: ${JSON.stringify({ beforeExpand, restored })}`,
|
||||
);
|
||||
}
|
||||
captures.push(await capture('restored'));
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{ view, variant, scheme, scale, width, height, initial, panned, zoomed, restored, captures },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
if (ws?.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ id: 2147483647, method: 'Browser.close' }));
|
||||
}
|
||||
await Promise.race([once(chrome, 'exit'), delay(3000)]);
|
||||
ws?.close();
|
||||
if (chrome.exitCode === null) chrome.kill('SIGTERM');
|
||||
chrome.stderr.destroy();
|
||||
chrome.unref();
|
||||
await new Promise((done) => {
|
||||
server.close(done);
|
||||
server.closeAllConnections();
|
||||
});
|
||||
await rm(profile, { recursive: true, force: true });
|
||||
}
|
||||
Reference in New Issue
Block a user