feat(app): add read-only saved-schedules list screen

This commit is contained in:
2026-10-21 17:00:50 +01:00
parent a290858373
commit ebfa7f7fac
17 changed files with 2229 additions and 0 deletions
+94
View File
@@ -0,0 +1,94 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import 'data/schedules_repository.dart';
import 'domain/saved_schedule.dart';
import 'ui/list/schedule_list_controller.dart';
import 'ui/list/schedule_list_view.dart';
/// The saved-schedules list body.
///
/// The shell supplies navigation chrome. Selecting a row reports the exact
/// [SavedSchedule] the server returned; this screen does not create, edit,
/// delete, pause or enable anything.
class SchedulesScreen extends StatefulWidget {
const SchedulesScreen({
super.key,
required this.gateway,
required this.onOpen,
this.pipelineId,
});
final ApiGateway gateway;
final ValueChanged<SavedSchedule> onOpen;
final int? pipelineId;
@override
State<SchedulesScreen> createState() => _SchedulesScreenState();
}
class _SchedulesScreenState extends State<SchedulesScreen> {
late SchedulesController _controller;
late final TextEditingController _searchController;
final ScrollController _scrollController = ScrollController();
@override
void initState() {
super.initState();
_controller = _createController();
_searchController = TextEditingController(text: _controller.query);
unawaited(_controller.refresh());
}
SchedulesController _createController() => SchedulesController(
repository: SchedulesRepository(widget.gateway),
pipelineId: widget.pipelineId,
);
@override
void didUpdateWidget(covariant SchedulesScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (identical(oldWidget.gateway, widget.gateway) &&
oldWidget.pipelineId == widget.pipelineId) {
return;
}
final query = _controller.query;
final filter = _controller.filter;
_controller.dispose();
_controller = _createController();
_controller.setQuery(query);
_controller.setFilter(filter);
unawaited(_controller.refresh());
}
@override
void dispose() {
_controller.dispose();
_searchController.dispose();
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final cupertino =
Localizations.of<MaterialLocalizations>(
context,
MaterialLocalizations,
) ==
null;
return AnimatedBuilder(
animation: _controller,
builder: (context, _) => SchedulesListView(
controller: _controller,
searchController: _searchController,
scrollController: _scrollController,
cupertino: cupertino,
onOpen: widget.onOpen,
onRefresh: () => unawaited(_controller.refresh()),
),
);
}
}
@@ -0,0 +1,168 @@
import 'package:flutter/foundation.dart';
import '../../data/schedules_repository.dart';
import '../../domain/saved_schedule.dart';
import 'schedule_list_format.dart';
enum ScheduleListFilter { all, enabled }
extension ScheduleListFilterLabel on ScheduleListFilter {
String get label => switch (this) {
ScheduleListFilter.all => 'All',
ScheduleListFilter.enabled => 'Enabled',
};
}
/// A list refresh failure, kept apart from a valid empty result.
class ScheduleListFailure {
const ScheduleListFailure(this.message, {this.unsupported = false});
factory ScheduleListFailure.from(Object error) {
final text = error is SchedulesRepositoryException
? error.message
: '$error';
if (text == _unsupportedReply || _unsupportedPattern.hasMatch(text)) {
return ScheduleListFailure(
'This server does not support saved schedules. '
'Upgrade the server to use schedules. ($text)',
unsupported: true,
);
}
return ScheduleListFailure(text);
}
final String message;
final bool unsupported;
/// The repository's exact report for a reply without `type: schedules`.
static const _unsupportedReply = 'The server returned no schedules response.';
/// Matches the web client's older-server detection, so a server that refuses
/// the command with its own `unknown request`/`unsupported` wording gets the
/// same upgrade guidance instead of only the raw error.
static final _unsupportedPattern = RegExp(
r'unknown (message|request|command)|unsupported.*schedule',
caseSensitive: false,
);
}
/// Loads saved run configurations with search and enabled filtering.
///
/// This controller is read-only: it only calls `list_schedules`. It never saves,
/// deletes, pauses or enables a schedule, and it never treats schedules as
/// pipeline definitions.
class SchedulesController extends ChangeNotifier {
SchedulesController({required this.repository, this.pipelineId});
final SchedulesRepository repository;
final int? pipelineId;
List<SavedSchedule> _schedules = const [];
List<SavedSchedule>? _visibleSchedules;
bool _loading = false;
bool _loaded = false;
ScheduleListFailure? _failure;
String _query = '';
ScheduleListFilter _filter = ScheduleListFilter.all;
int _generation = 0;
bool _disposed = false;
List<SavedSchedule> get schedules => _schedules;
bool get isLoading => _loading;
bool get hasLoaded => _loaded;
ScheduleListFailure? get failure => _failure;
String get query => _query;
ScheduleListFilter get filter => _filter;
/// Cached until the list, query or filter changes; the view, count label and
/// toolbar all read it during one build.
List<SavedSchedule> get visibleSchedules =>
_visibleSchedules ??= _filterSchedules();
List<SavedSchedule> _filterSchedules() {
final needle = _query.trim().toLowerCase();
return List.unmodifiable([
for (final schedule in _schedules)
if ((_filter == ScheduleListFilter.all || schedule.enabled) &&
(needle.isEmpty || _matches(schedule, needle)))
schedule,
]);
}
void _invalidateVisibility() => _visibleSchedules = null;
bool get isInitialLoading => _loading && !_loaded;
/// Empty-state wording that names the actual reason when the search box is
/// empty and only the enabled filter hides every row.
String get emptyMessage => _query.trim().isNotEmpty
? 'No schedules match this search.'
: 'No enabled schedules.';
String get countLabel =>
scheduleCountLabel(visibleSchedules.length, _schedules.length);
bool _matches(SavedSchedule schedule, String needle) {
final haystack = [
scheduleDisplayName(schedule),
schedule.prompt,
if (schedule.pipelineId != null) 'Pipeline ${schedule.pipelineId}',
].join('\n').toLowerCase();
return haystack.contains(needle);
}
void setQuery(String value) {
if (value == _query) return;
_query = value;
_invalidateVisibility();
_notify();
}
void setFilter(ScheduleListFilter value) {
if (value == _filter) return;
_filter = value;
_invalidateVisibility();
_notify();
}
void clearQuery() => setQuery('');
/// Reloads the list without recreating the screen, so the search field and
/// the list's scroll position survive a refresh.
///
/// Only the newest request may publish. A slower, older reply is ignored,
/// including one that completes after this controller was disposed.
Future<void> refresh() async {
final generation = ++_generation;
_loading = true;
_failure = null;
_notify();
try {
final schedules = await repository.listSchedules(pipelineId: pipelineId);
if (!_owns(generation)) return;
_schedules = List.unmodifiable(schedules);
_invalidateVisibility();
_loaded = true;
} catch (error) {
if (!_owns(generation)) return;
_failure = ScheduleListFailure.from(error);
} finally {
if (_owns(generation)) {
_loading = false;
_notify();
}
}
}
bool _owns(int generation) => !_disposed && generation == _generation;
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
@@ -0,0 +1,70 @@
import '../../domain/saved_schedule.dart';
/// User-facing values for one saved schedule row.
///
/// Every accessor reports what the server sent. A missing field keeps a
/// distinct "unavailable"/"not scheduled" value instead of being invented.
String scheduleDisplayName(SavedSchedule schedule) {
final name = schedule.name.trim();
return name.isEmpty ? 'Unnamed schedule' : name;
}
String scheduleStatusLabel(SavedSchedule schedule) =>
schedule.enabled ? 'Enabled' : 'Paused';
String schedulePipelineVersionValue(SavedSchedule schedule) {
final pipeline = schedule.pipelineId == null
? 'Pipeline unavailable'
: 'Pipeline ${schedule.pipelineId}';
final version = schedule.version == null
? 'Version unavailable'
: 'v${schedule.version}';
return '$pipeline · $version';
}
String scheduleWorkspaceValue(SavedSchedule schedule) {
final workspace = schedule.workspace.trim();
return workspace.isEmpty ? 'Workspace unavailable' : workspace;
}
String scheduleTimerValue(SavedSchedule schedule) {
final rule = schedule.rule;
final repeat = rule.every.isNotEmpty
? 'Every ${rule.every}'
: rule.times.isNotEmpty
? rule.times.join(', ')
: '';
if (repeat.isEmpty) return 'Timer unavailable';
return rule.days.isEmpty ? repeat : '$repeat · ${rule.days.join(', ')}';
}
/// Matches the web client: an empty or `Local` rule timezone means the server
/// applies its own timezone, which is not an absent value.
String scheduleTimezoneValue(SavedSchedule schedule) {
final timezone = schedule.rule.timezone.trim();
return timezone.isEmpty || timezone == 'Local' ? 'Server timezone' : timezone;
}
/// Paused schedules show the pause state, as in the current web client; enabled
/// schedules show the server's `next_due` or an honest unavailable value.
String scheduleNextDueValue(SavedSchedule schedule) {
if (!schedule.enabled) return 'Paused';
return scheduleDueValue(schedule.nextDue);
}
String scheduleDueValue(String value) {
if (value.isEmpty) return 'Not scheduled';
final date = DateTime.tryParse(value);
if (date == null) return 'Next time unavailable';
final local = date.toLocal();
String two(int part) => part.toString().padLeft(2, '0');
return '${local.year.toString().padLeft(4, '0')}-${two(local.month)}-'
'${two(local.day)} ${two(local.hour)}:${two(local.minute)} '
'(your local time)';
}
String scheduleCountLabel(int visible, int total) {
if (visible != total) return '$visible of $total schedules';
return total == 1 ? '1 schedule' : '$total schedules';
}
@@ -0,0 +1,115 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../domain/saved_schedule.dart';
import 'schedule_list_format.dart';
/// One tappable saved-schedule row with the server's actual values.
class ScheduleListRow extends StatelessWidget {
const ScheduleListRow({
super.key,
required this.schedule,
required this.cupertino,
required this.onOpen,
});
final SavedSchedule schedule;
final bool cupertino;
final VoidCallback onOpen;
@override
Widget build(BuildContext context) {
final content = Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: _details(context)),
const SizedBox(width: 8),
Icon(
cupertino ? CupertinoIcons.chevron_right : Icons.chevron_right,
color: _secondaryColor(context),
),
],
),
);
if (cupertino) {
return CupertinoButton(
padding: EdgeInsets.zero,
alignment: Alignment.centerLeft,
onPressed: onOpen,
child: content,
);
}
return InkWell(onTap: onOpen, child: content);
}
Widget _details(BuildContext context) {
final prompt = schedule.prompt;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Text(
scheduleDisplayName(schedule),
style: _titleStyle(context),
),
),
const SizedBox(width: 8),
Text(scheduleStatusLabel(schedule), style: _statusStyle(context)),
],
),
if (prompt.isNotEmpty) ...[
const SizedBox(height: 4),
Text(prompt, style: _bodyStyle(context)),
],
const SizedBox(height: 6),
_meta(context, schedulePipelineVersionValue(schedule)),
_meta(context, 'Workspace: ${scheduleWorkspaceValue(schedule)}'),
_meta(context, 'Timer: ${scheduleTimerValue(schedule)}'),
_meta(context, 'Timezone: ${scheduleTimezoneValue(schedule)}'),
_meta(context, 'Next due: ${scheduleNextDueValue(schedule)}'),
],
);
}
Widget _meta(BuildContext context, String value) =>
Text(value, style: _metaStyle(context));
TextStyle? _titleStyle(BuildContext context) => cupertino
? CupertinoTheme.of(
context,
).textTheme.textStyle.copyWith(fontWeight: FontWeight.w600)
: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600);
TextStyle? _bodyStyle(BuildContext context) =>
cupertino ? CupertinoTheme.of(context).textTheme.textStyle : null;
TextStyle? _metaStyle(BuildContext context) => cupertino
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
fontSize: 14,
color: _secondaryColor(context),
)
: Theme.of(
context,
).textTheme.bodySmall?.copyWith(color: _secondaryColor(context));
TextStyle? _statusStyle(BuildContext context) => _metaStyle(
context,
)?.copyWith(color: _statusColor(context), fontWeight: FontWeight.w600);
Color _secondaryColor(BuildContext context) => cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
Color _statusColor(BuildContext context) => schedule.enabled
? (cupertino
? CupertinoTheme.of(context).primaryColor
: Theme.of(context).colorScheme.primary)
: _secondaryColor(context);
}
@@ -0,0 +1,179 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'schedule_list_controller.dart';
const scheduleSearchFieldKey = ValueKey<String>('schedule-search-field');
const scheduleFilterKey = ValueKey<String>('schedule-filter');
const scheduleRefreshKey = ValueKey<String>('schedule-refresh');
/// Search, enabled filter and the read-only refresh control.
class ScheduleListToolbar extends StatelessWidget {
const ScheduleListToolbar({
super.key,
required this.controller,
required this.searchController,
required this.cupertino,
required this.onRefresh,
});
final SchedulesController controller;
final TextEditingController searchController;
final bool cupertino;
final VoidCallback onRefresh;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: _search(context),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
children: [
Expanded(
child: Align(
alignment: AlignmentDirectional.centerStart,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 480),
child: _filter(context),
),
),
),
const SizedBox(width: 8),
_refresh(context),
],
),
),
if (controller.hasLoaded)
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(controller.countLabel, style: _metaStyle(context)),
Text(
'Saved run configurations, not pipeline definitions.',
style: _metaStyle(context),
),
],
),
),
],
);
}
Widget _search(BuildContext context) {
if (cupertino) {
return CupertinoSearchTextField(
key: scheduleSearchFieldKey,
controller: searchController,
placeholder: 'Search schedules',
onChanged: controller.setQuery,
onSuffixTap: () {
searchController.clear();
controller.clearQuery();
},
);
}
return TextField(
key: scheduleSearchFieldKey,
controller: searchController,
onChanged: controller.setQuery,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
hintText: 'Search schedules',
prefixIcon: const Icon(Icons.search),
suffixIcon: controller.query.isEmpty
? null
: IconButton(
tooltip: 'Clear search',
icon: const Icon(Icons.clear),
onPressed: () {
searchController.clear();
controller.clearQuery();
},
),
),
);
}
Widget _filter(BuildContext context) {
if (cupertino) {
return CupertinoSlidingSegmentedControl<ScheduleListFilter>(
key: scheduleFilterKey,
groupValue: controller.filter,
onValueChanged: (value) {
if (value != null) controller.setFilter(value);
},
children: {
for (final filter in ScheduleListFilter.values)
filter: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
child: Text(filter.label),
),
},
);
}
return SegmentedButton<ScheduleListFilter>(
key: scheduleFilterKey,
segments: [
for (final filter in ScheduleListFilter.values)
ButtonSegment<ScheduleListFilter>(
value: filter,
label: Text(filter.label),
),
],
selected: {controller.filter},
showSelectedIcon: false,
onSelectionChanged: (selection) {
if (selection.isNotEmpty) controller.setFilter(selection.first);
},
);
}
Widget _refresh(BuildContext context) {
if (controller.isLoading) {
return Semantics(
label: 'Refreshing schedules',
liveRegion: true,
child: Padding(
padding: const EdgeInsets.all(12),
child: cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(strokeWidth: 2),
),
);
}
if (cupertino) {
return Semantics(
label: 'Refresh schedules',
child: CupertinoButton(
key: scheduleRefreshKey,
padding: EdgeInsets.zero,
onPressed: onRefresh,
child: const Icon(CupertinoIcons.refresh),
),
);
}
return IconButton(
key: scheduleRefreshKey,
tooltip: 'Refresh schedules',
onPressed: onRefresh,
icon: const Icon(Icons.refresh),
);
}
TextStyle? _metaStyle(BuildContext context) => cupertino
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
fontSize: 14,
color: CupertinoColors.secondaryLabel.resolveFrom(context),
)
: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
);
}
@@ -0,0 +1,188 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../domain/saved_schedule.dart';
import 'schedule_list_controller.dart';
import 'schedule_list_row.dart';
import 'schedule_list_toolbar.dart';
const scheduleListKey = ValueKey<String>('schedule-list');
const scheduleRetryKey = ValueKey<String>('schedule-retry');
/// Platform-adaptive list body. It owns no navigation chrome; the shell frames
/// it as the Schedules destination.
class SchedulesListView extends StatelessWidget {
const SchedulesListView({
super.key,
required this.controller,
required this.searchController,
required this.scrollController,
required this.cupertino,
required this.onOpen,
required this.onRefresh,
});
final SchedulesController controller;
final TextEditingController searchController;
final ScrollController scrollController;
final bool cupertino;
final ValueChanged<SavedSchedule> onOpen;
final VoidCallback onRefresh;
@override
Widget build(BuildContext context) {
return Column(
children: [
ScheduleListToolbar(
controller: controller,
searchController: searchController,
cupertino: cupertino,
onRefresh: onRefresh,
),
Expanded(child: _body(context)),
],
);
}
Widget _body(BuildContext context) {
final failure = controller.failure;
if (failure != null && controller.schedules.isEmpty) {
return _failureState(context, failure);
}
if (controller.isInitialLoading) return _loadingState(context);
if (controller.schedules.isEmpty) {
return _emptyState('No schedules yet.');
}
final content = controller.visibleSchedules.isEmpty
? _emptyState(controller.emptyMessage)
: _list(context);
// The banner slot is always present so a failed or recovered refresh does
// not change the list's ancestors. Replacing the ListView would rebuild the
// Scrollable and drop the user's scroll offset.
return Column(
children: [
if (failure != null)
_failureBanner(context, failure)
else
const SizedBox.shrink(),
Expanded(child: content),
],
);
}
Widget _list(BuildContext context) {
final schedules = controller.visibleSchedules;
return ListView.separated(
key: scheduleListKey,
controller: scrollController,
padding: const EdgeInsets.only(top: 4, bottom: 24),
itemCount: schedules.length,
separatorBuilder: (context, index) =>
cupertino ? _cupertinoSeparator(context) : const Divider(height: 1),
itemBuilder: (context, index) {
final schedule = schedules[index];
return ScheduleListRow(
key: ValueKey<String>(
'schedule-row-$index-${schedule.id ?? 'unknown'}',
),
schedule: schedule,
cupertino: cupertino,
onOpen: () => onOpen(schedule),
);
},
);
}
Widget _cupertinoSeparator(BuildContext context) => Container(
height: 1 / MediaQuery.devicePixelRatioOf(context),
color: CupertinoColors.separator.resolveFrom(context),
);
Widget _loadingState(BuildContext context) {
return Center(
child: Semantics(
liveRegion: true,
label: 'Loading schedules',
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
const SizedBox(height: 12),
const Text('Loading schedules…'),
],
),
),
);
}
Widget _emptyState(String message) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(message, textAlign: TextAlign.center),
),
);
}
Widget _failureState(BuildContext context, ScheduleListFailure failure) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_failureText(context, failure),
const SizedBox(height: 16),
_retryButton(),
],
),
),
);
}
Widget _failureBanner(BuildContext context, ScheduleListFailure failure) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: _failureText(context, failure)),
const SizedBox(width: 8),
_retryButton(),
],
),
);
}
Widget _failureText(BuildContext context, ScheduleListFailure failure) {
final color = cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error;
return Semantics(
liveRegion: true,
child: Text(
failure.message,
textAlign: TextAlign.center,
style: TextStyle(color: color),
),
);
}
Widget _retryButton() {
if (cupertino) {
return CupertinoButton(
key: scheduleRetryKey,
padding: EdgeInsets.zero,
onPressed: onRefresh,
child: const Text('Retry'),
);
}
return TextButton(
key: scheduleRetryKey,
onPressed: onRefresh,
child: const Text('Retry'),
);
}
}