feat(app): add native template gallery with detail and create

This commit is contained in:
2026-10-21 22:03:55 +01:00
parent 76fb2cdd87
commit c56b5d45a4
11 changed files with 2070 additions and 0 deletions
+208
View File
@@ -0,0 +1,208 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import '../../ui/adaptive/host.dart';
import 'data/template_repository.dart';
import 'domain/template_entry.dart';
import 'ui/template_create_dialog.dart';
import 'ui/template_detail.dart';
import 'ui/template_gallery.dart';
import 'ui/templates_failure.dart';
import 'ui/templates_frame.dart';
export 'ui/template_detail.dart'
show
templateCreateActionKey,
templateDetailKey,
templateSourceKey,
templateSourceLabel;
export 'ui/template_gallery.dart'
show
templateRowKey,
templatesEmptyKey,
templatesGalleryKey,
templatesLoadingKey;
export 'ui/templates_failure.dart'
show
templatesBannerRetryKey,
templatesErrorBannerKey,
templatesErrorKey,
templatesRetryKey;
export 'ui/templates_frame.dart' show templatesBackKey, templatesRefreshKey;
/// The reusable Templates gallery: the server's actual catalogue, one selected
/// template's metadata and verbatim selectable source, and the existing native
/// create-only prompt.
///
/// Loading and selecting only read. The single create action calls
/// [showTemplateCreateDialog] unchanged, so validate-then-submit semantics stay
/// there; an accepted `detail` is forwarded once through [onCreated]. Nothing
/// here publishes, runs, schedules or overwrites a pipeline.
///
/// Standalone use keeps this screen's own native app bar with Back and Refresh.
/// A shell that already owns navigation passes [embedded], which drops the bar
/// and keeps Back inside the detail and Refresh at the top of the body.
class TemplatesScreen extends StatefulWidget {
const TemplatesScreen({
super.key,
required this.gateway,
this.embedded = false,
this.onCreated,
});
final ApiGateway gateway;
final bool embedded;
final ValueChanged<JsonMap>? onCreated;
@override
State<TemplatesScreen> createState() => _TemplatesScreenState();
}
class _TemplatesScreenState extends State<TemplatesScreen> {
late TemplateRepository _repository = TemplateRepository(widget.gateway);
List<TemplateEntry> _templates = const [];
bool _loading = true;
bool _loaded = false;
String? _error;
String? _selectedKey;
int _generation = 0;
@override
void initState() {
super.initState();
unawaited(_load());
}
@override
void didUpdateWidget(TemplatesScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.gateway == widget.gateway) return;
// A different gateway is a different server: never keep this one's rows or
// selection while the replacement is read.
_repository = TemplateRepository(widget.gateway);
_templates = const [];
_loaded = false;
_selectedKey = null;
unawaited(_load());
}
bool _owns(int generation) => mounted && generation == _generation;
Future<void> _load() async {
final generation = ++_generation;
setState(() {
_loading = true;
_error = null;
});
try {
final templates = await _repository.listTemplates();
if (!_owns(generation)) return;
setState(() {
_templates = templates;
_loaded = true;
_loading = false;
final selected = _selectedKey;
if (selected != null &&
!templates.any((entry) => entry.key == selected)) {
_selectedKey = null;
}
});
} catch (error) {
if (!_owns(generation)) return;
setState(() {
_loading = false;
_error = _describe(error);
});
}
}
String _describe(Object error) {
final text = error is TemplateRepositoryException
? error.message
: '$error';
final message = text.trim();
if (message.isEmpty) return 'The templates could not be loaded.';
return message.startsWith('Exception: ') ? message.substring(11) : message;
}
TemplateEntry? get _selected {
for (final entry in _templates) {
if (entry.key == _selectedKey) return entry;
}
return null;
}
void _open(String key) => setState(() => _selectedKey = key);
void _back() => setState(() => _selectedKey = null);
void _openCreate(TemplateEntry template) {
unawaited(
showTemplateCreateDialog(
context: context,
template: template,
repository: _repository,
cupertino: usesCupertinoHost(context),
onCreated: (detail) => widget.onCreated?.call(detail),
),
);
}
@override
Widget build(BuildContext context) {
final selected = _selected;
final body = selected == null
? TemplateGallery(
templates: _templates,
loaded: _loaded,
loading: _loading,
error: _error,
onRetry: () => unawaited(_load()),
onOpen: _open,
)
: TemplateDetail(
entry: selected,
showBack: widget.embedded,
onBack: _back,
onCreate: () => _openCreate(selected),
);
final framed = TemplatesFrame(
body: _withFailure(context, body),
embedded: widget.embedded,
canGoBack: selected != null,
refreshing: _loading,
onBack: _back,
onRefresh: () => unawaited(_load()),
);
if (widget.embedded) return framed;
// A selected template is this screen's own page: native back returns to
// the gallery instead of leaving the destination.
return PopScope(
canPop: selected == null,
onPopInvokedWithResult: (didPop, _) {
if (!didPop && _selectedKey != null) _back();
},
child: framed,
);
}
/// A refused refresh stays visible above whichever body is current, so an
/// open template never hides a failed read. The rows and selection are kept.
Widget _withFailure(BuildContext context, Widget body) {
final error = _error;
if (error == null || !_loaded) return body;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TemplatesFailureBanner(
message: error,
retrying: _loading,
onRetry: () => unawaited(_load()),
),
Expanded(child: body),
],
);
}
}
@@ -0,0 +1,168 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/template_entry.dart';
/// Browser wording for the gallery and the selected template, kept verbatim.
const templateSourceLabel = 'Definition source';
const templateIncludesScheduleLabel = 'Includes a schedule';
const templateCreateActionLabel = 'Create pipeline from this template';
const templateDetailKey = ValueKey<String>('template-detail');
const templateSourceKey = ValueKey<String>('template-source');
const templateCreateActionKey = ValueKey<String>('template-create-action');
const templateDetailBackKey = ValueKey<String>('template-detail-back');
/// A gallery card's name: a blank name is the explicit unnamed placeholder.
String templateGalleryName(TemplateEntry entry) {
final name = entry.name.trim();
return name.isEmpty ? '(unnamed template)' : entry.name;
}
/// A detail's heading: a blank name falls back to the template's key.
String templateDetailName(TemplateEntry entry) {
final name = entry.name.trim();
return name.isEmpty ? entry.key : entry.name;
}
/// One template's metadata and its complete, selectable definition source.
///
/// Selecting and reading a template sends nothing. The one action opens the
/// existing create-only prompt through [onCreate]; this view never submits,
/// runs or schedules anything itself.
class TemplateDetail extends StatelessWidget {
const TemplateDetail({
super.key,
required this.entry,
required this.showBack,
required this.onBack,
required this.onCreate,
});
final TemplateEntry entry;
/// True under a shell/app bar that does not own a back control for this page.
final bool showBack;
final VoidCallback onBack;
final VoidCallback onCreate;
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
return ListView(
key: templateDetailKey,
padding: const EdgeInsets.only(bottom: 24),
children: [
if (showBack) _backRow(context, cupertino),
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_createButton(context, cupertino),
const SizedBox(height: 12),
Text(
templateDetailName(entry),
style: templateTitleStyle(context),
),
if (entry.description.trim().isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(entry.description),
),
const SizedBox(height: 16),
Text('Key', style: templateMutedStyle(context)),
SelectableText(entry.key, style: templateBodyStyle(context)),
if (entry.scheduled)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(templateIncludesScheduleLabel),
),
const SizedBox(height: 20),
Text(templateSourceLabel, style: templateSectionStyle(context)),
const SizedBox(height: 8),
// The server's source, byte-for-byte: no trim, re-indent or
// re-encoding, so selecting it copies exactly what was received.
SelectableText(
entry.source,
key: templateSourceKey,
style: templateBodyStyle(context),
),
],
),
),
],
);
}
Widget _createButton(BuildContext context, bool cupertino) {
if (cupertino) {
return CupertinoButton.filled(
key: templateCreateActionKey,
onPressed: onCreate,
child: const Text(templateCreateActionLabel),
);
}
return FilledButton(
key: templateCreateActionKey,
onPressed: onCreate,
child: const Text(templateCreateActionLabel),
);
}
Widget _backRow(BuildContext context, bool cupertino) {
final back = cupertino
? CupertinoButton(
key: templateDetailBackKey,
padding: EdgeInsets.zero,
onPressed: onBack,
child: const Icon(CupertinoIcons.back, semanticLabel: 'Back'),
)
: BackButton(key: templateDetailBackKey, onPressed: onBack);
return Padding(
padding: const EdgeInsets.fromLTRB(4, 4, 16, 0),
child: Row(
children: [
back,
const SizedBox(width: 4),
Expanded(
child: Text('Templates', style: templateSectionStyle(context)),
),
],
),
);
}
}
TextStyle? templateTitleStyle(BuildContext context) =>
usesCupertinoHost(context)
? CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle
: Theme.of(context).textTheme.headlineSmall;
TextStyle? templateSectionStyle(BuildContext context) =>
usesCupertinoHost(context)
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.titleMedium;
TextStyle? templateBodyStyle(BuildContext context) {
if (usesCupertinoHost(context)) {
// SelectableText needs an explicit baseline when it inherits no style.
return CupertinoTheme.of(
context,
).textTheme.textStyle.copyWith(inherit: true);
}
return Theme.of(context).textTheme.bodyMedium;
}
TextStyle? templateMutedStyle(BuildContext context) {
if (usesCupertinoHost(context)) {
return CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
}
final theme = Theme.of(context);
return theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
);
}
@@ -0,0 +1,138 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/template_entry.dart';
import 'template_detail.dart';
import 'templates_failure.dart';
const templatesGalleryKey = ValueKey<String>('template-gallery');
const templatesLoadingKey = ValueKey<String>('templates-loading');
const templatesEmptyKey = ValueKey<String>('templates-empty');
const _loadingLabel = 'Loading templates';
const _loadingMessage = 'Loading templates…';
const _emptyMessage = 'No templates are available on this server.';
Key templateRowKey(String key) => ValueKey<String>('template-row-$key');
/// The gallery's truthful states and native catalogue rows.
///
/// It owns no requests: loading, failure and the actual rows all come from the
/// screen, so opening a row only selects an already-read template.
class TemplateGallery extends StatelessWidget {
const TemplateGallery({
super.key,
required this.templates,
required this.loaded,
required this.loading,
required this.error,
required this.onRetry,
required this.onOpen,
});
final List<TemplateEntry> templates;
final bool loaded;
final bool loading;
final String? error;
final VoidCallback onRetry;
final ValueChanged<String> onOpen;
@override
Widget build(BuildContext context) => _body(context);
Widget _body(BuildContext context) {
if (!loaded) {
if (error != null) {
return TemplatesFailureState(
message: error!,
retrying: loading,
onRetry: onRetry,
);
}
return _loadingState(context);
}
if (templates.isEmpty) return _emptyState(context);
return usesCupertinoHost(context)
? _cupertinoList(context)
: _materialList(context);
}
Widget _loadingState(BuildContext context) {
return Center(
key: templatesLoadingKey,
child: Semantics(
liveRegion: true,
label: _loadingLabel,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
usesCupertinoHost(context)
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
const SizedBox(height: 12),
const Text(_loadingMessage),
],
),
),
);
}
Widget _emptyState(BuildContext context) {
return Center(
key: templatesEmptyKey,
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(_emptyMessage, style: templateMutedStyle(context)),
),
);
}
Widget _materialList(BuildContext context) {
return ListView.separated(
key: templatesGalleryKey,
itemCount: templates.length,
separatorBuilder: (_, _) => const Divider(height: 1),
itemBuilder: (context, index) {
final entry = templates[index];
return ListTile(
key: templateRowKey(entry.key),
title: Text(templateGalleryName(entry)),
subtitle: entry.description.trim().isEmpty
? null
: Text(entry.description),
trailing: const Icon(Icons.chevron_right),
onTap: () => onOpen(entry.key),
);
},
);
}
Widget _cupertinoList(BuildContext context) {
return ListView(
key: templatesGalleryKey,
children: [
CupertinoListSection.insetGrouped(
children: [
for (final entry in templates)
CupertinoListTile(
key: templateRowKey(entry.key),
title: _cupertinoText(templateGalleryName(entry)),
subtitle: entry.description.trim().isEmpty
? null
: _cupertinoText(entry.description),
trailing: const CupertinoListTileChevron(),
onTap: () => onOpen(entry.key),
),
],
),
],
);
}
/// The native tile is single-line by default. Let its content wrap at larger
/// text sizes instead of ellipsizing a template's own name; the row grows
/// with the content and nothing else about the tile is restyled.
Widget _cupertinoText(String text) =>
DefaultTextStyle.merge(maxLines: 3, child: Text(text));
}
@@ -0,0 +1,118 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
const templatesErrorKey = ValueKey<String>('templates-error');
const templatesRetryKey = ValueKey<String>('templates-retry');
const templatesErrorBannerKey = ValueKey<String>('templates-error-banner');
const templatesBannerRetryKey = ValueKey<String>('templates-banner-retry');
/// A refusal for a catalogue that never loaded: the whole body is the failure.
class TemplatesFailureState extends StatelessWidget {
const TemplatesFailureState({
super.key,
required this.message,
required this.retrying,
required this.onRetry,
});
final String message;
final bool retrying;
final VoidCallback onRetry;
@override
Widget build(BuildContext context) {
return Center(
key: templatesErrorKey,
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Semantics(
liveRegion: true,
child: Text(message, textAlign: TextAlign.center),
),
const SizedBox(height: 8),
_retryButton(
context,
buttonKey: templatesRetryKey,
retrying: retrying,
onRetry: onRetry,
),
],
),
),
);
}
}
/// A refused refresh, shown above whichever body stays visible.
///
/// The screen renders this above both the catalogue and an open template, so a
/// failed refresh can never be silent while a template is selected.
class TemplatesFailureBanner extends StatelessWidget {
const TemplatesFailureBanner({
super.key,
required this.message,
required this.retrying,
required this.onRetry,
});
final String message;
final bool retrying;
final VoidCallback onRetry;
@override
Widget build(BuildContext context) {
return Padding(
key: templatesErrorBannerKey,
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Semantics(
liveRegion: true,
child: Text(
message,
style: TextStyle(
color: usesCupertinoHost(context)
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error,
),
),
),
_retryButton(
context,
buttonKey: templatesBannerRetryKey,
retrying: retrying,
onRetry: onRetry,
),
],
),
);
}
}
Widget _retryButton(
BuildContext context, {
required Key buttonKey,
required bool retrying,
required VoidCallback onRetry,
}) {
final onPressed = retrying ? null : onRetry;
if (usesCupertinoHost(context)) {
return CupertinoButton(
key: buttonKey,
padding: EdgeInsets.zero,
onPressed: onPressed,
child: const Text('Retry'),
);
}
return TextButton(
key: buttonKey,
onPressed: onPressed,
child: const Text('Retry'),
);
}
@@ -0,0 +1,104 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
const templatesRefreshKey = ValueKey<String>('templates-refresh');
const templatesBackKey = ValueKey<String>('templates-back');
/// The screen's native chrome.
///
/// Standalone use keeps the host's own app bar with Back and Refresh. A shell
/// that already owns navigation passes [embedded], which drops the bar and
/// keeps Refresh at the top of the body.
class TemplatesFrame extends StatelessWidget {
const TemplatesFrame({
super.key,
required this.body,
required this.embedded,
required this.canGoBack,
required this.refreshing,
required this.onBack,
required this.onRefresh,
});
final Widget body;
final bool embedded;
final bool canGoBack;
final bool refreshing;
final VoidCallback onBack;
final VoidCallback onRefresh;
@override
Widget build(BuildContext context) {
if (embedded) return _embedded(context);
return usesCupertinoHost(context)
? _cupertino(context)
: _material(context);
}
Widget _embedded(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Align(
alignment: AlignmentDirectional.centerEnd,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: _refreshButton(context),
),
),
Expanded(child: body),
],
);
}
Widget _cupertino(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
leading: canGoBack
? CupertinoButton(
key: templatesBackKey,
padding: EdgeInsets.zero,
onPressed: onBack,
child: const Icon(CupertinoIcons.back, semanticLabel: 'Back'),
)
: null,
middle: const Text('Templates'),
trailing: _refreshButton(context),
),
child: SafeArea(child: body),
);
}
Widget _material(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Templates'),
leading: canGoBack
? BackButton(key: templatesBackKey, onPressed: onBack)
: null,
actions: [_refreshButton(context)],
),
body: SafeArea(child: body),
);
}
Widget _refreshButton(BuildContext context) {
final onPressed = refreshing ? null : onRefresh;
if (usesCupertinoHost(context)) {
return CupertinoButton(
key: templatesRefreshKey,
padding: EdgeInsets.zero,
onPressed: onPressed,
child: const Icon(CupertinoIcons.refresh, semanticLabel: 'Refresh'),
);
}
return IconButton(
key: templatesRefreshKey,
tooltip: 'Refresh',
onPressed: onPressed,
icon: const Icon(Icons.refresh),
);
}
}