initial commit
This commit is contained in:
@@ -0,0 +1,267 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
import '../../core/models/models.dart';
|
||||
import '../../core/network/api_exception.dart';
|
||||
import '../../core/theme/theme_x.dart';
|
||||
import '../../core/widgets/backup_target_form_dialog.dart';
|
||||
import '../../core/widgets/backup_targets_list.dart';
|
||||
import '../../core/widgets/empty_state.dart';
|
||||
import '../../core/widgets/error_banner.dart';
|
||||
import '../../core/widgets/sparkline.dart';
|
||||
import '../../data/repositories/node_repository.dart';
|
||||
import 'widgets/backup_config_form_dialog.dart';
|
||||
import 'widgets/backup_history_table.dart';
|
||||
|
||||
class BackupsScreen extends ConsumerWidget {
|
||||
const BackupsScreen({super.key});
|
||||
|
||||
Future<void> _runNow(BuildContext context, WidgetRef ref) async {
|
||||
final repo = ref.read(nodeRepositoryProvider);
|
||||
if (repo == null) return;
|
||||
try {
|
||||
await repo.runBackup();
|
||||
ref.invalidate(backupConfigProvider);
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Backup started')));
|
||||
}
|
||||
} catch (e) {
|
||||
final message = e is ApiException ? e.userMessage : e.toString();
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _addTarget(BuildContext context, WidgetRef ref) {
|
||||
return showBackupTargetFormDialog(
|
||||
context,
|
||||
onSave: (draft) async {
|
||||
final repo = ref.read(nodeRepositoryProvider);
|
||||
if (repo == null) throw const ApiException.unknown('No active connection.');
|
||||
await repo.addBackupTarget(draft);
|
||||
ref.invalidate(backupConfigProvider);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _editTarget(BuildContext context, WidgetRef ref, BackupTarget target) {
|
||||
return showBackupTargetFormDialog(
|
||||
context,
|
||||
existing: target,
|
||||
onSave: (draft) async {
|
||||
final repo = ref.read(nodeRepositoryProvider);
|
||||
if (repo == null) throw const ApiException.unknown('No active connection.');
|
||||
await repo.updateBackupTarget(target.id, draft);
|
||||
ref.invalidate(backupConfigProvider);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _deleteTarget(BuildContext context, WidgetRef ref, BackupTarget target) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Remove backup target?'),
|
||||
content: Text('This removes "${target.name}" from the node\'s backup targets.'),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.of(context).pop(false), child: const Text('Cancel')),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(backgroundColor: context.status.critical),
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: const Text('Remove'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true) return;
|
||||
|
||||
final repo = ref.read(nodeRepositoryProvider);
|
||||
if (repo == null) return;
|
||||
try {
|
||||
await repo.deleteBackupTarget(target.id);
|
||||
ref.invalidate(backupConfigProvider);
|
||||
} catch (e) {
|
||||
final message = e is ApiException ? e.userMessage : e.toString();
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _runTarget(WidgetRef ref, BackupTarget target) async {
|
||||
final repo = ref.read(nodeRepositoryProvider);
|
||||
if (repo == null) throw const ApiException.unknown('No active connection.');
|
||||
await repo.runBackupTarget(target.id);
|
||||
}
|
||||
|
||||
Future<RunState> _fetchProgress(WidgetRef ref, BackupTarget target) async {
|
||||
final repo = ref.read(nodeRepositoryProvider);
|
||||
if (repo == null) return const RunState();
|
||||
return repo.getBackupTargetProgress(target.id);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final configAsync = ref.watch(backupConfigProvider);
|
||||
|
||||
return configAsync.when(
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (error, stackTrace) => Center(
|
||||
child: ErrorBanner(
|
||||
message: error is ApiException ? error.userMessage : error.toString(),
|
||||
onRetry: () => ref.invalidate(backupConfigProvider),
|
||||
),
|
||||
),
|
||||
data: (config) {
|
||||
if (config == null) {
|
||||
return const Center(
|
||||
child: EmptyState(icon: Icons.cloud_outlined, title: 'No connection configured'),
|
||||
);
|
||||
}
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
children: [
|
||||
_ConfigCard(config: config, onRunNow: () => _runNow(context, ref)),
|
||||
const SizedBox(height: 22),
|
||||
Text('BACKUP TARGETS', style: context.text.titleSmall),
|
||||
const SizedBox(height: 10),
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: BackupTargetsList(
|
||||
targets: config.targets,
|
||||
onAdd: () => _addTarget(context, ref),
|
||||
onEdit: (target) => _editTarget(context, ref, target),
|
||||
onDelete: (target) => _deleteTarget(context, ref, target),
|
||||
onRun: (target) => _runTarget(ref, target),
|
||||
fetchProgress: (target) => _fetchProgress(ref, target),
|
||||
onSettled: (target, state) => ref.invalidate(backupConfigProvider),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 22),
|
||||
_DurationTrendCard(history: config.history),
|
||||
const SizedBox(height: 22),
|
||||
Text('EXECUTION HISTORY', style: context.text.titleSmall),
|
||||
const SizedBox(height: 10),
|
||||
BackupHistoryTable(history: config.history, targets: config.targets),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ConfigCard extends StatelessWidget {
|
||||
const _ConfigCard({required this.config, required this.onRunNow});
|
||||
|
||||
final BackupConfig config;
|
||||
final VoidCallback onRunNow;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final dateFormat = DateFormat('EEE, MMM d · HH:mm');
|
||||
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text('Node backup configuration', style: context.text.titleMedium),
|
||||
Row(
|
||||
children: [
|
||||
OutlinedButton.icon(
|
||||
onPressed: () => showBackupConfigFormDialog(context, existing: config),
|
||||
icon: const Icon(Icons.edit_outlined, size: 16),
|
||||
label: const Text('Edit'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
FilledButton.icon(
|
||||
onPressed: onRunNow,
|
||||
icon: const Icon(Icons.cloud_outlined, size: 16),
|
||||
label: const Text('Run all now'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
const Divider(height: 24),
|
||||
_kv(context, 'Source path', config.sourcePath?.isNotEmpty == true ? config.sourcePath! : 'Not set'),
|
||||
_kv(
|
||||
context,
|
||||
'Next run',
|
||||
config.nextRun == null ? 'Not scheduled' : dateFormat.format(config.nextRun!.toLocal()),
|
||||
),
|
||||
_kv(
|
||||
context,
|
||||
'Last run',
|
||||
config.lastRun == null ? 'Never' : dateFormat.format(config.lastRun!.toLocal()),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _kv(BuildContext context, String label, String value) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 10),
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox(width: 120, child: Text(label, style: context.text.bodySmall)),
|
||||
Expanded(child: Text(value, style: context.text.bodyMedium)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _DurationTrendCard extends StatelessWidget {
|
||||
const _DurationTrendCard({required this.history});
|
||||
|
||||
final List<BackupExecution> history;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final sorted = [...history]..sort((a, b) => a.timestamp.compareTo(b.timestamp));
|
||||
final recent = sorted.length > 10 ? sorted.sublist(sorted.length - 10) : sorted;
|
||||
|
||||
if (recent.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
final values = [for (final e in recent) e.durationSeconds.toDouble()];
|
||||
final latest = recent.last.durationSeconds;
|
||||
final avg = values.reduce((a, b) => a + b) / values.length;
|
||||
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
Sparkline(values: values),
|
||||
const SizedBox(width: 20),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text('Duration trend', style: context.text.titleMedium),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Latest ${latest}s · last ${recent.length}-run avg ${avg.toStringAsFixed(1)}s',
|
||||
style: context.text.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../../core/models/models.dart';
|
||||
import '../../../core/network/api_exception.dart';
|
||||
import '../../../data/repositories/node_repository.dart';
|
||||
|
||||
/// Edit dialog for the node-level [BackupConfig]'s source path. Target
|
||||
/// management (add/edit/remove/run/schedule) lives in the dedicated
|
||||
/// [BackupTargetsList] on the Backups screen, not in this dialog.
|
||||
Future<void> showBackupConfigFormDialog(BuildContext context, {required BackupConfig existing}) {
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
builder: (context) => _BackupConfigFormDialog(existing: existing),
|
||||
);
|
||||
}
|
||||
|
||||
class _BackupConfigFormDialog extends ConsumerStatefulWidget {
|
||||
const _BackupConfigFormDialog({required this.existing});
|
||||
|
||||
final BackupConfig existing;
|
||||
|
||||
@override
|
||||
ConsumerState<_BackupConfigFormDialog> createState() => _BackupConfigFormDialogState();
|
||||
}
|
||||
|
||||
class _BackupConfigFormDialogState extends ConsumerState<_BackupConfigFormDialog> {
|
||||
late final _sourcePathController = TextEditingController(text: widget.existing.sourcePath);
|
||||
bool _saving = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_sourcePathController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
setState(() {
|
||||
_saving = true;
|
||||
_error = null;
|
||||
});
|
||||
|
||||
final repo = ref.read(nodeRepositoryProvider);
|
||||
if (repo == null) {
|
||||
setState(() {
|
||||
_saving = false;
|
||||
_error = 'No active connection.';
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
final draft = widget.existing.copyWith(sourcePath: _sourcePathController.text.trim());
|
||||
|
||||
try {
|
||||
await repo.updateBackup(draft);
|
||||
ref.invalidate(backupConfigProvider);
|
||||
if (mounted) Navigator.of(context).pop();
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_saving = false;
|
||||
_error = e is ApiException ? e.userMessage : e.toString();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Edit backup configuration'),
|
||||
content: SizedBox(
|
||||
width: 420,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: _sourcePathController,
|
||||
decoration: const InputDecoration(labelText: 'Source path', hintText: '/opt'),
|
||||
),
|
||||
if (_error != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(_error!, style: TextStyle(color: Theme.of(context).colorScheme.error)),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: _saving ? null : () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: _saving
|
||||
? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Text('Save'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
import '../../../core/models/models.dart';
|
||||
import '../../../core/models/severity_mapping.dart';
|
||||
import '../../../core/theme/theme_x.dart';
|
||||
import '../../../core/widgets/data_table_scaffold.dart';
|
||||
import '../../../core/widgets/empty_state.dart';
|
||||
import '../../../core/widgets/mono_text.dart';
|
||||
import '../../../core/widgets/status_pill.dart';
|
||||
|
||||
class BackupHistoryTable extends StatelessWidget {
|
||||
const BackupHistoryTable({super.key, required this.history, required this.targets});
|
||||
|
||||
final List<BackupExecution> history;
|
||||
final List<BackupTarget> targets;
|
||||
|
||||
String _targetName(String? targetId) {
|
||||
if (targetId == null) return '—';
|
||||
for (final t in targets) {
|
||||
if (t.id == targetId) return t.name;
|
||||
}
|
||||
return targetId;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final sorted = [...history]..sort((a, b) => b.timestamp.compareTo(a.timestamp));
|
||||
final timeFormat = DateFormat('yyyy-MM-dd HH:mm');
|
||||
|
||||
return DataTableScaffold(
|
||||
empty: const EmptyState(
|
||||
icon: Icons.cloud_outlined,
|
||||
title: 'No backup history yet',
|
||||
message: 'Run a backup to see execution results here.',
|
||||
),
|
||||
columns: const [
|
||||
DataColumn(label: Text('Timestamp')),
|
||||
DataColumn(label: Text('Target')),
|
||||
DataColumn(label: Text('Result')),
|
||||
DataColumn(label: Text('Duration')),
|
||||
DataColumn(label: Text('Message')),
|
||||
],
|
||||
rows: [
|
||||
for (final execution in sorted)
|
||||
DataRow(
|
||||
cells: [
|
||||
DataCell(MonoText(timeFormat.format(execution.timestamp.toLocal()))),
|
||||
DataCell(Text(_targetName(execution.targetId))),
|
||||
DataCell(
|
||||
StatusPill(
|
||||
label: execution.success ? 'success' : 'failed',
|
||||
severity: severityForSuccess(execution.success),
|
||||
),
|
||||
),
|
||||
DataCell(
|
||||
Text(
|
||||
'${execution.durationSeconds}s',
|
||||
style: context.dataStyles.numericTabular,
|
||||
),
|
||||
),
|
||||
DataCell(
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 340),
|
||||
child: MonoText(execution.message, small: true, maxLines: 1),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../core/models/models.dart';
|
||||
import '../../core/models/severity_mapping.dart';
|
||||
import '../../core/network/api_exception.dart';
|
||||
import '../../core/theme/status_colors.dart';
|
||||
import '../../core/theme/theme_x.dart';
|
||||
import '../../core/utils/relative_time.dart';
|
||||
import '../../core/widgets/error_banner.dart';
|
||||
import '../../core/widgets/stat_tile.dart';
|
||||
import '../../data/repositories/nodes_repository.dart';
|
||||
import 'providers/dashboard_summary.dart';
|
||||
import 'providers/dashboard_summary_provider.dart';
|
||||
import 'widgets/activity_feed.dart';
|
||||
import 'widgets/quick_actions_row.dart';
|
||||
|
||||
class DashboardScreen extends ConsumerWidget {
|
||||
const DashboardScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final summaryAsync = ref.watch(dashboardSummaryProvider);
|
||||
final fleetAsync = ref.watch(aggregatedNodesProvider);
|
||||
|
||||
return summaryAsync.when(
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (error, stackTrace) => Center(
|
||||
child: ErrorBanner(
|
||||
message: error is ApiException ? error.userMessage : error.toString(),
|
||||
onRetry: () => ref.invalidate(dashboardSummaryProvider),
|
||||
),
|
||||
),
|
||||
data: (summary) => ListView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
children: [
|
||||
_StatRow(summary: summary, fleetAsync: fleetAsync),
|
||||
const SizedBox(height: 22),
|
||||
Text('QUICK ACTIONS', style: context.text.titleSmall),
|
||||
const SizedBox(height: 10),
|
||||
const QuickActionsRow(),
|
||||
const SizedBox(height: 22),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text('RECENT ACTIVITY', style: context.text.titleSmall),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Card(child: ActivityFeed(node: summary.node)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StatRow extends StatelessWidget {
|
||||
const _StatRow({required this.summary, required this.fleetAsync});
|
||||
|
||||
final DashboardSummary summary;
|
||||
final AsyncValue<List<AggregatedNodeStatus>> fleetAsync;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final services = summary.services;
|
||||
final up = services.where((s) => s.status == 'up').length;
|
||||
final down = services.where((s) => s.status == 'down').length;
|
||||
final unknown = services.length - up - down;
|
||||
|
||||
final servicesSeverity = down > 0
|
||||
? Severity.critical
|
||||
: unknown > 0
|
||||
? Severity.warning
|
||||
: Severity.good;
|
||||
final servicesCaption = services.isEmpty
|
||||
? 'No services discovered yet'
|
||||
: [
|
||||
if (down > 0) '$down down',
|
||||
if (unknown > 0) '$unknown unknown',
|
||||
].isEmpty
|
||||
? 'All running'
|
||||
: [if (down > 0) '$down down', if (unknown > 0) '$unknown unknown'].join(' · ');
|
||||
|
||||
final history = [...summary.node.backup.history]
|
||||
..sort((a, b) => b.timestamp.compareTo(a.timestamp));
|
||||
final lastBackup = history.isEmpty ? null : history.first;
|
||||
|
||||
final updates = [...summary.node.updateHistory]..sort((a, b) => b.timestamp.compareTo(a.timestamp));
|
||||
final lastUpdate = updates.isEmpty ? null : updates.first;
|
||||
|
||||
return Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 12,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 260,
|
||||
child: StatTile(
|
||||
label: 'Services',
|
||||
value: '$up',
|
||||
valueQualifier: '/ ${services.length} up',
|
||||
caption: servicesCaption,
|
||||
severity: services.isEmpty ? Severity.neutral : servicesSeverity,
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 260,
|
||||
child: StatTile(
|
||||
label: 'Last backup',
|
||||
value: lastBackup == null ? 'Never' : formatRelative(lastBackup.timestamp),
|
||||
caption: lastBackup == null
|
||||
? 'No backups run yet'
|
||||
: (lastBackup.success ? '${lastBackup.durationSeconds}s' : lastBackup.message),
|
||||
severity: lastBackup == null ? Severity.neutral : severityForSuccess(lastBackup.success),
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 260,
|
||||
child: StatTile(
|
||||
label: 'Last system update',
|
||||
value: lastUpdate == null ? 'Never' : formatRelative(lastUpdate.timestamp),
|
||||
caption: lastUpdate == null
|
||||
? 'No updates recorded yet'
|
||||
: '${lastUpdate.packages.length} package(s)',
|
||||
severity: lastUpdate == null ? Severity.neutral : severityForSuccess(lastUpdate.success),
|
||||
),
|
||||
),
|
||||
SizedBox(width: 260, child: _FleetTile(fleetAsync: fleetAsync)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _FleetTile extends StatelessWidget {
|
||||
const _FleetTile({required this.fleetAsync});
|
||||
|
||||
final AsyncValue<List<AggregatedNodeStatus>> fleetAsync;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return fleetAsync.when(
|
||||
loading: () => const StatTile(
|
||||
label: 'Fleet',
|
||||
value: '…',
|
||||
severity: Severity.neutral,
|
||||
),
|
||||
error: (error, stackTrace) => StatTile(
|
||||
label: 'Fleet',
|
||||
value: '—',
|
||||
caption: error is ApiException ? error.userMessage : error.toString(),
|
||||
severity: Severity.critical,
|
||||
),
|
||||
data: (nodes) {
|
||||
if (nodes.isEmpty) {
|
||||
return const StatTile(
|
||||
label: 'Fleet',
|
||||
value: '0',
|
||||
caption: 'No nodes registered',
|
||||
severity: Severity.neutral,
|
||||
);
|
||||
}
|
||||
final online = nodes.where((n) => n.error == null).length;
|
||||
final unreachable = nodes.where((n) => n.error != null).toList();
|
||||
return StatTile(
|
||||
label: 'Fleet',
|
||||
value: '$online',
|
||||
valueQualifier: '/ ${nodes.length} online',
|
||||
caption: unreachable.isEmpty
|
||||
? 'All nodes reachable'
|
||||
: 'unreachable: ${unreachable.map((n) => n.node.name).join(', ')}',
|
||||
severity: unreachable.isEmpty ? Severity.good : Severity.critical,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
import '../../../core/models/models.dart';
|
||||
|
||||
part 'dashboard_summary.freezed.dart';
|
||||
|
||||
/// Client-side composition of the two data sources the Dashboard needs —
|
||||
/// no server endpoint returns this shape directly. Not JSON-serializable
|
||||
/// (nothing here is ever sent/stored as JSON), so no `fromJson`/`toJson`.
|
||||
@freezed
|
||||
sealed class DashboardSummary with _$DashboardSummary {
|
||||
const factory DashboardSummary({required List<Service> services, required NodeInfo node}) =
|
||||
_DashboardSummary;
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'dashboard_summary.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// dart format off
|
||||
T _$identity<T>(T value) => value;
|
||||
/// @nodoc
|
||||
mixin _$DashboardSummary {
|
||||
|
||||
List<Service> get services; NodeInfo get node;
|
||||
/// Create a copy of DashboardSummary
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$DashboardSummaryCopyWith<DashboardSummary> get copyWith => _$DashboardSummaryCopyWithImpl<DashboardSummary>(this as DashboardSummary, _$identity);
|
||||
|
||||
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is DashboardSummary&&const DeepCollectionEquality().equals(other.services, services)&&(identical(other.node, node) || other.node == node));
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(runtimeType,const DeepCollectionEquality().hash(services),node);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'DashboardSummary(services: $services, node: $node)';
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $DashboardSummaryCopyWith<$Res> {
|
||||
factory $DashboardSummaryCopyWith(DashboardSummary value, $Res Function(DashboardSummary) _then) = _$DashboardSummaryCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
List<Service> services, NodeInfo node
|
||||
});
|
||||
|
||||
|
||||
$NodeInfoCopyWith<$Res> get node;
|
||||
|
||||
}
|
||||
/// @nodoc
|
||||
class _$DashboardSummaryCopyWithImpl<$Res>
|
||||
implements $DashboardSummaryCopyWith<$Res> {
|
||||
_$DashboardSummaryCopyWithImpl(this._self, this._then);
|
||||
|
||||
final DashboardSummary _self;
|
||||
final $Res Function(DashboardSummary) _then;
|
||||
|
||||
/// Create a copy of DashboardSummary
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline') @override $Res call({Object? services = null,Object? node = null,}) {
|
||||
return _then(_self.copyWith(
|
||||
services: null == services ? _self.services : services // ignore: cast_nullable_to_non_nullable
|
||||
as List<Service>,node: null == node ? _self.node : node // ignore: cast_nullable_to_non_nullable
|
||||
as NodeInfo,
|
||||
));
|
||||
}
|
||||
/// Create a copy of DashboardSummary
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$NodeInfoCopyWith<$Res> get node {
|
||||
|
||||
return $NodeInfoCopyWith<$Res>(_self.node, (value) {
|
||||
return _then(_self.copyWith(node: value));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Adds pattern-matching-related methods to [DashboardSummary].
|
||||
extension DashboardSummaryPatterns on DashboardSummary {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _DashboardSummary value)? $default,{required TResult orElse(),}){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _DashboardSummary() when $default != null:
|
||||
return $default(_that);case _:
|
||||
return orElse();
|
||||
|
||||
}
|
||||
}
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _DashboardSummary value) $default,){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _DashboardSummary():
|
||||
return $default(_that);}
|
||||
}
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _DashboardSummary value)? $default,){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _DashboardSummary() when $default != null:
|
||||
return $default(_that);case _:
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( List<Service> services, NodeInfo node)? $default,{required TResult orElse(),}) {final _that = this;
|
||||
switch (_that) {
|
||||
case _DashboardSummary() when $default != null:
|
||||
return $default(_that.services,_that.node);case _:
|
||||
return orElse();
|
||||
|
||||
}
|
||||
}
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( List<Service> services, NodeInfo node) $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _DashboardSummary():
|
||||
return $default(_that.services,_that.node);}
|
||||
}
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( List<Service> services, NodeInfo node)? $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _DashboardSummary() when $default != null:
|
||||
return $default(_that.services,_that.node);case _:
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
|
||||
class _DashboardSummary implements DashboardSummary {
|
||||
const _DashboardSummary({required final List<Service> services, required this.node}): _services = services;
|
||||
|
||||
|
||||
final List<Service> _services;
|
||||
@override List<Service> get services {
|
||||
if (_services is EqualUnmodifiableListView) return _services;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_services);
|
||||
}
|
||||
|
||||
@override final NodeInfo node;
|
||||
|
||||
/// Create a copy of DashboardSummary
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override @JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$DashboardSummaryCopyWith<_DashboardSummary> get copyWith => __$DashboardSummaryCopyWithImpl<_DashboardSummary>(this, _$identity);
|
||||
|
||||
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is _DashboardSummary&&const DeepCollectionEquality().equals(other._services, _services)&&(identical(other.node, node) || other.node == node));
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(runtimeType,const DeepCollectionEquality().hash(_services),node);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'DashboardSummary(services: $services, node: $node)';
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$DashboardSummaryCopyWith<$Res> implements $DashboardSummaryCopyWith<$Res> {
|
||||
factory _$DashboardSummaryCopyWith(_DashboardSummary value, $Res Function(_DashboardSummary) _then) = __$DashboardSummaryCopyWithImpl;
|
||||
@override @useResult
|
||||
$Res call({
|
||||
List<Service> services, NodeInfo node
|
||||
});
|
||||
|
||||
|
||||
@override $NodeInfoCopyWith<$Res> get node;
|
||||
|
||||
}
|
||||
/// @nodoc
|
||||
class __$DashboardSummaryCopyWithImpl<$Res>
|
||||
implements _$DashboardSummaryCopyWith<$Res> {
|
||||
__$DashboardSummaryCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _DashboardSummary _self;
|
||||
final $Res Function(_DashboardSummary) _then;
|
||||
|
||||
/// Create a copy of DashboardSummary
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override @pragma('vm:prefer-inline') $Res call({Object? services = null,Object? node = null,}) {
|
||||
return _then(_DashboardSummary(
|
||||
services: null == services ? _self._services : services // ignore: cast_nullable_to_non_nullable
|
||||
as List<Service>,node: null == node ? _self.node : node // ignore: cast_nullable_to_non_nullable
|
||||
as NodeInfo,
|
||||
));
|
||||
}
|
||||
|
||||
/// Create a copy of DashboardSummary
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$NodeInfoCopyWith<$Res> get node {
|
||||
|
||||
return $NodeInfoCopyWith<$Res>(_self.node, (value) {
|
||||
return _then(_self.copyWith(node: value));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// dart format on
|
||||
@@ -0,0 +1,39 @@
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../../core/network/api_exception.dart';
|
||||
import '../../../core/polling/polling_async_notifier.dart';
|
||||
import '../../../data/repositories/node_repository.dart';
|
||||
import '../../../data/repositories/services_repository.dart';
|
||||
import 'dashboard_summary.dart';
|
||||
|
||||
part 'dashboard_summary_provider.g.dart';
|
||||
|
||||
/// Polled every 20s while the Dashboard is mounted — deliberately its own
|
||||
/// notifier rather than watching `servicesListProvider`/`currentNodeProvider`
|
||||
/// directly, so Dashboard auto-refreshes independent of whether the
|
||||
/// Services screen (manual-refresh only) happens to be open too.
|
||||
@riverpod
|
||||
class DashboardSummaryNotifier extends _$DashboardSummaryNotifier
|
||||
with PollingMixin<DashboardSummary> {
|
||||
@override
|
||||
Duration get interval => const Duration(seconds: 20);
|
||||
|
||||
@override
|
||||
Future<DashboardSummary> fetch() async {
|
||||
final servicesRepo = ref.watch(servicesRepositoryProvider);
|
||||
final nodeRepo = ref.watch(nodeRepositoryProvider);
|
||||
if (servicesRepo == null || nodeRepo == null) {
|
||||
// The router redirects to Settings whenever there's no active
|
||||
// connection, so reaching this in the UI would mean that redirect
|
||||
// hasn't fired yet — an ApiException here (vs. a raw StateError)
|
||||
// keeps error handling on the same path as every other screen.
|
||||
throw const ApiException.unknown('No active connection.');
|
||||
}
|
||||
final services = await servicesRepo.getAll();
|
||||
final node = await nodeRepo.getNode();
|
||||
return DashboardSummary(services: services, node: node);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<DashboardSummary> build() => startPolling();
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'dashboard_summary_provider.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// Polled every 20s while the Dashboard is mounted — deliberately its own
|
||||
/// notifier rather than watching `servicesListProvider`/`currentNodeProvider`
|
||||
/// directly, so Dashboard auto-refreshes independent of whether the
|
||||
/// Services screen (manual-refresh only) happens to be open too.
|
||||
|
||||
@ProviderFor(DashboardSummaryNotifier)
|
||||
const dashboardSummaryProvider = DashboardSummaryNotifierProvider._();
|
||||
|
||||
/// Polled every 20s while the Dashboard is mounted — deliberately its own
|
||||
/// notifier rather than watching `servicesListProvider`/`currentNodeProvider`
|
||||
/// directly, so Dashboard auto-refreshes independent of whether the
|
||||
/// Services screen (manual-refresh only) happens to be open too.
|
||||
final class DashboardSummaryNotifierProvider
|
||||
extends $AsyncNotifierProvider<DashboardSummaryNotifier, DashboardSummary> {
|
||||
/// Polled every 20s while the Dashboard is mounted — deliberately its own
|
||||
/// notifier rather than watching `servicesListProvider`/`currentNodeProvider`
|
||||
/// directly, so Dashboard auto-refreshes independent of whether the
|
||||
/// Services screen (manual-refresh only) happens to be open too.
|
||||
const DashboardSummaryNotifierProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'dashboardSummaryProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$dashboardSummaryNotifierHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
DashboardSummaryNotifier create() => DashboardSummaryNotifier();
|
||||
}
|
||||
|
||||
String _$dashboardSummaryNotifierHash() =>
|
||||
r'807d0df3c8b7ce9652ae56fdba542b108aa99456';
|
||||
|
||||
/// Polled every 20s while the Dashboard is mounted — deliberately its own
|
||||
/// notifier rather than watching `servicesListProvider`/`currentNodeProvider`
|
||||
/// directly, so Dashboard auto-refreshes independent of whether the
|
||||
/// Services screen (manual-refresh only) happens to be open too.
|
||||
|
||||
abstract class _$DashboardSummaryNotifier
|
||||
extends $AsyncNotifier<DashboardSummary> {
|
||||
FutureOr<DashboardSummary> build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final created = build();
|
||||
final ref =
|
||||
this.ref as $Ref<AsyncValue<DashboardSummary>, DashboardSummary>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AsyncValue<DashboardSummary>, DashboardSummary>,
|
||||
AsyncValue<DashboardSummary>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleValue(ref, created);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/models/models.dart';
|
||||
import '../../../core/models/severity_mapping.dart';
|
||||
import '../../../core/theme/status_colors.dart';
|
||||
import '../../../core/theme/theme_x.dart';
|
||||
import '../../../core/utils/relative_time.dart';
|
||||
import '../../../core/widgets/empty_state.dart';
|
||||
|
||||
class _FeedEntry {
|
||||
const _FeedEntry({
|
||||
required this.timestamp,
|
||||
required this.title,
|
||||
required this.subtitle,
|
||||
required this.severity,
|
||||
required this.icon,
|
||||
});
|
||||
|
||||
final DateTime timestamp;
|
||||
final String title;
|
||||
final String subtitle;
|
||||
final Severity severity;
|
||||
final IconData icon;
|
||||
}
|
||||
|
||||
/// Merges backup executions and OS update records from [NodeInfo] into one
|
||||
/// reverse-chronological feed. There's no persisted scan-result log on the
|
||||
/// server to fold in here — only these two histories actually exist.
|
||||
class ActivityFeed extends StatelessWidget {
|
||||
const ActivityFeed({super.key, required this.node, this.maxEntries = 6});
|
||||
|
||||
final NodeInfo node;
|
||||
final int maxEntries;
|
||||
|
||||
List<_FeedEntry> _buildEntries() {
|
||||
final entries = <_FeedEntry>[
|
||||
for (final execution in node.backup.history)
|
||||
_FeedEntry(
|
||||
timestamp: execution.timestamp,
|
||||
title: execution.success ? 'Backup completed' : 'Backup failed',
|
||||
subtitle: execution.message.isEmpty
|
||||
? '${execution.durationSeconds}s'
|
||||
: execution.message,
|
||||
severity: severityForSuccess(execution.success),
|
||||
icon: Icons.cloud_outlined,
|
||||
),
|
||||
for (final update in node.updateHistory)
|
||||
_FeedEntry(
|
||||
timestamp: update.timestamp,
|
||||
title: update.success ? 'System update applied' : 'System update failed',
|
||||
subtitle: update.packages.isEmpty
|
||||
? update.message
|
||||
: '${update.packages.length} package(s)${update.message.isEmpty ? '' : ' · ${update.message}'}',
|
||||
severity: severityForSuccess(update.success),
|
||||
icon: Icons.history_rounded,
|
||||
),
|
||||
]..sort((a, b) => b.timestamp.compareTo(a.timestamp));
|
||||
|
||||
return entries.take(maxEntries).toList();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final entries = _buildEntries();
|
||||
|
||||
if (entries.isEmpty) {
|
||||
return const EmptyState(
|
||||
icon: Icons.history_rounded,
|
||||
title: 'No activity yet',
|
||||
message: 'Backup runs and system updates will show up here.',
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
for (var i = 0; i < entries.length; i++) ...[
|
||||
if (i > 0) const Divider(height: 1),
|
||||
_FeedRow(entry: entries[i]),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _FeedRow extends StatelessWidget {
|
||||
const _FeedRow({required this.entry});
|
||||
|
||||
final _FeedEntry entry;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = entry.severity.resolve(context.status, muted: context.colors.outline);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 11),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
width: 26,
|
||||
height: 26,
|
||||
decoration: BoxDecoration(
|
||||
color: Color.alphaBlend(color.withValues(alpha: 0.14), context.colors.surface),
|
||||
borderRadius: BorderRadius.circular(7),
|
||||
),
|
||||
child: Icon(entry.icon, size: 14, color: color),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(entry.title, style: context.text.labelLarge),
|
||||
Text(
|
||||
entry.subtitle,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: context.text.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
formatRelative(entry.timestamp),
|
||||
style: context.dataStyles.numericTabular.copyWith(fontSize: 12, color: context.colors.outline),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../../core/network/api_exception.dart';
|
||||
import '../../../data/repositories/node_repository.dart';
|
||||
import '../../../data/repositories/nodes_repository.dart';
|
||||
import '../providers/dashboard_summary_provider.dart';
|
||||
|
||||
class QuickActionsRow extends ConsumerStatefulWidget {
|
||||
const QuickActionsRow({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<QuickActionsRow> createState() => _QuickActionsRowState();
|
||||
}
|
||||
|
||||
class _QuickActionsRowState extends ConsumerState<QuickActionsRow> {
|
||||
bool _busy = false;
|
||||
|
||||
Future<void> _guarded(Future<String> Function() action) async {
|
||||
setState(() => _busy = true);
|
||||
try {
|
||||
final message = await action();
|
||||
if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
|
||||
} catch (e) {
|
||||
final message = e is ApiException ? e.userMessage : e.toString();
|
||||
if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
|
||||
} finally {
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _scan() => _guarded(() async {
|
||||
final repo = ref.read(nodeRepositoryProvider);
|
||||
if (repo == null) throw StateError('No active connection.');
|
||||
final result = await repo.scan();
|
||||
await ref.read(dashboardSummaryProvider.notifier).refresh();
|
||||
final changed = result.created.length + result.updated.length;
|
||||
return changed == 0
|
||||
? 'Scan complete — no changes (${result.found} compose file(s) found)'
|
||||
: 'Scan complete — ${result.created.length} new, ${result.updated.length} updated';
|
||||
});
|
||||
|
||||
Future<void> _runBackup() => _guarded(() async {
|
||||
final repo = ref.read(nodeRepositoryProvider);
|
||||
if (repo == null) throw StateError('No active connection.');
|
||||
await repo.runBackup();
|
||||
await ref.read(dashboardSummaryProvider.notifier).refresh();
|
||||
return 'Backup started';
|
||||
});
|
||||
|
||||
Future<void> _recheckFleet() => _guarded(() async {
|
||||
await ref.read(aggregatedNodesProvider.notifier).refresh();
|
||||
return 'Fleet status refreshed';
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Wrap(
|
||||
spacing: 10,
|
||||
runSpacing: 10,
|
||||
children: [
|
||||
FilledButton.icon(
|
||||
onPressed: _busy ? null : _scan,
|
||||
icon: const Icon(Icons.search_rounded, size: 17),
|
||||
label: const Text('Scan for services'),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _busy ? null : _runBackup,
|
||||
icon: const Icon(Icons.cloud_outlined, size: 17),
|
||||
label: const Text('Run backup now'),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _busy ? null : _recheckFleet,
|
||||
icon: const Icon(Icons.refresh_rounded, size: 17),
|
||||
label: const Text('Re-check fleet'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../core/models/models.dart';
|
||||
import '../../core/network/api_exception.dart';
|
||||
import '../../core/theme/theme_x.dart';
|
||||
import '../../core/widgets/error_banner.dart';
|
||||
import '../../data/repositories/nodes_repository.dart';
|
||||
import 'widgets/fleet_card_grid.dart';
|
||||
import 'widgets/fleet_table.dart';
|
||||
import 'widgets/node_form_dialog.dart';
|
||||
|
||||
class FleetScreen extends ConsumerWidget {
|
||||
const FleetScreen({super.key});
|
||||
|
||||
Future<void> _delete(BuildContext context, WidgetRef ref, RemoteNode node) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Remove node?'),
|
||||
content: Text('This removes "${node.name}" from the registry. It does not affect that host.'),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.of(context).pop(false), child: const Text('Cancel')),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(backgroundColor: context.status.critical),
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: const Text('Remove'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true) return;
|
||||
|
||||
final repo = ref.read(nodesRepositoryProvider);
|
||||
if (repo == null) return;
|
||||
try {
|
||||
await repo.delete(node.id);
|
||||
ref.invalidate(remoteNodesListProvider);
|
||||
ref.invalidate(aggregatedNodesProvider);
|
||||
} catch (e) {
|
||||
final message = e is ApiException ? e.userMessage : e.toString();
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final nodesAsync = ref.watch(remoteNodesListProvider);
|
||||
final aggregatedAsync = ref.watch(aggregatedNodesProvider);
|
||||
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text('REGISTERED NODES', style: context.text.titleSmall),
|
||||
FilledButton.icon(
|
||||
onPressed: () => showNodeFormDialog(context),
|
||||
icon: const Icon(Icons.add, size: 17),
|
||||
label: const Text('Register node'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
nodesAsync.when(
|
||||
loading: () => const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 40),
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
),
|
||||
error: (error, stackTrace) => ErrorBanner(
|
||||
message: error is ApiException ? error.userMessage : error.toString(),
|
||||
onRetry: () => ref.invalidate(remoteNodesListProvider),
|
||||
),
|
||||
data: (nodes) => FleetTable(
|
||||
nodes: nodes,
|
||||
aggregated: aggregatedAsync.value,
|
||||
onEdit: (node) => showNodeFormDialog(context, existing: node),
|
||||
onDelete: (node) => _delete(context, ref, node),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 22),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text('AGGREGATED SERVICES', style: context.text.titleSmall),
|
||||
Text(
|
||||
'live fan-out via /nodes/aggregated',
|
||||
style: context.dataStyles.dataMonoSmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
aggregatedAsync.when(
|
||||
loading: () => const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 40),
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
),
|
||||
error: (error, stackTrace) => ErrorBanner(
|
||||
message: error is ApiException ? error.userMessage : error.toString(),
|
||||
onRetry: () => ref.invalidate(aggregatedNodesProvider),
|
||||
),
|
||||
data: (entries) => FleetCardGrid(entries: entries),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/models/models.dart';
|
||||
import '../../../core/models/severity_mapping.dart';
|
||||
import '../../../core/theme/theme_x.dart';
|
||||
import '../../../core/widgets/empty_state.dart';
|
||||
import '../../../core/widgets/status_pill.dart';
|
||||
|
||||
/// One card per registered node showing its live services (via
|
||||
/// `/nodes/aggregated`), or an inline error card if this particular node
|
||||
/// was unreachable — a per-entry condition the local API itself reports,
|
||||
/// distinct from the aggregated fetch as a whole failing.
|
||||
class FleetCardGrid extends StatelessWidget {
|
||||
const FleetCardGrid({super.key, required this.entries});
|
||||
|
||||
final List<AggregatedNodeStatus> entries;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (entries.isEmpty) {
|
||||
return const EmptyState(
|
||||
icon: Icons.hub_outlined,
|
||||
title: 'Nothing to show yet',
|
||||
message: 'Register a node to see its live services here.',
|
||||
);
|
||||
}
|
||||
|
||||
return GridView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent: 320,
|
||||
mainAxisExtent: 180,
|
||||
crossAxisSpacing: 12,
|
||||
mainAxisSpacing: 12,
|
||||
),
|
||||
itemCount: entries.length,
|
||||
itemBuilder: (context, index) => _NodeCard(entry: entries[index]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _NodeCard extends StatelessWidget {
|
||||
const _NodeCard({required this.entry});
|
||||
|
||||
final AggregatedNodeStatus entry;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final hasError = entry.error != null;
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: context.colors.surface,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(
|
||||
color: hasError ? context.status.critical.withValues(alpha: 0.4) : context.colors.outlineVariant,
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(entry.node.name, style: context.text.labelLarge),
|
||||
const SizedBox(height: 10),
|
||||
Expanded(
|
||||
child: hasError
|
||||
? _ErrorCallout(message: entry.error!)
|
||||
: entry.services.isEmpty
|
||||
? Text('No services reported.', style: context.text.bodySmall)
|
||||
: ListView(
|
||||
padding: EdgeInsets.zero,
|
||||
children: [
|
||||
for (final service in entry.services)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 3.5),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
service.name,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: context.text.bodyMedium,
|
||||
),
|
||||
),
|
||||
StatusPill(
|
||||
label: service.status,
|
||||
severity: severityForServiceStatus(service.status),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ErrorCallout extends StatelessWidget {
|
||||
const _ErrorCallout({required this.message});
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: Color.alphaBlend(context.status.critical.withValues(alpha: 0.08), context.colors.surface),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: context.status.critical.withValues(alpha: 0.35)),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(Icons.error_outline, size: 15, color: context.status.critical),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
message,
|
||||
style: context.dataStyles.dataMonoSmall,
|
||||
maxLines: 3,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/models/models.dart';
|
||||
import '../../../core/theme/status_colors.dart';
|
||||
import '../../../core/theme/theme_x.dart';
|
||||
import '../../../core/utils/relative_time.dart';
|
||||
import '../../../core/widgets/data_table_scaffold.dart';
|
||||
import '../../../core/widgets/empty_state.dart';
|
||||
import '../../../core/widgets/mono_text.dart';
|
||||
import '../../../core/widgets/status_pill.dart';
|
||||
|
||||
class FleetTable extends StatelessWidget {
|
||||
const FleetTable({
|
||||
super.key,
|
||||
required this.nodes,
|
||||
required this.aggregated,
|
||||
required this.onEdit,
|
||||
required this.onDelete,
|
||||
});
|
||||
|
||||
final List<RemoteNode> nodes;
|
||||
|
||||
/// Null while the aggregated fetch is still loading/erroring — reachability
|
||||
/// then shows as "unknown" rather than guessing.
|
||||
final List<AggregatedNodeStatus>? aggregated;
|
||||
final void Function(RemoteNode node) onEdit;
|
||||
final void Function(RemoteNode node) onDelete;
|
||||
|
||||
({String label, Severity severity}) _reachability(RemoteNode node) {
|
||||
final entry = aggregated?.where((a) => a.node.id == node.id).firstOrNull;
|
||||
if (entry == null) return (label: 'unknown', severity: Severity.neutral);
|
||||
return entry.error == null
|
||||
? (label: 'online', severity: Severity.good)
|
||||
: (label: 'unreachable', severity: Severity.critical);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DataTableScaffold(
|
||||
empty: const EmptyState(
|
||||
icon: Icons.hub_outlined,
|
||||
title: 'No nodes registered',
|
||||
message: 'Register a sibling NodeMaster host to see it here.',
|
||||
),
|
||||
columns: const [
|
||||
DataColumn(label: Text('Node')),
|
||||
DataColumn(label: Text('URL')),
|
||||
DataColumn(label: Text('Tags')),
|
||||
DataColumn(label: Text('Status')),
|
||||
DataColumn(label: Text('Last seen')),
|
||||
DataColumn(label: Text('')),
|
||||
],
|
||||
rows: [
|
||||
for (final node in nodes)
|
||||
DataRow(
|
||||
cells: [
|
||||
DataCell(
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(node.name, style: context.text.labelLarge),
|
||||
if (node.description?.isNotEmpty == true)
|
||||
Text(node.description!, style: context.text.bodySmall),
|
||||
],
|
||||
),
|
||||
),
|
||||
DataCell(MonoText(node.url)),
|
||||
DataCell(
|
||||
Wrap(
|
||||
spacing: 4,
|
||||
children: [
|
||||
for (final tag in node.tags)
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: context.colors.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Text(tag, style: context.dataStyles.dataMonoSmall),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
DataCell(Builder(
|
||||
builder: (context) {
|
||||
final r = _reachability(node);
|
||||
return StatusPill(label: r.label, severity: r.severity);
|
||||
},
|
||||
)),
|
||||
DataCell(
|
||||
Text(
|
||||
node.lastSeen == null ? '—' : formatRelative(node.lastSeen!.toLocal()),
|
||||
style: context.text.bodySmall,
|
||||
),
|
||||
),
|
||||
DataCell(
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
IconButton(
|
||||
tooltip: 'Edit',
|
||||
icon: const Icon(Icons.edit_outlined, size: 18),
|
||||
onPressed: () => onEdit(node),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Remove',
|
||||
icon: const Icon(Icons.delete_outline, size: 18),
|
||||
onPressed: () => onDelete(node),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../../core/models/models.dart';
|
||||
import '../../../core/network/api_exception.dart';
|
||||
import '../../../data/repositories/nodes_repository.dart';
|
||||
|
||||
/// Add/edit dialog for a registered [RemoteNode]. This only edits the
|
||||
/// registry entry (name/url/description/tags) — reachability is never
|
||||
/// user-editable, it's always computed live via `/nodes/aggregated`.
|
||||
Future<void> showNodeFormDialog(BuildContext context, {RemoteNode? existing}) {
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
builder: (context) => _NodeFormDialog(existing: existing),
|
||||
);
|
||||
}
|
||||
|
||||
class _NodeFormDialog extends ConsumerStatefulWidget {
|
||||
const _NodeFormDialog({this.existing});
|
||||
|
||||
final RemoteNode? existing;
|
||||
|
||||
@override
|
||||
ConsumerState<_NodeFormDialog> createState() => _NodeFormDialogState();
|
||||
}
|
||||
|
||||
class _NodeFormDialogState extends ConsumerState<_NodeFormDialog> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
late final _nameController = TextEditingController(text: widget.existing?.name);
|
||||
late final _urlController = TextEditingController(text: widget.existing?.url);
|
||||
late final _descriptionController = TextEditingController(text: widget.existing?.description);
|
||||
late final _tagsController = TextEditingController(text: widget.existing?.tags.join(', '));
|
||||
bool _saving = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nameController.dispose();
|
||||
_urlController.dispose();
|
||||
_descriptionController.dispose();
|
||||
_tagsController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String? _validateUrl(String? value) {
|
||||
final trimmed = value?.trim() ?? '';
|
||||
if (trimmed.isEmpty) return 'Required.';
|
||||
final uri = Uri.tryParse(trimmed);
|
||||
if (uri == null || !uri.hasScheme || !uri.hasAuthority) {
|
||||
return 'Enter a full URL, e.g. https://edge-02.local:8080';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
if (!(_formKey.currentState?.validate() ?? false)) return;
|
||||
setState(() {
|
||||
_saving = true;
|
||||
_error = null;
|
||||
});
|
||||
|
||||
final repo = ref.read(nodesRepositoryProvider);
|
||||
if (repo == null) {
|
||||
setState(() {
|
||||
_saving = false;
|
||||
_error = 'No active connection.';
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
var url = _urlController.text.trim();
|
||||
if (url.endsWith('/')) url = url.substring(0, url.length - 1);
|
||||
final tags = _tagsController.text
|
||||
.split(',')
|
||||
.map((t) => t.trim())
|
||||
.where((t) => t.isNotEmpty)
|
||||
.toList();
|
||||
final description = _descriptionController.text.trim();
|
||||
|
||||
final draft = (widget.existing ?? const RemoteNode(name: '', url: '')).copyWith(
|
||||
name: _nameController.text.trim(),
|
||||
url: url,
|
||||
description: description.isEmpty ? null : description,
|
||||
tags: tags,
|
||||
);
|
||||
|
||||
try {
|
||||
if (widget.existing == null) {
|
||||
await repo.add(draft);
|
||||
} else {
|
||||
await repo.update(widget.existing!.id, draft);
|
||||
}
|
||||
ref.invalidate(remoteNodesListProvider);
|
||||
if (mounted) Navigator.of(context).pop();
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_saving = false;
|
||||
_error = e is ApiException ? e.userMessage : e.toString();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: Text(widget.existing == null ? 'Register node' : 'Edit node'),
|
||||
content: Form(
|
||||
key: _formKey,
|
||||
child: SizedBox(
|
||||
width: 420,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: _nameController,
|
||||
decoration: const InputDecoration(labelText: 'Name'),
|
||||
validator: (v) => (v == null || v.trim().isEmpty) ? 'Required.' : null,
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
TextFormField(
|
||||
controller: _urlController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Base URL',
|
||||
hintText: 'https://edge-02.local:8080',
|
||||
),
|
||||
validator: _validateUrl,
|
||||
keyboardType: TextInputType.url,
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
TextFormField(
|
||||
controller: _descriptionController,
|
||||
decoration: const InputDecoration(labelText: 'Description (optional)'),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
TextFormField(
|
||||
controller: _tagsController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Tags (optional, comma-separated)',
|
||||
hintText: 'prod, db',
|
||||
),
|
||||
),
|
||||
if (_error != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(_error!, style: TextStyle(color: Theme.of(context).colorScheme.error)),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: _saving ? null : () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: _saving
|
||||
? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Text('Save'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../core/models/models.dart';
|
||||
import '../../core/models/severity_mapping.dart';
|
||||
import '../../core/network/api_exception.dart';
|
||||
import '../../core/routing/route_paths.dart';
|
||||
import '../../core/theme/theme_x.dart';
|
||||
import '../../core/widgets/error_banner.dart';
|
||||
import '../../core/widgets/slide_over_panel.dart';
|
||||
import '../../core/widgets/status_pill.dart';
|
||||
import '../../data/repositories/services_repository.dart';
|
||||
import 'widgets/service_detail_body.dart';
|
||||
import 'widgets/service_form_dialog.dart';
|
||||
import 'widgets/services_table.dart';
|
||||
|
||||
class ServicesScreen extends ConsumerStatefulWidget {
|
||||
const ServicesScreen({super.key, this.serviceId});
|
||||
|
||||
/// Present when routed via `/services?id=...` — renders the slide-over
|
||||
/// detail panel for this service alongside the still-visible table.
|
||||
final String? serviceId;
|
||||
|
||||
@override
|
||||
ConsumerState<ServicesScreen> createState() => _ServicesScreenState();
|
||||
}
|
||||
|
||||
class _ServicesScreenState extends ConsumerState<ServicesScreen> {
|
||||
final _busyIds = <String>{};
|
||||
|
||||
Future<void> _run(String id, Future<void> Function() action, {String? successMessage}) async {
|
||||
setState(() => _busyIds.add(id));
|
||||
try {
|
||||
await action();
|
||||
ref.invalidate(servicesListProvider);
|
||||
if (mounted && successMessage != null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(successMessage)));
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
final message = e is ApiException ? e.userMessage : e.toString();
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
} finally {
|
||||
if (mounted) setState(() => _busyIds.remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
void _toggleRunning(Service service) {
|
||||
final repo = ref.read(servicesRepositoryProvider);
|
||||
if (repo == null) return;
|
||||
_run(service.id, () => service.status == 'up' ? repo.stop(service.id) : repo.start(service.id));
|
||||
}
|
||||
|
||||
void _backupNow(Service service) {
|
||||
final repo = ref.read(servicesRepositoryProvider);
|
||||
if (repo == null) return;
|
||||
_run(service.id, () => repo.backupNow(service.id), successMessage: 'Backup started');
|
||||
}
|
||||
|
||||
Future<void> _delete(Service service) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Delete service?'),
|
||||
content: Text('This removes "${service.name}" from NodeMaster. It does not stop or delete the container.'),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.of(context).pop(false), child: const Text('Cancel')),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(backgroundColor: context.status.critical),
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: const Text('Delete'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true) return;
|
||||
|
||||
final repo = ref.read(servicesRepositoryProvider);
|
||||
if (repo == null) return;
|
||||
await _run(service.id, () => repo.delete(service.id));
|
||||
if (mounted) context.go(RoutePaths.services);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final servicesAsync = ref.watch(servicesListProvider);
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
servicesAsync.maybeWhen(
|
||||
data: (services) => '${services.length} SERVICES',
|
||||
orElse: () => 'SERVICES',
|
||||
),
|
||||
style: context.text.titleSmall,
|
||||
),
|
||||
FilledButton.icon(
|
||||
onPressed: () => showServiceFormDialog(context),
|
||||
icon: const Icon(Icons.add, size: 17),
|
||||
label: const Text('Add service'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Expanded(
|
||||
child: servicesAsync.when(
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (error, stackTrace) => Align(
|
||||
alignment: Alignment.topCenter,
|
||||
child: ErrorBanner(
|
||||
message: error is ApiException ? error.userMessage : error.toString(),
|
||||
onRetry: () => ref.invalidate(servicesListProvider),
|
||||
),
|
||||
),
|
||||
data: (services) => SingleChildScrollView(
|
||||
child: ServicesTable(
|
||||
services: services,
|
||||
busyServiceIds: _busyIds,
|
||||
onRowTap: (service) => context.go(RoutePaths.serviceDetail(service.id)),
|
||||
onToggleRunning: _toggleRunning,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
_buildDetailPanel(servicesAsync),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDetailPanel(AsyncValue<List<Service>> servicesAsync) {
|
||||
final id = widget.serviceId;
|
||||
final service = servicesAsync.maybeWhen(
|
||||
data: (services) {
|
||||
for (final s in services) {
|
||||
if (s.id == id) return s;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
orElse: () => null,
|
||||
);
|
||||
|
||||
return SlideOverPanel(
|
||||
open: id != null,
|
||||
onClose: () => context.go(RoutePaths.services),
|
||||
title: service?.name ?? '',
|
||||
subtitle: service == null
|
||||
? null
|
||||
: StatusPill(label: service.status, severity: severityForServiceStatus(service.status)),
|
||||
body: service == null
|
||||
? const SizedBox.shrink()
|
||||
: ServiceDetailBody(service: service),
|
||||
headerActions: service == null
|
||||
? const []
|
||||
: [
|
||||
IconButton(
|
||||
tooltip: 'Edit',
|
||||
icon: const Icon(Icons.edit_outlined, size: 18),
|
||||
onPressed: () => showServiceFormDialog(context, existing: service),
|
||||
),
|
||||
],
|
||||
actions: service == null
|
||||
? const []
|
||||
: [
|
||||
OutlinedButton.icon(
|
||||
onPressed: () => _toggleRunning(service),
|
||||
icon: Icon(service.status == 'up' ? Icons.stop_rounded : Icons.play_arrow_rounded, size: 17),
|
||||
label: Text(service.status == 'up' ? 'Stop' : 'Start'),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: service.backup == null ? null : () => _backupNow(service),
|
||||
icon: const Icon(Icons.cloud_outlined, size: 17),
|
||||
label: const Text('Backup'),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(foregroundColor: context.status.critical),
|
||||
onPressed: () => _delete(service),
|
||||
icon: const Icon(Icons.delete_outline, size: 17),
|
||||
label: const Text('Delete'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
import '../../../core/models/models.dart';
|
||||
import '../../../core/models/severity_mapping.dart';
|
||||
import '../../../core/network/api_exception.dart';
|
||||
import '../../../core/theme/theme_x.dart';
|
||||
import '../../../core/widgets/backup_target_form_dialog.dart';
|
||||
import '../../../core/widgets/backup_targets_list.dart';
|
||||
import '../../../core/widgets/mono_text.dart';
|
||||
import '../../../core/widgets/status_pill.dart';
|
||||
import '../../../data/repositories/services_repository.dart';
|
||||
|
||||
/// The scrollable body of the Services slide-over panel — everything below
|
||||
/// the title/close row that [SlideOverPanel] already renders.
|
||||
class ServiceDetailBody extends ConsumerWidget {
|
||||
const ServiceDetailBody({super.key, required this.service});
|
||||
|
||||
final Service service;
|
||||
|
||||
Future<void> _addTarget(BuildContext context, WidgetRef ref) {
|
||||
return showBackupTargetFormDialog(
|
||||
context,
|
||||
onSave: (draft) async {
|
||||
final repo = ref.read(servicesRepositoryProvider);
|
||||
if (repo == null) throw const ApiException.unknown('No active connection.');
|
||||
await repo.addBackupTarget(service.id, draft);
|
||||
ref.invalidate(servicesListProvider);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _editTarget(BuildContext context, WidgetRef ref, BackupTarget target) {
|
||||
return showBackupTargetFormDialog(
|
||||
context,
|
||||
existing: target,
|
||||
onSave: (draft) async {
|
||||
final repo = ref.read(servicesRepositoryProvider);
|
||||
if (repo == null) throw const ApiException.unknown('No active connection.');
|
||||
await repo.updateBackupTarget(service.id, target.id, draft);
|
||||
ref.invalidate(servicesListProvider);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _deleteTarget(BuildContext context, WidgetRef ref, BackupTarget target) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Remove backup target?'),
|
||||
content: Text('This removes "${target.name}" from this service\'s backup targets.'),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.of(context).pop(false), child: const Text('Cancel')),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(backgroundColor: context.status.critical),
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: const Text('Remove'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true) return;
|
||||
|
||||
final repo = ref.read(servicesRepositoryProvider);
|
||||
if (repo == null) return;
|
||||
try {
|
||||
await repo.deleteBackupTarget(service.id, target.id);
|
||||
ref.invalidate(servicesListProvider);
|
||||
} catch (e) {
|
||||
final message = e is ApiException ? e.userMessage : e.toString();
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _runTarget(WidgetRef ref, BackupTarget target) async {
|
||||
final repo = ref.read(servicesRepositoryProvider);
|
||||
if (repo == null) throw const ApiException.unknown('No active connection.');
|
||||
await repo.runBackupTarget(service.id, target.id);
|
||||
}
|
||||
|
||||
Future<RunState> _fetchProgress(WidgetRef ref, BackupTarget target) async {
|
||||
final repo = ref.read(servicesRepositoryProvider);
|
||||
if (repo == null) return const RunState();
|
||||
return repo.getBackupTargetProgress(service.id, target.id);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final backup = service.backup;
|
||||
final targets = backup?.targets ?? const [];
|
||||
final history = (backup?.history ?? const []).reversed.take(5).toList();
|
||||
final timeFormat = DateFormat('MM-dd HH:mm');
|
||||
|
||||
return ListView(
|
||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 20),
|
||||
children: [
|
||||
_KvRow(label: 'Compose file', value: MonoText(service.composeFile)),
|
||||
_KvRow(
|
||||
label: 'Compose type',
|
||||
value: Text(service.composeType?.isNotEmpty == true ? service.composeType! : 'docker compose'),
|
||||
),
|
||||
_KvRow(
|
||||
label: 'Backup folder',
|
||||
value: service.backupFolder?.isNotEmpty == true
|
||||
? MonoText(service.backupFolder!)
|
||||
: Text('Not set', style: context.text.bodySmall),
|
||||
),
|
||||
_KvRow(label: 'Stop on backup', value: Text(service.stopOnBackup ? 'Yes' : 'No')),
|
||||
const SizedBox(height: 18),
|
||||
Text('BACKUP TARGETS', style: context.text.titleSmall),
|
||||
const SizedBox(height: 4),
|
||||
BackupTargetsList(
|
||||
targets: targets,
|
||||
onAdd: () => _addTarget(context, ref),
|
||||
onEdit: (target) => _editTarget(context, ref, target),
|
||||
onDelete: (target) => _deleteTarget(context, ref, target),
|
||||
onRun: (target) => _runTarget(ref, target),
|
||||
fetchProgress: (target) => _fetchProgress(ref, target),
|
||||
onSettled: (target, state) => ref.invalidate(servicesListProvider),
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
Text('RECENT BACKUPS', style: context.text.titleSmall),
|
||||
const SizedBox(height: 4),
|
||||
if (history.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Text('No backup history yet.', style: context.text.bodySmall),
|
||||
)
|
||||
else
|
||||
for (final execution in history)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 7),
|
||||
child: Row(
|
||||
children: [
|
||||
MonoText(timeFormat.format(execution.timestamp.toLocal()), small: true),
|
||||
const Spacer(),
|
||||
StatusPill(
|
||||
label: execution.success ? '${execution.durationSeconds}s' : 'failed',
|
||||
severity: severityForSuccess(execution.success),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _KvRow extends StatelessWidget {
|
||||
const _KvRow({required this.label, required this.value});
|
||||
|
||||
final String label;
|
||||
final Widget value;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
||||
decoration: BoxDecoration(border: Border(bottom: BorderSide(color: context.colors.outlineVariant))),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(width: 128, child: Text(label, style: context.text.bodySmall)),
|
||||
Expanded(child: value),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../../core/models/models.dart';
|
||||
import '../../../core/network/api_exception.dart';
|
||||
import '../../../data/repositories/services_repository.dart';
|
||||
|
||||
const _composeTypes = ['docker compose', 'docker-compose', 'podman-compose'];
|
||||
|
||||
/// Add/edit dialog for a [Service]'s core identity fields. Backup target
|
||||
/// configuration is deliberately out of scope here — that's a node/service
|
||||
/// backup-config concern owned by the Backups screen, not service CRUD.
|
||||
Future<void> showServiceFormDialog(BuildContext context, {Service? existing}) {
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
builder: (context) => _ServiceFormDialog(existing: existing),
|
||||
);
|
||||
}
|
||||
|
||||
class _ServiceFormDialog extends ConsumerStatefulWidget {
|
||||
const _ServiceFormDialog({this.existing});
|
||||
|
||||
final Service? existing;
|
||||
|
||||
@override
|
||||
ConsumerState<_ServiceFormDialog> createState() => _ServiceFormDialogState();
|
||||
}
|
||||
|
||||
class _ServiceFormDialogState extends ConsumerState<_ServiceFormDialog> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
late final _nameController = TextEditingController(text: widget.existing?.name);
|
||||
late final _composeFileController = TextEditingController(text: widget.existing?.composeFile);
|
||||
late final _backupFolderController = TextEditingController(text: widget.existing?.backupFolder);
|
||||
late String _composeType = widget.existing?.composeType?.isNotEmpty == true
|
||||
? widget.existing!.composeType!
|
||||
: _composeTypes.first;
|
||||
late bool _stopOnBackup = widget.existing?.stopOnBackup ?? false;
|
||||
bool _saving = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nameController.dispose();
|
||||
_composeFileController.dispose();
|
||||
_backupFolderController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
if (!(_formKey.currentState?.validate() ?? false)) return;
|
||||
setState(() {
|
||||
_saving = true;
|
||||
_error = null;
|
||||
});
|
||||
|
||||
final existing = widget.existing;
|
||||
final draft = (existing ?? const Service(name: '', composeFile: '')).copyWith(
|
||||
name: _nameController.text.trim(),
|
||||
composeFile: _composeFileController.text.trim(),
|
||||
composeType: _composeType,
|
||||
backupFolder: _backupFolderController.text.trim(),
|
||||
stopOnBackup: _stopOnBackup,
|
||||
);
|
||||
|
||||
final repo = ref.read(servicesRepositoryProvider);
|
||||
if (repo == null) {
|
||||
setState(() {
|
||||
_saving = false;
|
||||
_error = 'No active connection.';
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (existing == null) {
|
||||
await repo.add(draft);
|
||||
} else {
|
||||
await repo.update(existing.id, draft);
|
||||
}
|
||||
ref.invalidate(servicesListProvider);
|
||||
if (mounted) Navigator.of(context).pop();
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_saving = false;
|
||||
_error = e is ApiException ? e.userMessage : e.toString();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: Text(widget.existing == null ? 'Add service' : 'Edit service'),
|
||||
content: Form(
|
||||
key: _formKey,
|
||||
child: SizedBox(
|
||||
width: 420,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: _nameController,
|
||||
decoration: const InputDecoration(labelText: 'Name'),
|
||||
validator: (v) => (v == null || v.trim().isEmpty) ? 'Required.' : null,
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
TextFormField(
|
||||
controller: _composeFileController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Compose file',
|
||||
hintText: '/opt/compose/gitea/docker-compose.yml',
|
||||
),
|
||||
validator: (v) => (v == null || v.trim().isEmpty) ? 'Required.' : null,
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
DropdownButtonFormField<String>(
|
||||
initialValue: _composeType,
|
||||
decoration: const InputDecoration(labelText: 'Compose type'),
|
||||
items: [
|
||||
for (final type in _composeTypes) DropdownMenuItem(value: type, child: Text(type)),
|
||||
],
|
||||
onChanged: (value) => setState(() => _composeType = value ?? _composeTypes.first),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
TextFormField(
|
||||
controller: _backupFolderController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Backup folder (optional)',
|
||||
hintText: '/opt/data/containers/gitea',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: const Text('Stop container while backing up'),
|
||||
value: _stopOnBackup,
|
||||
onChanged: (value) => setState(() => _stopOnBackup = value),
|
||||
),
|
||||
if (_error != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(_error!, style: TextStyle(color: Theme.of(context).colorScheme.error)),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: _saving ? null : () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: _saving
|
||||
? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Text('Save'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/models/models.dart';
|
||||
import '../../../core/models/severity_mapping.dart';
|
||||
import '../../../core/theme/theme_x.dart';
|
||||
import '../../../core/widgets/data_table_scaffold.dart';
|
||||
import '../../../core/widgets/empty_state.dart';
|
||||
import '../../../core/widgets/mono_text.dart';
|
||||
import '../../../core/widgets/status_pill.dart';
|
||||
|
||||
class ServicesTable extends StatelessWidget {
|
||||
const ServicesTable({
|
||||
super.key,
|
||||
required this.services,
|
||||
required this.onRowTap,
|
||||
required this.onToggleRunning,
|
||||
required this.busyServiceIds,
|
||||
});
|
||||
|
||||
final List<Service> services;
|
||||
final void Function(Service service) onRowTap;
|
||||
final void Function(Service service) onToggleRunning;
|
||||
final Set<String> busyServiceIds;
|
||||
|
||||
String _backupSummary(Service service) {
|
||||
final targets = service.backup?.targets ?? const [];
|
||||
if (targets.isEmpty) return 'none';
|
||||
if (targets.length == 1) return targets.first.method.name;
|
||||
return '${targets.length} targets';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DataTableScaffold(
|
||||
empty: const EmptyState(
|
||||
icon: Icons.layers_outlined,
|
||||
title: 'No services yet',
|
||||
message: 'Scan a compose folder from the Dashboard, or add one manually.',
|
||||
),
|
||||
columns: const [
|
||||
DataColumn(label: Text('Service')),
|
||||
DataColumn(label: Text('Status')),
|
||||
DataColumn(label: Text('Compose file')),
|
||||
DataColumn(label: Text('Backup')),
|
||||
DataColumn(label: Text('')),
|
||||
],
|
||||
rows: [
|
||||
for (final service in services)
|
||||
DataRow(
|
||||
onSelectChanged: (_) => onRowTap(service),
|
||||
cells: [
|
||||
DataCell(
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(service.name, style: context.text.labelLarge),
|
||||
Text(
|
||||
service.composeType?.isNotEmpty == true ? service.composeType! : 'docker compose',
|
||||
style: context.text.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
DataCell(
|
||||
StatusPill(label: service.status, severity: severityForServiceStatus(service.status)),
|
||||
),
|
||||
DataCell(MonoText(service.composeFile)),
|
||||
DataCell(
|
||||
_backupSummary(service) == 'none'
|
||||
? Text('none', style: context.text.bodySmall)
|
||||
: Text(_backupSummary(service), style: context.text.bodyMedium),
|
||||
),
|
||||
DataCell(
|
||||
busyServiceIds.contains(service.id)
|
||||
? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: IconButton(
|
||||
tooltip: service.status == 'up' ? 'Stop' : 'Start',
|
||||
icon: Icon(service.status == 'up' ? Icons.stop_rounded : Icons.play_arrow_rounded, size: 20),
|
||||
onPressed: () => onToggleRunning(service),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../core/network/api_exception.dart';
|
||||
import '../../core/theme/theme_x.dart';
|
||||
import '../../data/repositories/node_repository.dart';
|
||||
import 'widgets/connection_form_dialog.dart';
|
||||
import 'widgets/connections_list.dart';
|
||||
import 'widgets/no_auth_callout.dart';
|
||||
import 'widgets/node_identity_form.dart';
|
||||
import 'widgets/theme_toggle.dart';
|
||||
|
||||
class SettingsScreen extends ConsumerWidget {
|
||||
const SettingsScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
children: [
|
||||
_Block(
|
||||
title: 'Connections',
|
||||
trailing: TextButton.icon(
|
||||
onPressed: () => showConnectionFormDialog(context),
|
||||
icon: const Icon(Icons.add, size: 17),
|
||||
label: const Text('Add connection'),
|
||||
),
|
||||
child: const ConnectionsList(),
|
||||
),
|
||||
const SizedBox(height: 22),
|
||||
_Block(title: 'Node identity', child: const _NodeIdentitySection()),
|
||||
const SizedBox(height: 22),
|
||||
_Block(
|
||||
title: 'Appearance',
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text('Theme'),
|
||||
ThemeToggle(),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 22),
|
||||
const NoAuthCallout(),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _NodeIdentitySection extends ConsumerWidget {
|
||||
const _NodeIdentitySection();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final nodeAsync = ref.watch(currentNodeProvider);
|
||||
|
||||
return nodeAsync.when(
|
||||
loading: () => const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2)),
|
||||
SizedBox(width: 10),
|
||||
Text('Contacting node…'),
|
||||
],
|
||||
),
|
||||
),
|
||||
error: (error, stackTrace) {
|
||||
final message = error is ApiException ? error.userMessage : error.toString();
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(Icons.error_outline, size: 18, color: context.status.critical),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(message, style: context.text.bodyMedium?.copyWith(color: context.status.critical)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
data: (node) {
|
||||
if (node == null) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Text('No connection selected.'),
|
||||
);
|
||||
}
|
||||
return NodeIdentityForm(node: node);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Block extends StatelessWidget {
|
||||
const _Block({required this.title, required this.child, this.trailing});
|
||||
|
||||
final String title;
|
||||
final Widget child;
|
||||
final Widget? trailing;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(title, style: context.text.titleMedium),
|
||||
trailing ?? const SizedBox.shrink(),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Card(child: child),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../../core/connections/connection.dart';
|
||||
import '../../../core/connections/connection_providers.dart';
|
||||
|
||||
/// Add/edit dialog for a saved [Connection]. Passing [existing] switches it
|
||||
/// to edit mode; omitting it creates a new connection and makes it active
|
||||
/// (the common "just point me at a node" first-run flow).
|
||||
Future<void> showConnectionFormDialog(
|
||||
BuildContext context, {
|
||||
Connection? existing,
|
||||
}) {
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
builder: (context) => _ConnectionFormDialog(existing: existing),
|
||||
);
|
||||
}
|
||||
|
||||
class _ConnectionFormDialog extends ConsumerStatefulWidget {
|
||||
const _ConnectionFormDialog({this.existing});
|
||||
|
||||
final Connection? existing;
|
||||
|
||||
@override
|
||||
ConsumerState<_ConnectionFormDialog> createState() => _ConnectionFormDialogState();
|
||||
}
|
||||
|
||||
class _ConnectionFormDialogState extends ConsumerState<_ConnectionFormDialog> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
late final _nameController = TextEditingController(text: widget.existing?.name);
|
||||
late final _urlController = TextEditingController(text: widget.existing?.baseUrl);
|
||||
bool _saving = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nameController.dispose();
|
||||
_urlController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String? _validateUrl(String? value) {
|
||||
final trimmed = value?.trim() ?? '';
|
||||
if (trimmed.isEmpty) return 'Required.';
|
||||
final uri = Uri.tryParse(trimmed);
|
||||
if (uri == null || !uri.hasScheme || !uri.hasAuthority) {
|
||||
return 'Enter a full URL, e.g. https://edge-01.local:8080';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
if (!(_formKey.currentState?.validate() ?? false)) return;
|
||||
setState(() => _saving = true);
|
||||
|
||||
final name = _nameController.text.trim();
|
||||
var url = _urlController.text.trim();
|
||||
if (url.endsWith('/')) url = url.substring(0, url.length - 1);
|
||||
|
||||
final existing = widget.existing;
|
||||
if (existing != null) {
|
||||
await ref
|
||||
.read(savedConnectionsProvider.notifier)
|
||||
.update(existing.copyWith(name: name, baseUrl: url));
|
||||
} else {
|
||||
final connection = Connection(
|
||||
id: 'conn_${DateTime.now().microsecondsSinceEpoch}',
|
||||
name: name,
|
||||
baseUrl: url,
|
||||
);
|
||||
await ref.read(savedConnectionsProvider.notifier).add(connection);
|
||||
await ref.read(activeConnectionIdProvider.notifier).setActive(connection.id);
|
||||
}
|
||||
|
||||
if (mounted) Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: Text(widget.existing == null ? 'Add connection' : 'Edit connection'),
|
||||
content: Form(
|
||||
key: _formKey,
|
||||
child: SizedBox(
|
||||
width: 380,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: _nameController,
|
||||
decoration: const InputDecoration(labelText: 'Name'),
|
||||
validator: (v) => (v == null || v.trim().isEmpty) ? 'Required.' : null,
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
TextFormField(
|
||||
controller: _urlController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Base URL',
|
||||
hintText: 'https://edge-01.local:8080',
|
||||
),
|
||||
validator: _validateUrl,
|
||||
keyboardType: TextInputType.url,
|
||||
onFieldSubmitted: (_) => _save(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: _saving ? null : () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: _saving
|
||||
? const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('Save'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../../core/connections/connection.dart';
|
||||
import '../../../core/connections/connection_providers.dart';
|
||||
import '../../../core/theme/theme_x.dart';
|
||||
import 'connection_form_dialog.dart';
|
||||
|
||||
class ConnectionsList extends ConsumerWidget {
|
||||
const ConnectionsList({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final connections = ref.watch(savedConnectionsProvider);
|
||||
final activeId = ref.watch(activeConnectionIdProvider);
|
||||
|
||||
if (connections.isEmpty) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'No connections saved yet.',
|
||||
style: context.text.bodyMedium,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
"Add one to start managing a NodeMaster host.",
|
||||
style: context.text.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final connection in connections)
|
||||
_ConnectionRow(
|
||||
connection: connection,
|
||||
active: connection.id == activeId,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ConnectionRow extends ConsumerWidget {
|
||||
const _ConnectionRow({required this.connection, required this.active});
|
||||
|
||||
final Connection connection;
|
||||
final bool active;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return InkWell(
|
||||
onTap: active
|
||||
? null
|
||||
: () => ref.read(activeConnectionIdProvider.notifier).setActive(connection.id),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: active ? context.status.good : context.colors.outline,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
active ? '${connection.name} · active' : connection.name,
|
||||
style: context.text.labelLarge,
|
||||
),
|
||||
Text(connection.baseUrl, style: context.dataStyles.dataMonoSmall),
|
||||
],
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Edit',
|
||||
icon: const Icon(Icons.edit_outlined, size: 18),
|
||||
onPressed: () => showConnectionFormDialog(context, existing: connection),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Remove',
|
||||
icon: const Icon(Icons.delete_outline, size: 18),
|
||||
onPressed: () => ref.read(savedConnectionsProvider.notifier).remove(connection.id),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/theme/theme_x.dart';
|
||||
|
||||
/// Static warning — NodeMaster's REST API has no built-in authentication.
|
||||
/// Anyone who can reach a node's port can start/stop services or trigger
|
||||
/// backups on it. Not dismissable: this is a standing property of the
|
||||
/// backend, not a one-time notice.
|
||||
class NoAuthCallout extends StatelessWidget {
|
||||
const NoAuthCallout({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: Color.alphaBlend(context.status.warning.withValues(alpha: 0.10), context.colors.surface),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: context.status.warning.withValues(alpha: 0.4)),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(Icons.warning_amber_rounded, size: 18, color: context.status.warning),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: RichText(
|
||||
text: TextSpan(
|
||||
style: context.text.bodyMedium,
|
||||
children: [
|
||||
TextSpan(text: 'No API authentication yet. ', style: const TextStyle(fontWeight: FontWeight.w700)),
|
||||
const TextSpan(
|
||||
text: "NodeMaster's REST API has no built-in auth — anyone who can reach a node's "
|
||||
'port can start, stop, or trigger backups on it. Until token auth ships, keep it '
|
||||
'behind a VPN or a reverse proxy with its own access control, and treat saved '
|
||||
'connection URLs as sensitive.',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../../core/models/models.dart';
|
||||
import '../../../core/network/api_exception.dart';
|
||||
import '../../../core/theme/status_colors.dart';
|
||||
import '../../../core/theme/theme_x.dart';
|
||||
import '../../../core/widgets/status_pill.dart';
|
||||
import '../../../data/repositories/node_repository.dart';
|
||||
import '../../dashboard/providers/dashboard_summary_provider.dart';
|
||||
|
||||
/// Edits `NodeInfo.hostname`/`description`/`resticPassword` (`PUT /node/`).
|
||||
/// Takes the already-loaded [node] rather than watching the provider
|
||||
/// itself, so the text fields have a stable initial value to build
|
||||
/// controllers from — the parent only renders this once
|
||||
/// `currentNodeProvider` has data.
|
||||
class NodeIdentityForm extends ConsumerStatefulWidget {
|
||||
const NodeIdentityForm({super.key, required this.node});
|
||||
|
||||
final NodeInfo node;
|
||||
|
||||
@override
|
||||
ConsumerState<NodeIdentityForm> createState() => _NodeIdentityFormState();
|
||||
}
|
||||
|
||||
class _NodeIdentityFormState extends ConsumerState<NodeIdentityForm> {
|
||||
late final _hostnameController = TextEditingController(text: widget.node.hostname);
|
||||
late final _descriptionController = TextEditingController(text: widget.node.description);
|
||||
final _passwordController = TextEditingController();
|
||||
bool _obscurePassword = true;
|
||||
bool _saving = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_hostnameController.dispose();
|
||||
_descriptionController.dispose();
|
||||
_passwordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
setState(() {
|
||||
_saving = true;
|
||||
_error = null;
|
||||
});
|
||||
|
||||
final repo = ref.read(nodeRepositoryProvider);
|
||||
if (repo == null) {
|
||||
setState(() {
|
||||
_saving = false;
|
||||
_error = 'No active connection.';
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
final newPassword = _passwordController.text;
|
||||
final draft = widget.node.copyWith(
|
||||
hostname: _hostnameController.text.trim(),
|
||||
description: _descriptionController.text.trim(),
|
||||
resticPassword: newPassword.isEmpty ? null : newPassword,
|
||||
);
|
||||
|
||||
try {
|
||||
await repo.updateNode(draft);
|
||||
// The password field is write-only — never echoed back by the API —
|
||||
// so clear it locally once it's been sent rather than leaving the
|
||||
// plaintext sitting in the form.
|
||||
_passwordController.clear();
|
||||
ref.invalidate(currentNodeProvider);
|
||||
ref.invalidate(dashboardSummaryProvider);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Saved')));
|
||||
}
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_error = e is ApiException ? e.userMessage : e.toString();
|
||||
});
|
||||
} finally {
|
||||
if (mounted) setState(() => _saving = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _hostnameController,
|
||||
decoration: const InputDecoration(labelText: 'Hostname'),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _descriptionController,
|
||||
decoration: const InputDecoration(labelText: 'Description'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _passwordController,
|
||||
obscureText: _obscurePassword,
|
||||
decoration: InputDecoration(
|
||||
labelText: widget.node.resticPasswordSet ? 'Change restic password' : 'Set restic password',
|
||||
hintText: widget.node.resticPasswordSet ? '••••••••' : 'Required to run restic backup targets',
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_obscurePassword ? Icons.visibility_outlined : Icons.visibility_off_outlined),
|
||||
onPressed: () => setState(() => _obscurePassword = !_obscurePassword),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16),
|
||||
child: StatusPill(
|
||||
label: widget.node.resticPasswordSet ? 'Password set' : 'Not configured',
|
||||
severity: widget.node.resticPasswordSet ? Severity.good : Severity.warning,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'Encrypts/decrypts every restic backup target on this node. Leave blank to keep the current '
|
||||
'password — the API never sends it back, so this field always shows empty. There is no way to '
|
||||
'unset it once configured.',
|
||||
style: context.text.bodySmall?.copyWith(color: context.colors.onSurfaceVariant),
|
||||
),
|
||||
if (_error != null) ...[
|
||||
const SizedBox(height: 10),
|
||||
Text(_error!, style: TextStyle(color: Theme.of(context).colorScheme.error)),
|
||||
],
|
||||
const SizedBox(height: 14),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: _saving
|
||||
? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Text('Save changes'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../../core/theme/theme_mode_provider.dart';
|
||||
|
||||
/// The full three-way Light/Dark/System control. The top bar's quick
|
||||
/// sun/moon icon (`NavRailShell`) only ever toggles between explicit
|
||||
/// light/dark — this is the one place "follow system" can be chosen.
|
||||
class ThemeToggle extends ConsumerWidget {
|
||||
const ThemeToggle({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final mode = ref.watch(themeModeControllerProvider);
|
||||
|
||||
return SegmentedButton<ThemeMode>(
|
||||
showSelectedIcon: false,
|
||||
segments: const [
|
||||
ButtonSegment(value: ThemeMode.light, label: Text('Light'), icon: Icon(Icons.light_mode_outlined, size: 16)),
|
||||
ButtonSegment(value: ThemeMode.dark, label: Text('Dark'), icon: Icon(Icons.dark_mode_outlined, size: 16)),
|
||||
ButtonSegment(
|
||||
value: ThemeMode.system,
|
||||
label: Text('System'),
|
||||
icon: Icon(Icons.brightness_auto_outlined, size: 16),
|
||||
),
|
||||
],
|
||||
selected: {mode},
|
||||
onSelectionChanged: (selected) =>
|
||||
ref.read(themeModeControllerProvider.notifier).setThemeMode(selected.first),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../core/models/models.dart';
|
||||
import '../../core/network/api_exception.dart';
|
||||
import '../../core/theme/theme_x.dart';
|
||||
import '../../core/widgets/error_banner.dart';
|
||||
import '../../data/repositories/node_repository.dart';
|
||||
import 'widgets/updates_table.dart';
|
||||
|
||||
class UpdatesScreen extends ConsumerWidget {
|
||||
const UpdatesScreen({super.key});
|
||||
|
||||
Future<void> _delete(BuildContext context, WidgetRef ref, UpdateRecord record) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Delete update record?'),
|
||||
content: const Text('This removes the record from NodeMaster\'s log. It does not undo the update.'),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.of(context).pop(false), child: const Text('Cancel')),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(backgroundColor: context.status.critical),
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: const Text('Delete'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true) return;
|
||||
|
||||
final repo = ref.read(nodeRepositoryProvider);
|
||||
if (repo == null) return;
|
||||
try {
|
||||
await repo.deleteUpdate(record.id);
|
||||
ref.invalidate(updatesListProvider);
|
||||
} catch (e) {
|
||||
final message = e is ApiException ? e.userMessage : e.toString();
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final updatesAsync = ref.watch(updatesListProvider);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
updatesAsync.maybeWhen(
|
||||
data: (records) => '${records.length} UPDATE RECORD(S)',
|
||||
orElse: () => 'UPDATE HISTORY',
|
||||
),
|
||||
style: context.text.titleSmall,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Expanded(
|
||||
child: updatesAsync.when(
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error: (error, stackTrace) => Align(
|
||||
alignment: Alignment.topCenter,
|
||||
child: ErrorBanner(
|
||||
message: error is ApiException ? error.userMessage : error.toString(),
|
||||
onRetry: () => ref.invalidate(updatesListProvider),
|
||||
),
|
||||
),
|
||||
data: (records) => SingleChildScrollView(
|
||||
child: UpdatesTable(
|
||||
records: records,
|
||||
onDelete: (record) => _delete(context, ref, record),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
import '../../../core/models/models.dart';
|
||||
import '../../../core/models/severity_mapping.dart';
|
||||
import '../../../core/theme/theme_x.dart';
|
||||
import '../../../core/widgets/data_table_scaffold.dart';
|
||||
import '../../../core/widgets/empty_state.dart';
|
||||
import '../../../core/widgets/mono_text.dart';
|
||||
import '../../../core/widgets/status_pill.dart';
|
||||
|
||||
class UpdatesTable extends StatelessWidget {
|
||||
const UpdatesTable({super.key, required this.records, required this.onDelete});
|
||||
|
||||
final List<UpdateRecord> records;
|
||||
final void Function(UpdateRecord record) onDelete;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final sorted = [...records]..sort((a, b) => b.timestamp.compareTo(a.timestamp));
|
||||
final timeFormat = DateFormat('yyyy-MM-dd HH:mm');
|
||||
|
||||
return DataTableScaffold(
|
||||
empty: const EmptyState(
|
||||
icon: Icons.history_rounded,
|
||||
title: 'No update history yet',
|
||||
message: 'OS package update runs will show up here.',
|
||||
),
|
||||
columns: const [
|
||||
DataColumn(label: Text('Timestamp')),
|
||||
DataColumn(label: Text('Result')),
|
||||
DataColumn(label: Text('Packages')),
|
||||
DataColumn(label: Text('Message')),
|
||||
DataColumn(label: Text('')),
|
||||
],
|
||||
rows: [
|
||||
for (final record in sorted)
|
||||
DataRow(
|
||||
cells: [
|
||||
DataCell(MonoText(timeFormat.format(record.timestamp.toLocal()))),
|
||||
DataCell(
|
||||
StatusPill(
|
||||
label: record.success ? 'success' : 'failed',
|
||||
severity: severityForSuccess(record.success),
|
||||
),
|
||||
),
|
||||
DataCell(_PackageChips(packages: record.packages)),
|
||||
DataCell(
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 320),
|
||||
child: Text(record.message, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
),
|
||||
DataCell(
|
||||
IconButton(
|
||||
tooltip: 'Delete',
|
||||
icon: const Icon(Icons.delete_outline, size: 18),
|
||||
onPressed: () => onDelete(record),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PackageChips extends StatelessWidget {
|
||||
const _PackageChips({required this.packages});
|
||||
|
||||
final List<String> packages;
|
||||
|
||||
static const _maxShown = 2;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (packages.isEmpty) {
|
||||
return Text('—', style: context.text.bodySmall);
|
||||
}
|
||||
final shown = packages.take(_maxShown).toList();
|
||||
final remaining = packages.length - shown.length;
|
||||
|
||||
return Wrap(
|
||||
spacing: 4,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
for (final package in shown)
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: context.colors.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Text(package, style: context.dataStyles.dataMonoSmall),
|
||||
),
|
||||
if (remaining > 0)
|
||||
Text('+$remaining more', style: context.text.bodySmall),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user