feat(app): graph pan, zoom and expanded view

This commit is contained in:
2026-10-22 02:05:20 +01:00
parent d5f24b8259
commit cc7eba59b6
19 changed files with 2622 additions and 200 deletions
@@ -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,
);