Merge: runs multi-select, delete and size sort

This commit is contained in:
2026-10-31 22:20:06 +00:00
22 changed files with 1928 additions and 142 deletions
@@ -0,0 +1,41 @@
import 'package:flutter/widgets.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../data/runs_repository.dart';
import '../domain/run_deletion.dart';
import 'delete_runs_dialog.dart';
/// Confirms and deletes the finished runs among [runs].
///
/// Active runs are left out; nothing is sent unless the operator confirms. A
/// transport or server error stays in the open prompt. The server's reply,
/// including any refusals, goes to [onDeleted] exactly as received.
Future<bool> confirmDeleteRuns(
BuildContext context, {
required Iterable<JsonMap> runs,
required ApiGateway gateway,
required ValueChanged<RunsDeletion> onDeleted,
bool? cupertino,
}) {
final deletable = runs.where(runIsDeletable).toList();
final ids = deletableRunIds(deletable);
if (ids.isEmpty) return Future.value(false);
return showDeleteRunsPrompt(
context: context,
count: ids.length,
size: runsSizeLabel(deletable),
cupertino: cupertino ?? usesCupertinoHost(context),
onSubmit: () async {
try {
onDeleted(await RunsRepository(gateway).deleteRuns(ids));
return null;
} catch (error) {
final message = '$error'.trim();
return message.isEmpty
? 'The server did not delete the runs.'
: message;
}
},
);
}
@@ -0,0 +1,154 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../domain/run_deletion.dart';
const deleteRunsConfirmKey = ValueKey<String>('runs.delete.confirm');
const deleteRunsKeepKey = ValueKey<String>('runs.delete.keep');
const deleteRunsErrorKey = ValueKey<String>('runs.delete.error');
/// Sends the confirmed deletion. Returns null once the server replied, or the
/// failure to show in the still-open prompt.
typedef DeleteRunsSubmit = Future<String?> Function();
/// Opens the native destructive confirmation for deleting [count] runs.
///
/// Nothing is sent until Delete is pressed; Cancel only closes the prompt.
/// Resolves true when the server answered the deletion.
Future<bool> showDeleteRunsPrompt({
required BuildContext context,
required int count,
required String? size,
required bool cupertino,
required DeleteRunsSubmit onSubmit,
}) async {
final prompt = _DeleteRunsPrompt(
count: count,
size: size,
cupertino: cupertino,
onSubmit: onSubmit,
);
final result = cupertino
? await showCupertinoDialog<bool>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
)
: await showDialog<bool>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
return result ?? false;
}
class _DeleteRunsPrompt extends StatefulWidget {
const _DeleteRunsPrompt({
required this.count,
required this.size,
required this.cupertino,
required this.onSubmit,
});
final int count;
final String? size;
final bool cupertino;
final DeleteRunsSubmit onSubmit;
@override
State<_DeleteRunsPrompt> createState() => _DeleteRunsPromptState();
}
class _DeleteRunsPromptState extends State<_DeleteRunsPrompt> {
bool _sending = false;
String? _error;
Future<void> _confirm() async {
if (_sending) return;
setState(() {
_sending = true;
_error = null;
});
final error = await widget.onSubmit();
if (!mounted) return;
if (error == null) {
Navigator.of(context).pop(true);
return;
}
setState(() {
_sending = false;
_error = error;
});
}
void _keep() {
if (!_sending) Navigator.of(context).pop(false);
}
@override
Widget build(BuildContext context) => PopScope(
canPop: !_sending,
child: widget.cupertino ? _cupertinoDialog(context) : _material(context),
);
Widget _material(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return AlertDialog(
scrollable: true,
title: Text(deleteRunsTitle(widget.count)),
content: _body(TextStyle(color: scheme.error)),
actions: [
TextButton(
key: deleteRunsKeepKey,
onPressed: _sending ? null : _keep,
child: const Text('Cancel'),
),
FilledButton(
key: deleteRunsConfirmKey,
style: FilledButton.styleFrom(
backgroundColor: scheme.error,
foregroundColor: scheme.onError,
),
onPressed: _sending ? null : _confirm,
child: Text(_sending ? 'Deleting…' : 'Delete'),
),
],
);
}
Widget _cupertinoDialog(BuildContext context) => CupertinoAlertDialog(
title: Text(deleteRunsTitle(widget.count)),
content: _body(
TextStyle(color: CupertinoColors.systemRed.resolveFrom(context)),
),
actions: [
CupertinoDialogAction(
key: deleteRunsKeepKey,
onPressed: _sending ? null : _keep,
child: const Text('Cancel'),
),
CupertinoDialogAction(
key: deleteRunsConfirmKey,
isDestructiveAction: true,
onPressed: _sending ? null : _confirm,
child: Text(_sending ? 'Deleting…' : 'Delete'),
),
],
);
Widget _body(TextStyle errorStyle) => Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(deleteRunsMessage(widget.count, size: widget.size)),
if (_error case final error?)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Semantics(
liveRegion: true,
child: Text(error, key: deleteRunsErrorKey, style: errorStyle),
),
),
],
);
}
@@ -1,4 +1,5 @@
import '../../../core/api_gateway.dart';
import '../domain/run_deletion.dart';
import '../domain/run_models.dart';
/// Protocol failure kept separate from transport errors; server error envelopes
@@ -10,6 +11,9 @@ class RunsRepositoryException implements Exception {
String toString() => message;
}
/// The most run ids one `delete_runs` request may carry.
const deleteRunsBatch = 1000;
/// Run protocol requests over the application's shared gateway.
class RunsRepository {
RunsRepository(this._gateway);
@@ -41,6 +45,49 @@ class RunsRepository {
'run_detail',
);
/// Deletes finished runs and their recorded data. The server answers
/// `runs_deleted` with the ids it removed, the ones it refused (with its
/// reason) and the bytes it freed.
///
/// The server accepts at most [deleteRunsBatch] ids per request, so a larger
/// selection is sent in consecutive batches and the replies combined. A
/// failing batch stops the rest; batches already answered are kept.
Future<RunsDeletion> deleteRuns(List<int> ids) async {
if (ids.isEmpty) {
throw const RunsRepositoryException('Choose runs to delete.');
}
RunsDeletion? result;
for (var start = 0; start < ids.length; start += deleteRunsBatch) {
final batch = ids.sublist(
start,
(start + deleteRunsBatch).clamp(0, ids.length),
);
final RunsDeletion deletion;
try {
final reply = await _gateway.call('delete_runs', {'run_ids': batch});
deletion =
RunsDeletion.fromReply(reply) ??
(throw const RunsRepositoryException(
'The server returned no runs_deleted reply.',
));
} catch (error) {
if (result == null) rethrow;
// Report what earlier batches deleted, and the rest as not deleted.
return result.merge(
RunsDeletion(
deleted: const [],
refused: [
for (final id in ids.sublist(start))
(runId: id, reason: '$error'),
],
),
);
}
result = result == null ? deletion : result.merge(deletion);
}
return result!;
}
/// Reads the exact recorded visit again; it never reruns its stage or tools.
///
/// The body is the web client's `repair_session_export` request: the run and
@@ -0,0 +1,56 @@
import 'package:shared_preferences/shared_preferences.dart';
/// The Runs list's persisted sort choice.
const runsSortStorageKey = 'pipelines.next.runsSort.v1';
/// The persistence seam for the Runs list's sort. Both directions may fail: a
/// null read means "nothing saved", a false write means "this session only".
abstract interface class RunsSortStore {
Future<String?> read();
Future<bool> write(String value);
}
/// `shared_preferences` storage under [runsSortStorageKey].
class SharedPreferencesRunsSortStore implements RunsSortStore {
const SharedPreferencesRunsSortStore();
@override
Future<String?> read() async {
try {
return (await SharedPreferences.getInstance()).getString(
runsSortStorageKey,
);
} catch (_) {
return null;
}
}
@override
Future<bool> write(String value) async {
try {
return await (await SharedPreferences.getInstance()).setString(
runsSortStorageKey,
value,
);
} catch (_) {
return false;
}
}
}
/// An in-memory store for tests and isolated fixtures.
class MemoryRunsSortStore implements RunsSortStore {
MemoryRunsSortStore([this.value]);
String? value;
@override
Future<String?> read() async => value;
@override
Future<bool> write(String value) async {
this.value = value;
return true;
}
}
@@ -0,0 +1,180 @@
import '../../../core/api_gateway.dart';
import 'run_models.dart' show runStateOf;
/// Run deletion and disk-size rules. No widgets here.
/// The states a run can be deleted in: it has finished one way or another.
const _terminalStates = {'succeeded', 'failed', 'canceled', 'interrupted'};
/// Why an active run cannot be selected or deleted, for its disabled control.
const runDeleteBlockedReason =
'Active runs can’t be deleted until they finish.';
/// Whether [run] has finished, so its recorded data may be deleted. A run
/// still executing (running, waiting, queued, pending) never qualifies, nor
/// does one whose status the client does not recognise.
bool runIsDeletable(JsonMap run) =>
run['id'] is int &&
run['executing'] != true &&
_terminalStates.contains(runStateOf(run['status']));
/// The run's recorded size on disk, or null when it is unknown: older servers
/// omit `size_bytes`, and the server sends 0 for "not measured yet".
int? runSizeBytes(JsonMap run) {
final value = run['size_bytes'];
if (value is int && value > 0) return value;
if (value is num && value > 0 && value.isFinite) return value.round();
return null;
}
/// A compact human size: `512 B`, `4.2 KB`, `340 MB`, `1.2 GB`.
///
/// Binary multiples, one decimal below ten units, whole units above.
String formatByteSize(int bytes) {
if (bytes < 1024) return '$bytes B';
const units = ['KB', 'MB', 'GB', 'TB', 'PB'];
var value = bytes / 1024;
var unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit++;
}
// Rounding 1023.6 MB up would print "1024 MB"; promote it instead.
if (value >= 1023.5 && unit < units.length - 1) {
value /= 1024;
unit++;
}
final text = value < 9.95
? value.toStringAsFixed(1).replaceFirst(RegExp(r'\.0$'), '')
: value.round().toString();
return '$text ${units[unit]}';
}
/// The known total of [runs]' sizes, and whether any size was unknown.
({int bytes, int unknown}) runsSizeTotal(Iterable<JsonMap> runs) {
var bytes = 0;
var unknown = 0;
for (final run in runs) {
final size = runSizeBytes(run);
if (size == null) {
unknown++;
} else {
bytes += size;
}
}
return (bytes: bytes, unknown: unknown);
}
/// The selection's size for its summary, or null when no size is known.
String? runsSizeLabel(Iterable<JsonMap> runs) {
final total = runsSizeTotal(runs);
if (total.bytes == 0 && total.unknown > 0) return null;
final size = formatByteSize(total.bytes);
return total.unknown > 0 ? '$size + unknown' : size;
}
String _runs(int count) => count == 1 ? '1 run' : '$count runs';
String deleteRunsTitle(int count) => 'Delete ${_runs(count)}?';
/// The confirmation's body. The freed amount is omitted when no size is known.
String deleteRunsMessage(int count, {String? size}) {
final whose = count == 1 ? 'its' : 'their';
final frees = size == null ? '' : ' and frees about $size';
return 'This removes $whose artifacts, documents and history$frees. '
'This can’t be undone.';
}
/// The deleted run ids are drawn from selected runs that can be deleted, in
/// list order.
List<int> deletableRunIds(Iterable<JsonMap> runs) => [
for (final run in runs)
if (runIsDeletable(run)) run['id'] as int,
];
/// One run the server kept, in its own words.
typedef RunDeleteRefusal = ({int runId, String reason});
/// The server's `runs_deleted` reply.
class RunsDeletion {
const RunsDeletion({
required this.deleted,
this.refused = const [],
this.freedBytes,
});
/// Parses the reply envelope, whose result is nested under `runs_deleted`,
/// or returns null when it is not a deletion reply.
static RunsDeletion? fromReply(JsonMap reply) {
final body = reply['runs_deleted'];
return body is Map ? fromBody(Map<String, dynamic>.from(body)) : null;
}
/// Parses the nested `{deleted, refused, freed_bytes}` result.
static RunsDeletion? fromBody(JsonMap reply) {
final deleted = reply['deleted'];
if (deleted is! List) return null;
final refused = reply['refused'];
final freed = reply['freed_bytes'];
return RunsDeletion(
deleted: [for (final id in deleted) ?_intId(id)],
refused: [
if (refused is List)
for (final entry in refused.whereType<Map>())
if (_intId(entry['run_id']) case final id?)
(runId: id, reason: '${entry['reason'] ?? ''}'.trim()),
],
freedBytes: freed is num && freed >= 0 ? freed.round() : null,
);
}
final List<int> deleted;
final List<RunDeleteRefusal> refused;
final int? freedBytes;
/// Combines the replies of consecutive batches into one outcome.
RunsDeletion merge(RunsDeletion other) => RunsDeletion(
deleted: [...deleted, ...other.deleted],
refused: [...refused, ...other.refused],
freedBytes: freedBytes == null && other.freedBytes == null
? null
: (freedBytes ?? 0) + (other.freedBytes ?? 0),
);
/// `Deleted 3 runs, freed 1.2 GB.` and one line per refused run.
String get report {
final lines = <String>[];
if (deleted.isNotEmpty || refused.isEmpty) {
final freed = freedBytes == null
? ''
: ', freed ${formatByteSize(freedBytes!)}';
lines.add('Deleted ${_runs(deleted.length)}$freed.');
}
if (refused.isNotEmpty) {
lines.add(
refused.length == 1
? '1 run was not deleted:'
: '${refused.length} runs were not deleted:',
);
for (final refusal in refused) {
final reason = refusal.reason.isEmpty
? 'refused by the server'
: refusal.reason;
lines.add('Run ${refusal.runId}: $reason');
}
}
return lines.join('\n');
}
}
/// The ids a `runs_removed` broadcast names.
List<int> removedRunIds(JsonMap frame) {
final ids = frame['run_ids'];
return ids is List ? [for (final id in ids) ?_intId(id)] : const [];
}
int? _intId(dynamic value) {
if (value is int) return value;
if (value is num && value == value.roundToDouble()) return value.toInt();
return null;
}
@@ -112,6 +112,8 @@ JsonMap _mergeRunFields(JsonMap current, JsonMap frame) {
for (final key in ['outcome', 'current_stage', 'created_at', 'finished_at']) {
if (!_blank(frame[key])) merged[key] = frame[key];
}
// Snapshot and terminal frames carry the measured size; others omit it.
if (frame['size_bytes'] is num) merged['size_bytes'] = frame['size_bytes'];
final oldExport = _positiveInt(current['export_pending_sequence']);
if (oldExport > 0 || frame.containsKey('export_pending_sequence')) {
merged['export_pending_sequence'] = _blank(frame['status'])
@@ -254,6 +254,20 @@ List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
case 'largest_first':
// Unknown sizes (older servers) sort after every known size.
final sa = a['size_bytes'], sb = b['size_bytes'];
// 0 means "not measured yet" and is unknown, like an absent size.
final an = sa is num && sa > 0 ? sa : null;
final bn = sb is num && sb > 0 ? sb : null;
primary = cmp(an == null ? 1 : 0, bn == null ? 1 : 0);
if (primary == 0 && an != null && bn != null) {
primary = bn.compareTo(an);
}
if (primary == 0) {
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
case 'pipeline_name':
primary = '${a['name'] ?? ''}'.toLowerCase().compareTo(
'${b['name'] ?? ''}'.toLowerCase(),
+12 -1
View File
@@ -14,6 +14,7 @@ import '../attention/runtime/attention_controller.dart';
import '../attention/runtime/attention_store.dart';
import 'actions/decision_action.dart';
import 'data/runs_repository.dart';
import 'data/runs_sort_store.dart';
import 'domain/run_decisions.dart';
import 'ui/run_pipeline_link.dart';
import 'ui/run_detail_view.dart';
@@ -45,6 +46,7 @@ class RunsScreen extends StatefulWidget {
this.attentionNow,
this.notifications,
this.attention,
this.sortStore = const SharedPreferencesRunsSortStore(),
});
final ApiGateway gateway;
@@ -89,6 +91,9 @@ class RunsScreen extends StatefulWidget {
/// The app's shared attention controller, mirrored on the shell's Runs tab.
final AttentionController? attention;
/// Where the list's sort choice persists; tests inject a memory store.
final RunsSortStore sortStore;
@override
State<RunsScreen> createState() => _RunsScreenState();
}
@@ -109,7 +114,13 @@ class _RunsScreenState extends State<RunsScreen> {
@override
void initState() {
super.initState();
controller = RunsController(RunsRepository(widget.gateway));
controller = RunsController(
RunsRepository(widget.gateway),
sortStore: widget.sortStore,
);
// A deleted open run closes its detail; the route returns to the list.
controller.onOpenRunRemoved = () =>
widget.onBack?.call(controller.pipelineId);
_reportedPipelineId = widget.initialPipelineId;
if (widget.initialPipelineId != null) {
controller.clearFilters();
@@ -117,6 +117,7 @@ class _RunDetailViewState extends State<RunDetailView> {
onRunChanged: widget.controller.acceptRunDetail,
cupertino: cupertino,
onRunOpened: widget.onRunOpened,
onDeleted: widget.controller.applyDeletion,
);
if (inShellBar) {
return ShellBar(
+147
View File
@@ -0,0 +1,147 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../../../ui/layout/app_list_avatar.dart';
import '../../../ui/layout/app_list_row.dart';
import '../../../ui/status/run_status_icon.dart';
import '../../../ui/text/relative_time.dart';
import '../domain/run_deletion.dart';
import '../domain/run_models.dart';
import 'run_more_menu.dart';
/// One run in the list: a status avatar, title/time, and one muted fact
/// line in the app's shared row. Its detail retains the full timestamp,
/// path, and other diagnostics.
///
/// In the list's select mode ([selecting]) the row leads with a checkbox, a
/// tap toggles it instead of opening the run, and the menu is hidden. Active
/// runs keep a disabled checkbox that says why.
class RunListRow extends StatelessWidget {
const RunListRow({
super.key,
required this.run,
required this.now,
this.selected = false,
this.divider = true,
this.onTap,
this.gateway,
this.onRunChanged,
this.onRunOpened,
this.onDeleted,
this.selecting = false,
this.checked = false,
this.onToggle,
this.onLongPress,
});
final JsonMap run;
final DateTime now;
final bool selected;
/// False for the last row before a day heading or the end of the list.
final bool divider;
final VoidCallback? onTap;
final ApiGateway? gateway;
final ValueChanged<JsonMap>? onRunChanged;
final ValueChanged<num>? onRunOpened;
final ValueChanged<RunsDeletion>? onDeleted;
/// The list is in select mode; [checked] is this run's selection.
final bool selecting;
final bool checked;
final VoidCallback? onToggle;
/// Enters select mode from a touch long-press.
final VoidCallback? onLongPress;
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final identity = runIdentity(run['title'], run['name']);
final id = run['id'];
final title = identity.label.isEmpty ? 'Run $id' : identity.label;
final facts = runRowFacts(run, now);
// A run without its own title is named by its pipeline, so the pipeline
// line does not repeat it.
final pipeline = identity.pipeline?.trim();
// With no stored title, `name` is already the row title; repeating it as
// a subtitle adds no identity. A titled run with an empty name genuinely
// lacks its pipeline, so make that absence explicit.
final pipelineLabel = pipeline == null
? null
: pipeline.isEmpty
? 'Pipeline unavailable'
: pipeline;
final scheduled = run['scheduled'] == true;
final bytes = runSizeBytes(run);
final size = bytes == null ? null : formatByteSize(bytes);
final subtitle = [
?pipelineLabel,
if (scheduled) 'Scheduled',
?facts.duration,
?facts.progress,
?size,
].join(' · ');
// A narrow pane keeps the decision facts: the pipeline, and progress
// while executing (duration only when there is no pipeline to show).
final compactSubtitle = [
?pipelineLabel,
if (scheduled) 'Scheduled',
if (run['executing'] == true && facts.progress != null) facts.progress!,
if (pipelineLabel == null && facts.duration != null) facts.duration!,
?size,
].join(' · ');
final state = runStateOf(run['status']);
return AppListRow(
key: ValueKey('run-row-$id'),
cupertino: cupertino,
selected: selected,
divider: divider,
onTap: selecting ? (runIsDeletable(run) ? onToggle : null) : onTap,
onLongPress: selecting ? null : onLongPress,
selectionControl: selecting ? _checkbox(context, cupertino) : null,
leading: AppListAvatar(
foreground: runStatusColor(state).resolveFrom(context),
child: RunStatusIcon(state: state, label: runStatusLabel(run)),
),
title: Text(title),
time: formatRelativeTimestamp('${run['created_at'] ?? ''}', now: now),
subtitle: Text(subtitle),
compactSubtitle: Text(compactSubtitle),
// A narrow list pane beside the open run leaves the row no room for a
// second control; the open run's detail beside it carries the same menu.
menu:
!selecting &&
gateway != null &&
onRunChanged != null &&
showRunMoreMenu(run, deletable: onDeleted != null)
? RunMoreMenu(
run: run,
gateway: gateway!,
onRunChanged: onRunChanged!,
onRunOpened: onRunOpened,
onDeleted: onDeleted,
cupertino: cupertino,
menuKey: ValueKey('run-list-more-menu-$id'),
)
: null,
);
}
Widget _checkbox(BuildContext context, bool cupertino) {
final id = run['id'];
final enabled = runIsDeletable(run);
final title = runIdentity(run['title'], run['name']).label;
final name = title.isEmpty ? 'run $id' : title;
final changed = enabled ? (_) => onToggle?.call() : null;
final box = cupertino
? CupertinoCheckbox(value: checked, onChanged: changed)
: Checkbox(value: checked, onChanged: changed);
return Semantics(
label: enabled ? 'Select $name' : 'Select $name. $runDeleteBlockedReason',
child: KeyedSubtree(key: ValueKey('run-select-$id'), child: box),
);
}
}
+33 -5
View File
@@ -4,18 +4,26 @@ import '../../../ui/layout/app_overflow_menu.dart';
import '../../../core/api_gateway.dart';
import '../../schedules/ui/run/schedule_run_action.dart';
import '../actions/delete_runs_action.dart';
import '../actions/retry_action.dart';
import '../actions/retry_eligibility.dart';
import '../actions/retry_wording.dart';
import '../actions/title_action.dart';
import '../actions/title_wording.dart';
import '../domain/run_deletion.dart';
import '../domain/run_models.dart' show runIdentity;
const runMoreMenuKey = ValueKey<String>('run-more-menu');
const deleteRunActionKey = ValueKey<String>('run-delete-action');
const deleteRunActionLabel = 'Delete run';
/// Whether the run has anything for its more menu.
bool showRunMoreMenu(JsonMap run) =>
runTitleId(run) != null || canScheduleRun(run) || _canRetry(run);
/// Whether the run has anything for its more menu. [deletable] says the host
/// can apply a deletion, so a finished run offers Delete run.
bool showRunMoreMenu(JsonMap run, {bool deletable = false}) =>
runTitleId(run) != null ||
canScheduleRun(run) ||
_canRetry(run) ||
(deletable && runIsDeletable(run));
/// The run's own name for its action sheet: its title or pipeline, else
/// `Run <id>`, as its list row shows it.
@@ -26,13 +34,14 @@ String runMoreMenuTitle(JsonMap run) {
bool _canRetry(JsonMap run) => retryRunId(run) != null && canRetryRun(run);
enum _RunMoreItem { retry, rename, schedule }
enum _RunMoreItem { retry, rename, schedule, delete }
/// Each item keeps the key its standalone button had.
Key _keyOf(_RunMoreItem item) => switch (item) {
_RunMoreItem.retry => retryActionKey,
_RunMoreItem.rename => runTitleActionKey,
_RunMoreItem.schedule => scheduleRunActionKey,
_RunMoreItem.delete => deleteRunActionKey,
};
/// The run detail's more menu: Retry (failed runs only), Rename and Schedule
@@ -47,6 +56,7 @@ class RunMoreMenu extends StatefulWidget {
required this.onRunChanged,
required this.cupertino,
this.onRunOpened,
this.onDeleted,
this.menuKey = runMoreMenuKey,
});
@@ -58,6 +68,9 @@ class RunMoreMenu extends StatefulWidget {
/// Opens the new run an accepted retry names.
final ValueChanged<num>? onRunOpened;
/// Applies an answered deletion; without it the menu offers no Delete run.
final ValueChanged<RunsDeletion>? onDeleted;
/// Detail menus retain the shared key; list rows supply a per-run key.
final Key menuKey;
@@ -73,6 +86,8 @@ class _RunMoreMenuState extends State<RunMoreMenu> {
if (_canRetry(run)) (_RunMoreItem.retry, retryActionLabel),
if (runTitleId(run) != null) (_RunMoreItem.rename, runTitleActionLabel),
if (canScheduleRun(run)) (_RunMoreItem.schedule, scheduleRunActionLabel),
if (widget.onDeleted != null && runIsDeletable(run))
(_RunMoreItem.delete, deleteRunActionLabel),
];
void _pick(BuildContext context, _RunMoreItem item) {
@@ -97,6 +112,14 @@ class _RunMoreMenuState extends State<RunMoreMenu> {
);
case _RunMoreItem.schedule:
openScheduleRunEditor(context, run: run, gateway: widget.gateway);
case _RunMoreItem.delete:
confirmDeleteRuns(
context,
runs: [run],
gateway: widget.gateway,
onDeleted: widget.onDeleted!,
cupertino: widget.cupertino,
);
}
}
@@ -109,7 +132,12 @@ class _RunMoreMenuState extends State<RunMoreMenu> {
sheetTitle: runMoreMenuTitle(run),
actions: [
for (final (item, label) in _items)
AppMenuAction(key: _keyOf(item), value: item, label: label),
AppMenuAction(
key: _keyOf(item),
value: item,
label: label,
destructive: item == _RunMoreItem.delete,
),
],
onSelected: _pick,
);
+82 -6
View File
@@ -2,12 +2,34 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/runs_repository.dart';
import '../data/runs_sort_store.dart';
import '../domain/run_deletion.dart';
import '../domain/run_events.dart';
import '../domain/run_models.dart';
import 'runs_filter_options.dart';
import 'runs_selection.dart';
class RunsController extends ChangeNotifier {
RunsController(this.repository);
RunsController(this.repository, {this.sortStore}) {
selection.addListener(notifyListeners);
unawaited(_restoreSort());
}
final RunsRepository repository;
/// Where the sort choice persists; null keeps it for this controller only.
final RunsSortStore? sortStore;
/// Multi-select for deletion and the last deletion report.
final RunsSelection selection = RunsSelection();
/// Called when the open run was deleted (here or by another client) and its
/// detail closed, so the host can return its route to the list.
VoidCallback? onOpenRunRemoved;
/// Deleted run ids never return: a list read already in flight when the
/// deletion landed must not bring a row back.
final Set<int> _removed = {};
bool _sortChosen = false;
StreamSubscription<JsonMap>? _subscription;
List<JsonMap> runs = [];
JsonMap? detail, usage;
@@ -40,9 +62,15 @@ class RunsController extends ChangeNotifier {
void listen(Stream<JsonMap> frames) {
_subscription?.cancel();
_subscription = frames
.where((f) => f['type'] == 'run_event')
.listen(_event);
_subscription = frames.listen((frame) {
switch (frame['type']) {
case 'run_event':
_event(frame);
case 'runs_removed':
// Another client deleted these runs.
removeRuns(removedRunIds(frame));
}
});
}
Future<void> load([int? initialId]) async {
@@ -54,7 +82,7 @@ class RunsController extends ChangeNotifier {
try {
final result = await repository.listRuns();
if (!_listOwned(token)) return;
runs = result.runs;
_setRuns(result.runs);
usage = result.usage;
} catch (e) {
if (!_listOwned(token)) return;
@@ -183,8 +211,52 @@ class RunsController extends ChangeNotifier {
}
void setSort(String value) {
_sortChosen = true;
sort = value;
notifyListeners();
unawaited(sortStore?.write(value));
}
/// Applies the saved sort unless the operator already chose one.
Future<void> _restoreSort() async {
final saved = await sortStore?.read();
if (_disposed || _sortChosen || saved == null || saved == sort) return;
if (!runSorts.any((option) => option.$1 == saved)) return;
sort = saved;
notifyListeners();
}
void _setRuns(List<JsonMap> value) {
runs = _removed.isEmpty
? value
: value.where((run) => !_removed.contains(run['id'])).toList();
selection.retain(runs);
}
/// Drops deleted runs from the list and the selection, and closes the open
/// detail when it showed one of them.
void removeRuns(Iterable<int> ids) {
final gone = ids.toSet();
if (gone.isEmpty) return;
_removed.addAll(gone);
final before = runs.length;
runs = runs.where((run) => !gone.contains(run['id'])).toList();
var changed = runs.length != before;
selection.retain(runs);
final open = _selectedId;
if (open != null && gone.contains(open)) {
back();
onOpenRunRemoved?.call();
changed = false; // back() already notified.
}
if (changed) notifyListeners();
}
/// Applies the server's `runs_deleted` reply: removes what it deleted and
/// records the report (including refusals) for the list.
void applyDeletion(RunsDeletion deletion) {
removeRuns(deletion.deleted);
selection.applied(deletion);
}
/// Returns every filter to its default, like the browser's `Clear filters`.
@@ -197,8 +269,10 @@ class RunsController extends ChangeNotifier {
}
void _event(JsonMap frame) {
if (_removed.contains(frame['run_id'])) return;
final folded = foldRunEvent(runs, frame);
runs = folded.runs;
selection.retain(runs);
if (detail?['id'] == frame['run_id']) {
detail = foldRunEventDetail(detail, frame);
}
@@ -232,7 +306,7 @@ class RunsController extends ChangeNotifier {
try {
final result = await repository.listRuns();
if (!_listOwned(token)) return;
runs = result.runs;
_setRuns(result.runs);
usage = result.usage;
error = null;
} catch (e) {
@@ -326,6 +400,8 @@ class RunsController extends ChangeNotifier {
@override
void dispose() {
_disposed = true;
selection.removeListener(notifyListeners);
selection.dispose();
_subscription?.cancel();
_detailRefresh?.cancel();
super.dispose();
@@ -6,6 +6,7 @@ import 'runs_controller.dart';
const runSorts = [
('newest_first', 'Newest first'),
('oldest_first', 'Oldest first'),
('largest_first', 'Largest first'),
('longest_duration', 'Longest duration'),
('shortest_duration', 'Shortest duration'),
('pipeline_name', 'Pipeline name'),
@@ -23,6 +24,10 @@ const runTimeRanges = [
('last_30_days', 'Last 30 days'),
];
/// Sorts that list runs flat instead of under day headings: an order by
/// size has no meaningful day grouping.
const flatRunSorts = {'largest_first'};
/// The pipelines the loaded runs belong to, by name then id.
List<({int id, String name})> runFilterPipelines(RunsController controller) {
final names = <int, String>{};
+70 -125
View File
@@ -1,6 +1,3 @@
import '../../../ui/layout/app_list_avatar.dart';
import '../../../ui/layout/app_list_row.dart';
import '../../../ui/layout/section_heading.dart';
import '../../../ui/motion/motion.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
@@ -8,19 +5,21 @@ import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/floating_bar_layout.dart';
import '../../../ui/adaptive/host.dart';
import '../../../ui/status/run_status_icon.dart';
import '../../attention/notify/notification_controller.dart';
import '../../attention/runtime/attention_controller.dart';
import '../../attention/runtime/attention_store.dart';
import '../../attention/ui/needs_you_runs_heading.dart';
import '../../../ui/text/relative_time.dart';
import '../domain/run_models.dart';
import '../../../shell/shell_bar.dart';
import 'run_more_menu.dart';
import 'run_list_row.dart';
import 'runs_controller.dart';
import 'runs_filter_options.dart';
import 'runs_selection_bar.dart';
import 'runs_stats_page.dart';
import 'runs_filters.dart';
export 'run_list_row.dart';
class RunsList extends StatelessWidget {
const RunsList({
super.key,
@@ -58,6 +57,30 @@ class RunsList extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Select mode replaces the bar: `N selected` and its size, Delete, Done.
if (controller.selection.active) {
final bar = runsSelectionBar(context, controller);
if (!ShellBar.available(context)) {
return _ownBar(context, [
Expanded(
child: Text(
[bar.title, ?bar.subtitle].join(' · '),
key: runsSelectionCountKey,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
...bar.actions,
]);
}
return ShellBar(
active: active,
title: bar.title,
subtitle: bar.subtitle,
actions: bar.actions,
child: _list(context),
);
}
final actions = [
// The Needs-you bell sits with the other actions, freeing the row.
NeedsYouRunsHeading(
@@ -73,22 +96,11 @@ class RunsList extends StatelessWidget {
...RunsBarActions(
controller,
).build(context, onStats: () => openRunsStats(context, controller)),
if (controller.runs.isNotEmpty) runsSelectAction(context, controller),
];
// Outside the app shell (the list on its own) the actions head the list.
if (!ShellBar.available(context)) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(8, 4, 8, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: actions,
),
),
Expanded(child: _list(context)),
],
);
return _ownBar(context, [const Spacer(), ...actions]);
}
return ShellBar(
active: active,
@@ -102,6 +114,17 @@ class RunsList extends StatelessWidget {
);
}
Widget _ownBar(BuildContext context, List<Widget> bar) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 8, 0),
child: Row(children: bar),
),
Expanded(child: _list(context)),
],
);
Widget _list(BuildContext context) {
if (controller.loading && controller.runs.isEmpty) {
return _state(
@@ -119,6 +142,8 @@ class RunsList extends StatelessWidget {
// behind the top bar with the runs and start below it at rest.
final header = [
if (controller.error != null) _inlineError(context),
if (controller.selection.report != null)
RunsDeleteReport(controller: controller),
RunsFilters(controller: controller),
];
if (controller.visibleRuns.isNotEmpty) return _groupedRuns(context, header);
@@ -145,11 +170,18 @@ class RunsList extends StatelessWidget {
}
Widget _groupedRuns(BuildContext context, List<Widget> header) {
final groups = groupRunsByDay(controller.visibleRuns, DateTime.now());
final entries = <({String? label, JsonMap? run})>[];
for (final group in groups) {
entries.add((label: group.label, run: null));
entries.addAll(group.runs.map((run) => (label: null, run: run)));
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)),
);
} else {
final groups = groupRunsByDay(controller.visibleRuns, DateTime.now());
for (final group in groups) {
entries.add((day: group, run: null));
entries.addAll(group.runs.map((run) => (day: null, run: run)));
}
}
// Runs that start while the list is open enter with a short fade.
return ArrivalScope(
@@ -158,10 +190,7 @@ class RunsList extends StatelessWidget {
);
}
Widget _entriesList(
List<({String? label, JsonMap? run})> entries,
List<Widget> header,
) {
Widget _entriesList(List<_Entry> entries, List<Widget> header) {
// The default padding is the media padding: the first row starts below
// the top bar and the last clears the floating tab bar.
return ListView.builder(
@@ -169,14 +198,12 @@ class RunsList extends StatelessWidget {
itemBuilder: (context, index) {
if (index < header.length) return header[index];
final entry = entries[index - header.length];
if (entry.label case final label?) {
if (entry.day case final day?) {
// A day heading reads as a divider between groups of runs.
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Semantics(
header: true,
child: SectionHeading(title: label, minHeight: 32),
),
return RunsDayHeading(
label: day.label,
runs: day.runs,
controller: controller,
);
}
// The last run of a day (before the next heading) has no divider.
@@ -269,7 +296,14 @@ class RunsList extends StatelessWidget {
Widget _runTile(BuildContext context, JsonMap run, {bool divider = true}) {
final id = run['id'];
final selection = controller.selection;
return RunListRow(
selecting: selection.active,
checked: selection.contains(id),
onToggle: () => selection.toggle(run),
// A long-press enters select mode with this run selected.
onLongPress: () => selection.enter(run),
onDeleted: controller.applyDeletion,
run: run,
divider: divider,
selected: id == controller.selectedRunId,
@@ -282,93 +316,4 @@ class RunsList extends StatelessWidget {
}
}
/// One run in the list: a status avatar, title/time, and one muted fact
/// line in the app's shared row. Its detail retains the full timestamp,
/// path, and other diagnostics.
class RunListRow extends StatelessWidget {
const RunListRow({
super.key,
required this.run,
required this.now,
this.selected = false,
this.divider = true,
this.onTap,
this.gateway,
this.onRunChanged,
this.onRunOpened,
});
final JsonMap run;
final DateTime now;
final bool selected;
/// False for the last row before a day heading or the end of the list.
final bool divider;
final VoidCallback? onTap;
final ApiGateway? gateway;
final ValueChanged<JsonMap>? onRunChanged;
final ValueChanged<num>? onRunOpened;
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final identity = runIdentity(run['title'], run['name']);
final id = run['id'];
final title = identity.label.isEmpty ? 'Run $id' : identity.label;
final facts = runRowFacts(run, now);
// A run without its own title is named by its pipeline, so the pipeline
// line does not repeat it.
final pipeline = identity.pipeline?.trim();
// With no stored title, `name` is already the row title; repeating it as
// a subtitle adds no identity. A titled run with an empty name genuinely
// lacks its pipeline, so make that absence explicit.
final pipelineLabel = pipeline == null
? null
: pipeline.isEmpty
? 'Pipeline unavailable'
: pipeline;
final scheduled = run['scheduled'] == true;
final subtitle = [
?pipelineLabel,
if (scheduled) 'Scheduled',
?facts.duration,
?facts.progress,
].join(' · ');
// A narrow pane keeps the decision facts: the pipeline, and progress
// while executing (duration only when there is no pipeline to show).
final compactSubtitle = [
?pipelineLabel,
if (scheduled) 'Scheduled',
if (run['executing'] == true && facts.progress != null) facts.progress!,
if (pipelineLabel == null && facts.duration != null) facts.duration!,
].join(' · ');
final state = runStateOf(run['status']);
return AppListRow(
key: ValueKey('run-row-$id'),
cupertino: cupertino,
selected: selected,
divider: divider,
onTap: onTap,
leading: AppListAvatar(
foreground: runStatusColor(state).resolveFrom(context),
child: RunStatusIcon(state: state, label: runStatusLabel(run)),
),
title: Text(title),
time: formatRelativeTimestamp('${run['created_at'] ?? ''}', now: now),
subtitle: Text(subtitle),
compactSubtitle: Text(compactSubtitle),
// A narrow list pane beside the open run leaves the row no room for a
// second control; the open run's detail beside it carries the same menu.
menu: gateway != null && onRunChanged != null && showRunMoreMenu(run)
? RunMoreMenu(
run: run,
gateway: gateway!,
onRunChanged: onRunChanged!,
onRunOpened: onRunOpened,
cupertino: cupertino,
menuKey: ValueKey('run-list-more-menu-$id'),
)
: null,
);
}
}
typedef _Entry = ({({String label, List<JsonMap> runs})? day, JsonMap? run});
@@ -0,0 +1,85 @@
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<int> _ids = {};
String? _report;
bool get active => _active;
Set<int> 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<JsonMap> 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<JsonMap> 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<JsonMap> 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();
}
}
@@ -0,0 +1,226 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../../../ui/layout/section_heading.dart';
import '../actions/delete_runs_action.dart';
import '../domain/run_deletion.dart';
import 'runs_controller.dart';
const runsSelectKey = ValueKey<String>('runs.select');
const runsSelectDoneKey = ValueKey<String>('runs.select.done');
const runsDeleteSelectedKey = ValueKey<String>('runs.select.delete');
const runsSelectionCountKey = ValueKey<String>('runs.select.count');
const runsDeleteReportKey = ValueKey<String>('runs.delete.report');
const runsDeleteReportDismissKey = ValueKey<String>(
'runs.delete.report.dismiss',
);
/// The day heading's Select all / Deselect all toggle key.
ValueKey<String> runsDaySelectKey(String day) =>
ValueKey('runs.select.day.$day');
/// The Runs bar's `Select` action, entering multi-select.
Widget runsSelectAction(BuildContext context, RunsController controller) {
void enter() => controller.selection.enter();
if (usesCupertinoHost(context)) {
return Semantics(
button: true,
label: 'Select',
excludeSemantics: true,
onTap: enter,
child: CupertinoButton(
key: runsSelectKey,
padding: EdgeInsets.zero,
minimumSize: const Size.square(kMinInteractiveDimensionCupertino),
onPressed: enter,
child: const Icon(CupertinoIcons.checkmark_circle),
),
);
}
return IconButton(
key: runsSelectKey,
tooltip: 'Select',
onPressed: enter,
icon: const Icon(Icons.checklist),
);
}
/// What the bar shows in select mode: `N selected` over the selection's size,
/// then Delete and Done.
({String title, String? subtitle, List<Widget> actions}) runsSelectionBar(
BuildContext context,
RunsController controller,
) {
final selection = controller.selection;
final selected = [
for (final run in controller.runs)
if (selection.contains(run['id'])) run,
];
final count = selected.length;
final size = count == 0 ? null : runsSizeLabel(selected);
final cupertino = usesCupertinoHost(context);
final delete = count == 0
? null
: () => confirmDeleteRuns(
context,
runs: selected,
gateway: controller.repository.gateway,
onDeleted: controller.applyDeletion,
cupertino: cupertino,
);
final deleteLabel = count == 0
? 'Delete selected runs'
: 'Delete $count selected ${count == 1 ? 'run' : 'runs'}';
final List<Widget> actions;
if (cupertino) {
actions = [
Semantics(
button: true,
enabled: delete != null,
label: deleteLabel,
excludeSemantics: true,
onTap: delete,
child: CupertinoButton(
key: runsDeleteSelectedKey,
onPressed: delete,
child: Text(
'Delete',
style: TextStyle(
color: delete == null
? null
: CupertinoColors.systemRed.resolveFrom(context),
),
),
),
),
CupertinoButton(
key: runsSelectDoneKey,
onPressed: selection.exit,
child: const Text('Done'),
),
];
} else {
final scheme = Theme.of(context).colorScheme;
actions = [
Semantics(
label: deleteLabel,
excludeSemantics: true,
onTap: delete,
button: true,
enabled: delete != null,
child: TextButton(
key: runsDeleteSelectedKey,
style: TextButton.styleFrom(foregroundColor: scheme.error),
onPressed: delete,
child: const Text('Delete'),
),
),
TextButton(
key: runsSelectDoneKey,
onPressed: selection.exit,
child: const Text('Done'),
),
];
}
return (title: '$count selected', subtitle: size, actions: actions);
}
/// A day's heading; in select mode it carries that day's Select all /
/// Deselect all toggle, covering only the day's finished runs.
class RunsDayHeading extends StatelessWidget {
const RunsDayHeading({
super.key,
required this.label,
required this.runs,
required this.controller,
});
final String label;
final List<JsonMap> runs;
final RunsController controller;
@override
Widget build(BuildContext context) {
final selection = controller.selection;
final trailing = <Widget>[];
if (selection.active) {
final any = deletableRunIds(runs).isNotEmpty;
final all = selection.allSelected(runs);
final text = all ? 'Deselect all' : 'Select all';
final toggle = any ? () => selection.toggleAll(runs) : null;
final key = runsDaySelectKey(label);
trailing.add(
Semantics(
button: true,
enabled: any,
label: any
? '$text $label'
: '$text $label. No finished runs to select.',
excludeSemantics: true,
onTap: toggle,
child: usesCupertinoHost(context)
? CupertinoButton(
key: key,
padding: const EdgeInsets.symmetric(horizontal: 8),
minimumSize: const Size(0, kMinInteractiveDimensionCupertino),
onPressed: toggle,
child: Text(text),
)
: TextButton(key: key, onPressed: toggle, child: Text(text)),
),
);
}
return Padding(
padding: const EdgeInsets.only(top: 8),
child: SectionHeading(
title: label,
minHeight: 32,
header: true,
trailing: trailing,
),
);
}
}
/// The last deletion's outcome above the list, until dismissed.
class RunsDeleteReport extends StatelessWidget {
const RunsDeleteReport({super.key, required this.controller});
final RunsController controller;
@override
Widget build(BuildContext context) {
final report = controller.selection.report;
if (report == null) return const SizedBox.shrink();
final cupertino = usesCupertinoHost(context);
final dismiss = controller.selection.dismissReport;
return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 8, 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Semantics(
liveRegion: true,
child: Text(report, key: runsDeleteReportKey),
),
),
cupertino
? CupertinoButton(
key: runsDeleteReportDismissKey,
padding: const EdgeInsets.symmetric(horizontal: 8),
onPressed: dismiss,
child: const Text('Dismiss'),
)
: TextButton(
key: runsDeleteReportDismissKey,
onPressed: dismiss,
child: const Text('Dismiss'),
),
],
),
);
}
}
+31 -4
View File
@@ -23,7 +23,9 @@ const appListRowDividerKey = ValueKey<String>('app-list-row-divider');
/// Layout: [leading] (an [AppListAvatar]), then a bold one-line [title] with
/// the [time] at its trailing edge, then one muted [subtitle] line (with an
/// optional [subtitleLeading] dot/prefix and [subtitleTrailing] mark), then
/// the optional [menu] (an `AppOverflowMenu`). An inset hairline [divider]
/// the optional [menu] (an `AppOverflowMenu`). A row in a multi-select list
/// puts its checkbox in [selectionControl], which leads the row even when it
/// is compact. An inset hairline [divider]
/// under the text column separates rows. Nothing has a fixed height: the row
/// grows with text scaling and every line ellipsises.
///
@@ -43,6 +45,8 @@ class AppListRow extends StatelessWidget {
this.subtitleTrailing,
this.menu,
this.onTap,
this.onLongPress,
this.selectionControl,
this.tapKey,
this.selected = false,
this.emphasized = false,
@@ -64,6 +68,12 @@ class AppListRow extends StatelessWidget {
final Widget? menu;
final VoidCallback? onTap;
/// A touch long-press on the row (for example, entering a select mode).
final VoidCallback? onLongPress;
/// A checkbox leading the row in a multi-select list; kept when compact.
final Widget? selectionControl;
/// Placed on the tap target ([InkWell] / [GestureDetector]).
final Key? tapKey;
final bool selected;
@@ -112,6 +122,11 @@ class AppListRow extends StatelessWidget {
),
child: Row(
children: [
if (selectionControl case final control?)
Padding(
padding: const EdgeInsetsDirectional.only(end: 8),
child: control,
),
if (showLeading)
Padding(
padding: const EdgeInsetsDirectional.only(end: _avatarGap),
@@ -130,6 +145,7 @@ class AppListRow extends StatelessWidget {
? _CupertinoRowSurface(
tapKey: tapKey,
onTap: onTap,
onLongPress: onLongPress,
selected: selected,
child: content,
)
@@ -138,11 +154,19 @@ class AppListRow extends StatelessWidget {
color: selected
? selectedColor(context, cupertino: false)
: Colors.transparent,
child: InkWell(key: tapKey, onTap: onTap, child: content),
child: InkWell(
key: tapKey,
onTap: onTap,
onLongPress: onLongPress,
child: content,
),
);
if (!divider) return surface;
final textStart =
start + (showLeading ? kAppListAvatarSize + _avatarGap : 0);
// The divider stays under the text column; a checkbox's width is
// not known here, so a selectable row's divider starts at the inset.
final textStart = selectionControl != null
? start
: start + (showLeading ? kAppListAvatarSize + _avatarGap : 0);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -289,11 +313,13 @@ class _CupertinoRowSurface extends StatefulWidget {
required this.tapKey,
required this.onTap,
required this.selected,
this.onLongPress,
required this.child,
});
final Key? tapKey;
final VoidCallback? onTap;
final VoidCallback? onLongPress;
final bool selected;
final Widget child;
@@ -320,6 +346,7 @@ class _CupertinoRowSurfaceState extends State<_CupertinoRowSurface> {
key: widget.tapKey,
behavior: HitTestBehavior.opaque,
onTap: widget.onTap,
onLongPress: widget.onLongPress,
onTapDown: enabled ? (_) => _press(true) : null,
onTapUp: enabled ? (_) => _press(false) : null,
onTapCancel: enabled ? () => _press(false) : null,