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

109 lines
2.5 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/runs_repository.dart';
import '../domain/run_events.dart';
import '../domain/run_models.dart';
class RunsController extends ChangeNotifier {
RunsController(this.repository);
final RunsRepository repository;
StreamSubscription<JsonMap>? _subscription;
List<JsonMap> runs = [];
JsonMap? detail;
String? error;
bool loading = false;
String query = '', sort = 'newest_first';
int _selection = 0;
Timer? _refresh;
void listen(Stream<JsonMap> frames) {
_subscription?.cancel();
_subscription = frames
.where((f) => f['type'] == 'run_event')
.listen(_event);
}
Future<void> load([int? initialId]) async {
final token = ++_selection;
loading = true;
error = null;
notifyListeners();
try {
final result = await repository.listRuns();
if (token != _selection) return;
runs = result.runs;
if (initialId != null) await select(initialId);
} catch (e) {
if (token == _selection) error = '$e';
}
if (token == _selection) {
loading = false;
notifyListeners();
}
}
Future<void> select(num id) async {
final token = ++_selection;
detail = null;
error = null;
loading = true;
notifyListeners();
try {
final value = await repository.getRun(id);
if (token == _selection) detail = value;
} catch (e) {
if (token == _selection) error = '$e';
}
if (token == _selection) {
loading = false;
notifyListeners();
}
}
void back() {
++_selection;
detail = null;
error = null;
notifyListeners();
}
void setQuery(String value) {
query = value;
notifyListeners();
}
void _event(JsonMap frame) {
final folded = foldRunEvent(runs, frame);
runs = folded.runs;
if (detail?['id'] == frame['run_id']) {
detail = foldRunEventDetail(detail, frame);
}
if (detail != null && runDetailNeedsFullSync(frame)) {
_refresh?.cancel();
_refresh = Timer(
const Duration(milliseconds: 150),
() => select(detail!['id'] as num),
);
}
notifyListeners();
}
List<JsonMap> get visibleRuns => sortRuns(
runs
.where(
(r) => '${r['title'] ?? r['name'] ?? ''}'.toLowerCase().contains(
query.toLowerCase(),
),
)
.toList(),
sort: sort,
);
@override
void dispose() {
_subscription?.cancel();
_refresh?.cancel();
super.dispose();
}
}