import 'package:flutter/widgets.dart'; import '../../core/api_gateway.dart'; import 'data/runs_repository.dart'; import 'ui/run_detail_view.dart'; import 'ui/runs_controller.dart'; import 'ui/runs_list.dart'; /// The runs destination's list/detail switch. /// /// The controller's `selectedRunId` is the only selection source, so an /// initial run, a pending detail, a failed detail, Back and a route change all /// navigate the same way. The shell owns the app bar; this screen adds no /// second one. class RunsScreen extends StatefulWidget { const RunsScreen({ super.key, required this.gateway, this.initialRunId, this.syncToken = 0, this.onRunSelected, this.onBack, }); final ApiGateway gateway; /// The run the current route names, or null for the list. final int? initialRunId; /// Advances when the shared socket is replaced. The loaded screen refreshes /// in place instead of being remounted, so its selection survives. final int syncToken; final ValueChanged? onRunSelected; final VoidCallback? onBack; @override State createState() => _RunsScreenState(); } class _RunsScreenState extends State { late final RunsController controller; num? _shownRunId; @override void initState() { super.initState(); controller = RunsController(RunsRepository(widget.gateway)); controller.listen(widget.gateway.frames); controller.addListener(_selectionChanged); controller.load(widget.initialRunId); } @override void didUpdateWidget(covariant RunsScreen oldWidget) { super.didUpdateWidget(oldWidget); if (widget.syncToken != oldWidget.syncToken) { controller.resync(); } if (widget.initialRunId != oldWidget.initialRunId) { final id = widget.initialRunId; if (id == null) { if (controller.selectedRunId != null) controller.back(); } else if (controller.selectedRunId != id) { controller.select(id); } } } /// Rebuild the switch only when the selection changes. Detail progress and /// live updates are already watched by [RunDetailView] and [RunsList], so /// this avoids a second whole-detail rebuild per notification. void _selectionChanged() { final selected = controller.selectedRunId; if (selected == _shownRunId) return; _shownRunId = selected; if (mounted) setState(() {}); } void _select(num id) { controller.select(id); widget.onRunSelected?.call(id.toInt()); } void _back() { controller.back(); widget.onBack?.call(); } @override void dispose() { controller.removeListener(_selectionChanged); controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final selected = controller.selectedRunId != null; return Stack( children: [ AnimatedBuilder( animation: controller, builder: (context, _) => Offstage( offstage: selected, child: RunsList(controller: controller, onSelected: _select), ), ), if (selected) RunDetailView( controller: controller, gateway: widget.gateway, onBack: _back, ), ], ); } }