Merge main into chat tab re-tap

This commit is contained in:
2026-11-12 03:52:20 +00:00
31 changed files with 1615 additions and 845 deletions
+5 -2
View File
@@ -28,6 +28,7 @@ import '../features/runs/ui/run_search_selection.dart';
import '../features/search/domain/search_target.dart';
import '../features/settings/settings_screen.dart';
import '../features/settings/settings_store.dart';
import '../features/walkthrough/first_run_walkthrough.dart';
import '../features/walkthrough/walkthrough_gate.dart';
import '../features/walkthrough/walkthrough_store.dart';
import '../features/updates/app_updates.dart';
@@ -945,9 +946,8 @@ class _PipelinesAppState extends State<PipelinesApp>
),
// Settings is a page of the Pipelines tab (its bar's gear), not a
// tab; the shell shows it with Back to Pipelines.
AppDestination.settings: (_) => SettingsScreen(
AppDestination.settings: (context) => SettingsScreen(
terminalLayout: _terminals.layout,
navigationScope: _navigationScope,
client: _session.client,
// A phone signs in at the web login; a browser has its own.
showSignIn: !kIsWeb,
@@ -961,6 +961,9 @@ class _PipelinesAppState extends State<PipelinesApp>
notifications: _notifications,
deliveryService: _deliveryService,
deliveryServiceController: _deliveryController,
// The Help and about row replays the first-run walkthrough. It only
// shows it; the device's seen record is left alone.
onShowWalkthrough: () => unawaited(showFirstRunWalkthrough(context)),
),
},
);
@@ -50,6 +50,7 @@ class NtfySettingsController extends ChangeNotifier {
bool _loading = false;
String? _saving;
String _error = '';
bool _loadFailed = false;
bool _disposed = false;
/// The stored values, or null before the first successful load.
@@ -60,6 +61,9 @@ class NtfySettingsController extends ChangeNotifier {
String? get saving => _saving;
String get error => _error;
/// Whether the latest load failed; the stored values, if any, are kept.
bool get loadFailed => _loadFailed;
/// Whether the checkboxes accept a change now.
bool get enabled => _values != null && !_loading && _saving == null;
@@ -67,11 +71,13 @@ class NtfySettingsController extends ChangeNotifier {
if (_loading) return;
_loading = true;
_error = '';
_loadFailed = false;
_notify();
try {
final reply = await gateway.call('notification_settings');
_values = _decode(reply);
} catch (error) {
_loadFailed = true;
_error = 'Could not load notification settings: $error';
} finally {
_loading = false;
@@ -1,7 +1,12 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../../core/session/server_session.dart';
import '../settings_layout.dart';
import '../settings_server_load.dart';
import '../settings_server_view.dart';
import 'session_security_api.dart';
/// The server's sign-in security: a warning when its password predates the
@@ -30,40 +35,47 @@ class SettingsSecuritySection extends StatefulWidget {
}
class _SettingsSecuritySectionState extends State<SettingsSecuritySection> {
SessionSecurity? _security;
// One load per endpoint, created in initState: rebuilding never refetches.
late ServerLoad<SessionSecurity> _security = _loaderFor(widget.endpoint);
String? _message;
bool _busy = false;
Timer? _endpointSettle;
@override
void initState() {
super.initState();
_load();
}
// The view starts the load when the section mounts (a lazy page section).
ServerLoad<SessionSecurity> _loaderFor(String endpoint) =>
ServerLoad(() => loadSessionSecurity(endpoint));
@override
void didUpdateWidget(SettingsSecuritySection oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.endpoint != widget.endpoint) _load();
}
Future<void> _load() async {
final endpoint = widget.endpoint;
try {
final security = await loadSessionSecurity(endpoint);
if (!mounted || endpoint != widget.endpoint) return;
setState(() {
_security = security;
_message = null;
});
} on SessionSecurityException catch (error) {
if (!mounted || endpoint != widget.endpoint) return;
setState(() {
_security = null;
_message = error.message;
});
// The endpoint follows the URL draft while it is typed; wait until it
// settles so each keystroke does not start a request.
if (oldWidget.endpoint != widget.endpoint) {
_endpointSettle?.cancel();
_endpointSettle = Timer(settingsEndpointDebounce, _switchEndpoint);
}
}
void _switchEndpoint() {
if (!mounted) return;
setState(() {
_security.dispose();
_message = null;
_security = _loaderFor(widget.endpoint);
});
}
@override
void dispose() {
_endpointSettle?.cancel();
_security.dispose();
super.dispose();
}
static String _describe(Object error) => error is SessionSecurityException
? error.message
: 'Could not read sign-in security: $error';
Future<bool> _confirm() async {
const title = Text('Sign out everywhere?');
const body = Text(
@@ -123,7 +135,6 @@ class _SettingsSecuritySectionState extends State<SettingsSecuritySection> {
@override
Widget build(BuildContext context) {
final security = _security;
final button = OutlinedButton(
key: const Key('settings-revoke-all'),
onPressed: _busy ? null : _revokeAll,
@@ -132,16 +143,22 @@ class _SettingsSecuritySectionState extends State<SettingsSecuritySection> {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (security != null && security.weakPassword)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
key: const Key('settings-weak-password'),
'This server\'s sign-in password is weak. '
'${security.rule.isEmpty ? '' : '${security.rule} '}'
'Run ./password on the server to choose a stronger one.',
),
),
ServerSettingsView<SessionSecurity>(
load: _security,
describe: _describe,
retryKey: const Key('settings-security-retry'),
builder: (context, security) => security.weakPassword
? Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
key: const Key('settings-weak-password'),
'This server\'s sign-in password is weak. '
'${security.rule.isEmpty ? '' : '${security.rule} '}'
'Run ./password on the server to choose a stronger one.',
),
)
: const SizedBox.shrink(),
),
const Text(
'Signing out everywhere ends every session of this server\'s web '
'login. Changing the password with ./password does the same.',
+1 -1
View File
@@ -13,5 +13,5 @@ abstract final class SettingsKeys {
static const keyboardShortcuts = ValueKey<String>(
'settings.keyboardShortcuts',
);
static const walkthrough = ValueKey<String>('settings.walkthrough');
static const showWalkthrough = ValueKey<String>('settings.showWalkthrough');
}
+14 -3
View File
@@ -4,9 +4,9 @@
/// from the active Material theme, so text scaling and platform defaults are
/// never overridden here.
///
/// The page is a column of grouped sections. It starts at the top bar's own
/// side inset, so on a wide window the groups line up under the title pill
/// instead of floating in the middle, and stops growing at a reading width.
/// The page is a column of grouped sections. On a narrow window it fills the
/// width inside the top bar's own side inset; on a wide window it is centred
/// at a reading width beside the section index.
library;
/// The widest the column of groups grows on a wide window.
@@ -39,3 +39,14 @@ const double settingsRowInset = 16;
/// The corner radius of a Material group.
const double settingsGroupRadius = 16;
/// The wide layout's jump index: shown beside the list from this body width,
/// and [settingsIndexWidth] wide.
const double settingsIndexMinWidth = 840;
const double settingsIndexWidth = 176;
/// How far below the viewport a lazy section starts loading, in viewports.
const double settingsPreloadViewports = 1;
/// How long a changing endpoint must settle before a server section reloads.
const Duration settingsEndpointDebounce = Duration(milliseconds: 600);
@@ -100,7 +100,11 @@ class _SettingsNtfySectionState extends State<SettingsNtfySection> {
enabled ? (value) => _controller.toggle(setting.key, value) : null,
),
];
final retry = values == null && widget.connected && !_controller.loading;
// A failed refresh keeps the last values and offers Retry beside them.
final retry =
widget.connected &&
!_controller.loading &&
(values == null || _controller.loadFailed);
return SettingsGroup(
title: ntfySectionTitle,
footer: Column(
@@ -131,11 +135,7 @@ class _SettingsNtfySectionState extends State<SettingsNtfySection> {
);
}
Widget _tile(
NtfySetting setting,
bool value,
ValueChanged<bool>? onChanged,
) {
Widget _tile(NtfySetting setting, bool value, ValueChanged<bool>? onChanged) {
return CheckboxListTile(
key: ntfySettingKey(setting.key),
title: Text(setting.label),
@@ -0,0 +1,79 @@
import 'package:flutter/material.dart';
import 'settings_section.dart';
/// The Settings search field: filters the sections as the operator types.
class SettingsSearchField extends StatelessWidget {
const SettingsSearchField({
super.key,
required this.controller,
required this.onChanged,
});
final TextEditingController controller;
final ValueChanged<String> onChanged;
@override
Widget build(BuildContext context) =>
ValueListenableBuilder<TextEditingValue>(
valueListenable: controller,
builder: (context, value, _) => TextField(
key: const ValueKey<String>('settings.search'),
controller: controller,
onChanged: onChanged,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
hintText: 'Search settings',
prefixIcon: const Icon(Icons.search),
suffixIcon: value.text.isEmpty
? null
: IconButton(
tooltip: 'Clear search',
icon: const Icon(Icons.close),
onPressed: () {
controller.clear();
onChanged('');
},
),
border: const OutlineInputBorder(),
),
),
);
}
/// The wide layout's slim jump index: one link per visible section.
class SettingsSectionIndex extends StatelessWidget {
const SettingsSectionIndex({
super.key,
required this.sections,
required this.onJump,
});
final List<SettingsSection> sections;
final ValueChanged<String> onJump;
@override
Widget build(BuildContext context) => Semantics(
container: true,
label: 'Settings sections',
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
for (final section in sections)
TextButton(
key: ValueKey<String>('settings.index.${section.id}'),
onPressed: () => onJump(section.id),
style: TextButton.styleFrom(
alignment: AlignmentDirectional.centerStart,
),
child: Text(
section.title,
textAlign: TextAlign.start,
overflow: TextOverflow.ellipsis,
),
),
],
),
);
}
@@ -0,0 +1,224 @@
part of 'settings_screen.dart';
/// The Settings page's sections, in order. Each entry keeps the widgets the
/// former category pages held; a server-backed entry is `lazy`.
extension _SettingsPageSections on _SettingsScreenState {
List<SettingsSection> _pageSections() {
final servers = widget.servers;
return [
SettingsSection(
id: 'interface-size',
title: 'Interface size',
keywords: 'text size scale zoom large small font',
builder: (_) => const SettingsScaleSection(),
),
SettingsSection(
id: 'animations',
title: 'Animations',
keywords: 'animation speed motion quick switch',
builder: (_) => SettingsAnimationSection(
controller:
widget.animationSpeed ?? AnimationSpeedController.instance,
),
),
SettingsSection(
id: 'font',
title: fontSectionTitle,
keywords: 'font typeface custom text',
builder: (_) => SettingsFontSection(
controller: widget.fonts ?? AppFontController.instance,
),
),
SettingsSection(
id: 'terminal',
title: 'Terminal',
keywords: 'terminal layout mode split',
builder: (_) => SettingsTerminalSection(
layout: widget.terminalLayout ?? TerminalLayout.instance,
),
),
if (servers != null) ...[
SettingsSection(
id: 'servers',
title: 'Servers',
keywords: 'saved server profile add remove switch address',
builder: (_) => SavedServersSection(connections: servers),
),
SettingsSection(
id: 'managed-connection',
title: 'Connection',
keywords: 'address current reconnect disconnect status',
builder: (_) => ManagedConnectionSection(
client: widget.client,
controller: _controller,
),
),
] else
SettingsSection(
id: 'connection',
title: 'Connection',
keywords: 'server url address connect disconnect reconnect status',
builder: (_) => SettingsConnectionSection(
controller: _controller,
serverUrlField: _serverUrlField,
),
),
if (widget.showSignIn)
SettingsSection(
id: 'sign-in',
title: 'Sign in',
keywords: 'login password web account',
builder: (_) => _single(
'Sign in',
SettingsSignInSection(
endpoint: _endpoint,
onChanged: _reconnectAfterSignIn,
),
),
),
if (widget.showSignIn || kIsWeb)
SettingsSection(
id: 'sign-in-security',
title: 'Sign-in security',
keywords: 'password sessions sign out everywhere revoke weak',
lazy: true,
builder: (_) => _single(
'Sign-in security',
SettingsSecuritySection(
endpoint: _endpoint,
onSignedOut: _reconnectAfterSignIn,
),
),
),
SettingsSection(
id: 'workspace',
title: 'Workspace',
keywords: 'workspace path folder directory server save',
builder: (_) => SettingsWorkspaceSection(
controller: _controller,
workspaceField: _workspaceField,
),
),
if (widget.notifications case final notifications?)
SettingsSection(
id: 'notifications',
title: notificationSectionTitle,
keywords: 'notification permission browser alerts enable',
builder: (_) =>
SettingsNotificationsSection(controller: notifications),
),
if (widget.deliveryService case final service? when service.supported)
SettingsSection(
id: 'device-delivery',
title: deviceDeliveryTitle,
keywords: 'background delivery battery android notifications',
builder: (_) => SettingsDeviceDeliverySection(
bridge: service,
controller: widget.deliveryServiceController,
requestNotificationPermission: widget.notifications == null
? null
: () async {
await widget.notifications!.requestPermission();
},
),
),
SettingsSection(
id: 'phone-notifications',
title: ntfySectionTitle,
keywords: 'ntfy push phone run finished chat needs you',
lazy: true,
builder: (_) => SettingsNtfySection(
gateway: widget.client,
connected:
widget.client.state.kind == transport.ConnectionKind.connected,
),
),
SettingsSection(
id: 'data',
title: 'Data management',
keywords: 'storage retention worktrees cleanup disk usage',
builder: (_) => _single(
'Data management',
SettingsStorageSection(gateway: widget.client),
),
),
SettingsSection(
id: 'server',
title: 'Server',
keywords: 'health cpu memory gpu process stats',
builder: (_) =>
_single('Server', SettingsHealthSection(gateway: widget.client)),
),
if (widget.onOpenSchedules case final open?)
SettingsSection(
id: 'library',
title: 'Library',
keywords: 'schedules saved runs pipelines',
builder: (_) => SettingsGroup(
title: 'Library',
leadingRows: true,
children: [SettingsSchedulesSection(onOpen: open)],
),
),
if (widget.showAndroidDownload)
SettingsSection(
id: 'android-app',
title: 'Android app',
keywords: 'apk download install',
builder: (_) =>
_single('Android app', const SettingsAndroidDownloadSection()),
),
if (widget.showSignIn && appUpdatesSupported)
SettingsSection(
id: 'app-updates',
title: 'App updates',
keywords: 'update version build install',
builder: (_) => _single(
'App updates',
SettingsUpdatesSection(endpoint: _endpoint, servers: servers),
),
)
else if (!widget.showAndroidDownload)
SettingsSection(
id: 'app-updates-managed',
title: 'App updates',
keywords: 'update version build administrator',
builder: (_) => _single(
'App updates',
const Text(
'This installation is updated by its server administrator.',
),
),
),
// Help and about: the walkthrough's "Show the walkthrough" row sits in
// this group beside the keyboard shortcuts.
SettingsSection(
id: 'help',
title: 'Help and about',
keywords: 'keyboard shortcuts help about walkthrough tour guide',
builder: (_) => SettingsGroup(
title: 'Help and about',
leadingRows: true,
children: [
const SettingsKeyboardShortcutsSection(),
SettingsRow(
key: SettingsKeys.showWalkthrough,
leading: const Icon(Icons.school_outlined),
title: const Text('Show the walkthrough'),
subtitle: const Text('Replay the short tour of Pipelines.'),
chevron: true,
enabled: widget.onShowWalkthrough != null,
onTap: widget.onShowWalkthrough,
),
],
),
),
];
}
/// A group holding one free-form block (a form, a status with buttons).
Widget _single(String title, Widget child) => SettingsGroup(
title: title,
children: <Widget>[SettingsGroupItem(child: child)],
);
}
+32 -16
View File
@@ -8,6 +8,7 @@ import 'package:flutter/material.dart';
import '../../core/transport/pipelines_client.dart' as transport;
import '../attention/notify/notification_controller.dart';
import '../attention/notify/notification_models.dart';
import 'default_endpoint.dart';
import 'settings_controller.dart';
import 'settings_font_section.dart';
@@ -18,8 +19,8 @@ import '../../ui/theme/app_font_controller.dart';
import 'settings_group.dart';
import 'storage/settings_storage_section.dart';
import 'health/settings_health_section.dart';
import 'settings_page_body.dart';
import 'settings_tabs.dart';
import 'settings_search_page.dart';
import 'settings_section.dart';
import 'settings_notifications_section.dart';
import 'settings_ntfy_section.dart';
import 'settings_device_delivery_section.dart';
@@ -37,12 +38,15 @@ import 'server_connections.dart';
import 'saved_servers_section.dart';
import 'managed_connection_section.dart';
import 'settings_keyboard_shortcuts_section.dart';
import 'settings_walkthrough_section.dart';
import 'settings_keys.dart';
import 'settings_row.dart';
part 'settings_topic_pages.dart';
part 'settings_page_sections.dart';
/// The Settings destination: the server connection and the server-side
/// workspace in native Material controls.
/// The Settings destination: one searchable page of grouped Material sections.
///
/// Local settings render at once. Server-backed sections load lazily (see
/// [SettingsSearchPage]) and never block the page.
///
/// The shared [transport.PipelinesClient] is supplied by the shell. This screen
/// subscribes to it, connects/disconnects it and pings it on connected, but it
@@ -57,7 +61,6 @@ class SettingsScreen extends StatefulWidget {
this.store,
this.ping,
this.embedded = false,
this.navigationScope,
this.onOpenSchedules,
this.notifications,
this.showSignIn = false,
@@ -68,8 +71,13 @@ class SettingsScreen extends StatefulWidget {
this.fonts,
this.animationSpeed,
this.terminalLayout,
this.onShowWalkthrough,
});
/// Opens the first-run walkthrough from the Help and about group. Null
/// leaves the row present but disabled.
final VoidCallback? onShowWalkthrough;
/// The device's interface font; defaults to the app's shared controller.
final AppFontController? fonts;
final AnimationSpeedController? animationSpeed;
@@ -104,9 +112,6 @@ class SettingsScreen extends StatefulWidget {
/// The application shell already owns the native navigation bar and safe area.
final bool embedded;
/// The logical server scope used to restore the last Settings category.
final String? navigationScope;
/// Opens the saved-schedule list above Settings.
final VoidCallback? onOpenSchedules;
@@ -179,15 +184,26 @@ class _SettingsScreenState extends State<SettingsScreen> {
@override
Widget build(BuildContext context) {
final content = SettingsTopicTabs(
pages: _topicPages(),
navigationScope: widget.navigationScope,
);
if (widget.embedded) return content;
final page = SettingsSearchPage(sections: _pageSections());
if (widget.embedded) {
// The shell's floating tab bar sits over this body, and the body reads
// the bar's height as its bottom padding. The page's rows are controls
// and text, so they stop at the bar's top edge instead of scrolling
// under the glass where they cannot be read. The reserved space is
// removed from the page's own inset so it is not counted twice.
return Padding(
padding: EdgeInsets.only(bottom: MediaQuery.paddingOf(context).bottom),
child: MediaQuery.removePadding(
context: context,
removeBottom: true,
child: SafeArea(bottom: false, child: page),
),
);
}
return Scaffold(
extendBodyBehindAppBar: true,
appBar: const SegmentedBar(title: 'Settings'),
body: content,
body: SafeArea(bottom: false, child: page),
);
}
}
@@ -0,0 +1,226 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'settings_layout.dart';
import 'settings_page_chrome.dart';
import 'settings_section.dart';
import 'settings_skeleton.dart';
/// The one Settings page: a pinned search field over a scrolling column of
/// grouped sections, with a jump index beside it on wide layouts.
///
/// Local sections render at once. A [SettingsSection.lazy] section shows a
/// skeleton until the list scrolls within a viewport of it or a search matches
/// it; once reached it stays mounted, so its loaded value survives scrolling.
class SettingsSearchPage extends StatefulWidget {
const SettingsSearchPage({super.key, required this.sections});
final List<SettingsSection> sections;
@override
State<SettingsSearchPage> createState() => _SettingsSearchPageState();
}
class _SettingsSearchPageState extends State<SettingsSearchPage> {
final TextEditingController _search = TextEditingController();
final ScrollController _scroll = ScrollController();
final GlobalKey _viewport = GlobalKey();
final Map<String, GlobalKey> _keys = {};
final Set<String> _activated = {};
String _query = '';
bool _activationScheduled = false;
@override
void initState() {
super.initState();
_scheduleActivation();
}
@override
void dispose() {
_search.dispose();
_scroll.dispose();
super.dispose();
}
bool get _searching => _query.trim().isNotEmpty;
List<SettingsSection> get _visible => [
for (final section in widget.sections)
if (section.matches(_query)) section,
];
GlobalKey _keyFor(String id) => _keys.putIfAbsent(id, GlobalKey.new);
bool _isActive(SettingsSection section) =>
!section.lazy || _activated.contains(section.id) || _searching;
void _onQueryChanged(String value) {
setState(() {
_query = value;
if (_searching) {
_activated.addAll([
for (final section in _visible)
if (section.lazy) section.id,
]);
}
});
_scheduleActivation(jumpToFirstMatch: true);
}
/// Activation and jumps run after the frame: they read layout, and a scroll
/// notification may arrive during layout.
void _scheduleActivation({bool jumpToFirstMatch = false}) {
if (_activationScheduled) return;
_activationScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_activationScheduled = false;
if (!mounted) return;
if (jumpToFirstMatch) _jumpForQuery();
_activateNear();
});
}
void _jumpForQuery() {
if (_searching) {
final first = _visible.firstOrNull;
if (first != null) _jumpTo(first.id);
} else if (_scroll.hasClients) {
unawaited(
_scroll.animateTo(
0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
),
);
}
}
void _jumpTo(String id) {
final context = _keys[id]?.currentContext;
if (context == null) return;
unawaited(
Scrollable.ensureVisible(
context,
duration: const Duration(milliseconds: 250),
curve: Curves.easeOut,
),
);
}
void _activateNear() {
final viewport = _viewport.currentContext?.findRenderObject();
if (viewport is! RenderBox || !viewport.hasSize) return;
final top = viewport.localToGlobal(Offset.zero).dy;
final limit = top + viewport.size.height * (1 + settingsPreloadViewports);
var changed = false;
for (final section in widget.sections) {
if (!section.lazy || _activated.contains(section.id)) continue;
final box = _keys[section.id]?.currentContext?.findRenderObject();
if (box is! RenderBox || !box.hasSize || !box.attached) continue;
if (box.localToGlobal(Offset.zero).dy <= limit) {
_activated.add(section.id);
changed = true;
}
}
if (changed) setState(() {});
}
@override
Widget build(BuildContext context) {
final insets = MediaQuery.paddingOf(context);
final visible = _visible;
return LayoutBuilder(
builder: (context, constraints) {
final wide = constraints.maxWidth >= settingsIndexMinWidth;
return Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: Padding(
padding: EdgeInsetsDirectional.fromSTEB(
insets.left + settingsPageSidePadding,
insets.top + settingsPageTopPadding,
insets.right + settingsPageSidePadding,
0,
),
child: Align(
alignment: Alignment.topCenter,
child: ConstrainedBox(
constraints: const BoxConstraints(
maxWidth: settingsContentMaxWidth,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SettingsSearchField(
controller: _search,
onChanged: _onQueryChanged,
),
const SizedBox(height: settingsSectionGap),
Expanded(child: _list(visible, insets)),
],
),
),
),
),
),
if (wide && visible.isNotEmpty)
SizedBox(
width: settingsIndexWidth,
child: Padding(
padding: EdgeInsetsDirectional.only(
top: insets.top + settingsPageTopPadding,
),
child: SettingsSectionIndex(
sections: visible,
onJump: _jumpTo,
),
),
),
],
);
},
);
}
Widget _list(List<SettingsSection> visible, EdgeInsets insets) {
if (visible.isEmpty) {
return Padding(
padding: const EdgeInsets.all(settingsRowInset),
child: Text('No settings match "${_search.text.trim()}".'),
);
}
return NotificationListener<ScrollNotification>(
onNotification: (_) {
_scheduleActivation();
return false;
},
child: KeyedSubtree(
key: _viewport,
child: SingleChildScrollView(
key: const ValueKey<String>('settings.scroll'),
controller: _scroll,
padding: EdgeInsets.only(
bottom: insets.bottom + settingsPageBottomPadding,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
for (final (index, section) in visible.indexed) ...<Widget>[
if (index > 0) const SizedBox(height: settingsSectionGap),
KeyedSubtree(
key: _keyFor(section.id),
child: _isActive(section)
? Builder(builder: section.builder)
: SettingsSkeleton(title: section.title),
),
],
],
),
),
),
);
}
}
@@ -0,0 +1,44 @@
import 'package:flutter/widgets.dart';
/// One headed group of the single Settings page.
///
/// A section is searchable by its [title] and [keywords], listed in the wide
/// layout's jump index, and built on demand when it is [lazy]: a server-backed
/// section shows a skeleton until the page is scrolled near it or a search
/// matches it, so the page never waits for the server.
class SettingsSection {
const SettingsSection({
required this.id,
required this.title,
required this.builder,
this.keywords = '',
this.lazy = false,
});
/// A stable identifier for keys and jump links.
final String id;
/// The heading shown in the index, the skeleton and the group.
final String title;
/// Extra words the search also matches (setting names, descriptions).
final String keywords;
/// Whether this section reads the server and loads only when near or searched.
final bool lazy;
final WidgetBuilder builder;
/// Whether every word of [query] appears in the title or keywords, ignoring
/// case. An empty query matches every section.
bool matches(String query) {
final words = query
.trim()
.toLowerCase()
.split(RegExp(r'\s+'))
.where((word) => word.isNotEmpty);
if (words.isEmpty) return true;
final haystack = '$title $keywords'.toLowerCase();
return words.every(haystack.contains);
}
}
@@ -0,0 +1,66 @@
import 'package:flutter/foundation.dart';
/// One server-backed Settings value.
///
/// It loads once when its section mounts, never starts a second load while one
/// is in flight, and keeps the last good value when a refresh fails, so a
/// flaky server shows stale data with a Retry rather than an empty section.
class ServerLoad<T> extends ChangeNotifier {
ServerLoad(this._fetch);
final Future<T> Function() _fetch;
T? _value;
bool _hasValue = false;
Object? _error;
bool _loading = false;
Future<void>? _inFlight;
bool _disposed = false;
/// The last value the server returned, or null before the first success.
T? get value => _value;
bool get hasValue => _hasValue;
/// The error from the latest attempt, cleared when a new attempt starts.
Object? get error => _error;
bool get loading => _loading;
/// Starts a load unless one is already running; returns that load's future.
Future<void> load() {
final running = _inFlight;
if (running != null) return running;
_loading = true;
_error = null;
_notify();
final future = _run();
_inFlight = future;
return future;
}
/// Retries after a failure or refreshes a cached value.
Future<void> refresh() => load();
Future<void> _run() async {
try {
final next = await _fetch();
if (_disposed) return;
_value = next;
_hasValue = true;
} catch (error) {
if (!_disposed) _error = error;
} finally {
_loading = false;
_inFlight = null;
_notify();
}
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
@@ -0,0 +1,138 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'settings_layout.dart';
import 'settings_server_load.dart';
import 'settings_theme.dart';
String _describeDefault(Object error) => '$error';
/// Shows a [ServerLoad] inside its section: the last value (with any refresh
/// error and a Retry beside it), a placeholder while the first load runs, or
/// the error with Retry. Other sections are never affected by this one.
///
/// The view starts the first load when it mounts, which happens only once the
/// page reaches its section; a cached value is never refetched by a rebuild.
class ServerSettingsView<T> extends StatefulWidget {
const ServerSettingsView({
super.key,
required this.load,
required this.builder,
this.describe = _describeDefault,
this.retryKey,
});
final ServerLoad<T> load;
final Widget Function(BuildContext context, T value) builder;
/// Turns a failure into the line the operator reads.
final String Function(Object error) describe;
final Key? retryKey;
@override
State<ServerSettingsView<T>> createState() => _ServerSettingsViewState<T>();
}
class _ServerSettingsViewState<T> extends State<ServerSettingsView<T>> {
@override
void initState() {
super.initState();
_startIfNeeded();
}
@override
void didUpdateWidget(ServerSettingsView<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.load != widget.load) _startIfNeeded();
}
void _startIfNeeded() {
final load = widget.load;
if (!load.hasValue && !load.loading && load.error == null) {
unawaited(load.load());
}
}
@override
Widget build(BuildContext context) {
final load = widget.load;
return ListenableBuilder(
listenable: load,
builder: (context, _) => _content(context, load),
);
}
Widget _content(BuildContext context, ServerLoad<T> load) {
final error = load.error;
if (load.hasValue) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
widget.builder(context, load.value as T),
if (error != null) _error(context, error),
],
);
}
if (error != null) return _error(context, error);
return const SettingsPlaceholder();
}
Widget _error(BuildContext context, Object error) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Semantics(
liveRegion: true,
child: Text(
widget.describe(error),
style: settingsTextStyle(context, error: true),
),
),
Align(
alignment: AlignmentDirectional.centerStart,
child: TextButton(
key: widget.retryKey,
onPressed: widget.load.loading ? null : () => widget.load.refresh(),
child: const Text('Retry'),
),
),
],
);
}
/// A loading placeholder for a value that has not arrived: two text-height
/// bars in the surface colour, sized from the text scale.
class SettingsPlaceholder extends StatelessWidget {
const SettingsPlaceholder({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scaler = MediaQuery.textScalerOf(context);
final line = scaler.scale(theme.textTheme.bodyMedium?.fontSize ?? 14);
final color = theme.colorScheme.surfaceContainerHighest;
Widget bar(double widthFactor) => FractionallySizedBox(
alignment: AlignmentDirectional.centerStart,
widthFactor: widthFactor,
child: Container(
height: line,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(settingsFieldGap),
),
),
);
return Semantics(
label: 'Loading',
excludeSemantics: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
bar(0.9),
const SizedBox(height: settingsTitleGap),
bar(0.6),
],
),
);
}
}
@@ -0,0 +1,19 @@
import 'package:flutter/material.dart';
import 'settings_group.dart';
import 'settings_server_view.dart';
/// A group-shaped placeholder for a lazy section that has not been reached yet.
/// It keeps the section's heading, so the page reads the same before and after
/// the section loads.
class SettingsSkeleton extends StatelessWidget {
const SettingsSkeleton({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) => SettingsGroup(
title: title,
children: const <Widget>[SettingsGroupItem(child: SettingsPlaceholder())],
);
}
@@ -1,170 +0,0 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'settings_topic_store.dart';
import '../../core/storage/ordered_local_storage.dart';
import '../../ui/motion/surface_visibility.dart';
enum SettingsTopic {
appearance('Appearance'),
connection('Connection'),
notifications('Notifications'),
tools('Tools'),
updates('Updates');
const SettingsTopic(this.label);
final String label;
}
/// Topic pages are created on first visit, then retained with their drafts and
/// independent scroll positions. Hidden pages do not tick animations.
class SettingsTopicTabs extends StatefulWidget {
const SettingsTopicTabs({
super.key,
required this.pages,
this.navigationScope,
this.selectionStore,
});
final Map<SettingsTopic, WidgetBuilder> pages;
/// Null keeps standalone previews independent of application persistence.
final String? navigationScope;
final SettingsTopicStore? selectionStore;
@override
State<SettingsTopicTabs> createState() => _SettingsTopicTabsState();
}
class _SettingsTopicTabsState extends State<SettingsTopicTabs>
with SingleTickerProviderStateMixin {
late final TabController _tabs;
SettingsTopic _selected = SettingsTopic.appearance;
final Set<SettingsTopic> _visited = {SettingsTopic.appearance};
SettingsTopicStore? _store;
int _revision = 0;
bool _restoring = false;
@override
void initState() {
super.initState();
_tabs = TabController(length: SettingsTopic.values.length, vsync: this);
_tabs.addListener(_changed);
_bindStore();
}
@override
void didUpdateWidget(SettingsTopicTabs oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.navigationScope != widget.navigationScope ||
oldWidget.selectionStore != widget.selectionStore) {
_bindStore();
}
}
void _bindStore() {
_store =
widget.selectionStore ??
(widget.navigationScope == null
? null
: SharedPreferencesSettingsTopicStore(widget.navigationScope!));
final revision = ++_revision;
final store = _store;
if (store == null) return;
unawaited(_restore(store, revision));
}
Future<void> _restore(SettingsTopicStore store, int revision) async {
String? saved;
try {
saved = await _ordered(store, store.load);
} catch (_) {
return;
}
if (!mounted || revision != _revision) return;
final topic =
SettingsTopic.values
.where((topic) => topic.name == saved)
.firstOrNull ??
SettingsTopic.appearance;
_restoring = true;
_tabs.index = topic.index;
_restoring = false;
}
Future<T> _ordered<T>(
SettingsTopicStore store,
Future<T> Function() operation,
) => store is SharedPreferencesSettingsTopicStore
? operation()
: orderedLocalStorage(store, operation);
void _persist(SettingsTopicStore store, String topic) {
// Register accepted choices synchronously, before a replacement can load.
// The production store coordinates all instances by their preference key.
unawaited(
_ordered(store, () => store.save(topic)).catchError((Object _) {
// Navigation continues when the local preference cannot be saved.
}),
);
}
void _changed() {
if (!mounted) return;
final next = SettingsTopic.values[_tabs.index];
if (next == _selected) return;
setState(() {
_selected = next;
_visited.add(next);
});
if (_restoring) return;
++_revision;
final store = _store;
if (store != null) _persist(store, next.name);
}
@override
void dispose() {
_tabs.removeListener(_changed);
_tabs.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final tabs = TabBar(
controller: _tabs,
isScrollable: true,
tabAlignment: TabAlignment.start,
tabs: [for (final topic in SettingsTopic.values) Tab(text: topic.label)],
);
return SafeArea(
bottom: false,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Semantics(container: true, label: 'Settings categories', child: tabs),
Expanded(
child: IndexedStack(
index: _selected.index,
children: [
for (final topic in SettingsTopic.values)
if (_visited.contains(topic))
TickerMode(
enabled: topic == _selected,
child: SurfaceVisibility(
shown: true,
current: topic == _selected,
child: KeyedSubtree(
key: ValueKey('settings-topic-${topic.name}'),
child: Builder(builder: widget.pages[topic]!),
),
),
)
else
const SizedBox.shrink(),
],
),
),
],
),
);
}
}
@@ -1,131 +0,0 @@
part of 'settings_screen.dart';
extension _SettingsTopicPages on _SettingsScreenState {
Map<SettingsTopic, WidgetBuilder> _topicPages() {
final servers = widget.servers;
return {
SettingsTopic.appearance: (_) => SettingsPageBody(
children: [
const SettingsScaleSection(),
SettingsAnimationSection(
controller:
widget.animationSpeed ?? AnimationSpeedController.instance,
),
SettingsFontSection(
controller: widget.fonts ?? AppFontController.instance,
),
SettingsTerminalSection(
layout: widget.terminalLayout ?? TerminalLayout.instance,
),
],
),
SettingsTopic.connection: (_) => SettingsPageBody(
children: [
if (servers != null) ...[
SavedServersSection(connections: servers),
ManagedConnectionSection(
client: widget.client,
controller: _controller,
),
] else
SettingsConnectionSection(
controller: _controller,
serverUrlField: _serverUrlField,
),
if (widget.showSignIn)
_single(
'Sign in',
SettingsSignInSection(
endpoint: _endpoint,
onChanged: _reconnectAfterSignIn,
),
),
if (widget.showSignIn || kIsWeb)
_single(
'Sign-in security',
SettingsSecuritySection(
endpoint: _endpoint,
onSignedOut: _reconnectAfterSignIn,
),
),
SettingsWorkspaceSection(
controller: _controller,
workspaceField: _workspaceField,
),
],
),
SettingsTopic.notifications: (_) => SettingsPageBody(
children: [
if (widget.notifications case final notifications?)
SettingsNotificationsSection(controller: notifications),
if (widget.deliveryService case final service? when service.supported)
SettingsDeviceDeliverySection(
bridge: service,
controller: widget.deliveryServiceController,
requestNotificationPermission: widget.notifications == null
? null
: () async {
await widget.notifications!.requestPermission();
},
),
SettingsNtfySection(
gateway: widget.client,
connected:
widget.client.state.kind == transport.ConnectionKind.connected,
),
],
),
SettingsTopic.tools: (_) => SettingsPageBody(
children: [
_single(
'Data management',
SettingsStorageSection(gateway: widget.client),
),
_single('Server', SettingsHealthSection(gateway: widget.client)),
SettingsGroup(
title: 'Help',
leadingRows: true,
children: const [
SettingsKeyboardShortcutsSection(),
SettingsWalkthroughSection(),
],
),
if (widget.onOpenSchedules case final open?)
SettingsGroup(
title: 'Library',
leadingRows: true,
children: [SettingsSchedulesSection(onOpen: open)],
),
],
),
SettingsTopic.updates: (_) => SettingsPageBody(
children: [
if (widget.showAndroidDownload)
_single('Android app', const SettingsAndroidDownloadSection()),
if (widget.showSignIn && appUpdatesSupported)
_single(
'App updates',
SettingsUpdatesSection(
endpoint: _endpoint,
servers: widget.servers,
),
),
if (!widget.showAndroidDownload &&
!(widget.showSignIn && appUpdatesSupported))
_single(
'App updates',
const Text(
'This installation is updated by its server administrator.',
),
),
],
),
};
}
/// A group holding one free-form block (a form, a status with buttons).
Widget _single(String title, Widget child) => SettingsGroup(
title: title,
children: <Widget>[SettingsGroupItem(child: child)],
);
}
@@ -1,37 +0,0 @@
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/servers/server_scope.dart';
import '../../core/storage/ordered_local_storage.dart';
const settingsTopicKey = 'pipelines.next.settingsTopic.v1';
abstract interface class SettingsTopicStore {
Future<String?> load();
Future<void> save(String topic);
}
/// Stores only the selected category, never unsaved fields or popup state.
class SharedPreferencesSettingsTopicStore implements SettingsTopicStore {
const SharedPreferencesSettingsTopicStore(this.scope);
final String scope;
String get key => scopedServerKey(settingsTopicKey, scope);
@override
Future<String?> load() => orderedLocalStorage(key, () async {
try {
return (await SharedPreferences.getInstance()).getString(key);
} catch (_) {
return null;
}
});
@override
Future<void> save(String topic) => orderedLocalStorage(key, () async {
try {
final preferences = await SharedPreferences.getInstance();
await preferences.setString(key, topic);
} catch (_) {
// The mounted category remains usable when local storage is unavailable.
}
});
}
@@ -1,23 +0,0 @@
import 'package:flutter/material.dart';
import '../walkthrough/first_run_walkthrough.dart';
import 'settings_keys.dart';
import 'settings_row.dart';
/// Reopens the first-run walkthrough. It only shows the walkthrough; it never
/// changes the device's seen record.
class SettingsWalkthroughSection extends StatelessWidget {
const SettingsWalkthroughSection({super.key});
@override
Widget build(BuildContext context) => SettingsRow(
key: SettingsKeys.walkthrough,
leading: const Icon(Icons.school_outlined),
title: const Text('Show the walkthrough'),
subtitle: const Text(
'Four short steps: connect, set up an agent, run, chat.',
),
chevron: true,
onTap: () => showFirstRunWalkthrough(context),
);
}
+172
View File
@@ -0,0 +1,172 @@
# settings-single-page — Settings as one searchable, grouped page
## What changed
Settings is one scrolling page of Material sections instead of five tabs.
A pinned search field filters sections by title and keywords and jumps to the
first match. On a wide body (≥ 840 px) a slim jump index sits beside the list.
The content column is 720 px, centred beside the index.
Server-backed sections load lazily: a section renders a skeleton until the list
scrolls within one viewport of it, or a search matches it. Once reached it stays
mounted and keeps its last value.
| File | Lines | Responsibility |
| --- | --- | --- |
| `lib/features/settings/settings_section.dart` | 44 | Section model: id, title, keywords, `lazy`, builder, query match |
| `lib/features/settings/settings_search_page.dart` | 226 | The page: pinned search, lazy activation, jump, index beside on wide |
| `lib/features/settings/settings_page_chrome.dart` | 79 | Search field and the jump index widget |
| `lib/features/settings/settings_page_sections.dart` | 213 | The ordered section list (part of `settings_screen.dart`) |
| `lib/features/settings/settings_screen.dart` | 191 | Builds the page; `navigationScope` parameter removed |
| `lib/features/settings/settings_server_load.dart` | 66 | `ServerLoad<T>`: one in-flight load, cached last value, refresh |
| `lib/features/settings/settings_server_view.dart` | 138 | Skeleton / cached value / inline error with Retry; starts its load on mount |
| `lib/features/settings/settings_skeleton.dart` | 19 | Group-shaped placeholder for a not-yet-reached lazy section |
| `lib/features/settings/settings_layout.dart` | +17 | Index width and breakpoint, preload distance, endpoint debounce |
| `lib/features/settings/security/settings_security_section.dart` | 172 | `ServerLoad` + inline Retry; endpoint reload debounced 600 ms (was per keystroke) |
| `lib/features/settings/ntfy_settings_controller.dart` | +6 | `loadFailed` flag |
| `lib/features/settings/settings_ntfy_section.dart` | +6 | Retry also after a failed refresh with cached values |
| `lib/application/pipelines_app.dart` | −1 | Drops the `navigationScope` argument |
Removed: `settings_tabs.dart`, `settings_topic_pages.dart`, `settings_topic_store.dart`
(the remembered-category store), and their tests `settings_tabs_test.dart` and
`settings_topic_restore_test.dart`. `SettingsPageBody` is unchanged (health and
storage screens still use it).
## Server loads found
- Sign-in security fetched on mount and again on every keystroke of the URL
draft (its endpoint followed the draft). Now one load per endpoint, debounced.
- Sign-in security caught only `SessionSecurityException`; any other failure left
the section silent. Now every failure shows inline with Retry.
- Phone notifications (ntfy) loaded on mount of the category. Now lazy.
- Health and storage are navigation rows; they fetch only when opened. Unchanged.
- No sequential server awaits on the page's load path were found.
## Help and about
The group `Help and about` (section id `help`, `settings_page_sections.dart`) holds
the keyboard shortcuts row and a "Show the walkthrough" row (`SettingsKeys.showWalkthrough`).
The walkthrough itself is not in this codebase yet (the parallel run adds it), so the
row takes an optional `SettingsScreen.onShowWalkthrough` callback. Without a callback
the row is present but disabled. The parallel run wires the callback in `pipelines_app.dart`
or the shell; this stage did not add a walkthrough action.
## Focused results
Command (from `app/`):
`tool/memwatch/full.sh 'test/features/settings/settings_server_load_test.dart test/features/settings/settings_search_page_test.dart test/features/settings/settings_screen_test.dart test/features/settings/settings_layout_test.dart test/features/settings/settings_library_test.dart test/features/settings/settings_shell_background_test.dart test/features/settings/settings_initial_connection_test.dart test/features/settings/settings_ntfy_section_test.dart test/features/settings/security/settings_security_section_test.dart test/application/settings_page_test.dart test/application/settings_registration_test.dart'`
Result: PASS, 51 passed, 0 failed, 0 skipped (memwatch verdict names only these paths).
An earlier run of the same list had 2 failures in the new walkthrough tests (a
type cast on the `SettingsRow` key instead of its `ListTile`); fixed, then passed.
`tool/analyze.sh` on the settings lib/test paths and the two application tests: clean.
New coverage:
- `settings_server_load_test.dart`: concurrent loads share one request; a failed
refresh keeps the cached value and a retry clears the error; a reply after
dispose is dropped.
- `settings_search_page_test.dart`: local sections render while a server section
has not answered (no request until reached); search filters by title and
keywords with all words required; a search that matches a lazy section loads it;
a failing server section shows its own Retry while other sections stay;
the jump index shows at 1200 px and not at 390 px.
- `settings_screen_test.dart`: Help and about keeps the shortcuts row and is searchable;
"Show the walkthrough" row is enabled and calls its callback when a callback is given,
is disabled without one, and is reachable by search ("walkthrough").
- `settings_layout_test.dart`: centred 720 px column beside the index; narrow fills the inset; the search field is pinned under the bar.
Expectation changes (behaviour the task asked for, not new behaviour):
- Tab-selection helper became `openSettingsSection(tester, title)`, which scrolls to a heading.
- URL and workspace fields are addressed by key, because the search field is now the first text field.
- The ping test now asserts the request order (`ping`, then `notification_settings` on a tall window), since the ntfy section is near the top there.
## Affected states (not captured here)
Phone and desktop, light and dark: no build or capture was run in this stage;
ui-review owns those. States to capture: default page; search with matches; search
with no match; index on wide; a lazy section as skeleton and loaded; a server
section with error and Retry.
## Limitations
- Search matches whole sections (title and keywords), not individual rows.
- Lazy activation is by viewport distance; a long window loads ntfy and security
on open.
- Not on-device verified.
- The "Check for updates" action walks the servers sequentially when pressed. That
is a user action, not the page load, and was left unchanged.
## Re-entry after land: main moved (merge of main)
Main changed the Settings files this branch rewrote, so the merge conflicted in
`settings_keys.dart`, `settings_screen.dart` and `settings_topic_pages.dart`.
Resolution (merge staged, not committed):
- `settings_topic_pages.dart` stays deleted. Its main-side change added a
walkthrough row to the old tab layout; this page already has the row.
- `settings_keys.dart` keeps `SettingsKeys.showWalkthrough` only; main's
`SettingsKeys.walkthrough` is dropped.
- `settings_screen.dart` keeps this branch's imports; main's
`settings_walkthrough_section.dart` import is dropped.
- `settings_walkthrough_section.dart` and its test
`test/features/settings/settings_walkthrough_test.dart` (main's, for the removed
tab row) are deleted. The reopen behaviour stays covered by the Help and about
row test in `settings_screen_test.dart`.
- `pipelines_app.dart` now passes `onShowWalkthrough` to Settings, calling
`showFirstRunWalkthrough(context)`. Before this, the row was disabled in the
app because nothing supplied the handler. The settings route builder now names
its parameter `context`.
- Main's device-delivery changes (warning, connection log, `open()`) merged
cleanly and are kept.
Focused results (memwatch, from app/):
- Passing: settings_screen_test, settings_device_delivery_section_test,
settings_search_page_test, settings_layout_test, settings_library_test,
settings_server_load_test, first_run_walkthrough_test, walkthrough_gate_test.
- Failing: `test/application/settings_page_test.dart` (2 tests: the bar gear
case and the rail case) and `test/application/settings_registration_test.dart`
(1 test). The same tests fail on untouched main, and the pre-merge branch
commit passes them. Likely cause: main's Pipelines bar now includes the
terminal toggle (`pipelines_app.dart` `_shellFor`), which pushes out the
`pipelines-open-settings` gear. Not fixed here; these tests need a decision on
the gear.
- `settings_tabs_test.dart` and `settings_topic_restore_test.dart` do not exist
on this branch; they are stale names in the change list.
`tool/analyze.sh`: clean.
Not on-device verified; no UI captured in this stage.
## Re-entry after ui-review: phone bar over the page
ui-review (visit 2) captured the phone page panned under the shell's floating tab
bar. The bar's glass let the Terminal help text and its controls show through the
bar, so they could not be read.
Cause: the shell's `Scaffold` uses `extendBody`, so the page's body reads the bar's
height as its bottom padding. The page padded only its scroll end, so rows scrolled
under the bar.
Fix (`settings_screen.dart`, embedded branch): the page's viewport now ends at the
bar's top edge. It reserves the body's bottom padding (the bar's height, or the
system inset when no bar shows) and removes that padding from its subtree, so the
page's own end padding is not counted twice. The non-embedded (own Scaffold) branch
is unchanged. On a wide window the bar is in the rail, so the reserved space is zero.
New regression test: `settings_screen_test.dart`, "phone: the page scrolls to rest
above the floating tab bar". It pumps the page in a `Scaffold(extendBody: true)` with
an 80 px bottom bar at 390×844, scrolls to the end, and asserts the list viewport and
the last row (the walkthrough row) end above the bar. It was confirmed to fail on the
previous embedded layout and to pass with this fix.
Focused results (memwatch, from app/, same path list as above, plus the new test):
- 49 passed, 3 failed. The 3 failures are the known application tests from the
land stage: `settings_page_test.dart` (390 and 1200 cases) and
`settings_registration_test.dart`. They fail at a tap on `segmented.more` and a
route check before reaching this layout. Not changed here.
- `tool/analyze.sh` on the settings lib/test paths and the two application tests: clean.
Affected states to re-capture (ui-review owns this): phone light and dark, panned to
the end of the page (the walkthrough row and Terminal help text must sit above the
bar); desktop, where the bar is in the rail and nothing changes.
Not on-device verified; no UI was built or captured in this stage.
+2 -2
View File
@@ -1,4 +1,4 @@
import '../features/settings/settings_topic_test_helper.dart';
import '../features/settings/settings_section_test_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/application/pipelines_app.dart';
@@ -84,7 +84,7 @@ void main() {
expect(provider.value.uri.path, '/settings');
expect(find.byType(SettingsScreen), findsOneWidget);
expect(find.text('Quick switch animation'), findsOneWidget);
await selectSettingsTopic(tester, 'Connection');
await openSettingsSection(tester, 'Connection');
expect(find.text('Server URL'), findsOneWidget);
// A page of Pipelines: Back in its bar, Settings selected in the bar.
expect(find.byKey(const ValueKey('shell.back')), findsOneWidget);
@@ -1,4 +1,4 @@
import '../features/settings/settings_topic_test_helper.dart';
import '../features/settings/settings_section_test_helper.dart';
import 'dart:convert';
import 'package:flutter/material.dart';
@@ -54,7 +54,7 @@ void main() {
await tester.pump();
expect(provider.value.uri.path, '/settings');
expect(find.text('Quick switch animation'), findsOneWidget);
await selectSettingsTopic(tester, 'Connection');
await openSettingsSection(tester, 'Connection');
expect(find.text('Server URL'), findsOneWidget);
expect(find.text('Settings — Not implemented'), findsNothing);
expect(sockets, 1);
@@ -16,28 +16,39 @@ import 'package:pipelines_app/features/settings/settings_store.dart';
import 'package:pipelines_app/features/settings/settings_trust_warning.dart';
import 'fake_channel.dart';
import 'settings_topic_test_helper.dart';
import 'settings_section_test_helper.dart';
void main() {
testWidgets('groups start at the bar inset and stop at the reading width', (
testWidgets('groups are centred at the reading width beside the index', (
tester,
) async {
await _pump(tester, size: const Size(1200, 1600));
// The list area is the window less the jump index and the side insets.
const area = 1200 - settingsIndexWidth - 2 * settingsPageSidePadding;
final expectedLeft =
settingsPageSidePadding + (area - settingsContentMaxWidth) / 2;
final groups = find.byType(SettingsGroup);
expect(groups, findsWidgets);
for (final group in groups.evaluate()) {
final rect = tester.getRect(find.byWidget(group.widget));
// The column starts where the bar's title pill does, not centred.
expect(rect.left, closeTo(settingsPageSidePadding, 0.01));
expect(rect.left, closeTo(expectedLeft, 0.01));
expect(rect.width, closeTo(settingsContentMaxWidth, 0.01));
}
// A header's text lines up with its rows' text.
final header = tester.getRect(find.text('Connection').last);
expect(
header.left,
closeTo(settingsPageSidePadding + settingsRowInset, 0.01),
);
final groupLeft = tester.getRect(find.byType(SettingsGroup).first).left;
final header = tester.getRect(find.text('Connection').first);
expect(header.left, closeTo(groupLeft + settingsRowInset, 0.01));
});
testWidgets('on a narrow window the groups fill the inset width', (
tester,
) async {
await _pump(tester, size: const Size(390, 844));
final group = tester.getRect(find.byType(SettingsGroup).first);
expect(group.left, closeTo(settingsPageSidePadding, 0.01));
expect(group.width, closeTo(390 - 2 * settingsPageSidePadding, 0.01));
});
testWidgets('Material groups are flat surfaces, not elevated cards', (
@@ -64,32 +75,24 @@ void main() {
}
// The trust warning is the Connection group's footer, not a card.
expect(find.byType(SettingsTrustWarning), findsOneWidget);
final title = tester.widget<Text>(find.text('Connection').last);
final theme = Theme.of(tester.element(find.text('Connection').last));
final title = tester.widget<Text>(find.text('Connection').first);
final theme = Theme.of(tester.element(find.text('Connection').first));
expect(title.style?.color, theme.colorScheme.primary);
});
testWidgets('content starts below the bar and persistent topic tabs', (
testWidgets('content starts below the bar, with the search field pinned', (
tester,
) async {
const barHeight = 72.0;
await _pump(tester, topPadding: barHeight);
final first = tester.getRect(find.byType(SettingsGroup).first);
expect(
first.top,
closeTo(
barHeight +
tester.getSize(find.byType(TabBar)).height +
settingsPageTopPadding,
0.01,
),
);
// The topic selector stays above each page scroll view.
expect(
tester.getRect(find.byKey(const ValueKey('settings.scroll')).last).top,
barHeight + tester.getSize(find.byType(TabBar)).height,
// The search field sits under the bar and stays above the scrolling list.
final search = tester.getRect(
find.byKey(const ValueKey('settings.search')),
);
expect(search.top, closeTo(barHeight + settingsPageTopPadding, 0.01));
final list = tester.getRect(find.byKey(const ValueKey('settings.scroll')));
expect(list.top, greaterThan(search.bottom));
});
testWidgets('the notification tile is the section\'s only title', (
@@ -101,9 +104,9 @@ void main() {
addTearDown(notifications.dispose);
await _pump(tester, notifications: notifications);
await selectSettingsTopic(tester, 'Notifications');
expect(find.text('Notifications'), findsNWidgets(2));
expect(find.text('Connection').last, findsOneWidget);
await openSettingsSection(tester, 'Notifications');
expect(find.text('Notifications'), findsOneWidget);
expect(find.text('Connection'), findsOneWidget);
});
testWidgets('server rows show which server is selected', (tester) async {
@@ -183,5 +186,5 @@ Future<void> _pump(
);
await tester.pump();
await tester.pump();
await selectSettingsTopic(tester, 'Connection');
await openSettingsSection(tester, 'Connection');
}
@@ -7,9 +7,9 @@ import 'package:pipelines_app/features/settings/settings_screen.dart';
import 'package:pipelines_app/features/settings/settings_store.dart';
import 'fake_channel.dart';
import 'settings_topic_test_helper.dart';
import 'settings_section_test_helper.dart';
/// The Tools topic's Library group lists Schedules only: Templates left
/// The Library section lists Schedules only: Templates left
/// Settings, and Schedules keeps its own route.
void main() {
Future<void> pump(
@@ -34,10 +34,12 @@ void main() {
),
);
await tester.pump();
await selectSettingsTopic(tester, 'Tools');
if (onOpenSchedules != null) await openSettingsSection(tester, 'Library');
}
testWidgets('Tools offers Schedules and no Templates entry', (tester) async {
testWidgets('Library offers Schedules and no Templates entry', (
tester,
) async {
var opened = 0;
await pump(tester, onOpenSchedules: () => opened++);
@@ -9,7 +9,7 @@ import 'package:pipelines_app/features/settings/settings_screen.dart';
import 'package:pipelines_app/features/settings/settings_store.dart';
import 'fake_channel.dart';
import 'settings_topic_test_helper.dart';
import 'settings_section_test_helper.dart';
void main() {
testWidgets('renders idle settings without opening a connection', (
@@ -34,7 +34,7 @@ void main() {
expect(find.text('Not connected'), findsOneWidget);
expect(find.text('Saved workspace: /srv/pipelines'), findsOneWidget);
expect(
tester.widget<TextField>(find.byType(TextField).first).controller?.text,
tester.widget<TextField>(serverUrlField).controller?.text,
'ws://saved.test/connect',
);
expect(find.byKey(SettingsKeys.connect), findsOneWidget);
@@ -65,7 +65,7 @@ void main() {
),
);
final field = tester.widget<TextField>(find.byType(TextField).first);
final field = tester.widget<TextField>(serverUrlField);
expect(field.maxLines, 2);
expect(field.controller?.text, contains('/connect'));
expect(tester.takeException(), isNull);
@@ -82,15 +82,14 @@ void main() {
store: MemorySettingsStore(serverUrl: 'ws://127.0.0.1:8080/connect'),
);
final fields = find.byType(TextField);
final url = tester.widget<TextField>(fields.first);
final url = tester.widget<TextField>(serverUrlField);
expect(url.minLines, 1);
// The URL field grows only when its text wraps: one line is the same
// height as the single-line workspace field below it.
Size editable(Finder field) => tester.getSize(
find.descendant(of: field, matching: find.byType(EditableText)),
);
expect(editable(fields.first).height, editable(fields.last).height);
expect(editable(serverUrlField).height, editable(workspaceField).height);
});
testWidgets('an invalid URL shows the field error and opens no socket', (
@@ -101,7 +100,7 @@ void main() {
addTearDown(client.dispose);
await _pump(tester, client);
await tester.enterText(find.byType(TextField).first, 'http://example.test');
await tester.enterText(serverUrlField, 'http://example.test');
await tester.pump();
await tester.tap(find.byKey(SettingsKeys.connect));
await tester.pump();
@@ -119,10 +118,7 @@ void main() {
addTearDown(client.dispose);
await _pump(tester, client);
await tester.enterText(
find.byType(TextField).first,
'ws://example.test:8123',
);
await tester.enterText(serverUrlField, 'ws://example.test:8123');
await tester.pump();
await tester.tap(find.byKey(SettingsKeys.connect));
await tester.pump();
@@ -162,9 +158,13 @@ void main() {
findsOneWidget,
);
expect(find.text('Connect'), findsNothing);
// Notification settings are loaded only when their topic is opened.
expect(factory.last.decodedOutgoing, hasLength(1));
await selectSettingsTopic(tester, 'Notifications');
// Notification settings load once their lazy section is near the list:
// this tall window reaches it on open, after the single ping.
expect(factory.last.decodedOutgoing.map((message) => message['type']), [
'ping',
'notification_settings',
]);
await openSettingsSection(tester, 'Phone notifications');
_answerNtfySettings(factory.last);
await tester.pump();
await tester.pump();
@@ -179,10 +179,7 @@ void main() {
addTearDown(client.dispose);
await _pump(tester, client);
await tester.enterText(
find.byType(TextField).first,
'ws://example.test:8123',
);
await tester.enterText(serverUrlField, 'ws://example.test:8123');
await tester.pump();
await tester.tap(find.byKey(SettingsKeys.connect));
await tester.pump();
@@ -206,7 +203,7 @@ void main() {
expect(find.text(serverDetailsPending), findsNothing);
expect(find.text('Server build unavailable'), findsOneWidget);
expect(find.text('Server time unavailable'), findsOneWidget);
await selectSettingsTopic(tester, 'Notifications');
await openSettingsSection(tester, 'Phone notifications');
_answerNtfySettings(factory.last);
await tester.pump();
});
@@ -220,7 +217,7 @@ void main() {
final store = MemorySettingsStore();
await _pump(tester, client, store: store);
final workspace = find.byType(TextField).at(1);
final workspace = workspaceField;
await tester.enterText(workspace, 'relative/path');
await tester.pump();
@@ -270,7 +267,7 @@ void main() {
200,
scrollable: find
.descendant(
of: find.byKey(const ValueKey('settings-topic-connection')),
of: find.byKey(const ValueKey<String>('settings.scroll')),
matching: find.byType(Scrollable),
)
.first,
@@ -318,20 +315,88 @@ void main() {
await _pump(tester, client);
final labels = <String>[
tester
.getSemantics(find.byType(TextField).at(0))
.getSemanticsData()
.label,
tester
.getSemantics(find.byType(TextField).at(1))
.getSemanticsData()
.label,
tester.getSemantics(serverUrlField).getSemanticsData().label,
tester.getSemantics(workspaceField).getSemanticsData().label,
];
expect(labels[0], contains('Server URL'));
expect(labels[1], contains('Workspace path (on the server)'));
handle.dispose();
});
testWidgets('Help and about keeps the keyboard shortcuts row', (
tester,
) async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
await _pump(tester, client);
await openSettingsSection(tester, 'Help and about');
expect(find.text('Help and about'), findsOneWidget);
expect(find.byKey(SettingsKeys.keyboardShortcuts), findsOneWidget);
// Help is a plain section of the page, so the search reaches it too.
await tester.enterText(
find.byKey(const ValueKey<String>('settings.search')),
'shortcuts',
);
await tester.pump();
expect(find.byKey(SettingsKeys.keyboardShortcuts), findsOneWidget);
expect(find.text('Server URL'), findsNothing);
});
testWidgets('Help and about has a Show the walkthrough row', (tester) async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
var shown = 0;
await _pump(tester, client, onShowWalkthrough: () => shown++);
await openSettingsSection(tester, 'Help and about');
final row = find.byKey(SettingsKeys.showWalkthrough);
expect(find.text('Show the walkthrough'), findsOneWidget);
expect(row, findsOneWidget);
expect(
tester
.widget<ListTile>(find.descendant(of: row, matching: find.byType(ListTile)))
.enabled,
isTrue,
);
await tester.tap(row);
await tester.pump();
expect(shown, 1);
// The search reaches the row as well.
await tester.enterText(
find.byKey(const ValueKey<String>('settings.search')),
'walkthrough',
);
await tester.pump();
expect(find.byKey(SettingsKeys.showWalkthrough), findsOneWidget);
});
testWidgets('Show the walkthrough row is disabled without a handler', (
tester,
) async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
addTearDown(client.dispose);
await _pump(tester, client);
await openSettingsSection(tester, 'Help and about');
final row = find.byKey(SettingsKeys.showWalkthrough);
expect(row, findsOneWidget);
expect(
tester
.widget<ListTile>(find.descendant(of: row, matching: find.byType(ListTile)))
.enabled,
isFalse,
);
});
testWidgets('unmounting leaves the shared client usable', (tester) async {
final factory = FakeChannelFactory();
final client = transport.PipelinesClient(channelFactory: factory.call);
@@ -348,8 +413,74 @@ void main() {
await tester.pump();
await connecting;
});
testWidgets('phone: the page scrolls to rest above the floating tab bar', (
tester,
) async {
await tester.binding.setSurfaceSize(const Size(390, 844));
addTearDown(() => tester.binding.setSurfaceSize(null));
final client = transport.PipelinesClient(
channelFactory: FakeChannelFactory().call,
);
addTearDown(client.dispose);
// The shell's shape: a body that extends behind a bottom bar, which the
// body reads as its bottom padding.
const barKey = ValueKey<String>('test.tabBar');
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(
extendBody: true,
body: SettingsScreen(
client: client,
store: MemorySettingsStore(),
embedded: true,
onShowWalkthrough: () {},
),
bottomNavigationBar: const SizedBox(
key: barKey,
width: double.infinity,
height: 80,
),
),
),
);
await tester.pump();
await tester.pump();
final scroll = find.byKey(const ValueKey<String>('settings.scroll'));
// Each lazy section that the scroll reaches grows the list, so keep
// scrolling until the page stops moving.
for (var i = 0; i < 6; i++) {
await tester.drag(scroll, const Offset(0, -10000));
await tester.pump();
await tester.pump();
}
final barTop = tester.getTopLeft(find.byKey(barKey)).dy;
// Nothing scrolls under the bar: the list's viewport ends at its top edge,
// and the last row (the page's end) sits above it at rest.
expect(tester.getRect(scroll).bottom, lessThanOrEqualTo(barTop + 0.5));
expect(
tester.getRect(find.byKey(SettingsKeys.showWalkthrough)).bottom,
lessThanOrEqualTo(barTop + 0.5),
);
expect(tester.takeException(), isNull);
});
}
/// The Server URL and Workspace fields, addressed by their keys: the search
/// field is the page's first text field.
Finder get serverUrlField => find.descendant(
of: find.byKey(SettingsKeys.serverUrl),
matching: find.byType(TextField),
);
Finder get workspaceField => find.descendant(
of: find.byKey(SettingsKeys.workspace),
matching: find.byType(TextField),
);
Future<void> _pump(
WidgetTester tester,
transport.PipelinesClient client, {
@@ -357,6 +488,7 @@ Future<void> _pump(
TargetPlatform platform = TargetPlatform.android,
double textScale = 1,
Size size = const Size(800, 1200),
VoidCallback? onShowWalkthrough,
}) async {
await tester.binding.setSurfaceSize(size);
addTearDown(() => tester.binding.setSurfaceSize(null));
@@ -372,12 +504,13 @@ Future<void> _pump(
home: SettingsScreen(
client: client,
store: store ?? MemorySettingsStore(),
onShowWalkthrough: onShowWalkthrough,
),
),
);
await tester.pump();
await tester.pump();
await selectSettingsTopic(tester, 'Connection');
await openSettingsSection(tester, 'Connection');
}
/// Answers the Settings screen's queued ntfy-settings load on [channel].
@@ -0,0 +1,249 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/settings/settings_search_page.dart';
import 'package:pipelines_app/features/settings/settings_section.dart';
import 'package:pipelines_app/features/settings/settings_server_load.dart';
import 'package:pipelines_app/features/settings/settings_server_view.dart';
/// Fills the page so a section placed after it starts far below the viewport.
List<SettingsSection> _filler(int count) => [
for (var i = 0; i < count; i++)
SettingsSection(
id: 'filler-$i',
title: 'Filler $i',
builder: (_) => const SizedBox(height: 400, child: Text('filler body')),
),
];
Future<void> _pump(
WidgetTester tester,
List<SettingsSection> sections, {
Size size = const Size(800, 600),
}) async {
await tester.binding.setSurfaceSize(size);
addTearDown(() => tester.binding.setSurfaceSize(null));
await tester.pumpWidget(
MaterialApp(
home: Scaffold(body: SettingsSearchPage(sections: sections)),
),
);
await tester.pump();
await tester.pump();
}
void main() {
testWidgets('local settings render while a server section has not answered', (
tester,
) async {
var fetches = 0;
final reply = Completer<int>();
final load = ServerLoad<int>(() {
fetches++;
return reply.future;
});
addTearDown(load.dispose);
await _pump(tester, [
..._filler(6),
SettingsSection(
id: 'server',
title: 'Phone notifications',
lazy: true,
builder: (_) => ServerSettingsView<int>(
load: load,
builder: (_, value) => Text('Server $value'),
),
),
]);
// The local sections are built and the server section is only a skeleton:
// no request runs until the list reaches it.
expect(find.text('filler body'), findsWidgets);
expect(find.text('Phone notifications'), findsOneWidget);
expect(fetches, 0);
expect(tester.takeException(), isNull);
await tester.ensureVisible(find.text('Phone notifications'));
await tester.pump();
await tester.pump();
expect(fetches, 1);
// The reply is still pending, and the page keeps working.
expect(find.bySemanticsLabel('Loading'), findsOneWidget);
expect(find.text('filler body'), findsWidgets);
reply.complete(3);
await tester.pump();
expect(find.text('Server 3'), findsOneWidget);
});
testWidgets('search filters sections by title and keywords', (tester) async {
await _pump(tester, [
SettingsSection(
id: 'animations',
title: 'Animations',
keywords: 'motion speed',
builder: _titled('Animations'),
),
SettingsSection(
id: 'terminal',
title: 'Terminal',
keywords: 'layout split',
builder: _titled('Terminal'),
),
]);
expect(find.text('Animations'), findsOneWidget);
expect(find.text('Terminal'), findsOneWidget);
await tester.enterText(
find.byKey(const ValueKey('settings.search')),
'motion',
);
await tester.pump();
expect(find.text('Animations'), findsOneWidget);
expect(find.text('Terminal'), findsNothing);
// Every word must match: "motion layout" matches neither section.
await tester.enterText(
find.byKey(const ValueKey('settings.search')),
'motion layout',
);
await tester.pump();
expect(find.text('Animations'), findsNothing);
expect(find.text('Terminal'), findsNothing);
expect(find.textContaining('No settings match'), findsOneWidget);
await tester.tap(find.byTooltip('Clear search'));
await tester.pump();
expect(find.text('Animations'), findsOneWidget);
expect(find.text('Terminal'), findsOneWidget);
});
testWidgets('a search that matches a server section loads it at once', (
tester,
) async {
var fetches = 0;
final load = ServerLoad<int>(() async {
fetches++;
return 9;
});
addTearDown(load.dispose);
await _pump(tester, [
..._filler(6),
SettingsSection(
id: 'server',
title: 'Phone notifications',
keywords: 'ntfy push',
lazy: true,
builder: (_) => ServerSettingsView<int>(
load: load,
builder: (_, value) => Text('Server $value'),
),
),
]);
expect(fetches, 0);
await tester.enterText(
find.byKey(const ValueKey('settings.search')),
'ntfy',
);
await tester.pump();
await tester.pump();
await tester.pump();
expect(fetches, 1);
expect(find.text('Server 9'), findsOneWidget);
expect(find.text('filler body'), findsNothing);
});
testWidgets(
'a failing server section shows its own Retry; others are unaffected',
(tester) async {
var attempts = 0;
final load = ServerLoad<String>(() async {
attempts++;
if (attempts == 1) throw StateError('server unreachable');
return 'Stored';
});
addTearDown(load.dispose);
await _pump(tester, [
SettingsSection(
id: 'local',
title: 'Animations',
builder: (_) =>
const Column(children: [Text('Animations'), Text('Local value')]),
),
SettingsSection(
id: 'server',
title: 'Sign-in security',
lazy: true,
builder: (_) => ServerSettingsView<String>(
load: load,
retryKey: const Key('server-retry'),
builder: (_, value) => Text('Security $value'),
),
),
]);
await tester.pump();
expect(find.textContaining('server unreachable'), findsOneWidget);
expect(find.byKey(const Key('server-retry')), findsOneWidget);
expect(find.text('Local value'), findsOneWidget);
expect(find.text('Animations'), findsOneWidget);
await tester.tap(find.byKey(const Key('server-retry')));
await tester.pump();
await tester.pump();
expect(attempts, 2);
expect(find.text('Security Stored'), findsOneWidget);
expect(find.byKey(const Key('server-retry')), findsNothing);
expect(find.text('Local value'), findsOneWidget);
},
);
testWidgets('wide layouts list every visible section in the jump index', (
tester,
) async {
final sections = [
SettingsSection(
id: 'animations',
title: 'Animations',
builder: _titled('Animations'),
),
SettingsSection(
id: 'terminal',
title: 'Terminal',
builder: _titled('Terminal'),
),
];
await _pump(tester, sections, size: const Size(1200, 800));
expect(
find.byKey(const ValueKey('settings.index.animations')),
findsOneWidget,
);
expect(
find.byKey(const ValueKey('settings.index.terminal')),
findsOneWidget,
);
await tester.tap(find.byKey(const ValueKey('settings.index.terminal')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
expect(tester.takeException(), isNull);
});
testWidgets('a narrow layout has no jump index', (tester) async {
await _pump(tester, [
SettingsSection(
id: 'animations',
title: 'Animations',
builder: _titled('Animations'),
),
], size: const Size(390, 844));
expect(
find.byKey(const ValueKey('settings.index.animations')),
findsNothing,
);
});
}
WidgetBuilder _titled(String title) =>
(_) => Text(title);
@@ -0,0 +1,11 @@
import 'package:flutter_test/flutter_test.dart';
/// Scrolls the Settings page to the heading [title] and lets a lazy section
/// that the scroll reaches load its content.
Future<void> openSettingsSection(WidgetTester tester, String title) async {
final heading = find.text(title).first;
await tester.ensureVisible(heading);
await tester.pump();
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
}
@@ -0,0 +1,65 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/settings/settings_server_load.dart';
void main() {
test('concurrent loads share one request', () async {
var calls = 0;
final reply = Completer<int>();
final load = ServerLoad<int>(() {
calls++;
return reply.future;
});
addTearDown(load.dispose);
final first = load.load();
final second = load.refresh();
expect(calls, 1);
expect(load.loading, isTrue);
reply.complete(7);
await first;
await second;
expect(load.value, 7);
expect(load.hasValue, isTrue);
expect(load.loading, isFalse);
expect(load.error, isNull);
});
test(
'a failed refresh keeps the last value; a retry clears the error',
() async {
var calls = 0;
final load = ServerLoad<String>(() async {
calls++;
if (calls == 2) throw StateError('server unreachable');
return 'value $calls';
});
addTearDown(load.dispose);
await load.load();
expect(load.value, 'value 1');
await load.refresh();
expect(load.value, 'value 1', reason: 'the cached value survives');
expect(load.error, isA<StateError>());
await load.refresh();
expect(load.error, isNull);
expect(load.value, 'value 3');
expect(calls, 3);
},
);
test('a reply that lands after dispose is dropped quietly', () async {
final reply = Completer<int>();
final load = ServerLoad<int>(() => reply.future);
final pending = load.load();
load.dispose();
reply.complete(1);
await pending;
expect(load.hasValue, isFalse);
});
}
@@ -1,105 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/settings/settings_tabs.dart';
import 'settings_topic_test_helper.dart';
class _Page extends StatefulWidget {
const _Page({required this.name, required this.onMount});
final String name;
final VoidCallback onMount;
@override
State<_Page> createState() => _PageState();
}
class _PageState extends State<_Page> {
final text = TextEditingController();
final scroll = ScrollController();
@override
void initState() {
super.initState();
widget.onMount();
}
@override
void dispose() {
text.dispose();
scroll.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => SingleChildScrollView(
controller: scroll,
child: Column(
children: [
TextField(controller: text),
for (var i = 0; i < 80; i++) Text('${widget.name} item $i'),
],
),
);
}
void main() {
testWidgets('lazy topic pages retain draft and scroll', (tester) async {
final mounts = <SettingsTopic, int>{};
final tabs = SettingsTopicTabs(
pages: {
for (final topic in SettingsTopic.values)
topic: (_) => _Page(
name: topic.name,
onMount: () =>
mounts.update(topic, (count) => count + 1, ifAbsent: () => 1),
),
},
);
await tester.pumpWidget(MaterialApp(home: Scaffold(body: tabs)));
expect(mounts, {SettingsTopic.appearance: 1});
final appearance = tester.state<_PageState>(find.byType(_Page));
appearance.text.text = 'Keep this draft';
appearance.scroll.jumpTo(150);
await tester.pump();
await selectSettingsTopic(tester, 'Connection');
expect(mounts, {SettingsTopic.appearance: 1, SettingsTopic.connection: 1});
final connection = tester.state<_PageState>(find.byType(_Page));
connection.text.text = 'Unsubmitted server';
connection.scroll.jumpTo(280);
await selectSettingsTopic(tester, 'Appearance');
expect(tester.state(find.byType(_Page)), same(appearance));
expect(appearance.text.text, 'Keep this draft');
expect(appearance.scroll.offset, 150);
await selectSettingsTopic(tester, 'Connection');
expect(tester.state(find.byType(_Page)), same(connection));
expect(connection.text.text, 'Unsubmitted server');
expect(connection.scroll.offset, 280);
expect(mounts.values, everyElement(1));
});
testWidgets('all topics reachable at narrow large text', (tester) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final tabs = SettingsTopicTabs(
pages: {
for (final topic in SettingsTopic.values)
topic: (_) => Text('${topic.label} content'),
},
);
Widget scale(BuildContext context, Widget? child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: const TextScaler.linear(2)),
child: child!,
);
await tester.pumpWidget(
MaterialApp(
builder: scale,
home: Scaffold(body: tabs),
),
);
for (final topic in SettingsTopic.values) {
await selectSettingsTopic(tester, topic.label);
expect(find.text('${topic.label} content'), findsOneWidget);
expect(tester.takeException(), isNull);
}
});
}
@@ -1,203 +0,0 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/servers/server_scope.dart';
import 'package:pipelines_app/core/storage/ordered_local_storage.dart';
import 'package:pipelines_app/features/settings/settings_tabs.dart';
import 'package:pipelines_app/features/settings/settings_topic_store.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'settings_topic_test_helper.dart';
Widget host({String? scope, SettingsTopicStore? store}) {
final tabs = SettingsTopicTabs(
navigationScope: scope,
selectionStore: store,
pages: {
for (final topic in SettingsTopic.values)
topic: (_) => Text('${topic.name} page'),
},
);
return MaterialApp(home: Scaffold(body: tabs));
}
class DelayedStore implements SettingsTopicStore {
final read = Completer<String?>();
final saves = <String>[];
final pending = <Completer<void>>[];
bool blockWrites = false;
@override
Future<String?> load() => read.future;
@override
Future<void> save(String topic) async {
saves.add(topic);
if (blockWrites) {
final gate = Completer<void>();
pending.add(gate);
await gate.future;
}
}
}
class SharedTopicBackend {
final firstWrite = Completer<void>();
final writes = <String>[];
String? value;
}
class SharedQueuedTopicStore implements SettingsTopicStore {
SharedQueuedTopicStore(this.backend);
final SharedTopicBackend backend;
@override
Future<String?> load() async => backend.value;
@override
Future<void> save(String topic) async {
backend.writes.add(topic);
if (backend.writes.length == 1) await backend.firstWrite.future;
backend.value = topic;
}
}
void main() {
testWidgets('restores selected category after recreation', (tester) async {
SharedPreferences.setMockInitialValues({});
await tester.pumpWidget(host(scope: 'server-a'));
await tester.pumpAndSettle();
await selectSettingsTopic(tester, 'Connection');
expect(find.text('connection page'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpWidget(host(scope: 'server-a'));
await tester.pumpAndSettle();
expect(find.text('connection page'), findsOneWidget);
final preferences = await SharedPreferences.getInstance();
expect(
preferences.getString(scopedServerKey(settingsTopicKey, 'server-a')),
'connection',
);
});
testWidgets('server scopes and malformed selections are independent', (
tester,
) async {
SharedPreferences.setMockInitialValues({
scopedServerKey(settingsTopicKey, 'server-a'): 'connection',
scopedServerKey(settingsTopicKey, 'server-b'): 'not-a-topic',
});
await tester.pumpWidget(host(scope: 'server-a'));
await tester.pumpAndSettle();
expect(find.text('connection page'), findsOneWidget);
await tester.pumpWidget(host(scope: 'server-b'));
await tester.pumpAndSettle();
expect(find.text('appearance page'), findsOneWidget);
await tester.pumpWidget(host(scope: 'server-a'));
await tester.pumpAndSettle();
expect(find.text('connection page'), findsOneWidget);
});
testWidgets('standalone category tabs do not read or write preferences', (
tester,
) async {
SharedPreferences.setMockInitialValues({settingsTopicKey: 'updates'});
await tester.pumpWidget(host());
await tester.pumpAndSettle();
expect(find.text('appearance page'), findsOneWidget);
await selectSettingsTopic(tester, 'Connection');
expect(
(await SharedPreferences.getInstance()).getString(settingsTopicKey),
'updates',
);
});
testWidgets('late restore cannot overwrite a newer user selection', (
tester,
) async {
final store = DelayedStore();
await tester.pumpWidget(host(store: store));
await selectSettingsTopic(tester, 'Connection');
store.read.complete('updates');
await tester.pumpAndSettle();
expect(find.text('connection page'), findsOneWidget);
expect(store.saves, ['connection']);
});
testWidgets('writes are serialized so the latest selection wins last', (
tester,
) async {
final store = DelayedStore()..blockWrites = true;
store.read.complete(null);
await tester.pumpWidget(host(store: store));
await tester.pumpAndSettle();
await selectSettingsTopic(tester, 'Connection');
await selectSettingsTopic(tester, 'Notifications');
expect(store.saves, ['connection']);
store.pending.first.complete();
await tester.pumpAndSettle();
expect(store.saves, ['connection', 'notifications']);
store.pending.last.complete();
await tester.pumpAndSettle();
expect(find.text('notifications page'), findsOneWidget);
});
for (final newerChoice in [false, true]) {
testWidgets('recreation preserves accepted B; newer choice: $newerChoice', (
tester,
) async {
final backend = SharedTopicBackend();
final store = SharedQueuedTopicStore(backend);
await tester.pumpWidget(host(store: store));
await tester.pumpAndSettle();
await selectSettingsTopic(tester, 'Connection');
expect(backend.writes, ['connection']);
await selectSettingsTopic(tester, 'Notifications');
expect(backend.writes, ['connection']);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpWidget(host(store: store));
if (newerChoice) await selectSettingsTopic(tester, 'Tools');
backend.firstWrite.complete();
await tester.pumpAndSettle();
expect(
find.text(newerChoice ? 'tools page' : 'notifications page'),
findsOneWidget,
);
expect(backend.value, newerChoice ? 'tools' : 'notifications');
expect(backend.writes, [
'connection',
'notifications',
if (newerChoice) 'tools',
]);
});
}
testWidgets('production replacement reads after all accepted old writes', (
tester,
) async {
SharedPreferences.setMockInitialValues({});
const oldStore = SharedPreferencesSettingsTopicStore('ownership-check');
final gate = Completer<void>();
final oldA = orderedLocalStorage(oldStore.key, () async {
await gate.future;
await (await SharedPreferences.getInstance()).setString(
oldStore.key,
'connection',
);
});
final oldB = oldStore.save('notifications');
final replacement = SharedPreferencesSettingsTopicStore('ownership-check');
var readFinished = false;
final read = replacement.load().then((value) {
readFinished = true;
return value;
});
await tester.pump();
expect(readFinished, isFalse);
gate.complete();
await oldA;
await oldB;
expect(await read, 'notifications');
await replacement.save('tools');
expect(
(await SharedPreferences.getInstance()).getString(oldStore.key),
'tools',
);
});
}
@@ -1,9 +0,0 @@
import 'package:flutter_test/flutter_test.dart';
Future<void> selectSettingsTopic(WidgetTester tester, String topic) async {
final label = find.text(topic).first;
await tester.ensureVisible(label);
await tester.tap(label);
await tester.pump();
await tester.pump(const Duration(milliseconds: 350));
}
@@ -1,36 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/settings/settings_keys.dart';
import 'package:pipelines_app/features/settings/settings_walkthrough_section.dart';
import 'package:pipelines_app/ui/theme/app_theme.dart';
void main() {
testWidgets('Settings reopens the walkthrough on the first page', (
tester,
) async {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = const Size(390, 844);
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
theme: appLightTheme(),
home: const Scaffold(body: SettingsWalkthroughSection()),
),
);
expect(find.text('Show the walkthrough'), findsOneWidget);
expect(find.text('Welcome to Pipelines'), findsNothing);
await tester.tap(find.byKey(SettingsKeys.walkthrough));
await tester.pumpAndSettle();
expect(find.text('Welcome to Pipelines'), findsOneWidget);
expect(find.text('Step 1 of 4'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey<String>('walkthrough.skip')));
await tester.pumpAndSettle();
expect(find.text('Welcome to Pipelines'), findsNothing);
});
}