Files
pipelines/app/lib/features/runs/ui/run_detail_tabs.dart
T

491 lines
18 KiB
Dart

import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../graph/widgets/run_graph_view.dart';
import '../../artifacts/ui/artifact_gallery_action.dart';
import '../../artifacts/ui/artifact_gallery_page.dart';
import '../../changes/changes.dart';
import 'run_changes_action.dart';
import 'run_detail_content.dart';
import 'run_graph_preview.dart';
import 'run_detail_tab.dart';
import 'run_detail_tab_bodies.dart';
import 'run_detail_tab_strip.dart';
import 'run_detail_timeline.dart';
import 'run_detail_visit.dart';
import 'run_detail_visit_facts.dart';
import 'run_search_selection.dart';
/// The least height the selected tab keeps for its own content.
///
/// A header and tab strip that would leave the tab less than this may scroll
/// instead, so scaled title text or a short window cannot squeeze the Graph
/// canvas away. The Graph view's own legend is one wrapped row pair; this
/// reserve keeps its bounded canvas positive at 320px with 2x text.
const double kRunDetailMinContentHeight = 240;
/// Below this width (a phone) the run detail's tabs sit at the bottom.
const double kRunDetailBottomTabsWidth = 600;
/// The run detail's tabbed body: the host-built header and platform tab strip
/// above the bounded selected tab.
///
/// The Graph tab fills its slot with [RunGraphView] from the run's own pinned
/// graph and recorded steps. A visited stage click selects that stage's latest
/// recorded visit and switches to Timeline, where that visit's pane opens. A
/// node with no recorded visit reports nothing, so no visit is invented.
class RunDetailTabs extends StatefulWidget {
const RunDetailTabs({
super.key,
required this.run,
required this.header,
required this.cupertino,
required this.copying,
required this.copyStatus,
required this.onCopy,
required this.gateway,
required this.onRunChanged,
required this.configuredEndpoint,
this.initialStageKey,
this.initialVisit,
});
final JsonMap run;
/// The host's own header: identity, status and the run actions. It stays
/// outside the tab body, so switching tabs never drops an action.
final Widget header;
final bool cupertino;
final bool copying;
final String? copyStatus;
final VoidCallback onCopy;
/// The shared gateway and accepted-detail fold used by the visit session's
/// export-only repair. Tabs never open their own socket.
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
/// The configured server origin used to resolve a recorded session export
/// through the landed safe-link helper. Blank leaves relative urls unresolved.
final String configuredEndpoint;
/// The stage a `/runs/:id/stage/:key` route names, or null for the plain
/// detail. It selects a recorded visit; a declared but unvisited stage only
/// selects its graph node, so no visit is ever invented.
final String? initialStageKey;
/// The zero-based index among [initialStageKey]'s recorded visits. Null opens
/// the stage's latest visit, exactly as a Graph node click does.
final int? initialVisit;
@override
State<RunDetailTabs> createState() => _RunDetailTabsState();
}
class _RunDetailTabsState extends State<RunDetailTabs> {
RunDetailTab _tab = RunDetailTab.summary;
String? _selectedStage;
int? _selectedVisit;
/// The visit whose page is open, and the live run that page follows.
int? _shownVisit;
Route<void>? _visitRoute;
late final ValueNotifier<JsonMap> _liveRun = ValueNotifier(widget.run);
/// The Summary's collapsible Input and Output sections. A search text hit
/// expands the one its recorded field names, exactly as the browser opens the
/// matching Summary section. The detail owns them so the tab body stays a
/// presentation widget.
final _inputSection = ExpansibleController();
final _outputSection = ExpansibleController();
/// The search request last applied by this detail, so a rebuild of the same
/// request never reopens a pane the operator closed in the meantime.
RunSearchSelection? _appliedSearchSelection;
@override
void initState() {
super.initState();
_applyInitialVisit();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_applySearchSelection();
}
@override
void dispose() {
_inputSection.dispose();
_outputSection.dispose();
_liveRun.dispose();
super.dispose();
}
@override
void didUpdateWidget(covariant RunDetailTabs oldWidget) {
super.didUpdateWidget(oldWidget);
_liveRun.value = widget.run;
final sameRun = '${widget.run['id']}' == '${oldWidget.run['id']}';
final sameTarget =
widget.initialStageKey == oldWidget.initialStageKey &&
widget.initialVisit == oldWidget.initialVisit;
// A different run is a different detail: its visits and graph do not carry
// the previous run's selection.
if (!sameRun) {
_tab = RunDetailTab.summary;
_selectedStage = null;
_selectedVisit = null;
_inputSection.collapse();
_outputSection.collapse();
_applyInitialVisit();
} else if (!sameTarget) {
// A route that names another stage or visit is applied to the same run.
// Rebuilds from a live refresh keep the operator's own selection.
_applyInitialVisit();
}
}
/// Opens the visit a route names, without presenting any visit the run did
/// not record.
///
/// A route with a stage key and no visit opens that stage's latest recorded
/// visit, the same visit a Graph node click opens. A valid index selects that
/// visit among the stage's own visits; an out-of-range index is clamped to the
/// stage's last recorded visit, as the web client does, so the address bar and
/// the pane never disagree about which visit is real. A declared but
/// unvisited stage selects its Graph node only.
void _applyInitialVisit() {
final stageKey = widget.initialStageKey;
if (stageKey == null || stageKey.isEmpty) {
_selectedStage = null;
_selectedVisit = null;
return;
}
final index = routeDetailVisitIndex(
widget.run['steps'],
stageKey,
widget.initialVisit,
);
if (index != null) {
_selectedStage = stageKey;
_selectedVisit = index;
_tab = RunDetailTab.timeline;
return;
}
_selectedVisit = null;
// The key is not a recorded visit. Only a stage the pinned graph actually
// declares can be selected; anything else leaves the plain detail intact.
if (detailVisitHasDefinition(detailGraph(widget.run), stageKey)) {
// The Summary's graph preview shows the selected stage.
_selectedStage = stageKey;
_tab = RunDetailTab.summary;
} else {
_selectedStage = null;
}
}
/// Selects the Summary section or recorded visit a search result names.
///
/// The request is applied once per loaded run and is consumed afterwards. A
/// retired or unknown field still selects the plain Summary, exactly as the
/// browser's `searchFieldTab` does, and a visit the run did not record falls
/// back to the plain Summary, so no stale hit leaves an unrelated pane open.
void _applySearchSelection() {
final scope = RunSearchSelectionScope.maybeOf(context);
final selection = scope?.selection;
if (scope == null || selection == null) {
_appliedSearchSelection = null;
return;
}
if (selection == _appliedSearchSelection) return;
final id = widget.run['id'];
if (id is! num || id.toInt() != selection.runId) return;
_appliedSearchSelection = selection;
_selectSearchTarget(resolveRunSearchSelection(selection, widget.run));
final consumed = scope.onConsumed;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) consumed();
});
}
void _selectSearchTarget(RunSearchTarget target) {
switch (target) {
case RunSummaryTarget(:final section):
_tab = RunDetailTab.summary;
_selectedStage = null;
_selectedVisit = null;
switch (section) {
case RunSummarySection.input:
_inputSection.expand();
case RunSummarySection.output:
_outputSection.expand();
case null:
// A hit that names no section must not leave a previously expanded
// one open; the Summary panel starts collapsed.
_inputSection.collapse();
_outputSection.collapse();
}
case RunVisitTarget(:final stageKey, :final timelineIndex):
if (detailVisitStepAt(widget.run, timelineIndex) == null) return;
_selectedStage = stageKey;
_selectedVisit = timelineIndex;
_tab = RunDetailTab.timeline;
}
}
/// Selects the stage's latest recorded visit. An unvisited stage has none,
/// so the detail stays where it is rather than fabricating a visit.
void _openStage(String stageKey) {
final index = latestDetailVisitIndex(widget.run['steps'], stageKey);
if (index == null) return;
setState(() {
_selectedStage = stageKey;
_selectedVisit = index;
_tab = RunDetailTab.timeline;
});
}
/// Opens one recorded timeline row. The row index is also the index into the
/// detail's own steps, so the pane reads exactly the visit it came from.
void _openVisit(int index) {
if (detailVisitStepAt(widget.run, index) == null) return;
setState(() => _selectedVisit = index);
}
/// Brings the open visit page in line with the selection after this frame:
/// a cleared selection closes it, another visit replaces it.
void _syncVisitPage() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || _selectedVisit == _shownVisit) return;
final open = _visitRoute;
if (open != null) {
_shownVisit = null;
_visitRoute = null;
if (open.isActive) Navigator.of(context).removeRoute(open);
}
final index = _selectedVisit;
if (index != null) _pushVisit(index);
});
}
/// Opens [index]'s visit as its own page. The page follows the live run, so
/// a visit still running keeps updating; leaving it returns to the timeline.
Future<void> _pushVisit(int index) async {
_shownVisit = index;
final cupertino = widget.cupertino;
Widget page(BuildContext pageContext) => ValueListenableBuilder<JsonMap>(
valueListenable: _liveRun,
builder: (context, run, _) {
final visits = detailTimeline(run['steps']);
final step = detailVisitStepAt(run, index);
final pane = index < visits.length && step != null
? RunVisitPane(
run: run,
visit: visits[index],
visitIndex: index,
step: step,
runSteps: detailRunSteps(run),
gateway: widget.gateway,
onRunChanged: widget.onRunChanged,
configuredEndpoint: widget.configuredEndpoint,
cupertino: cupertino,
onClose: () => Navigator.of(pageContext).pop(),
)
: const Center(child: Text('This visit is no longer recorded.'));
// The pane names the visit; the bar names the run it belongs to.
final title = detailTitle(run);
if (cupertino) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
leading: CupertinoNavigationBarBackButton(
key: const Key('run-visit-back'),
onPressed: () => Navigator.of(pageContext).pop(),
),
middle: Text(title),
),
child: SafeArea(child: pane),
);
}
return Scaffold(
appBar: AppBar(
leading: BackButton(
key: const Key('run-visit-back'),
onPressed: () => Navigator.of(pageContext).pop(),
),
title: Text(title),
),
body: SafeArea(top: false, child: pane),
);
},
);
final route = cupertino
? CupertinoPageRoute<void>(builder: page)
: MaterialPageRoute<void>(builder: page);
_visitRoute = route;
await Navigator.of(context).push<void>(route);
// Only the page the operator left clears the selection; one replaced by
// another selection has already handed over.
if (!mounted || _visitRoute != route) return;
setState(() {
_visitRoute = null;
_shownVisit = null;
_selectedVisit = null;
});
}
/// Artifacts once the run has recorded steps; Changes once it has stopped
/// executing, since a snapshot would not follow live captures.
List<RunDetailTab> _tabsFor(JsonMap run) => [
for (final tab in renderedRunDetailTabs)
if (switch (tab) {
RunDetailTab.artifacts => showRunArtifactsAction(run),
RunDetailTab.changes => showRunChangesAction(run),
_ => true,
})
tab,
];
@override
Widget build(BuildContext context) {
// A selected visit opens on its own page; the tab keeps the list.
if (_selectedVisit != _shownVisit) _syncVisitPage();
final tabs = _tabsFor(widget.run);
// A tab the run no longer offers falls back to Summary.
final shown = tabs.contains(_tab) || !renderedRunDetailTabs.contains(_tab)
? _tab
: RunDetailTab.summary;
return LayoutBuilder(
builder: (context, constraints) {
final headerLimit = _headerLimit(constraints);
// On a phone the tabs are a bottom bar, under the content they switch.
final bottomTabs = constraints.maxWidth < kRunDetailBottomTabsWidth;
final strip = RunDetailTabStrip(
tabs: tabs,
selected: shown,
bottom: bottomTabs,
onSelected: (tab) => setState(() => _tab = tab),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ConstrainedBox(
constraints: BoxConstraints(maxHeight: headerLimit),
child: SingleChildScrollView(
key: ValueKey('run-detail-header-${widget.run['id']}'),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [widget.header, if (!bottomTabs) strip],
),
),
),
// Every tab gets the bounded remaining height. The scrolling tabs
// own their content; the Graph tab fills the slot so its canvas is
// never asked for an unbounded extent.
Expanded(
key: ValueKey('run-detail-body-${widget.run['id']}'),
child: _body(shown),
),
if (bottomTabs) SafeArea(top: false, child: strip),
],
);
},
);
}
Widget _body(RunDetailTab tab) {
switch (tab) {
case RunDetailTab.summary:
return runDetailSummaryTab(
context: context,
run: widget.run,
cupertino: widget.cupertino,
copying: widget.copying,
copyStatus: widget.copyStatus,
onCopy: widget.onCopy,
inputController: _inputSection,
outputController: _outputSection,
graphPreview: RunGraphPreview(
graph: detailGraph(widget.run),
run: widget.run,
selectedStage: _selectedStage,
onStageSelected: _openStage,
),
);
case RunDetailTab.graph:
return RunGraphView(
key: const Key('run-detail-graph'),
graph: detailGraph(widget.run),
run: widget.run,
selectedStage: _selectedStage,
onStageSelected: _openStage,
);
case RunDetailTab.input:
return runDetailFieldTab(
tabKey: 'input',
value: widget.run['input'],
empty: 'No input recorded.',
cupertino: widget.cupertino,
);
case RunDetailTab.output:
return runDetailFieldTab(
tabKey: 'output',
value: widget.run['output'],
empty: 'No output recorded.',
cupertino: widget.cupertino,
);
case RunDetailTab.artifacts:
return ArtifactGalleryPage(
key: ValueKey('run-detail-artifacts-${widget.run['id']}'),
steps: runDetailArtifactSteps(widget.run),
executing: runDetailExecuting(widget.run),
configuredEndpoint: widget.configuredEndpoint,
embedded: true,
);
case RunDetailTab.changes:
final viewer = ChangesViewer(
key: ValueKey('run-detail-changes-${widget.run['id']}'),
steps: runDetailChangeSteps(widget.run),
// The tab is the run's final changes; each visit's own are in its
// timeline detail.
showSummary: true,
finalOnly: true,
);
// A CupertinoApp supplies no Material theme; follow the host so the
// viewer's section text stays readable.
return widget.cupertino
? Theme(data: hostTextTheme(context), child: viewer)
: viewer;
case RunDetailTab.timeline:
final visits = detailTimeline(widget.run['steps']);
final index = _selectedVisit;
return RunTimelineList(
visits: visits,
selectedSequence: index != null && index >= 0 && index < visits.length
? visits[index].sequence
: null,
cupertino: widget.cupertino,
onSelected: _openVisit,
);
}
}
/// The header keeps its natural height while at least
/// [kRunDetailMinContentHeight] remains for the tab, and never more than the
/// detail itself; past that it scrolls.
double _headerLimit(BoxConstraints constraints) {
if (!constraints.hasBoundedHeight) return double.infinity;
final height = constraints.maxHeight;
// Below twice the reserve the two shares meet at 40%, so the header stays
// reachable even when the detail is shorter than the reserve itself.
final floorShare = height * 0.4;
final reserve = height - kRunDetailMinContentHeight;
return math.max(floorShare, reserve).clamp(0.0, height);
}
}