import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../domain/run_deletion.dart'; /// The Runs list's multi-select mode and the last deletion report. /// /// Only finished runs can be selected ([runIsDeletable]); the ids are the /// server's run ids, so a list reload keeps the selection of runs still shown. class RunsSelection extends ChangeNotifier { bool _active = false; final Set _ids = {}; String? _report; bool get active => _active; Set get ids => Set.unmodifiable(_ids); int get count => _ids.length; bool contains(Object? id) => _ids.contains(id); /// The last deletion's outcome, until dismissed or replaced. String? get report => _report; void enter([JsonMap? run]) { _active = true; if (run != null && runIsDeletable(run)) _ids.add(run['id'] as int); notifyListeners(); } void exit() { if (!_active && _ids.isEmpty) return; _active = false; _ids.clear(); notifyListeners(); } void toggle(JsonMap run) { if (!_active || !runIsDeletable(run)) return; final id = run['id'] as int; if (!_ids.remove(id)) _ids.add(id); notifyListeners(); } /// Whether every deletable run of [runs] (one day) is selected. bool allSelected(Iterable runs) { final ids = deletableRunIds(runs); return ids.isNotEmpty && ids.every(_ids.contains); } /// Selects every finished run of [runs], or deselects them all when they /// already are. Active runs are never selected. void toggleAll(Iterable runs) { if (!_active) return; final ids = deletableRunIds(runs); if (ids.isEmpty) return; if (ids.every(_ids.contains)) { _ids.removeAll(ids); } else { _ids.addAll(ids); } notifyListeners(); } /// Drops ids no longer listed (deleted, removed elsewhere, or now active). void retain(Iterable runs) { final keep = deletableRunIds(runs).toSet(); final before = _ids.length; _ids.retainWhere(keep.contains); if (_ids.length != before) notifyListeners(); } /// Records a deletion: its ids leave the selection, and the mode ends once /// nothing (no refused run) remains selected. void applied(RunsDeletion deletion) { _ids.removeAll(deletion.deleted); if (_ids.isEmpty) _active = false; _report = deletion.report; notifyListeners(); } void dismissReport() { if (_report == null) return; _report = null; notifyListeners(); } }