Merge: perf round 1 — shared clock, narrower shell rebuilds, quiet run events
This commit is contained in:
@@ -187,12 +187,26 @@ JsonMap? newRunSummaryFromFrame(JsonMap frame) {
|
||||
: (runs: [row, ...runs], needsResync: false);
|
||||
}
|
||||
final updated = _mergeRunFields(runs[index], frame);
|
||||
if (identical(updated, runs[index])) return (runs: runs, needsResync: false);
|
||||
// A frame that repeats the row's state (a busy run's progress stream)
|
||||
// keeps the same list, so its holders can skip a rebuild.
|
||||
if (identical(updated, runs[index]) || _sameFields(updated, runs[index])) {
|
||||
return (runs: runs, needsResync: false);
|
||||
}
|
||||
final next = [...runs];
|
||||
next[index] = updated;
|
||||
return (runs: next, needsResync: false);
|
||||
}
|
||||
|
||||
/// Shallow equality: nested values compare by identity, so a rebuilt nested
|
||||
/// map counts as a change.
|
||||
bool _sameFields(JsonMap a, JsonMap b) {
|
||||
if (a.length != b.length) return false;
|
||||
for (final entry in a.entries) {
|
||||
if (!b.containsKey(entry.key) || b[entry.key] != entry.value) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
JsonMap? foldRunEventDetail(JsonMap? detail, JsonMap frame) {
|
||||
if (detail == null || detail['id'] != frame['run_id']) return detail;
|
||||
if (_stale(detail['status'], frame['status'], runLifecycleRank) &&
|
||||
|
||||
@@ -271,6 +271,7 @@ class RunsController extends ChangeNotifier {
|
||||
void _event(JsonMap frame) {
|
||||
if (_removed.contains(frame['run_id'])) return;
|
||||
final folded = foldRunEvent(runs, frame);
|
||||
final before = (runs: runs, detail: detail);
|
||||
runs = folded.runs;
|
||||
selection.retain(runs);
|
||||
if (detail?['id'] == frame['run_id']) {
|
||||
@@ -285,6 +286,11 @@ class RunsController extends ChangeNotifier {
|
||||
(folded.needsResync || runDetailNeedsFullSync(frame))) {
|
||||
_scheduleDetailRefresh(selected);
|
||||
}
|
||||
// A frame that changed neither the list nor the open detail shows
|
||||
// nothing new; the refreshes above notify for themselves.
|
||||
if (identical(before.runs, runs) && identical(before.detail, detail)) {
|
||||
return;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
|
||||
@@ -146,7 +146,9 @@ class RunsList extends StatelessWidget {
|
||||
RunsDeleteReport(controller: controller),
|
||||
RunsFilters(controller: controller),
|
||||
];
|
||||
if (controller.visibleRuns.isNotEmpty) return _groupedRuns(context, header);
|
||||
// Filtered and sorted once per build: the getter recomputes every read.
|
||||
final visible = controller.visibleRuns;
|
||||
if (visible.isNotEmpty) return _groupedRuns(context, header, visible);
|
||||
return BelowTopBar(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
@@ -169,15 +171,17 @@ class RunsList extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _groupedRuns(BuildContext context, List<Widget> header) {
|
||||
Widget _groupedRuns(
|
||||
BuildContext context,
|
||||
List<Widget> header,
|
||||
List<JsonMap> visible,
|
||||
) {
|
||||
final entries = <_Entry>[];
|
||||
if (flatRunSorts.contains(controller.sort)) {
|
||||
// An order by size is one flat list: day headings would split it.
|
||||
entries.addAll(
|
||||
controller.visibleRuns.map((run) => (day: null, run: run)),
|
||||
);
|
||||
entries.addAll(visible.map((run) => (day: null, run: run)));
|
||||
} else {
|
||||
final groups = groupRunsByDay(controller.visibleRuns, DateTime.now());
|
||||
final groups = groupRunsByDay(visible, DateTime.now());
|
||||
for (final group in groups) {
|
||||
entries.add((day: group, run: null));
|
||||
entries.addAll(group.runs.map((run) => (day: null, run: run)));
|
||||
@@ -185,7 +189,7 @@ class RunsList extends StatelessWidget {
|
||||
}
|
||||
// Runs that start while the list is open enter with a short fade.
|
||||
return ArrivalScope(
|
||||
ids: [for (final run in controller.visibleRuns) '${run['id']}'],
|
||||
ids: [for (final run in visible) '${run['id']}'],
|
||||
child: _entriesList(entries, header),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -140,78 +140,81 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
|
||||
),
|
||||
);
|
||||
}).toList();
|
||||
return ListenableBuilder(
|
||||
listenable: _bar,
|
||||
builder: (context, _) {
|
||||
final spec = _bar.specFor(_selected);
|
||||
// One floating glass tab bar at every width: full width on a phone,
|
||||
// sized to its tabs at the right edge on a wide window (the bar judges
|
||||
// that itself, live). Content keeps the whole width and scrolls behind
|
||||
// it, learning the bar's height as its bottom media padding. Neither
|
||||
// scaffold's structure depends on the width, so resizing never
|
||||
// remounts a destination.
|
||||
//
|
||||
// While the tab shows its list beside an open item the bar keeps
|
||||
// the same place, bottom right near the thumb: the item pane learns
|
||||
// the bar's height (see ListDetailPanes) and floats its own tabs or
|
||||
// composer above it, so the two never overlap.
|
||||
final split = _bar.split(_selected);
|
||||
final bar = FloatingDestinationBar(
|
||||
cupertino: widget.cupertino,
|
||||
currentIndex: index,
|
||||
onTap: (value) => _select(shellTabDestinations[value]),
|
||||
items: _destinationItems(),
|
||||
);
|
||||
// Destinations reach the top edge and scroll behind the floating top
|
||||
// bar too: each learns the bar's height as its top media padding and
|
||||
// pads its own lists by it (see withTopBarClearance).
|
||||
final topBar = _ListPaneBar(
|
||||
split: split,
|
||||
bar: _segmentedBar(spec, details.label, page: page),
|
||||
);
|
||||
// The scaffolds below swap the system insets for their bars'
|
||||
// heights; panes beside a list read the real ones from here.
|
||||
final system = MediaQuery.paddingOf(context);
|
||||
// A page (Settings) closes to Pipelines on the system Back too. The
|
||||
// scope is always there, so opening the page never remounts the shell.
|
||||
Widget backable(Widget child) => PopScope(
|
||||
canPop: !page,
|
||||
onPopInvokedWithResult: (didPop, _) {
|
||||
if (!didPop) _closePage();
|
||||
},
|
||||
child: child,
|
||||
);
|
||||
if (widget.cupertino) {
|
||||
return backable(
|
||||
ShellSystemInsets(
|
||||
padding: system,
|
||||
child: CupertinoPageScaffold(
|
||||
navigationBar: topBar,
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
bottom: false,
|
||||
child: FloatingBarOverlay(
|
||||
bar: bar,
|
||||
child: _destinationStack(contents),
|
||||
),
|
||||
),
|
||||
// Only the bar shows the registry's state, so a published bar or badge
|
||||
// rebuilds its bar alone; the destinations and scaffold stay as built.
|
||||
_bar.focus = _selected;
|
||||
// One floating glass tab bar at every width: full width on a phone,
|
||||
// sized to its tabs at the right edge on a wide window (the bar judges
|
||||
// that itself, live). Content keeps the whole width and scrolls behind
|
||||
// it, learning the bar's height as its bottom media padding. Neither
|
||||
// scaffold's structure depends on the width, so resizing never
|
||||
// remounts a destination.
|
||||
//
|
||||
// While the tab shows its list beside an open item the bar keeps
|
||||
// the same place, bottom right near the thumb: the item pane learns
|
||||
// the bar's height (see ListDetailPanes) and floats its own tabs or
|
||||
// composer above it, so the two never overlap.
|
||||
final bar = ListenableBuilder(
|
||||
listenable: _bar.badges,
|
||||
builder: (context, _) => FloatingDestinationBar(
|
||||
cupertino: widget.cupertino,
|
||||
currentIndex: index,
|
||||
onTap: (value) => _select(shellTabDestinations[value]),
|
||||
items: _destinationItems(),
|
||||
),
|
||||
);
|
||||
// Destinations reach the top edge and scroll behind the floating top
|
||||
// bar too: each learns the bar's height as its top media padding and
|
||||
// pads its own lists by it (see withTopBarClearance).
|
||||
SegmentedBar currentBar() =>
|
||||
_segmentedBar(_bar.specFor(_selected), details.label, page: page);
|
||||
final topBar = _ListPaneBar(
|
||||
listenable: _bar.bar,
|
||||
initial: currentBar(),
|
||||
split: () => _bar.split(_selected),
|
||||
bar: currentBar,
|
||||
);
|
||||
// The scaffolds below swap the system insets for their bars'
|
||||
// heights; panes beside a list read the real ones from here.
|
||||
final system = MediaQuery.paddingOf(context);
|
||||
// A page (Settings) closes to Pipelines on the system Back too. The
|
||||
// scope is always there, so opening the page never remounts the shell.
|
||||
Widget backable(Widget child) => PopScope(
|
||||
canPop: !page,
|
||||
onPopInvokedWithResult: (didPop, _) {
|
||||
if (!didPop) _closePage();
|
||||
},
|
||||
child: child,
|
||||
);
|
||||
if (widget.cupertino) {
|
||||
return backable(
|
||||
ShellSystemInsets(
|
||||
padding: system,
|
||||
child: CupertinoPageScaffold(
|
||||
navigationBar: topBar,
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
bottom: false,
|
||||
child: FloatingBarOverlay(
|
||||
bar: bar,
|
||||
child: _destinationStack(contents),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return backable(
|
||||
ShellSystemInsets(
|
||||
padding: system,
|
||||
child: Scaffold(
|
||||
extendBodyBehindAppBar: true,
|
||||
appBar: topBar,
|
||||
body: _destinationStack(contents),
|
||||
extendBody: true,
|
||||
bottomNavigationBar: bar,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
return backable(
|
||||
ShellSystemInsets(
|
||||
padding: system,
|
||||
child: Scaffold(
|
||||
extendBodyBehindAppBar: true,
|
||||
appBar: topBar,
|
||||
body: _destinationStack(contents),
|
||||
extendBody: true,
|
||||
bottomNavigationBar: bar,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -328,24 +331,38 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
|
||||
/// beside an open item ([ShellPaneSplit]); the item's own bar takes the rest
|
||||
/// of the same row. The bar keeps its place in the scaffold either way, so a
|
||||
/// split never remounts it.
|
||||
///
|
||||
/// It rebuilds itself when [listenable] (the focused destination's published
|
||||
/// bar) changes; [initial] supplies the size and obstruction, which do not
|
||||
/// depend on the published contents.
|
||||
class _ListPaneBar extends StatelessWidget
|
||||
implements ObstructingPreferredSizeWidget {
|
||||
const _ListPaneBar({required this.split, required this.bar});
|
||||
const _ListPaneBar({
|
||||
required this.listenable,
|
||||
required this.initial,
|
||||
required this.split,
|
||||
required this.bar,
|
||||
});
|
||||
|
||||
final bool split;
|
||||
final SegmentedBar bar;
|
||||
final Listenable listenable;
|
||||
final SegmentedBar initial;
|
||||
final bool Function() split;
|
||||
final SegmentedBar Function() bar;
|
||||
|
||||
@override
|
||||
Size get preferredSize => bar.preferredSize;
|
||||
Size get preferredSize => initial.preferredSize;
|
||||
|
||||
@override
|
||||
bool shouldFullyObstruct(BuildContext context) =>
|
||||
bar.shouldFullyObstruct(context);
|
||||
initial.shouldFullyObstruct(context);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListPaneWidth(
|
||||
split: split,
|
||||
alignment: AlignmentDirectional.topStart,
|
||||
child: bar,
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: listenable,
|
||||
builder: (context, _) => ListPaneWidth(
|
||||
split: split(),
|
||||
alignment: AlignmentDirectional.topStart,
|
||||
child: bar(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -53,9 +53,37 @@ class ShellBarSpec {
|
||||
}
|
||||
|
||||
/// The bar contents each tab's open screen has published.
|
||||
///
|
||||
/// It notifies its own listeners of every visible change. A host that shows
|
||||
/// one destination's bar at a time sets [focus] and may listen to [bar] and
|
||||
/// [badges] separately: a hidden tab republishing its bar (a list rebuilding
|
||||
/// on a run event) then rebuilds nothing, and a badge change rebuilds only
|
||||
/// the tab bar.
|
||||
class ShellBarRegistry extends ChangeNotifier {
|
||||
final Map<AppDestination, (Object, ShellBarSpec)> _specs = {};
|
||||
final Map<(AppDestination, ShellBadgeKind), int> _badges = {};
|
||||
final _Notifier _bar = _Notifier();
|
||||
final _Notifier _badgeNotifier = _Notifier();
|
||||
|
||||
/// The destination whose bar is on screen; null treats every destination
|
||||
/// as shown. Bar changes of other destinations are kept without notifying:
|
||||
/// the host rebuilds when it changes the focus.
|
||||
AppDestination? focus;
|
||||
|
||||
/// Notifies when the focused destination's bar spec or split changes.
|
||||
Listenable get bar => _bar;
|
||||
|
||||
/// Notifies when any tab badge count changes.
|
||||
Listenable get badges => _badgeNotifier;
|
||||
|
||||
bool _shown(AppDestination destination) =>
|
||||
focus == null || focus == destination;
|
||||
|
||||
void _barChanged(AppDestination destination) {
|
||||
if (!_shown(destination)) return;
|
||||
_bar.notify();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
final Map<AppDestination, int> _splits = {};
|
||||
|
||||
@@ -68,7 +96,7 @@ class ShellBarRegistry extends ChangeNotifier {
|
||||
if (_disposed) return;
|
||||
final before = split(destination);
|
||||
_splits[destination] = (_splits[destination] ?? 0) + (value ? 1 : -1);
|
||||
if (split(destination) != before) notifyListeners();
|
||||
if (split(destination) != before) _barChanged(destination);
|
||||
}
|
||||
|
||||
/// The count a tab's screen published for [kind], 0 when none.
|
||||
@@ -78,6 +106,7 @@ class ShellBarRegistry extends ChangeNotifier {
|
||||
void _setBadge(AppDestination destination, ShellBadgeKind kind, int count) {
|
||||
if (_disposed || badge(destination, kind) == count) return;
|
||||
_badges[(destination, kind)] = count;
|
||||
_badgeNotifier.notify();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@@ -86,6 +115,8 @@ class ShellBarRegistry extends ChangeNotifier {
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_bar.dispose();
|
||||
_badgeNotifier.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -99,17 +130,21 @@ class ShellBarRegistry extends ChangeNotifier {
|
||||
// A screen's update can land after the shell itself has gone.
|
||||
if (_disposed) return;
|
||||
_specs[destination] = (owner, spec);
|
||||
notifyListeners();
|
||||
_barChanged(destination);
|
||||
}
|
||||
|
||||
void _clear(AppDestination destination, Object owner) {
|
||||
if (_disposed) return;
|
||||
if (_specs[destination]?.$1 != owner) return;
|
||||
_specs.remove(destination);
|
||||
notifyListeners();
|
||||
_barChanged(destination);
|
||||
}
|
||||
}
|
||||
|
||||
class _Notifier extends ChangeNotifier {
|
||||
void notify() => notifyListeners();
|
||||
}
|
||||
|
||||
/// Places one tab's content under the shell's bar registry.
|
||||
class ShellBarScope extends InheritedWidget {
|
||||
const ShellBarScope({
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// One minute clock shared by every relative-time label.
|
||||
///
|
||||
/// A list of rows used to run one timer per row; this clock runs a single
|
||||
/// timer, aligned to the start of each wall-clock minute, only while some
|
||||
/// label listens and the app is visible. Labels re-read [now] when it
|
||||
/// notifies and rebuild only if their text changed.
|
||||
class RelativeTimeClock extends ChangeNotifier with WidgetsBindingObserver {
|
||||
RelativeTimeClock();
|
||||
|
||||
/// The clock the app's labels share.
|
||||
static final RelativeTimeClock shared = RelativeTimeClock();
|
||||
|
||||
DateTime _now = DateTime.now();
|
||||
Timer? _timer;
|
||||
bool _observing = false;
|
||||
bool _hidden = false;
|
||||
|
||||
/// The clock's current minute-resolution time. It advances by the elapsed
|
||||
/// delay on each tick, which keeps it consistent under a fake clock.
|
||||
DateTime get now => _now;
|
||||
|
||||
/// Whether a tick is scheduled (a label listens and the app is visible).
|
||||
@visibleForTesting
|
||||
bool get ticking => _timer != null;
|
||||
|
||||
@override
|
||||
void addListener(VoidCallback listener) {
|
||||
final first = !hasListeners;
|
||||
super.addListener(listener);
|
||||
if (!first) return;
|
||||
_now = DateTime.now();
|
||||
_hidden = switch (WidgetsBinding.instance.lifecycleState) {
|
||||
AppLifecycleState.hidden ||
|
||||
AppLifecycleState.paused ||
|
||||
AppLifecycleState.detached => true,
|
||||
_ => false,
|
||||
};
|
||||
if (!_observing) {
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_observing = true;
|
||||
}
|
||||
_schedule();
|
||||
}
|
||||
|
||||
@override
|
||||
void removeListener(VoidCallback listener) {
|
||||
super.removeListener(listener);
|
||||
if (hasListeners) return;
|
||||
_stop();
|
||||
if (_observing) {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_observing = false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed) {
|
||||
_hidden = false;
|
||||
_now = DateTime.now();
|
||||
notifyListeners();
|
||||
_schedule();
|
||||
} else if (state == AppLifecycleState.hidden ||
|
||||
// Not inactive: a desktop window that lost focus is still visible.
|
||||
state == AppLifecycleState.paused ||
|
||||
state == AppLifecycleState.detached) {
|
||||
_hidden = true;
|
||||
_stop();
|
||||
}
|
||||
}
|
||||
|
||||
void _schedule() {
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
if (_hidden || !hasListeners) return;
|
||||
final intoMinute = Duration(
|
||||
seconds: _now.second,
|
||||
milliseconds: _now.millisecond,
|
||||
microseconds: _now.microsecond,
|
||||
);
|
||||
final delay = const Duration(minutes: 1) - intoMinute;
|
||||
_timer = Timer(delay, () {
|
||||
_timer = null;
|
||||
_now = _now.add(delay);
|
||||
notifyListeners();
|
||||
_schedule();
|
||||
});
|
||||
}
|
||||
|
||||
void _stop() {
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_stop();
|
||||
if (_observing) WidgetsBinding.instance.removeObserver(this);
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,93 +1,79 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'relative_time.dart';
|
||||
import 'relative_time_clock.dart';
|
||||
|
||||
/// A relative-time label that rebuilds only itself when its formatter can
|
||||
/// change. It stops its timer while the app is backgrounded.
|
||||
/// A relative-time label that rebuilds only itself, and only when its text
|
||||
/// changes. Every label follows one shared minute [RelativeTimeClock] rather
|
||||
/// than a timer of its own; a label whose tickers are muted (an offstage tab
|
||||
/// or a covered route) skips the ticks and catches up when shown again.
|
||||
class RelativeTimeLabel extends StatefulWidget {
|
||||
const RelativeTimeLabel({super.key, required this.instant, this.now});
|
||||
const RelativeTimeLabel({
|
||||
super.key,
|
||||
required this.instant,
|
||||
this.now,
|
||||
this.clock,
|
||||
});
|
||||
|
||||
final DateTime? instant;
|
||||
|
||||
/// The time the label starts from; the shared clock advances it.
|
||||
final DateTime? now;
|
||||
|
||||
/// The clock to follow; [RelativeTimeClock.shared] when null.
|
||||
final RelativeTimeClock? clock;
|
||||
|
||||
@override
|
||||
State<RelativeTimeLabel> createState() => _RelativeTimeLabelState();
|
||||
}
|
||||
|
||||
class _RelativeTimeLabelState extends State<RelativeTimeLabel>
|
||||
with WidgetsBindingObserver {
|
||||
Timer? _timer;
|
||||
DateTime _now = DateTime.now();
|
||||
class _RelativeTimeLabelState extends State<RelativeTimeLabel> {
|
||||
late RelativeTimeClock _clock;
|
||||
late DateTime _now;
|
||||
bool _shown = true;
|
||||
bool _stale = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_schedule();
|
||||
_now = widget.now ?? DateTime.now();
|
||||
_clock = widget.clock ?? RelativeTimeClock.shared;
|
||||
_clock.addListener(_tick);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(RelativeTimeLabel oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.instant != widget.instant) _schedule();
|
||||
final clock = widget.clock ?? RelativeTimeClock.shared;
|
||||
if (clock == _clock) return;
|
||||
_clock.removeListener(_tick);
|
||||
_clock = clock..addListener(_tick);
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed) {
|
||||
_now = DateTime.now();
|
||||
if (mounted) setState(() {});
|
||||
_schedule(current: _now);
|
||||
} else if (state == AppLifecycleState.hidden ||
|
||||
// Not inactive: a desktop window that lost focus is still visible.
|
||||
state == AppLifecycleState.paused ||
|
||||
state == AppLifecycleState.detached) {
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
}
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
_shown = TickerMode.valuesOf(context).enabled;
|
||||
if (_shown && _stale) _advance();
|
||||
}
|
||||
|
||||
void _schedule({DateTime? current}) {
|
||||
_timer?.cancel();
|
||||
final instant = widget.instant;
|
||||
if (instant == null) return;
|
||||
final now = current ?? widget.now ?? DateTime.now();
|
||||
_now = now;
|
||||
final next = _nextBoundary(instant, now);
|
||||
final delay = next.difference(now);
|
||||
_timer = Timer(delay.isNegative ? Duration.zero : delay, () {
|
||||
if (!mounted) return;
|
||||
_now = _now.add(delay);
|
||||
setState(() {});
|
||||
_schedule(current: _now);
|
||||
});
|
||||
/// Moves to the clock's time; true when the text changed.
|
||||
bool _advance() {
|
||||
_stale = false;
|
||||
final next = _clock.now;
|
||||
if (!next.isAfter(_now)) return false;
|
||||
final before = formatRelativeTime(widget.instant, now: _now);
|
||||
_now = next;
|
||||
return formatRelativeTime(widget.instant, now: _now) != before;
|
||||
}
|
||||
|
||||
DateTime _nextBoundary(DateTime instant, DateTime now) {
|
||||
final difference = now.difference(instant);
|
||||
final age = difference.abs();
|
||||
final unit = age < const Duration(hours: 1)
|
||||
? const Duration(minutes: 1)
|
||||
: age < const Duration(days: 1)
|
||||
? const Duration(hours: 1)
|
||||
: age < const Duration(days: 7)
|
||||
? const Duration(days: 1)
|
||||
: null;
|
||||
if (unit != null) {
|
||||
final units = age.inMilliseconds ~/ unit.inMilliseconds;
|
||||
final boundary = difference.isNegative
|
||||
// Future labels use a decreasing count. Add a second so an exact
|
||||
// boundary does not immediately schedule another zero-delay timer.
|
||||
? instant.subtract(unit * units).add(const Duration(seconds: 1))
|
||||
: instant.add(unit * (units + 1));
|
||||
if (boundary.isAfter(now)) return boundary;
|
||||
void _tick() {
|
||||
if (!mounted || widget.instant == null) return;
|
||||
if (!_shown) {
|
||||
_stale = true;
|
||||
return;
|
||||
}
|
||||
final midnight = DateTime(now.year, now.month, now.day + 1);
|
||||
return midnight.isAfter(now)
|
||||
? midnight
|
||||
: now.add(const Duration(minutes: 1));
|
||||
if (_advance()) setState(() {});
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -102,8 +88,7 @@ class _RelativeTimeLabelState extends State<RelativeTimeLabel>
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_timer?.cancel();
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_clock.removeListener(_tick);
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
// Measures wasted background work outside the chat transcript: timers kept
|
||||
// alive by list rows, rebuilds per minute tick, offstage tabs' work and the
|
||||
// rebuilds a burst of run events causes. Each scenario prints its numbers
|
||||
// (`BENCH ...`) and asserts the budgets the shared clock and the narrowed
|
||||
// notifications keep.
|
||||
import 'dart:async';
|
||||
|
||||
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/runs/data/runs_repository.dart';
|
||||
import 'package:pipelines_app/features/runs/ui/runs_controller.dart';
|
||||
import 'package:pipelines_app/features/runs/ui/runs_list.dart';
|
||||
import 'package:pipelines_app/shell/adaptive_shell.dart';
|
||||
import 'package:pipelines_app/shell/destination.dart';
|
||||
import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart';
|
||||
import 'package:pipelines_app/ui/text/relative_time_label.dart';
|
||||
|
||||
class _Gateway implements ApiGateway {
|
||||
final controller = StreamController<JsonMap>.broadcast(sync: true);
|
||||
List<JsonMap> runs = [];
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => controller.stream;
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async => {
|
||||
'runs': [for (final run in runs) Map<String, dynamic>.of(run)],
|
||||
};
|
||||
}
|
||||
|
||||
/// Counts element rebuilds by widget type while installed.
|
||||
class _Rebuilds {
|
||||
final Map<Type, int> counts = {};
|
||||
void install() => debugOnRebuildDirtyWidget = (element, _) => counts.update(
|
||||
element.widget.runtimeType,
|
||||
(n) => n + 1,
|
||||
ifAbsent: () => 1,
|
||||
);
|
||||
void uninstall() => debugOnRebuildDirtyWidget = null;
|
||||
int of(Type type) => counts[type] ?? 0;
|
||||
int get total => counts.values.fold(0, (a, b) => a + b);
|
||||
void reset() => counts.clear();
|
||||
}
|
||||
|
||||
/// Tracks every Timer created in its zone (one-shot and periodic).
|
||||
class _Timers {
|
||||
final List<Timer> created = [];
|
||||
int get active => created.where((t) => t.isActive).length;
|
||||
late final ZoneSpecification spec = ZoneSpecification(
|
||||
createTimer: (self, parent, zone, duration, f) {
|
||||
final timer = parent.createTimer(zone, duration, f);
|
||||
created.add(timer);
|
||||
return timer;
|
||||
},
|
||||
createPeriodicTimer: (self, parent, zone, period, f) {
|
||||
final timer = parent.createPeriodicTimer(zone, period, f);
|
||||
created.add(timer);
|
||||
return timer;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
List<JsonMap> _runs(int count, DateTime now) => [
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
'id': i + 1,
|
||||
'name': 'Pipeline ${i % 7}',
|
||||
'title': 'Run ${i + 1}',
|
||||
'status': i < 20 ? 'running' : 'succeeded',
|
||||
'executing': i < 20,
|
||||
'completed_steps': 1,
|
||||
// The lifecycle fields a server list row carries.
|
||||
'notify_mode': 'auto',
|
||||
'resource_wait': null,
|
||||
'cancel_requested': false,
|
||||
'cleanup_unconfirmed': false,
|
||||
// Every 20 seconds back: the newest rows change label each minute.
|
||||
'created_at': now.subtract(Duration(seconds: 20 * i)).toIso8601String(),
|
||||
},
|
||||
];
|
||||
|
||||
void main() {
|
||||
late _Gateway gateway;
|
||||
late RunsController controller;
|
||||
final rebuilds = _Rebuilds();
|
||||
|
||||
setUp(() async {
|
||||
gateway = _Gateway()..runs = _runs(300, DateTime.now());
|
||||
controller = RunsController(RunsRepository(gateway));
|
||||
controller.listen(gateway.frames);
|
||||
await controller.load();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
rebuilds.uninstall();
|
||||
controller.dispose();
|
||||
await gateway.controller.close();
|
||||
});
|
||||
|
||||
Widget shell(AppDestination destination) => MaterialApp(
|
||||
home: AdaptiveShell(
|
||||
destination: destination,
|
||||
destinationBodies: {
|
||||
AppDestination.runs: (_) => AnimatedBuilder(
|
||||
animation: controller,
|
||||
builder: (_, _) =>
|
||||
RunsList(controller: controller, onSelected: (_) {}),
|
||||
),
|
||||
AppDestination.pipelines: (_) => const Center(child: Text('pipelines')),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
/// Sends frame [i] of a busy stream: most frames repeat a running row's
|
||||
/// current state; every fifth advances its step count.
|
||||
void frame(int i) {
|
||||
final id = 1 + i % 20;
|
||||
final row = gateway.runs[id - 1];
|
||||
if (i % 5 == 0) row['completed_steps'] = 2 + i;
|
||||
gateway.controller.add({
|
||||
'type': 'run_event',
|
||||
'run_id': id,
|
||||
'status': 'running',
|
||||
'completed_steps': row['completed_steps'],
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> sizeView(WidgetTester tester) async {
|
||||
tester.view.physicalSize = const Size(400, 900);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
}
|
||||
|
||||
testWidgets('300-run list: timers and rebuilds per minute tick', (
|
||||
tester,
|
||||
) async {
|
||||
await sizeView(tester);
|
||||
final timers = _Timers();
|
||||
await runZoned(zoneSpecification: timers.spec, () async {
|
||||
await tester.pumpWidget(shell(AppDestination.runs));
|
||||
await tester.pump();
|
||||
final labels = find.byType(RelativeTimeLabel).evaluate().length;
|
||||
final active = timers.active;
|
||||
// Measure one whole minute after the first tick, wherever it falls.
|
||||
await tester.pump(const Duration(minutes: 1));
|
||||
await tester.pump();
|
||||
final created = timers.created.length;
|
||||
rebuilds
|
||||
..reset()
|
||||
..install();
|
||||
await tester.pump(const Duration(minutes: 1));
|
||||
await tester.pump();
|
||||
final perMinute = timers.created.length - created;
|
||||
rebuilds.uninstall();
|
||||
// ignore: avoid_print
|
||||
print(
|
||||
'BENCH list300 mountedLabels=$labels activeTimers=$active '
|
||||
'labelRebuildsPerMinute=${rebuilds.of(RelativeTimeLabel)} '
|
||||
'totalRebuildsPerMinute=${rebuilds.total} '
|
||||
'timersScheduledPerMinute=$perMinute',
|
||||
);
|
||||
expect(active, lessThanOrEqualTo(1));
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
expect(timers.active, 0);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('offstage Runs tab: minute ticks and run events', (tester) async {
|
||||
await sizeView(tester);
|
||||
final timers = _Timers();
|
||||
await runZoned(zoneSpecification: timers.spec, () async {
|
||||
await tester.pumpWidget(shell(AppDestination.runs));
|
||||
await tester.pump();
|
||||
await tester.pumpWidget(shell(AppDestination.pipelines));
|
||||
await tester.pump(const Duration(seconds: 1)); // fade-through done
|
||||
final active = timers.active;
|
||||
rebuilds
|
||||
..reset()
|
||||
..install();
|
||||
await tester.pump(const Duration(minutes: 2));
|
||||
await tester.pump();
|
||||
final tick = rebuilds.of(RelativeTimeLabel);
|
||||
rebuilds.reset();
|
||||
for (var i = 0; i < 50; i++) {
|
||||
frame(i);
|
||||
await tester.pump();
|
||||
}
|
||||
await tester.pump();
|
||||
rebuilds.uninstall();
|
||||
// ignore: avoid_print
|
||||
print(
|
||||
'BENCH offstage activeTimers=$active labelRebuildsIn2Minutes=$tick '
|
||||
'burst50: runsListRebuilds=${rebuilds.of(RunsList)} '
|
||||
'shellBarRebuilds=${rebuilds.of(FloatingDestinationBar)} '
|
||||
'totalRebuilds=${rebuilds.total}',
|
||||
);
|
||||
expect(tick, 0);
|
||||
expect(rebuilds.of(FloatingDestinationBar), 0);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
expect(timers.active, 0);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('visible Runs tab: a 50-frame run_event burst', (tester) async {
|
||||
await sizeView(tester);
|
||||
var notifications = 0;
|
||||
controller.addListener(() => notifications++);
|
||||
await tester.pumpWidget(shell(AppDestination.runs));
|
||||
await tester.pump();
|
||||
rebuilds
|
||||
..reset()
|
||||
..install();
|
||||
// Frames arrive between frames on a real socket: pump after each.
|
||||
for (var i = 0; i < 50; i++) {
|
||||
frame(i);
|
||||
await tester.pump();
|
||||
}
|
||||
await tester.pump();
|
||||
rebuilds.uninstall();
|
||||
// ignore: avoid_print
|
||||
print(
|
||||
'BENCH visibleBurst50 controllerNotifications=$notifications '
|
||||
'runsListRebuilds=${rebuilds.of(RunsList)} '
|
||||
'runRowRebuilds=${rebuilds.of(RunListRow)} '
|
||||
'shellBarRebuilds=${rebuilds.of(FloatingDestinationBar)} '
|
||||
'totalRebuilds=${rebuilds.total}',
|
||||
);
|
||||
final top = rebuilds.counts.entries.toList()
|
||||
..sort((a, b) => b.value - a.value);
|
||||
// ignore: avoid_print
|
||||
print(
|
||||
'BENCH top ${top.take(15).map((e) => '${e.key}=${e.value}').join(' ')}',
|
||||
);
|
||||
// Only the ten frames that advance a step change anything visible.
|
||||
expect(notifications, lessThanOrEqualTo(10));
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
}
|
||||
@@ -1,45 +1,96 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/ui/text/relative_time.dart';
|
||||
import 'package:pipelines_app/ui/text/relative_time_clock.dart';
|
||||
import 'package:pipelines_app/ui/text/relative_time_label.dart';
|
||||
|
||||
/// The start of the current wall-clock minute, where the shared clock ticks.
|
||||
DateTime _minute() {
|
||||
final now = DateTime.now();
|
||||
return DateTime(now.year, now.month, now.day, now.hour, now.minute);
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('updates at the next relative-time boundary', (tester) async {
|
||||
final instant = DateTime.now().subtract(const Duration(minutes: 4));
|
||||
final clock = RelativeTimeClock.shared;
|
||||
|
||||
testWidgets('updates on the next minute tick', (tester) async {
|
||||
final instant = _minute().subtract(const Duration(minutes: 4));
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: RelativeTimeLabel(instant: instant)),
|
||||
);
|
||||
expect(find.text('4m'), findsOneWidget);
|
||||
|
||||
await tester.pump(const Duration(minutes: 1, seconds: 1));
|
||||
await tester.pump(const Duration(minutes: 1));
|
||||
expect(find.text('5m'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('future labels schedule their next boundary', (tester) async {
|
||||
final instant = DateTime.now().add(const Duration(minutes: 4));
|
||||
testWidgets('future labels count down on the ticks', (tester) async {
|
||||
final instant = _minute().add(
|
||||
const Duration(minutes: 4, milliseconds: 500),
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: RelativeTimeLabel(instant: instant)),
|
||||
);
|
||||
expect(find.text('in 3m'), findsOneWidget);
|
||||
expect(find.text(formatRelativeTime(instant)!), findsOneWidget);
|
||||
|
||||
await tester.pump(const Duration(minutes: 1, seconds: 1));
|
||||
await tester.pump(const Duration(minutes: 2));
|
||||
expect(find.text('in 2m'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('cancels its timer when disposed', (tester) async {
|
||||
testWidgets('many labels share one timer, released when disposed', (
|
||||
tester,
|
||||
) async {
|
||||
final instant = DateTime.now().subtract(const Duration(minutes: 4));
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: RelativeTimeLabel(
|
||||
instant: DateTime.now().subtract(const Duration(minutes: 4)),
|
||||
home: Wrap(
|
||||
children: [
|
||||
for (var i = 0; i < 50; i++) RelativeTimeLabel(instant: instant),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(clock.ticking, isTrue);
|
||||
await tester.pumpWidget(const MaterialApp(home: SizedBox()));
|
||||
expect(clock.ticking, isFalse);
|
||||
await tester.pump(const Duration(hours: 1));
|
||||
});
|
||||
|
||||
testWidgets('a muted label skips ticks and catches up when shown', (
|
||||
tester,
|
||||
) async {
|
||||
final instant = _minute().subtract(const Duration(minutes: 4));
|
||||
var builds = 0;
|
||||
Widget app(bool enabled) => MaterialApp(
|
||||
home: TickerMode(
|
||||
enabled: enabled,
|
||||
child: Builder(
|
||||
builder: (_) {
|
||||
builds++;
|
||||
return RelativeTimeLabel(instant: instant);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(app(false));
|
||||
final label = find.byType(RelativeTimeLabel);
|
||||
var labelBuilds = 0;
|
||||
debugOnRebuildDirtyWidget = (element, _) {
|
||||
if (element.widget is RelativeTimeLabel) labelBuilds++;
|
||||
};
|
||||
addTearDown(() => debugOnRebuildDirtyWidget = null);
|
||||
await tester.pump(const Duration(minutes: 1));
|
||||
expect(labelBuilds, 0);
|
||||
expect(find.descendant(of: label, matching: find.text('4m')), findsOneWidget);
|
||||
|
||||
await tester.pumpWidget(app(true));
|
||||
expect(find.text('5m'), findsOneWidget);
|
||||
expect(builds, 2);
|
||||
});
|
||||
|
||||
testWidgets('keeps ticking while inactive, pauses while hidden and '
|
||||
'refreshes on resume', (tester) async {
|
||||
final instant = DateTime.now().subtract(const Duration(minutes: 4));
|
||||
final instant = _minute().subtract(const Duration(minutes: 4));
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(home: RelativeTimeLabel(instant: instant)),
|
||||
);
|
||||
@@ -49,12 +100,13 @@ void main() {
|
||||
WidgetsBinding.instance.handleAppLifecycleStateChanged(
|
||||
AppLifecycleState.inactive,
|
||||
);
|
||||
await tester.pump(const Duration(minutes: 1, seconds: 1));
|
||||
await tester.pump(const Duration(minutes: 1));
|
||||
expect(find.text('5m'), findsOneWidget);
|
||||
|
||||
WidgetsBinding.instance.handleAppLifecycleStateChanged(
|
||||
AppLifecycleState.hidden,
|
||||
);
|
||||
expect(clock.ticking, isFalse);
|
||||
await tester.pump(const Duration(minutes: 1, seconds: 1));
|
||||
expect(find.text('5m'), findsOneWidget);
|
||||
|
||||
@@ -64,8 +116,8 @@ void main() {
|
||||
WidgetsBinding.instance.handleAppLifecycleStateChanged(
|
||||
AppLifecycleState.resumed,
|
||||
);
|
||||
expect(clock.ticking, isTrue);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(minutes: 1, seconds: 1));
|
||||
expect(find.text('5m'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user